answer
stringlengths
17
10.2M
package com.ayros.historycleaner.ui; import android.app.Activity; import android.app.TabActivity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.TabHost; import android.widget.TabHost.OnTabChangeListener; import android.widget.TabHost.TabSpec; import com.ayros.historycleaner.R; import com.ayros.historycleaner.helpers.Logger; @SuppressWarnings("deprecation") public class MainActivity extends TabActivity { TabHost tabHost; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tabHost = getTabHost(); TabSpec cleanSpec = tabHost.newTabSpec("Clear"); cleanSpec.setIndicator("Clear"); Intent cleanIntent = new Intent(this, CleanActivity.class); cleanSpec.setContent(cleanIntent); tabHost.addTab(cleanSpec); TabSpec profileSpec = tabHost.newTabSpec("Profiles"); profileSpec.setIndicator("Profiles"); Intent profileIntent = new Intent(this, ProfileActivity.class); profileSpec.setContent(profileIntent); tabHost.addTab(profileSpec); tabHost.setOnTabChangedListener(new OnTabChangeListener() { @Override public void onTabChanged(String tabId) { try { MainActivity.this.invalidateOptionsMenu(); } catch (NoSuchMethodError e) { Logger.errorST("Could not call invalidOptionsMenu method"); e.printStackTrace(); } } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { String tabTag = getTabHost().getCurrentTabTag(); Activity activity = getLocalActivityManager().getActivity(tabTag); return activity.onCreateOptionsMenu(menu); } public boolean onOptionsItemSelected(MenuItem item) { String tabTag = getTabHost().getCurrentTabTag(); Activity activity = getLocalActivityManager().getActivity(tabTag); if (activity instanceof CleanActivity || activity instanceof ProfileActivity) { return activity.onOptionsItemSelected(item); } return false; } }
package org.hisp.dhis.android.core.dataset; import org.hisp.dhis.android.core.arch.call.D2Progress; import org.hisp.dhis.android.core.arch.handlers.internal.Handler; import org.hisp.dhis.android.core.arch.repositories.children.internal.ChildrenAppender; import org.hisp.dhis.android.core.arch.repositories.collection.ReadOnlyWithUploadCollectionRepository; import org.hisp.dhis.android.core.arch.repositories.collection.internal.ReadOnlyCollectionRepositoryImpl; import org.hisp.dhis.android.core.arch.repositories.filters.internal.BooleanFilterConnector; import org.hisp.dhis.android.core.arch.repositories.filters.internal.DateFilterConnector; import org.hisp.dhis.android.core.arch.repositories.filters.internal.EnumFilterConnector; import org.hisp.dhis.android.core.arch.repositories.filters.internal.FilterConnectorFactory; import org.hisp.dhis.android.core.arch.repositories.filters.internal.StringFilterConnector; import org.hisp.dhis.android.core.arch.repositories.scope.RepositoryScope; import org.hisp.dhis.android.core.common.State; import org.hisp.dhis.android.core.dataset.DataSetCompleteRegistrationTableInfo.Columns; import org.hisp.dhis.android.core.dataset.internal.DataSetCompleteRegistrationPostCall; import org.hisp.dhis.android.core.dataset.internal.DataSetCompleteRegistrationStore; import java.util.Map; import javax.inject.Inject; import dagger.Reusable; import io.reactivex.Observable; @Reusable public final class DataSetCompleteRegistrationCollectionRepository extends ReadOnlyCollectionRepositoryImpl<DataSetCompleteRegistration, DataSetCompleteRegistrationCollectionRepository> implements ReadOnlyWithUploadCollectionRepository<DataSetCompleteRegistration> { private final DataSetCompleteRegistrationPostCall postCall; private final DataSetCompleteRegistrationStore dataSetCompleteRegistrationStore; @Inject DataSetCompleteRegistrationCollectionRepository( final DataSetCompleteRegistrationStore store, final Map<String, ChildrenAppender<DataSetCompleteRegistration>> childrenAppenders, final RepositoryScope scope, final Handler<DataSetCompleteRegistration> handler, final DataSetCompleteRegistrationPostCall postCall) { super(store, childrenAppenders, scope, new FilterConnectorFactory<>(scope, s -> new DataSetCompleteRegistrationCollectionRepository(store, childrenAppenders, s, handler, postCall))); this.postCall = postCall; this.dataSetCompleteRegistrationStore = store; } public DataSetCompleteRegistrationObjectRepository value(final String period, final String organisationUnit, final String dataSet, final String attributeOptionCombo) { RepositoryScope updatedScope = byPeriod().eq(period) .byOrganisationUnitUid().eq(organisationUnit) .byDataSetUid().eq(dataSet) .byAttributeOptionComboUid().eq(attributeOptionCombo) .scope; return new DataSetCompleteRegistrationObjectRepository( dataSetCompleteRegistrationStore, childrenAppenders, updatedScope, period, organisationUnit, dataSet, attributeOptionCombo); } @Override public Observable<D2Progress> upload() { return Observable.fromCallable(() -> byState().in(State.TO_POST, State.TO_UPDATE).blockingGetWithoutChildren() ).flatMap(postCall::uploadDataSetCompleteRegistrations); } @Override public void blockingUpload() { upload().blockingSubscribe(); } public StringFilterConnector<DataSetCompleteRegistrationCollectionRepository> byPeriod() { return cf.string(Columns.PERIOD); } public StringFilterConnector<DataSetCompleteRegistrationCollectionRepository> byDataSetUid() { return cf.string(Columns.DATA_SET); } public StringFilterConnector<DataSetCompleteRegistrationCollectionRepository> byOrganisationUnitUid() { return cf.string(Columns.ORGANISATION_UNIT); } public StringFilterConnector<DataSetCompleteRegistrationCollectionRepository> byAttributeOptionComboUid() { return cf.string(Columns.ATTRIBUTE_OPTION_COMBO); } public DateFilterConnector<DataSetCompleteRegistrationCollectionRepository> byDate() { return cf.date(Columns.DATE); } public StringFilterConnector<DataSetCompleteRegistrationCollectionRepository> byStoredBy() { return cf.string(Columns.STORED_BY); } public BooleanFilterConnector<DataSetCompleteRegistrationCollectionRepository> byDeleted() { return cf.bool(Columns.DELETED); } public EnumFilterConnector<DataSetCompleteRegistrationCollectionRepository, State> byState() { return cf.enumC(Columns.STATE); } }
package npe; public class GuaranteedFieldDereference { Object x; public GuaranteedFieldDereference(Object x) { this.x = x; } int test0Report() { int result = 0; if (x == null) result = 42; result += x.hashCode(); return result; } int test1Report(boolean b) { int result = 0; if (x == null) result = 42; if (b) result++; result += x.hashCode(); return result; } int test2Report(boolean b, boolean b2) { int result = 0; if (x == null) result = 42; if (b) result++; if (b2) result += x.hashCode(); else result -= x.hashCode(); return result; } String test3Report() { String value = null; StringBuffer result = new StringBuffer(); String xAsString = null; if (x instanceof String) xAsString = (String) x; result.append(x.hashCode()); if (xAsString != null) value = xAsString.toLowerCase(); if (value == null) result.append(value); else result.append("foo"); result.append(" bar "); result.append(xAsString.trim()); return result.toString(); } void assertTrue(boolean b) { if (!b) throw new RuntimeException("Failed"); } int test4DoNotReport() { if (x == null) assertTrue(false); return x.hashCode(); } int test5DoNotReport() { assertTrue(x!=null); return x.hashCode(); } int test6aReport() { Object y = null; if (x == null) throw new NullPointerException(); return y.hashCode(); } int test6bReport() { Object y = null; if (x == null) throw new NullPointerException(); else return y.hashCode(); } int test7Report() { Object y = null; if (x == null) assertTrue(false); return y.hashCode(); } int test8Report( boolean b1, boolean b2) { int result = 0; Object y = null; if (b1) y = new Object(); // At this point y is null on a simple path // but guaranteed to be dereferenced if (b2) result = 1; else result = 2; // At this point y is null on a complex path // at this point, regardless of whether assertTrue is a thrower // or not, we are guaranteed to either dereference y or terminate // abnormally if (x == null) assertTrue(false); result += y.hashCode(); return result; } int test9Report( boolean b1, boolean b2) { int result = 0; Object y = null; if (b1) y = new Object(); // At this point y is null on a simple path // but guaranteed to be dereferenced if (b2) result = 1; else result = 2; // At this point y is null on a complex path // at this point, we will either dereference y or // terminate abnormally if (x == null) throw new IllegalArgumentException("x should not be null"); result += y.hashCode(); return result; } int test10IDontKnow(boolean b1, boolean b2, boolean b3) { int result = 0; Object y = null; if (b1) y = new Object(); // At this point y is null on a simple path // but guaranteed to be dereferenced if (b2) result = 1; else result = 2; // At this point y is null on a complex path assertTrue(b1); result += y.hashCode(); return result; } int test11Report( boolean b1, boolean b2) { if (x == null) System.out.println("x is null"); if (b1) System.out.println("b is true"); if (b2) throw new IllegalArgumentException("b2 must be false"); return x.hashCode(); } int test12DoNotReport() { if (x == null) System.out.println("x is null"); if (x == null) throw new NullPointerException(); else return x.hashCode(); } }
package org.datavec.api.transform.analysis.histogram; import org.datavec.api.writable.Writable; public class StringHistogramCounter implements HistogramCounter { private final int minLength; private final int maxLength; private final int nBins; private final double[] bins; private final long[] binCounts; public StringHistogramCounter(int minLength, int maxLength, int nBins) { this.minLength = minLength; this.maxLength = maxLength; this.nBins = nBins; bins = new double[nBins + 1]; //+1 because bins are defined by a range of values: bins[i] to bins[i+1] double step = ((double) (maxLength - minLength)) / nBins; for (int i = 0; i < bins.length; i++) { if (i == bins.length - 1) bins[i] = maxLength; else bins[i] = i * step; } binCounts = new long[nBins]; } @Override public HistogramCounter add(Writable w) { double d = w.toString().length(); //Not super efficient, but linear search on 20-50 items should be good enough int idx = -1; for (int i = 0; i < nBins; i++) { if (d >= bins[i] && d < bins[i + 1]) { idx = i; break; } } if (idx == -1) idx = nBins - 1; binCounts[idx]++; return this; } @Override public StringHistogramCounter merge(HistogramCounter other) { if (other == null) return this; if (!(other instanceof StringHistogramCounter)) throw new IllegalArgumentException("Cannot merge " + other); StringHistogramCounter o = (StringHistogramCounter) other; if (minLength != o.minLength || maxLength != o.maxLength) throw new IllegalStateException("Min/max values differ: (" + minLength + "," + maxLength + ") " + " vs. (" + o.minLength + "," + o.maxLength + ")"); if (nBins != o.nBins) throw new IllegalStateException("Different number of bins: " + nBins + " vs " + o.nBins); for (int i = 0; i < nBins; i++) { binCounts[i] += o.binCounts[i]; } return this; } @Override public double[] getBins() { return bins; } @Override public long[] getCounts() { return binCounts; } }
package io.debezium.connector.oracle; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.debezium.jdbc.JdbcConnection; import io.debezium.pipeline.ErrorHandler; import io.debezium.pipeline.EventDispatcher; import io.debezium.pipeline.source.spi.StreamingChangeEventSource; import io.debezium.relational.TableId; import io.debezium.util.Clock; import oracle.jdbc.OracleConnection; import oracle.sql.NUMBER; import oracle.streams.StreamsException; import oracle.streams.XStreamOut; import oracle.streams.XStreamUtility; /** * A {@link StreamingChangeEventSource} based on Oracle's XStream API. The XStream event handler loop is executed in a * separate executor. * * @author Gunnar Morling */ public class OracleStreamingChangeEventSource implements StreamingChangeEventSource { private static final Logger LOGGER = LoggerFactory.getLogger(OracleStreamingChangeEventSource.class); private final JdbcConnection jdbcConnection; private final EventDispatcher<TableId> dispatcher; private final ErrorHandler errorHandler; private final Clock clock; private final OracleDatabaseSchema schema; private final OracleOffsetContext offsetContext; private final String xStreamServerName; private volatile XStreamOut xsOut; public OracleStreamingChangeEventSource(OracleConnectorConfig connectorConfig, OracleOffsetContext offsetContext, JdbcConnection jdbcConnection, EventDispatcher<TableId> dispatcher, ErrorHandler errorHandler, Clock clock, OracleDatabaseSchema schema) { this.jdbcConnection = jdbcConnection; this.dispatcher = dispatcher; this.errorHandler = errorHandler; this.clock = clock; this.schema = schema; this.offsetContext = offsetContext; this.xStreamServerName = connectorConfig.getXoutServerName(); } @Override public void execute(ChangeEventSourceContext context) throws InterruptedException { try { // 1. connect xsOut = XStreamOut.attach((OracleConnection) jdbcConnection.connection(), xStreamServerName, convertScnToPosition(offsetContext.getScn()), 1, 1, XStreamOut.DEFAULT_MODE); LcrEventHandler handler = new LcrEventHandler(errorHandler, dispatcher, clock, schema, offsetContext); // 2. receive events while running while(context.isRunning()) { LOGGER.trace("Receiving LCR"); xsOut.receiveLCRCallback(handler, XStreamOut.DEFAULT_MODE); } } catch (Exception e) { throw new RuntimeException(e); } finally { // 3. disconnect if (this.xsOut != null) { try { XStreamOut xsOut = this.xsOut; this.xsOut = null; xsOut.detach(XStreamOut.DEFAULT_MODE); } catch (StreamsException e) { LOGGER.error("Couldn't detach from XStream outbound server " + xStreamServerName, e); } } } } @Override public void commitOffset(Map<String, ?> offset) { if (xsOut != null) { try { LOGGER.debug("Recording offsets to Oracle"); xsOut.setProcessedLowWatermark( convertScnToPosition((Long) offset.get(SourceInfo.SCN_KEY)), XStreamOut.DEFAULT_MODE ); LOGGER.trace("Offsets recorded to Oracle"); } catch (StreamsException e) { throw new RuntimeException("Couldn't set processed low watermark", e); } } } private byte[] convertScnToPosition(long scn) { try { return XStreamUtility.convertSCNToPosition(new NUMBER(scn), XStreamUtility.POS_VERSION_V2); } catch (StreamsException e) { throw new RuntimeException(e); } } }
package com.mobstac.beaconstacdemo; import android.Manifest; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Handler; import android.support.v4.app.ActivityCompat; import android.util.Log; import com.google.android.gms.nearby.Nearby; import com.google.android.gms.nearby.messages.Message; import com.google.android.gms.nearby.messages.MessageListener; import com.mobstac.beaconstac.Beaconstac; import com.mobstac.beaconstac.core.MSException; import com.mobstac.beaconstac.interfaces.MSErrorListener; import com.mobstac.beaconstac.interfaces.MSSyncListener; import com.mobstac.beaconstac.utils.Util; public class NearbyBeaconBroadcastReceiver extends BroadcastReceiver { Beaconstac beaconstac = null; @Override public void onReceive(final Context context, Intent intent) { if (Util.isAppIsInBackground(context.getApplicationContext())) { Nearby.getMessagesClient(context).handleIntent(intent, new MessageListener() { @Override public void onFound(Message message) { try { if (ActivityCompat.checkSelfPermission(context.getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(context.getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return; } beaconstac = Beaconstac.initialize(context.getApplicationContext(), "MY_DEVELOPER_TOKEN", new MSSyncListener() { @Override public void onSuccess() { beaconstac.startScanningBeacons(new MSErrorListener() { @Override public void onError(MSException msException) { } }); autoStopScan(context, 10000); } @Override public void onFailure(MSException msException) { } }); } catch (MSException e) { e.printStackTrace(); } } @Override public void onLost(Message message) { } }); } } private void autoStopScan(final Context context, int duration){ if (beaconstac != null) { Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { beaconstac.stopScanningBeacons(new MSErrorListener() { @Override public void onError(MSException msException) { } }); } }, duration); // Set the duration for which the scan needs to run for. } else { // Handle reinitialization if Beaconstac's instance is null. Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { try { if (ActivityCompat.checkSelfPermission(context.getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(context.getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return; } beaconstac = Beaconstac.initialize(context.getApplicationContext(), "MY_DEVELOPER_TOKEN", new MSSyncListener() { @Override public void onSuccess() { beaconstac.stopScanningBeacons(new MSErrorListener() { @Override public void onError(MSException msException) { } }); } @Override public void onFailure(MSException msException) { // Stop scan even if initialization failed beaconstac.stopScanningBeacons(new MSErrorListener() { @Override public void onError(MSException msException) { } }); } }); } catch (MSException e) { e.printStackTrace(); } } }, duration); // Set the duration for which the scan needs to run for. } } }
package com.platypii.baseline; import com.platypii.baseline.altimeter.MyAltimeter; import com.platypii.baseline.audible.CheckTextToSpeechTask; import com.platypii.baseline.audible.MyAudible; import com.platypii.baseline.bluetooth.BluetoothService; import com.platypii.baseline.cloud.BaselineCloud; import com.platypii.baseline.jarvis.AutoStop; import com.platypii.baseline.jarvis.FlightComputer; import com.platypii.baseline.location.LandingZone; import com.platypii.baseline.location.LocationService; import com.platypii.baseline.sensors.MySensorManager; import com.platypii.baseline.tracks.MigrateTracks; import com.platypii.baseline.tracks.TrackLogger; import com.platypii.baseline.util.Convert; import com.platypii.baseline.util.Numbers; import android.Manifest; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.os.Handler; import android.preference.PreferenceManager; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.util.Log; import com.google.android.gms.maps.model.LatLng; import com.google.firebase.crash.FirebaseCrash; /** * Start and stop essential services. * This class provides essential services intended to persist between activities. * This class will also keep services running if logging or audible is enabled. */ public class Services { private static final String TAG = "Services"; // Count the number of times an activity has started. // This allows us to only stop services once the app is really done. private static int startCount = 0; private static boolean initialized = false; // How long to wait after the last activity shutdown to terminate services private final static Handler handler = new Handler(); private static final int shutdownDelay = 10000; // Have we checked for TTS data? private static boolean ttsLoaded = false; // Services public static final TrackLogger logger = new TrackLogger(); public static final BluetoothService bluetooth = new BluetoothService(); public static final LocationService location = new LocationService(bluetooth); public static final MyAltimeter alti = location.alti; public static final MySensorManager sensors = new MySensorManager(); public static final FlightComputer flightComputer = new FlightComputer(); public static final MyAudible audible = new MyAudible(); private static final Notifications notifications = new Notifications(); public static final BaselineCloud cloud = new BaselineCloud(); /** * We want preferences to be available as early as possible. * Call this in onCreate */ static void create(@NonNull Activity activity) { if(!created) { Log.i(TAG, "Loading app preferences"); loadPreferences(activity); created = true; } } private static boolean created = false; static void start(@NonNull Activity activity) { startCount++; if(startCount == 1 && initialized) { // This happens when services are started again before the shutdown delay Log.i(TAG, "Services still alive"); handler.removeCallbacks(stopRunnable); } if(!initialized) { initialized = true; final long startTime = System.currentTimeMillis(); Log.i(TAG, "Starting services"); final Context appContext = activity.getApplicationContext(); // Start the various services Log.i(TAG, "Starting bluetooth service"); if(bluetooth.preferences.preferenceEnabled) { bluetooth.start(activity); } // Initialize track logger Log.i(TAG, "Starting logger service"); logger.start(appContext); Log.i(TAG, "Starting location service"); if (ActivityCompat.checkSelfPermission(appContext, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { // Enable location services try { location.start(appContext); } catch (SecurityException e) { Log.e(TAG, "Failed to start location service", e); } } else { final String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION}; ActivityCompat.requestPermissions(activity, permissions, BaseActivity.RC_LOCATION); } Log.i(TAG, "Starting sensors"); sensors.start(appContext); Log.i(TAG, "Starting altimeter"); alti.start(appContext); Log.i(TAG, "Starting flight services"); flightComputer.start(appContext); // TTS is prerequisite for audible if(ttsLoaded) { Log.i(TAG, "Text-to-speech data already loaded, starting audible"); FirebaseCrash.log("text-to-speech already loaded"); audible.start(appContext); } else { Log.i(TAG, "Checking for text-to-speech data"); new CheckTextToSpeechTask(activity).execute(); } Log.i(TAG, "Starting notification bar service"); notifications.start(appContext); Log.i(TAG, "Starting cloud services"); cloud.start(appContext); // Check if migration is necessary MigrateTracks.migrate(appContext); Log.i(TAG, "Services started in " + (System.currentTimeMillis() - startTime) + " ms"); } else if(startCount > 2) { // Activity lifecycles can overlap Log.w(TAG, "Services started more than twice"); } else { Log.v(TAG, "Services already started"); } } /** * BaseActivity calls this function once text-to-speech data is ready */ static void onTtsLoaded(@NonNull Activity context) { // TTS loaded, start the audible FirebaseCrash.log("onTtsLoaded from " + context.getLocalClassName()); if(!ttsLoaded) { Log.i(TAG, "Text-to-speech data loaded, starting audible"); ttsLoaded = true; if(initialized) { audible.start(context.getApplicationContext()); } } else { Log.w(TAG, "Text-to-speech already loaded"); FirebaseCrash.report(new IllegalStateException("Text-to-speech loaded twice")); } } static void stop() { startCount if(startCount == 0) { Log.i(TAG, String.format("All activities have stopped. Services will stop in %.3fs", shutdownDelay * 0.001)); handler.postDelayed(stopRunnable, shutdownDelay); } } /** * A thread that shuts down services after activity has stopped */ private static final Runnable stopRunnable = new Runnable() { @Override public void run() { stopIfIdle(); } }; /** * Stop services IF nothing is using them */ private static synchronized void stopIfIdle() { if(initialized && startCount == 0) { if(!logger.isLogging() && !audible.isEnabled()) { Log.i(TAG, "All activities have stopped. Stopping services."); // Stop services cloud.stop(); notifications.stop(); audible.stop(); flightComputer.stop(); alti.stop(); sensors.stop(); location.stop(); logger.stop(); bluetooth.stop(); initialized = false; } else { if(logger.isLogging()) { Log.w(TAG, "All activities have stopped, but still recording track. Leaving services running."); } if(audible.isEnabled()) { Log.w(TAG, "All activities have stopped, but audible still active. Leaving services running."); } // Try again periodically handler.postDelayed(stopRunnable, shutdownDelay); } } } private static void loadPreferences(Context context) { final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); // Metric Convert.metric = prefs.getBoolean("metric_enabled", false); // Auto-stop AutoStop.preferenceEnabled = prefs.getBoolean("auto_stop_enabled", true); // Bluetooth bluetooth.preferences.load(context); // Home location final double home_latitude = Numbers.parseDouble(prefs.getString("home_latitude", null)); final double home_longitude = Numbers.parseDouble(prefs.getString("home_longitude", null)); if(Numbers.isReal(home_latitude) && Numbers.isReal(home_longitude)) { // Set home location LandingZone.homeLoc = new LatLng(home_latitude, home_longitude); } } }
package hu.bme.mit.massif.examples.api.common; import hu.bme.mit.massif.communication.ICommandEvaluator; import hu.bme.mit.massif.communication.command.MatlabCommand; import hu.bme.mit.massif.communication.command.MatlabCommandFactory; import hu.bme.mit.massif.communication.commandevaluation.CommandEvaluatorImpl; import hu.bme.mit.massif.communication.matlabcontrol.MatlabControlEvaluator; import hu.bme.mit.massif.communication.matlabengine.MatlabEngineEvaluator; import hu.bme.mit.massif.examples.api.settings.GenericExampleSettings; import hu.bme.mit.massif.examples.api.settings.MatlabControlExampleSettings; import hu.bme.mit.massif.examples.api.settings.MatlabServerExampleSettings; import hu.bme.mit.massif.simulink.SimulinkModel; import hu.bme.mit.massif.simulink.api.Exporter; import hu.bme.mit.massif.simulink.api.Importer; import hu.bme.mit.massif.simulink.api.ModelObject; import hu.bme.mit.massif.simulink.api.exception.SimulinkApiException; import java.io.File; import java.io.IOException; import com.mathworks.engine.EngineException; import br.com.embraer.massif.commandevaluation.client.MatlabClient; import br.com.embraer.massif.commandevaluation.exception.MatlabRMIException; public class MassifExampleHelper { public static void exampleExport(ICommandEvaluator commandEvaluator) throws SimulinkApiException, IOException { MatlabCommandFactory commandFactory = new MatlabCommandFactory(commandEvaluator); // EMF model to read and export String modelPath = GenericExampleSettings.EMF_MODEL_PATH; String modelName = GenericExampleSettings.EMF_MODEL_NAME; Exporter exporter = new Exporter(); SimulinkModel loadedModel = exporter.loadSimulinkModel(modelPath + modelName); exporter.export(loadedModel, commandFactory); String fqn = loadedModel.getSimulinkRef().getFQN(); exporter.saveSimulinkModel(fqn,"slx"); } public static void exampleImport(ICommandEvaluator commandEvaluator) throws SimulinkApiException, IOException { MatlabCommandFactory factory = new MatlabCommandFactory(commandEvaluator); String modelPath = GenericExampleSettings.SIMULINK_MODEL_PATH; String modelName = GenericExampleSettings.SIMULINK_MODEL_NAME; System.out.println("Importing model: " + modelPath + modelName); MatlabCommand addModelPath = factory.addPath(); addModelPath.addParam(modelPath); addModelPath.execute(); // Model name to save the imported Simulink library String importedModelName = GenericExampleSettings.OUTPUT_DIRECTORY + File.separator + modelName; ModelObject model = new ModelObject(modelName, commandEvaluator); model.setLoadPath(modelPath); // Import each model using the FAM Leaf filter model.registerApplicableFilters("famfilter"); Importer importer = new Importer(model); importer.traverseAndCreateEMFModel(GenericExampleSettings.IMPORT_MODE); importer.saveEMFModel(importedModelName); MatlabCommand closeSystem = factory.closeSystem(); closeSystem.addParam(modelName); closeSystem.execute(); } public static ICommandEvaluator createCommandEvaluator(MatlabConnector connector) throws MatlabRMIException, SimulinkApiException, EngineException, InterruptedException { switch (connector) { case COMMAND_EVALUATION_SERVER: String hostAddress = MatlabServerExampleSettings.HOST_ADDRESS; int hostPort = MatlabServerExampleSettings.HOST_PORT; String serviceName = MatlabServerExampleSettings.SERVICE_NAME; MatlabClient matlabClient = new MatlabClient(hostAddress, hostPort, serviceName); return new CommandEvaluatorImpl(matlabClient); case MATLAB_CONTROL: return new MatlabControlEvaluator(MatlabControlExampleSettings.MATLAB_PATH, GenericExampleSettings.PRINT_ISSUED_COMMANDS); case MATLAB_ENGINE: return new MatlabEngineEvaluator(GenericExampleSettings.PRINT_ISSUED_COMMANDS); default: throw new SimulinkApiException("Not supported connector was set: " + connector); } } }
package info.nightscout.utils; import android.text.format.DateUtils; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.TimeZone; import java.util.regex.Matcher; import java.util.regex.Pattern; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; /** * The Class DateUtil. A simple wrapper around SimpleDateFormat to ease the handling of iso date string &lt;-&gt; date obj * with TZ */ public class DateUtil { /** * The date format in iso. */ public static String FORMAT_DATE_ISO = "yyyy-MM-dd'T'HH:mm:ss'Z'"; public static String FORMAT_DATE_ISO_MSEC = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; /** * Takes in an ISO date string of the following format: * yyyy-mm-ddThh:mm:ss.ms+HoMo * * @param isoDateString the iso date string * @return the date * @throws Exception the exception */ public static Date fromISODateString(String isoDateString) throws Exception { SimpleDateFormat f = new SimpleDateFormat(FORMAT_DATE_ISO); Date date; f.setTimeZone(TimeZone.getTimeZone("UTC")); try { date = f.parse(isoDateString); } catch (ParseException e) { f = new SimpleDateFormat(FORMAT_DATE_ISO_MSEC); f.setTimeZone(TimeZone.getTimeZone("UTC")); date = f.parse(isoDateString); } return date; } /** * Render date * * @param date the date obj * @param format - if not specified, will use FORMAT_DATE_ISO * @param tz - tz to set to, if not specified uses local timezone * @return the iso-formatted date string */ public static String toISOString(Date date, String format, TimeZone tz) { if (format == null) format = FORMAT_DATE_ISO; if (tz == null) tz = TimeZone.getDefault(); DateFormat f = new SimpleDateFormat(format); f.setTimeZone(tz); return f.format(date); } public static String toISOString(Date date) { return toISOString(date, FORMAT_DATE_ISO, TimeZone.getTimeZone("UTC")); } public static String toISOString(long date) { return toISOString(new Date(date), FORMAT_DATE_ISO, TimeZone.getTimeZone("UTC")); } public static Date toDate(Integer seconds) { Calendar calendar = new GregorianCalendar(); calendar.set(Calendar.HOUR_OF_DAY, seconds / 60 / 60); String a = calendar.getTime().toString(); calendar.set(Calendar.MINUTE, (seconds / 60) % 60); String b = calendar.getTime().toString(); calendar.set(Calendar.SECOND, 0); String c = calendar.getTime().toString(); return calendar.getTime(); } public static int toSeconds(String hh_colon_mm) { Pattern p = Pattern.compile("(\\d+):(\\d+)"); Matcher m = p.matcher(hh_colon_mm); int retval = 0; if (m.find()) { retval = SafeParse.stringToInt(m.group(1)) * 60 * 60 + SafeParse.stringToInt(m.group(2)) * 60; } return retval; } public static String dateString(Date date) { //return DateUtils.formatDateTime(MainApp.instance(), date.getTime(), DateUtils.FORMAT_SHOW_DATE); this provide month name not number DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT); return df.format(date); } public static String dateString(long mills) { //return DateUtils.formatDateTime(MainApp.instance(), mills, DateUtils.FORMAT_SHOW_DATE); this provide month name not number DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT); return df.format(mills); } public static String timeString(Date date) { return DateUtils.formatDateTime(MainApp.instance(), date.getTime(), DateUtils.FORMAT_SHOW_TIME); } public static String timeString(long mills) { return DateUtils.formatDateTime(MainApp.instance(), mills, DateUtils.FORMAT_SHOW_TIME); } public static String dateAndTimeString(Date date) { return dateString(date) + " " + timeString(date); } public static String dateAndTimeString(long mills) { return dateString(mills) + " " + timeString(mills); } public static String minAgo(long time) { int mins = (int) ((System.currentTimeMillis() - time) / 1000 / 60); return String.format(MainApp.sResources.getString(R.string.minago), mins); } }
package org.openalpr.app; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.EditText; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.TimeoutError; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import com.google.android.gms.appindexing.Action; import com.google.android.gms.appindexing.AppIndex; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.gcm.GoogleCloudMessaging; import com.google.android.gms.iid.InstanceID; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; public class LoginActivity extends AppCompatActivity { private static final String TAG = "LoginActivity"; private Context context; protected GoogleCloudMessaging gcm = null; protected InstanceID iid = null; private GoogleApiClient client; // method uses AsyncTask to get a GCM registration token @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); context = getApplicationContext(); // GCM InstanceID is refreshed and saved globally in app iid = InstanceID.getInstance(context); gcm = GoogleCloudMessaging.getInstance(context); Constants.INST_ID = iid.getId(); // GCM API token is refreshed and saved globally new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... params) { Log.d(TAG, "doInBackground: GCM API"); String msg = ""; // attempts to get a Registration token for GCM try { msg = InstanceID.getInstance(context).getToken(Constants.PROJECT_ID, "GCM"); } catch (IOException e) { e.printStackTrace(); Log.v(TAG, "IOException: " + e); } // returns the token in string form, null if no token was received return msg; } @Override protected void onPostExecute(String msg) { Log.v(TAG, "onPostExecute: GCM API"); // save token in global variables Constants.REG_TOKEN = msg; } }.execute(null, null, null); // TODO check if this is needed for Instance ID or for GCM upstream // ATTENTION: This was auto-generated to implement the App Indexing API. client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build(); } /** * FORMAT: "variable_name - function" * * u - EditText variable for text input in username field * p - EditText variable for text input in password field * username - String variable for text in username field * password - String variable for text in password field * * @param view current view of app */ public void Login(View view) { Log.d(TAG, "Login Button Pressed"); // get user input from view EditText u = (EditText) findViewById(R.id.username); EditText p = (EditText) findViewById(R.id.password); String username = u.getText().toString(); String password = p.getText().toString(); Log.d(TAG, "Username: " + username); Log.d(TAG, "Password: " + password); // username and password sent to server attemptLogin(username, password); } /** * Username and password sent out to the server, * @param username attempted username sign in * @param password attempted password sign in */ private void attemptLogin(String username, String password) { Log.d(TAG, "attemptLogin"); // requests queue to be sent to server RequestQueue queue = Volley.newRequestQueue(this); // JSONObject to be sent to server JSONObject json = formatJSONLogin(username, password); // check to make sure json variable is not empty if( !(json.toString().equals("{}")) ) { // new request to be sent out to server Log.d(TAG, "create and send JSON POST request"); JsonObjectRequest jsonRequest = new JsonObjectRequest (Request.Method.POST, Constants.aws_address, json, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Log.d(TAG, "onResponse: " + response.toString()); // break down JSON response from server, send user to new // activity if successful registration, or inform of fail interpretResponse(response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.d(TAG, "Error: " + error.getMessage()); // check for server timeout error if( error.networkResponse == null ) { if( error.getClass().equals(TimeoutError.class) ) { Log.d(TAG, "Error: server timeout"); // display pop up to user informing of server timeout String message = "There may be a problem with the " + "server. Please try logging in again. Press " + "Re-Try to reattempt to log in."; String confirm = "Re-Try."; userPopUp(message, confirm); } } else { Log.d(TAG, "Error: server problem"); // display pop up to user informing of server issue // usual error is no internet access String message = "There may be a problem with your " + "internet access. Please check your connection " + "to the internet and press Re-Try to " + "reattempt to log in."; String confirm = "Re-Try."; userPopUp(message, confirm); } } }); // new request added to queue queue.add(jsonRequest); } else { Log.d(TAG, "json variable empty error"); // display pop up informing user of data problem String message = "There may be a problem with processing you data. " + "Please press Re-Try to reattempt to log in."; String confirm = "Re-Try."; userPopUp(message, confirm); } } /** * Takes JSON response from server and decides whether user is * authentic or not * @param response JSON response from server */ private void interpretResponse(JSONObject response) { Log.d(TAG, "interpretResponse() form server"); // attempt to breakdown JSON response try{ // get login status from JSON object String login = response.get("login").toString(); // TODO TEST make sure server is returning expected JSON "login" if( login.equals("success") ) { Log.d(TAG, "interpretResponse: success"); // set global username Variables.username = response.get("username").toString(); // TODO TEST make sure server is returning expected JSON "username" // display pop up to user informing of successful log in String message = "Log in successful. Press Continue to access account. "; String confirm = "Continue."; userPopUp(message, confirm); // send user to home activity Intent intent = new Intent(this, ConfirmPlateActivity.class); startActivity(intent); } else { // assume "login : failed" Log.d(TAG, "interpretResponse: failed"); // display pop up to user wrong log in info String message = "There was a problem with your username or password. " + "Press Re-Try to reattempt log in."; String confirm = "Re-Try."; userPopUp(message, confirm); } } catch (JSONException je) { Log.d(TAG, "JSON get error: " + je); je.printStackTrace(); // display pop up to user informing of error String message = "There was an error processing the server response. " + "Sorry for the inconvenience. Press Re-Try to attempt to log in again."; String confirm = "Re-Try."; userPopUp(message, confirm); } } /** * JSON object prepared to be sent to server for login * @param username username to be put into JSON * @param password password to be put into JSON * @return a JSON object to be sent to server */ private JSONObject formatJSONLogin(String username, String password) { Log.d(TAG, "formatJSONLogin()"); JSONObject json = new JSONObject(); // attempt to put user login info, and gcm token into JSON try { json.put("messageType","login"); json.put("username", username); json.put("password", password); json.put("gcm_user_id", Variables.gcm_user_id); // TODO TEST that this is how server is expecting JSON } catch (JSONException je) { je.printStackTrace(); Log.d(TAG, "JSONException: " + je); // json is returned as an empty object if error occurs json = new JSONObject(); } Log.d(TAG, "formatJSONLogin result: " + json.toString() ); return json; } /** * Register button is pressed, sends user to register activity * @param view current view */ public void redirectToRegister(View view) { Log.d(TAG, "Register Button Pressed"); Intent intent = new Intent(context, RegisterActivity.class); startActivity(intent); } /** * TODO ask Anthony what this does * @param requestCode TODO ask Anthony * @param resultCode TODO ask Anthony * @param intent TODO ask Anthony */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); Intent scanIntent = new Intent(this, ScanPlate.class); String platePath = intent.getStringExtra("picture"); scanIntent.putExtra("platepicture", platePath); Log.d(TAG, "Starting ScanPlate.class"); Log.d(TAG, "Image file path: " + platePath); startActivity(scanIntent); } /** * Create pop up for user to inform about server response or data processing * @param message message displayed to user * @param confirm acceptance button text */ private void userPopUp(String message, String confirm) { Log.d(TAG, "errorPopUp"); AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setMessage(message).setCancelable(false).setPositiveButton(confirm, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Log.d(TAG, "errorPopUp : onClick"); // do nothing } }); // display message builder.create().show(); } @Override public void onStart() { super.onStart(); // TODO see if this is needed for GCM Instance ID or upstream messaging // ATTENTION: This was auto-generated to implement the App Indexing API. client.connect(); Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Login Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://org.openalpr.app/http/host/path") ); AppIndex.AppIndexApi.start(client, viewAction); } @Override public void onStop() { super.onStop(); // TODO see if this is needed for GCM Instance ID or upstream messaging // ATTENTION: This was auto-generated to implement the App Indexing API. Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Login Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://org.openalpr.app/http/host/path") ); AppIndex.AppIndexApi.end(client, viewAction); client.disconnect(); } }
package rs.laxsrbija.piro; import android.app.Activity; import android.content.Context; import android.net.Uri; import android.net.wifi.SupplicantState; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Build; public class PiroContract { public static final String APP_NAME = "PIRO"; public static final String SERVER_SCHEME = "http"; public static final boolean SEPARATE_LOCAL_AND_EXTERNAL_IP = true; public static final String SSID = "<WIFI SSID>"; public static final String SERVER_ADDRESS_INTERNAL = "<INTERNAL ADDRESS>"; public static final String SERVER_ADDRESS_EXTERNAL = "<EXTERNAL ADDRESS>"; public static final String PIRO_DIR = "piro"; public static final String QUERY_DIR = "rpi"; public static final String QUERY_TARGET ="piro-query.php"; public static final String FUNCTION = "f"; public static final String ARGUMENT = "arg"; public static final String GET_JSON_FUNCTION = "getJSON"; public static final String RELAY_TOGGLE_FUNCTION = "toggleRelay"; public static final String PC_TOGGLE_FUNCTION = "togglePC"; public static final String ARG_LED_RIGHT = "1"; public static final String ARG_LED_CENTER = "0"; public static final String ARG_LED_LEFT = "2"; public static final String HEATING_TOGGLE_FUNCTION = "toggleThermal"; public static final String HEATING_INCREMENT = "increment"; public static final String HEATING_DECREMENT = "decrement"; public static final String HEATING_MODE = "setMode"; public static final String ARG_MODE_AUTO = "0"; public static final String ARG_MODE_DAY = "2"; public static final String ARG_MODE_NIGHT = "3"; public static final String ARG_MODE_FROST = "4"; public static class JSON { public static final String RELAY_LED_CENTER = "ledCentar"; public static final String RELAY_LED_RIGHT = "ledDesno"; public static final String RELAY_LED_LEFT = "ledLevo"; public static final String RELAY_PC = "racunar"; public static final String HEATER_STATUS = "statusPeci"; public static final String HEATER_TEMP = "temperaturaPeci"; public static final String HEATER_MODE = "rezimPeci"; public static final String WEATHER_CITY = "grad"; public static final String WEATHER_CURRENT_TEMP = "trenutnaTemperatura"; public static final String WEATHER_CURRENT_CONDITIONS = "trenutnaStanje"; public static final String WEATHER_CURRENT_ICON = "trenutnaIkona"; public static final String WEATHER_CURRENT_PRECIPITATION = "padavine"; public static final String WEATHER_CURRENT_VISIBILITY = "vidljivost"; public static final String WEATHER_CURRENT_FEELS_LIKE = "subjektivniOsecaj"; public static final String WEATHER_CURRENT_UV = "uvIndeks"; public static final String WEATHER_DAY = "dan"; public static final String WEATHER_DAILY_CONDITIONS = "dnevnaStanje"; public static final String WEATHER_DAILY_HIGH = "dnevnaMax"; public static final String WEATHER_DAILY_LOW = "dnevnaMin"; public static final String WEATHER_DAILY_ICON = "dnevnaIkona"; public static final String SYSTEM_UPTIME = "systemUptime"; public static final String SYSTEM_LOAD = "systemLoad"; public static final String SYSTEM_TEMP = "systemTemperature"; } public static Uri.Builder buildPreliminaryURI(Activity activity) { Uri.Builder builder = new Uri.Builder(); builder.scheme(SERVER_SCHEME) .authority(getServerAddress(activity)) .appendPath(PIRO_DIR) .appendPath(QUERY_DIR) .appendPath(QUERY_TARGET); return builder; } public static String getServerAddress(Activity activity) { if (!SEPARATE_LOCAL_AND_EXTERNAL_IP) { return SERVER_ADDRESS_EXTERNAL; } if (Build.FINGERPRINT.contains("generic")) { return SERVER_ADDRESS_INTERNAL; } WifiManager wifiManager = (WifiManager) activity.getSystemService(Context.WIFI_SERVICE); WifiInfo wifiInfo; wifiInfo = wifiManager.getConnectionInfo(); if (wifiInfo.getSupplicantState() == SupplicantState.COMPLETED) { String ssid = wifiInfo.getSSID(); // Log.v("PIRO", "Wifi SSID: " + ssid); if (ssid != null && ssid.contains(SSID)) { return SERVER_ADDRESS_INTERNAL; } } // Log.v("PIRO", "Wifi not connected"); return SERVER_ADDRESS_EXTERNAL; } }
package com.oracle.truffle.sl; import java.io.*; import java.math.*; import java.util.Arrays; import java.util.Scanner; import com.oracle.truffle.api.*; import com.oracle.truffle.api.dsl.*; import com.oracle.truffle.api.instrument.*; import com.oracle.truffle.api.nodes.*; import com.oracle.truffle.api.source.*; import com.oracle.truffle.api.tools.*; import com.oracle.truffle.sl.builtins.*; import com.oracle.truffle.sl.factory.*; import com.oracle.truffle.sl.nodes.*; import com.oracle.truffle.sl.nodes.call.*; import com.oracle.truffle.sl.nodes.controlflow.*; import com.oracle.truffle.sl.nodes.expression.*; import com.oracle.truffle.sl.nodes.instrument.*; import com.oracle.truffle.sl.nodes.local.*; import com.oracle.truffle.sl.parser.*; import com.oracle.truffle.sl.runtime.*; public class SLMain { /* Demonstrate per-type tabulation of node execution counts */ private static boolean nodeExecCounts = false; /* Demonstrate per-line tabulation of STATEMENT node execution counts */ private static boolean statementCounts = false; /* Demonstrate per-line tabulation of STATEMENT coverage */ private static boolean coverage = false; /** * The main entry point. Use the mx command "mx sl" to run it with the correct class path setup. */ public static void main(String[] args) throws IOException { SLContext context = SLContextFactory.create(new BufferedReader(new InputStreamReader(System.in)), System.out); Source source; if (args.length == 0) { source = Source.fromReader(new InputStreamReader(System.in), "stdin"); } else { source = Source.fromFileName(args[0]); } int repeats = 1; if (args.length >= 2) { repeats = Integer.parseInt(args[1]); } run(context, source, System.out, repeats); } /** * Parse and run the specified SL source. Factored out in a separate method so that it can also * be used by the unit test harness. */ public static long run(SLContext context, Source source, PrintStream logOutput, int repeats) { if (logOutput != null) { logOutput.println("== running on " + Truffle.getRuntime().getName()); // logOutput.println("Source = " + source.getCode()); } if (statementCounts || coverage) { Probe.registerASTProber(new SLStandardASTProber()); } NodeExecCounter nodeExecCounter = null; if (nodeExecCounts) { nodeExecCounter = new NodeExecCounter(); nodeExecCounter.install(); } NodeExecCounter statementExecCounter = null; if (statementCounts) { statementExecCounter = new NodeExecCounter(StandardSyntaxTag.STATEMENT); statementExecCounter.install(); } CoverageTracker coverageTracker = null; if (coverage) { coverageTracker = new CoverageTracker(); coverageTracker.install(); } /* Parse the SL source file. */ Parser.parseSL(context, source); /* Lookup our main entry point, which is per definition always named "main". */ SLFunction main = context.getFunctionRegistry().lookup("main"); if (main.getCallTarget() == null) { throw new SLException("No function main() defined in SL source file."); } /* Change to true if you want to see the AST on the console. */ boolean printASTToLog = false; /* Change to true if you want to see source attribution for the AST to the console */ boolean printSourceAttributionToLog = false; /* Change to dump the AST to IGV over the network. */ boolean dumpASTToIGV = false; printScript("before execution", context, logOutput, printASTToLog, printSourceAttributionToLog, dumpASTToIGV); long totalRuntime = 0; try { for (int i = 0; i < repeats; i++) { long start = System.nanoTime(); /* Call the main entry point, without any arguments. */ try { Object result = main.getCallTarget().call(); if (result != SLNull.SINGLETON) { SLFunction function = context.getFunctionRegistry().lookup("println"); if (function != null) { function.getCallTarget().call(result); } else { context.getOutput().println(result); } } } catch (UnsupportedSpecializationException ex) { context.getOutput().println(formatTypeError(ex)); } long end = System.nanoTime(); totalRuntime += end - start; if (logOutput != null && repeats > 1) { logOutput.println("== iteration " + (i + 1) + ": " + ((end - start) / 1000000) + " ms"); } } } finally { printScript("after execution", context, logOutput, printASTToLog, printSourceAttributionToLog, dumpASTToIGV); } if (nodeExecCounter != null) { nodeExecCounter.print(System.out); nodeExecCounter.dispose(); } if (statementExecCounter != null) { statementExecCounter.print(System.out); statementExecCounter.dispose(); } if (coverageTracker != null) { coverageTracker.print(System.out); coverageTracker.dispose(); } return totalRuntime; } /** * When dumpASTToIGV is true: dumps the AST of all functions to the IGV visualizer, via a socket * connection. IGV can be started with the mx command "mx igv". * <p> * When printASTToLog is true: prints the ASTs to the console. */ private static void printScript(String groupName, SLContext context, PrintStream logOutput, boolean printASTToLog, boolean printSourceAttributionToLog, boolean dumpASTToIGV) { if (dumpASTToIGV) { GraphPrintVisitor graphPrinter = new GraphPrintVisitor(); graphPrinter.beginGroup(groupName); for (SLFunction function : context.getFunctionRegistry().getFunctions()) { RootCallTarget callTarget = function.getCallTarget(); if (callTarget != null) { graphPrinter.beginGraph(function.toString()).visit(callTarget.getRootNode()); } } graphPrinter.printToNetwork(true); } if (printASTToLog && logOutput != null) { for (SLFunction function : context.getFunctionRegistry().getFunctions()) { RootCallTarget callTarget = function.getCallTarget(); if (callTarget != null) { logOutput.println("=== " + function); NodeUtil.printTree(logOutput, callTarget.getRootNode()); } } } if (printSourceAttributionToLog && logOutput != null) { for (SLFunction function : context.getFunctionRegistry().getFunctions()) { RootCallTarget callTarget = function.getCallTarget(); if (callTarget != null) { logOutput.println("=== " + function); NodeUtil.printSourceAttributionTree(logOutput, callTarget.getRootNode()); } } } } /** * Provides a user-readable message for run-time type errors. SL is strongly typed, i.e., there * are no automatic type conversions of values. Therefore, Truffle does the type checking for * us: if no matching node specialization for the actual values is found, then we have a type * error. Specialized nodes use the {@link UnsupportedSpecializationException} to report that no * specialization was found. We therefore just have to convert the information encapsulated in * this exception in a user-readable form. */ private static String formatTypeError(UnsupportedSpecializationException ex) { StringBuilder result = new StringBuilder(); result.append("Type error"); if (ex.getNode() != null && ex.getNode().getSourceSection() != null) { SourceSection ss = ex.getNode().getSourceSection(); if (ss != null && !(ss instanceof NullSourceSection)) { result.append(" at ").append(ss.getSource().getName()).append(" line ").append(ss.getStartLine()).append(" col ").append(ss.getStartColumn()); } } result.append(": operation"); if (ex.getNode() != null) { NodeInfo nodeInfo = SLContext.lookupNodeInfo(ex.getNode().getClass()); if (nodeInfo != null) { result.append(" \"").append(nodeInfo.shortName()).append("\""); } } result.append(" not defined for"); String sep = " "; for (int i = 0; i < ex.getSuppliedValues().length; i++) { Object value = ex.getSuppliedValues()[i]; Node node = ex.getSuppliedNodes()[i]; if (node != null) { result.append(sep); sep = ", "; if (value instanceof Long || value instanceof BigInteger) { result.append("Number ").append(value); } else if (value instanceof Boolean) { result.append("Boolean ").append(value); } else if (value instanceof String) { result.append("String \"").append(value).append("\""); } else if (value instanceof SLFunction) { result.append("Function ").append(value); } else if (value == SLNull.SINGLETON) { result.append("NULL"); } else if (value == null) { // value is not evaluated because of short circuit evaluation result.append("ANY"); } else { result.append(value); } } } return result.toString(); } }
package org.innovateuk.ifs.crm.transactional; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.spi.ILoggingEvent; import org.innovateuk.ifs.BaseServiceUnitTest; import org.innovateuk.ifs.LambdaMatcher; import org.innovateuk.ifs.address.domain.AddressType; import org.innovateuk.ifs.address.resource.OrganisationAddressType; import org.innovateuk.ifs.application.resource.ApplicationEvent; import org.innovateuk.ifs.application.resource.ApplicationResource; import org.innovateuk.ifs.application.resource.ApplicationState; import org.innovateuk.ifs.application.transactional.ApplicationSummarisationService; import org.innovateuk.ifs.commons.service.ServiceResult; import org.innovateuk.ifs.competition.publiccontent.resource.FundingType; import org.innovateuk.ifs.competition.resource.CompetitionResource; import org.innovateuk.ifs.competition.transactional.CompetitionService; import org.innovateuk.ifs.log.MemoryAppender; import org.innovateuk.ifs.organisation.resource.OrganisationAddressResource; import org.innovateuk.ifs.organisation.resource.OrganisationResource; import org.innovateuk.ifs.organisation.transactional.OrganisationAddressService; import org.innovateuk.ifs.organisation.transactional.OrganisationService; import org.innovateuk.ifs.sil.crm.resource.SilContact; import org.innovateuk.ifs.sil.crm.service.SilCrmEndpoint; import org.innovateuk.ifs.user.resource.UserResource; import org.innovateuk.ifs.user.transactional.BaseUserService; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.slf4j.LoggerFactory; import org.springframework.test.util.ReflectionTestUtils; import java.math.BigDecimal; import java.time.LocalDate; import java.time.ZonedDateTime; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.function.Predicate; import static java.util.Arrays.asList; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.innovateuk.ifs.address.builder.AddressResourceBuilder.newAddressResource; import static org.innovateuk.ifs.address.builder.AddressTypeBuilder.newAddressType; import static org.innovateuk.ifs.address.builder.AddressTypeResourceBuilder.newAddressTypeResource; import static org.innovateuk.ifs.commons.service.ServiceResult.serviceSuccess; import static org.innovateuk.ifs.organisation.builder.OrganisationAddressResourceBuilder.newOrganisationAddressResource; import static org.innovateuk.ifs.organisation.builder.OrganisationExecutiveOfficerResourceBuilder.newOrganisationExecutiveOfficerResource; import static org.innovateuk.ifs.organisation.builder.OrganisationResourceBuilder.newOrganisationResource; import static org.innovateuk.ifs.organisation.builder.OrganisationSicCodeResourceBuilder.newOrganisationSicCodeResource; import static org.innovateuk.ifs.user.builder.UserResourceBuilder.newUserResource; import static org.innovateuk.ifs.user.resource.Role.APPLICANT; import static org.innovateuk.ifs.user.resource.Role.MONITORING_OFFICER; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * Tests around the {@link CrmServiceImpl}. */ public class CrmServiceImplTest extends BaseServiceUnitTest<CrmServiceImpl> { @Mock private BaseUserService baseUserService; @Mock private CompetitionService competitionService; @Mock private ApplicationSummarisationService applicationSummarisationService; @Mock private OrganisationService organisationService; @Mock private OrganisationAddressService organisationAddressService; @Mock private SilCrmEndpoint silCrmEndpoint; private static MemoryAppender memoryAppender; private static final String LOGGER_NAME = "org.innovateuk.ifs.crm.transactional"; @Before public void setup() { Logger logger = (Logger) LoggerFactory.getLogger(LOGGER_NAME); memoryAppender = new MemoryAppender(); memoryAppender.setContext((LoggerContext) LoggerFactory.getILoggerFactory()); logger.setLevel(Level.DEBUG); logger.addAppender(memoryAppender); memoryAppender.start(); //tell tests to return the specified LOCAL_DATE when calling ZonedDateTime.now(clock) ZonedDateTime fixedClock = ZonedDateTime.parse("2021-10-12T09:38:12.850Z"); TimeMachine.useFixedClockAt(fixedClock); ReflectionTestUtils.setField(service, "eligibilityStatusChangeSource", "IFS"); ReflectionTestUtils.setField(service, "isLoanPartBEnabled", true); } @After public void cleanUp() { memoryAppender.reset(); memoryAppender.stop(); } @Override protected CrmServiceImpl supplyServiceUnderTest() { CrmServiceImpl service = new CrmServiceImpl(); ReflectionTestUtils.setField(service, "newOrganisationSearchEnabled", false); return service; } @Test public void syncExternalCrmContact() { long userId = 1L; UserResource user = newUserResource().withRoleGlobal(APPLICANT).build(); List<OrganisationResource> organisations = newOrganisationResource().withCompaniesHouseNumber("Something", "Else").build(2); when(baseUserService.getUserById(userId)).thenReturn(serviceSuccess(user)); when(organisationService.getAllByUserId(userId)).thenReturn(serviceSuccess(organisations)); when(silCrmEndpoint.updateContact(any(SilContact.class))).thenReturn(serviceSuccess()); ServiceResult<Void> result = service.syncCrmContact(userId); assertThat(result.isSuccess(), equalTo(true)); verify(silCrmEndpoint).updateContact(LambdaMatcher.createLambdaMatcher(matchExternalSilContact(user, organisations.get(0)))); verify(silCrmEndpoint).updateContact(LambdaMatcher.createLambdaMatcher(matchExternalSilContact(user, organisations.get(1)))); } @Test public void syncExternalCrmContactWithOrganisationUpdates() { long userId = 1L; UserResource user = newUserResource() .withRoleGlobal(APPLICANT) .build(); OrganisationResource organisation = newOrganisationResource() .withDateOfIncorporation(LocalDate.now()) .withSicCodes(newOrganisationSicCodeResource().withSicCode("code-1", "code-2").build(2)) .withExecutiveOfficers(newOrganisationExecutiveOfficerResource().withName("director-1", "director-2").build(2)) .build(); AddressType addressType = newAddressType() .withId(OrganisationAddressType.REGISTERED.getId()) .withName(OrganisationAddressType.REGISTERED.name()) .build(); OrganisationAddressResource organisationAddressResource = newOrganisationAddressResource() .withAddress(newAddressResource() .withAddressLine1("Line1") .withAddressLine2("Line2") .withAddressLine3("Line3") .withCounty("County") .withTown("Town") .withCountry("Country") .withPostcode("Postcode").build()) .withAddressType(newAddressTypeResource() .withId(OrganisationAddressType.REGISTERED.getId()) .withName(OrganisationAddressType.REGISTERED.name()).build()) .build(); when(baseUserService.getUserById(userId)).thenReturn(serviceSuccess(user)); when(organisationService.getAllByUserId(userId)).thenReturn(serviceSuccess(Collections.singletonList(organisation))); when(organisationAddressService.findByOrganisationIdAndAddressType(organisation.getId(), addressType)) .thenReturn(serviceSuccess(Collections.singletonList(organisationAddressResource))); when(silCrmEndpoint.updateContact(any(SilContact.class))).thenReturn(serviceSuccess()); ReflectionTestUtils.setField(service, "newOrganisationSearchEnabled", true); ServiceResult<Void> result = service.syncCrmContact(userId); assertThat(result.isSuccess(), equalTo(true)); verify(silCrmEndpoint).updateContact(LambdaMatcher.createLambdaMatcher(matchExternalSilContactWithOrganisationUpdates(user, organisation))); } @Test public void syncExternalCrmContactForProject() { long userId = 1L; long projectId = 2L; UserResource user = newUserResource().withRoleGlobal(APPLICANT).build(); OrganisationResource organisation = newOrganisationResource() .withCompaniesHouseNumber("Something", "Else") .build(); when(baseUserService.getUserById(userId)).thenReturn(serviceSuccess(user)); when(organisationService.getByUserAndProjectId(userId, projectId)).thenReturn(serviceSuccess(organisation)); when(silCrmEndpoint.updateContact(any(SilContact.class))).thenReturn(serviceSuccess()); ServiceResult<Void> result = service.syncCrmContact(userId, projectId); assertThat(result.isSuccess(), equalTo(true)); verify(silCrmEndpoint).updateContact(LambdaMatcher.createLambdaMatcher(matchExternalSilContact(user, organisation))); } @Test public void syncExternalCrmContactForProjectWithOrganisationUpdates() { long userId = 1L; long projectId = 2L; UserResource user = newUserResource() .withRoleGlobal(APPLICANT) .build(); OrganisationResource organisation = newOrganisationResource() .withDateOfIncorporation(LocalDate.now()) .withSicCodes(newOrganisationSicCodeResource().withSicCode("code-1", "code-2").build(2)) .withExecutiveOfficers(newOrganisationExecutiveOfficerResource().withName("director-1", "director-2").build(2)) .build(); AddressType addressType = newAddressType() .withId(OrganisationAddressType.REGISTERED.getId()) .withName(OrganisationAddressType.REGISTERED.name()) .build(); OrganisationAddressResource organisationAddressResource = newOrganisationAddressResource() .withAddress(newAddressResource() .withAddressLine1("Line1") .withAddressLine2("Line2") .withAddressLine3("Line3") .withCounty("County") .withTown("Town") .withCountry("Country") .withPostcode("Postcode").build()) .withAddressType(newAddressTypeResource() .withId(OrganisationAddressType.REGISTERED.getId()) .withName(OrganisationAddressType.REGISTERED.name()).build()) .build(); when(baseUserService.getUserById(userId)).thenReturn(serviceSuccess(user)); when(organisationService.getByUserAndProjectId(userId, projectId)).thenReturn(serviceSuccess(organisation)); when(organisationAddressService.findByOrganisationIdAndAddressType(organisation.getId(), addressType)) .thenReturn(serviceSuccess(Collections.singletonList(organisationAddressResource))); when(silCrmEndpoint.updateContact(any(SilContact.class))).thenReturn(serviceSuccess()); ReflectionTestUtils.setField(service, "newOrganisationSearchEnabled", true); ServiceResult<Void> result = service.syncCrmContact(userId, projectId); assertThat(result.isSuccess(), equalTo(true)); verify(silCrmEndpoint).updateContact(LambdaMatcher.createLambdaMatcher(matchExternalSilContactWithOrganisationUpdates(user, organisation))); } @Test public void syncExternalCrmContactWithExperienceTypeLOANShouldHaveAllAttributes() { String expectedLogMessage = "Updating CRM contact test@innovate.com and organisation OrganisationResource 6 \n" + "Payload is:SilContact(ifsUuid=17a0e34c-719a-4db4-b011-ccd4c375ad79, experienceType=Loan, ifsAppID=3, email=test@innovate.com, lastName=Doe, firstName=Jon, title=null, jobTitle=null, " + "address=null, organisation=SilOrganisation(name=OrganisationResource 6, registrationNumber=null, registeredAddress=SilAddress(buildingName=Line1, " + "street=Line2, Line3, locality=County, town=Town, postcode=Postcode, country=Country), srcSysOrgId=6), sourceSystem=IFS, srcSysContactId=1) "; long userId = 1L; long applicationId = 3L; long competitionId = 4L; CompetitionResource competitionResource = new CompetitionResource(); competitionResource.setFundingType(FundingType.LOAN); UserResource user = newUserResource() .withRoleGlobal(APPLICANT) .withId(1L) .withEmail("test@innovate.com") .withFirstName("Jon") .withLastName("Doe") .withUid("17a0e34c-719a-4db4-b011-ccd4c375ad79") .build(); List<OrganisationResource> organisation = Arrays.asList(newOrganisationResource() .withDateOfIncorporation(LocalDate.now()) .withSicCodes(newOrganisationSicCodeResource().withSicCode("code-1", "code-2").build(2)) .withExecutiveOfficers(newOrganisationExecutiveOfficerResource().withName("director-1", "director-2").build(2)) .build()); AddressType addressType = newAddressType() .withId(OrganisationAddressType.REGISTERED.getId()) .withName(OrganisationAddressType.REGISTERED.name()) .build(); OrganisationAddressResource organisationAddressResource = newOrganisationAddressResource() .withAddress(newAddressResource() .withAddressLine1("Line1") .withAddressLine2("Line2") .withAddressLine3("Line3") .withCounty("County") .withTown("Town") .withCountry("Country") .withPostcode("Postcode").build()) .withAddressType(newAddressTypeResource() .withId(OrganisationAddressType.REGISTERED.getId()) .withName(OrganisationAddressType.REGISTERED.name()).build()) .build(); when(baseUserService.getUserById(userId)).thenReturn(serviceSuccess(user)); when(organisationService.getAllByUserId(userId)).thenReturn(serviceSuccess(organisation)); when(organisationAddressService.findByOrganisationIdAndAddressType(organisation.get(0).getId(), addressType)) .thenReturn(serviceSuccess(Collections.singletonList(organisationAddressResource))); when(silCrmEndpoint.updateContact(any(SilContact.class))).thenReturn(serviceSuccess()); when(competitionService.getCompetitionById(competitionId)).thenReturn(serviceSuccess(competitionResource)); ReflectionTestUtils.setField(service, "newOrganisationSearchEnabled", true); ServiceResult<Void> result = service.syncCrmContact(userId, competitionId, applicationId); assertThat(result.isSuccess(), equalTo(true)); verify(silCrmEndpoint).updateContact(LambdaMatcher.createLambdaMatcher(matchExternalSilContactWithOrganisationUpdates(user, organisation.get(0)))); List<ILoggingEvent> eventList = memoryAppender.search("Payload", Level.INFO); assertEquals(expectedLogMessage, eventList.get(0).getMessage()); } @Test public void syncExternalCrmContactWithExperienceTypeNotLoanShouldHaveAttributesStripped() { String expectedLogMessage = "Updating CRM contact test@innovate.com and organisation OrganisationResource 6 \n" + "Payload is:SilContact(ifsUuid=17a0e34c-719a-4db4-b011-ccd4c375ad79, experienceType=null, ifsAppID=null, email=test@innovate.com, lastName=Doe, firstName=Jon, title=null, " + "jobTitle=null, address=null, organisation=SilOrganisation(name=OrganisationResource 6, registrationNumber=null, registeredAddress=SilAddress(buildingName=Line1, street=Line2, Line3, " + "locality=County, town=Town, postcode=Postcode, country=Country), srcSysOrgId=6), sourceSystem=IFS, srcSysContactId=1) "; long userId = 1L; long applicationId = 3L; long competitionId = 4L; CompetitionResource competitionResource = new CompetitionResource(); competitionResource.setFundingType(FundingType.GRANT); UserResource user = newUserResource() .withRoleGlobal(APPLICANT) .withId(1L) .withEmail("test@innovate.com") .withFirstName("Jon") .withLastName("Doe") .withUid("17a0e34c-719a-4db4-b011-ccd4c375ad79") .build(); List<OrganisationResource> organisation = Arrays.asList(newOrganisationResource() .withDateOfIncorporation(LocalDate.now()) .withSicCodes(newOrganisationSicCodeResource().withSicCode("code-1", "code-2").build(2)) .withExecutiveOfficers(newOrganisationExecutiveOfficerResource().withName("director-1", "director-2").build(2)) .build()); AddressType addressType = newAddressType() .withId(OrganisationAddressType.REGISTERED.getId()) .withName(OrganisationAddressType.REGISTERED.name()) .build(); OrganisationAddressResource organisationAddressResource = newOrganisationAddressResource() .withAddress(newAddressResource() .withAddressLine1("Line1") .withAddressLine2("Line2") .withAddressLine3("Line3") .withCounty("County") .withTown("Town") .withCountry("Country") .withPostcode("Postcode").build()) .withAddressType(newAddressTypeResource() .withId(OrganisationAddressType.REGISTERED.getId()) .withName(OrganisationAddressType.REGISTERED.name()).build()) .build(); when(baseUserService.getUserById(userId)).thenReturn(serviceSuccess(user)); when(organisationService.getAllByUserId(userId)).thenReturn(serviceSuccess(organisation)); when(organisationAddressService.findByOrganisationIdAndAddressType(organisation.get(0).getId(), addressType)) .thenReturn(serviceSuccess(Collections.singletonList(organisationAddressResource))); when(silCrmEndpoint.updateContact(any(SilContact.class))).thenReturn(serviceSuccess()); when(competitionService.getCompetitionById(competitionId)).thenReturn(serviceSuccess(competitionResource)); ReflectionTestUtils.setField(service, "newOrganisationSearchEnabled", true); ServiceResult<Void> result = service.syncCrmContact(userId, competitionId, applicationId); assertThat(result.isSuccess(), equalTo(true)); verify(silCrmEndpoint).updateContact(LambdaMatcher.createLambdaMatcher(matchExternalSilContactWithOrganisationUpdates(user, organisation.get(0)))); List<ILoggingEvent> eventList = memoryAppender.search("Payload", Level.INFO); assertEquals(expectedLogMessage, eventList.get(0).getMessage()); } @Test public void syncMonitoringOfficerOnlyCrmContact() { long userId = 1L; UserResource user = newUserResource().withRoleGlobal(MONITORING_OFFICER).build(); when(baseUserService.getUserById(userId)).thenReturn(serviceSuccess(user)); when(organisationService.getAllByUserId(userId)).thenReturn(serviceSuccess(Collections.emptyList())); when(silCrmEndpoint.updateContact(any(SilContact.class))).thenReturn(serviceSuccess()); ServiceResult<Void> result = service.syncCrmContact(userId); assertThat(result.isSuccess(), equalTo(true)); verify(silCrmEndpoint).updateContact(LambdaMatcher.createLambdaMatcher(matchMonitoringOfficerSilContact(user))); } @Test public void syncMonitoringOfficerAndExternalCrmContact() { long userId = 1L; UserResource user = newUserResource().withRolesGlobal(asList(APPLICANT, MONITORING_OFFICER)).build(); List<OrganisationResource> organisations = newOrganisationResource().withCompaniesHouseNumber("Something", "Else").build(2); when(baseUserService.getUserById(userId)).thenReturn(serviceSuccess(user)); when(organisationService.getAllByUserId(userId)).thenReturn(serviceSuccess(organisations)); when(silCrmEndpoint.updateContact(any(SilContact.class))).thenReturn(serviceSuccess()); ServiceResult<Void> result = service.syncCrmContact(userId); assertThat(result.isSuccess(), equalTo(true)); verify(silCrmEndpoint).updateContact(LambdaMatcher.createLambdaMatcher(matchExternalSilContact(user, organisations.get(0)))); verify(silCrmEndpoint).updateContact(LambdaMatcher.createLambdaMatcher(matchExternalSilContact(user, organisations.get(1)))); verify(silCrmEndpoint).updateContact(LambdaMatcher.createLambdaMatcher(matchMonitoringOfficerSilContact(user))); } private Predicate<SilContact> matchExternalSilContact(UserResource user, OrganisationResource organisation) { return silContact -> { assertThat(silContact.getSrcSysContactId(), equalTo(String.valueOf(user.getId()))); assertThat(silContact.getOrganisation().getRegistrationNumber(), equalTo(organisation.getCompaniesHouseNumber())); assertNull(silContact.getOrganisation().getRegisteredAddress()); return true; }; } private Predicate<SilContact> matchExternalSilContactWithOrganisationUpdates(UserResource user, OrganisationResource organisation) { return silContact -> { assertThat(silContact.getSrcSysContactId(), equalTo(String.valueOf(user.getId()))); assertThat(silContact.getOrganisation().getRegisteredAddress().getBuildingName(), equalTo("Line1")); assertThat(silContact.getOrganisation().getRegisteredAddress().getStreet(), equalTo("Line2, Line3")); assertThat(silContact.getOrganisation().getRegisteredAddress().getLocality(), equalTo("County")); assertThat(silContact.getOrganisation().getRegisteredAddress().getTown(), equalTo("Town")); assertThat(silContact.getOrganisation().getRegisteredAddress().getPostcode(), equalTo("Postcode")); assertThat(silContact.getOrganisation().getRegisteredAddress().getCountry(), equalTo("Country")); return true; }; } private Predicate<SilContact> matchMonitoringOfficerSilContact(UserResource user) { return silContact -> { assertThat(silContact.getSrcSysContactId(), equalTo(String.valueOf(user.getId()))); assertThat(silContact.getOrganisation().getRegistrationNumber(), equalTo("")); return true; }; } @Test public void syncCrmLoanApplicationSubmittedStateTest() { String expectedLogMessage = "Updating CRM application for appId:3 state:SUBMITTED, " + "payload:SilLoanApplication(applicationID=3, applicationSubmissionDate=2021-10-12T09:38:12.850Z, applicationName=Sample skips for plastic storage, " + "applicationLocation=RG1 5LF, projectDuration=11, projectTotalCost=10.0, projectOtherFunding=1.0, markedIneligible=null, eligibilityStatusChangeDate=null, eligibilityStatusChangeSource=null)"; long applicationId = 3L; long competitionId = 4L; ApplicationResource applicationResource = new ApplicationResource(); applicationResource.setId(applicationId); applicationResource.setApplicationState(ApplicationState.SUBMITTED); applicationResource.setSubmittedDate(ZonedDateTime.parse("2021-10-12T09:38:12.850Z")); applicationResource.setName("Sample skips for plastic storage"); applicationResource.setDurationInMonths(11l); applicationResource.setCompetition(competitionId); applicationResource.setEvent("submitted"); CompetitionResource competitionResource = new CompetitionResource(); competitionResource.setFundingType(FundingType.LOAN); when(competitionService.getCompetitionById(competitionId)).thenReturn(serviceSuccess(competitionResource)); when(applicationSummarisationService.getProjectTotalFunding(applicationResource.getId())).thenReturn(serviceSuccess(BigDecimal.TEN)); when(applicationSummarisationService.getProjectOtherFunding(applicationResource.getId())).thenReturn(serviceSuccess(BigDecimal.ONE)); when(applicationSummarisationService.getProjectLocation(applicationResource.getId())).thenReturn(serviceSuccess("RG1 5LF")); ServiceResult<Void> result = service.syncCrmApplicationState(applicationResource); List<ILoggingEvent> eventList = memoryAppender.search("payload:", Level.INFO); assertEquals(expectedLogMessage, eventList.get(0).getMessage()); } @Test public void syncCrmLoanApplicationIneligibleStateTest() { String expectedLogMessage = "Updating CRM application for appId:3 state:INELIGIBLE, " + "payload:SilLoanApplication(applicationID=3, applicationSubmissionDate=null, applicationName=null, applicationLocation=null, projectDuration=null, " + "projectTotalCost=null, projectOtherFunding=null, markedIneligible=true, eligibilityStatusChangeDate=2021-10-12T09:38:12.850Z, eligibilityStatusChangeSource=IFS)"; long applicationId = 3L; long competitionId = 4L; ApplicationResource applicationResource = new ApplicationResource(); applicationResource.setId(applicationId); applicationResource.setApplicationState(ApplicationState.INELIGIBLE); applicationResource.setSubmittedDate(ZonedDateTime.parse("2021-10-12T09:38:12.850Z")); applicationResource.setName("Sample skips for plastic storage"); applicationResource.setDurationInMonths(11l); applicationResource.setCompetition(competitionId); applicationResource.setEvent(ApplicationEvent.MARK_INELIGIBLE.getType()); CompetitionResource competitionResource = new CompetitionResource(); competitionResource.setFundingType(FundingType.LOAN); when(competitionService.getCompetitionById(competitionId)).thenReturn(serviceSuccess(competitionResource)); when(applicationSummarisationService.getProjectTotalFunding(applicationResource.getId())).thenReturn(serviceSuccess(BigDecimal.TEN)); when(applicationSummarisationService.getProjectOtherFunding(applicationResource.getId())).thenReturn(serviceSuccess(BigDecimal.ONE)); when(applicationSummarisationService.getProjectLocation(applicationResource.getId())).thenReturn(serviceSuccess("RG1 5LF")); ReflectionTestUtils.setField(service, "eligibilityStatusChangeSource", "IFS"); ServiceResult<Void> result = service.syncCrmApplicationState(applicationResource); List<ILoggingEvent> eventList = memoryAppender.search("payload:", Level.INFO); assertEquals(expectedLogMessage, eventList.get(0).getMessage()); } @Test public void syncCrmLoanApplicationIneligibleInformedStateTest() { String expectedLogMessage = "Updating CRM application for appId:3 state:INELIGIBLE_INFORMED, " + "payload:SilLoanApplication(applicationID=3, applicationSubmissionDate=null, applicationName=null, applicationLocation=null, " + "projectDuration=null, projectTotalCost=null, projectOtherFunding=null, markedIneligible=true, eligibilityStatusChangeDate=2021-10-12T09:38:12.850Z, eligibilityStatusChangeSource=IFS)"; long applicationId = 3L; long competitionId = 4L; ApplicationResource applicationResource = new ApplicationResource(); applicationResource.setId(applicationId); applicationResource.setApplicationState(ApplicationState.INELIGIBLE_INFORMED); applicationResource.setSubmittedDate(ZonedDateTime.parse("2021-10-12T09:38:12.850Z")); applicationResource.setName("Sample skips for plastic storage"); applicationResource.setDurationInMonths(11l); applicationResource.setCompetition(competitionId); applicationResource.setEvent(ApplicationEvent.INFORM_INELIGIBLE.getType()); CompetitionResource competitionResource = new CompetitionResource(); competitionResource.setFundingType(FundingType.LOAN); when(competitionService.getCompetitionById(competitionId)).thenReturn(serviceSuccess(competitionResource)); when(applicationSummarisationService.getProjectTotalFunding(applicationResource.getId())).thenReturn(serviceSuccess(BigDecimal.TEN)); when(applicationSummarisationService.getProjectOtherFunding(applicationResource.getId())).thenReturn(serviceSuccess(BigDecimal.ONE)); when(applicationSummarisationService.getProjectLocation(applicationResource.getId())).thenReturn(serviceSuccess("RG1 5LF")); ReflectionTestUtils.setField(service, "eligibilityStatusChangeSource", "IFS"); ServiceResult<Void> result = service.syncCrmApplicationState(applicationResource); List<ILoggingEvent> eventList = memoryAppender.search("payload:", Level.INFO); assertEquals(expectedLogMessage, eventList.get(0).getMessage()); } @Test public void syncCrmLoanApplicationReinstatedStateTest() { String expectedLogMessage = "Updating CRM application for appId:3 state:SUBMITTED, " + "payload:SilLoanApplication(applicationID=3, applicationSubmissionDate=null, applicationName=null, applicationLocation=null, projectDuration=null, projectTotalCost=null, projectOtherFunding=null, " + "markedIneligible=false, eligibilityStatusChangeDate=2021-10-12T09:38:12.850Z, eligibilityStatusChangeSource=IFS)"; long applicationId = 3L; long competitionId = 4L; ApplicationResource applicationResource = new ApplicationResource(); applicationResource.setId(applicationId); applicationResource.setApplicationState(ApplicationState.SUBMITTED); applicationResource.setSubmittedDate(ZonedDateTime.parse("2021-10-12T09:38:12.850Z")); applicationResource.setName("Sample skips for plastic storage"); applicationResource.setDurationInMonths(11l); applicationResource.setCompetition(competitionId); applicationResource.setEvent(ApplicationEvent.REINSTATE_INELIGIBLE.getType()); CompetitionResource competitionResource = new CompetitionResource(); competitionResource.setFundingType(FundingType.LOAN); when(competitionService.getCompetitionById(competitionId)).thenReturn(serviceSuccess(competitionResource)); when(applicationSummarisationService.getProjectTotalFunding(applicationResource.getId())).thenReturn(serviceSuccess(BigDecimal.TEN)); when(applicationSummarisationService.getProjectOtherFunding(applicationResource.getId())).thenReturn(serviceSuccess(BigDecimal.ONE)); when(applicationSummarisationService.getProjectLocation(applicationResource.getId())).thenReturn(serviceSuccess("RG1 5LF")); ServiceResult<Void> result = service.syncCrmApplicationState(applicationResource); List<ILoggingEvent> eventList = memoryAppender.search("payload:", Level.INFO); assertEquals(expectedLogMessage, eventList.get(0).getMessage()); } }
package org.innovateuk.ifs.testdata.data; import org.innovateuk.ifs.competition.publiccontent.resource.FundingType; import org.innovateuk.ifs.competition.resource.*; import org.innovateuk.ifs.testdata.builders.CompetitionLineBuilder; import org.innovateuk.ifs.testdata.builders.CompetitionLineBuilder.BuilderOrder; import org.innovateuk.ifs.testdata.builders.data.CompetitionLine; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; import static java.util.Arrays.asList; import static org.hibernate.validator.internal.util.CollectionHelper.asSet; import static org.innovateuk.ifs.category.domain.InnovationArea.DIGITAL_MANUFACTORING_ID; import static org.innovateuk.ifs.category.domain.InnovationArea.NONE; import static org.innovateuk.ifs.category.domain.ResearchCategory.*; import static org.innovateuk.ifs.competition.resource.CompetitionTypeEnum.*; import static org.innovateuk.ifs.organisation.resource.OrganisationTypeEnum.*; import static org.innovateuk.ifs.testdata.builders.CompetitionLineBuilder.aCompetitionLine; import static org.innovateuk.ifs.util.CollectionFunctions.combineLists; public class CompetitionWebTestData { private static Long LEAD_TECHNOLOGIST_ID = 24L; private static Long PETER_FREEMAN_ID = 25L; private static Long EXECUTIVE_ID = 20L; public static List<CompetitionLine> buildCompetitionLines() { return getCompetitionLineBuilders().stream().map(CompetitionLineBuilder::build).collect(Collectors.toList()); } private static List<CompetitionLineBuilder> getCompetitionLineBuilders() { return combineLists( getNonIfsLineBuilders(), getReadyToOpenCompetitionLineBuilders(), getOpenCompetitionLineBuilders(), getClosedCompetitionLineBuilders(), getInAssessmentCompetitionLineBuilders(), getAssessorFeedbackCompetitionLineBuilders(), getFundersPanelCompetitionLineBuilders(), getProjectSetupCompetitionLineBuilders() ).stream() .sorted(Comparator.comparing(l -> l.getBuilderOrder().ordinal())) .collect(Collectors.toList()); } private static List<CompetitionLineBuilder> getProjectSetupCompetitionLineBuilders() { return asList( grantCompetition() .withName("Connected digital additive manufacturing"), grantCompetition() .withName("New designs for a circular economy"), grantCompetition() .withName("Rolling stock future developments") .withLeadTechnologist(PETER_FREEMAN_ID) .withResearchRatio(100), grantCompetition() .withName("Biosciences round three: plastic recovery in the industrial sector") .withLeadTechnologist(PETER_FREEMAN_ID) .withResearchRatio(50), grantCompetition() .withName("Integrated delivery programme - solar vehicles") .withHasAssessmentPanel(true) .withHasInterviewStage(true), grantCompetition() .withName("Enhanced energy saving competition") .withLeadApplicantTypes(asSet(BUSINESS, RESEARCH, RTO, PUBLIC_SECTOR_OR_CHARITY)), grantCompetition() .withName("Growth table comp"), grantCompetition() .withName("No Growth table comp") .withIncludeProjectGrowth(false), grantCompetition() .withName("Project Setup Comp 1"), grantCompetition() .withName("Project Setup Comp 2"), grantCompetition() .withName("Project Setup Comp 3"), grantCompetition() .withName("Project Setup Comp 4"), grantCompetition() .withName("Project Setup Comp 5"), grantCompetition() .withName("Project Setup Comp 6"), grantCompetition() .withName("Project Setup Comp 7"), grantCompetition() .withName("Project Setup Comp 8"), grantCompetition() .withName("Project Setup Comp 9"), grantCompetition() .withName("Project Setup Comp 10"), grantCompetition() .withName("Project Setup Comp 11"), grantCompetition() .withName("Project Setup Comp 12"), grantCompetition() .withName("Project Setup Comp 13"), grantCompetition() .withName("Project Setup Comp 14"), grantCompetition() .withName("Project Setup Comp 15"), grantCompetition() .withName("Project Setup Comp 16"), grantCompetition() .withName("Project Setup Comp 17"), grantCompetition() .withName("Project Setup Comp 18"), grantCompetition() .withName("Project Setup Comp 19"), grantCompetition() .withName("Project Setup Comp 20"), loanCompetition() .withName("Project setup loan comp") .withLeadTechnologist(PETER_FREEMAN_ID), grantCompetition() .withName("583 Covid deminis round 1 project setup") .withIncludeProjectGrowth(false) .withIncludeYourOrganisation(false), grantCompetition() .withName("Post award service competition"), investorPartnershipCompetition() .withName("Investor partnership project setup"), grantCompetition() .withName("Connect competition"), grantCompetition() .withName("Auditor competition"), grantCompetition() .withName("Innovation continuity loan competition"), procurementCompetition() .withName("The Sustainable Innovation Fund: SBRI phase 1"), procurementCompetition() .withName("SBRI competition"), ktpCompetition() .withName("KTP Africa project setup"), grantCompetition() .withName("Live project competition") .withLeadApplicantTypes(asSet(BUSINESS, RESEARCH, RTO, PUBLIC_SECTOR_OR_CHARITY)), grantCompetition() .withName("subsidy control comp in project setup") .withFundingRules(FundingRules.SUBSIDY_CONTROL) ) .stream() .map(competitionLineBuilder -> competitionLineBuilder.withCompetitionStatus(CompetitionStatus.PROJECT_SETUP)) .collect(Collectors.toList()); } private static List<CompetitionLineBuilder> getInAssessmentCompetitionLineBuilders() { return asList( grantCompetition() .withName("Sustainable living models for the future"), grantCompetition() .withName("Assessment is awesome"), grantCompetition() .withName("Assessment is awesome 2"), grantCompetition() .withName("Assessments of load capabilities"), grantCompetition() .withName("Expression of Interest: Assistive technologies for caregivers") .withHasAssessmentPanel(true) .withHasInterviewStage(true) .withCompetitionType(EXPRESSION_OF_INTEREST), grantCompetition() .withName("Living models for the future"), grantCompetition() .withName("583 Covid deminis round 1") .withIncludeProjectGrowth(false) .withIncludeYourOrganisation(false), grantCompetition() .withName("Multiple choice assessed"), ktpCompetition() .withName("KTP assessment") .withAssessorFinanceView(AssessorFinanceView.ALL) .withIncludeProjectGrowth(false) .withIncludeYourOrganisation(false), ktpCompetition() .withName("KTP assessment Detailed Finances") .withAssessorFinanceView(AssessorFinanceView.DETAILED), ktpCompetition() .withName("KTP assessment Overview Finances"), ktpCompetition() .withName("KTP cofunding"), grantCompetition() .withName("Non KTP competition all finance overview") .withAssessorFinanceView(AssessorFinanceView.ALL), ktpCompetition() .withName("KTP cofunding single application"), grantCompetition() .withName("Subsidy control comp in assessment") .withFundingRules(FundingRules.SUBSIDY_CONTROL) ) .stream() .map(competitionLineBuilder -> competitionLineBuilder.withCompetitionStatus(CompetitionStatus.IN_ASSESSMENT)) .collect(Collectors.toList()); } private static List<CompetitionLineBuilder> getFundersPanelCompetitionLineBuilders() { return asList( grantCompetition() .withName("Internet of Things") .withResearchRatio(100) .withLeadTechnologist(PETER_FREEMAN_ID) .withBuilderOrder(BuilderOrder.FIRST), ktpCompetition() .withName("KTP in panel"), ktpCompetition() .withName("NON-FEC KTP project competition"), ktpCompetition() .withName("KTP notifications") .withBuilderOrder(BuilderOrder.LAST), grantCompetition() .withName("Living models for the future world") .withHasInterviewStage(true) ) .stream() .map(competitionLineBuilder -> competitionLineBuilder.withCompetitionStatus(CompetitionStatus.FUNDERS_PANEL)) .collect(Collectors.toList()); } private static List<CompetitionLineBuilder> getReadyToOpenCompetitionLineBuilders() { return asList( grantCompetition() .withName("Photonics for health") .withLeadTechnologist(PETER_FREEMAN_ID), ofGemCompetition() .withName("OfGem competition") ) .stream() .map(competitionLineBuilder -> competitionLineBuilder.withCompetitionStatus(CompetitionStatus.READY_TO_OPEN)) .collect(Collectors.toList()); } private static List<CompetitionLineBuilder> getAssessorFeedbackCompetitionLineBuilders() { return asList( grantCompetition() .withName("Integrated delivery programme - low carbon vehicles") .withHasInterviewStage(true) .withHasAssessmentPanel(true) ) .stream() .map(competitionLineBuilder -> competitionLineBuilder.withCompetitionStatus(CompetitionStatus.ASSESSOR_FEEDBACK)) .collect(Collectors.toList()); } private static List<CompetitionLineBuilder> getClosedCompetitionLineBuilders() { return asList( grantCompetition() .withName("Machine learning for transport infrastructure") .withInnovationAreas(asSet(29L)) .withInnovationSector("Infrastructure systems") .withAssessorCount(3), grantCompetition() .withName("Personalised Smart HUDs for space helmets") .withCompetitionType(AEROSPACE_TECHNOLOGY_INSTITUTE), grantCompetition() .withName("Smart monitoring in high-pressure engineering systems") .withCompetitionType(ADVANCED_PROPULSION_CENTRE) ) .stream() .map(competitionLineBuilder -> competitionLineBuilder.withCompetitionStatus(CompetitionStatus.CLOSED)) .collect(Collectors.toList()); } private static List<CompetitionLineBuilder> getOpenCompetitionLineBuilders() { return asList( grantCompetition() .withName("Home and industrial efficiency programme") .withResubmission(true) .withIncludeYourOrganisation(false) .withIncludeProjectGrowth(false) .withResearchRatio(100) .withAssessorCount(1) .withLeadApplicantTypes(asSet(BUSINESS, RTO)) .withResearchCategory(asSet(FEASIBILITY_STUDIES_ID, INDUSTRIAL_RESEARCH_ID, EXPERIMENTAL_DEVELOPMENT_ID)), grantCompetition() .withName("Predicting market trends programme") .withResearchCategory(asSet(FEASIBILITY_STUDIES_ID, INDUSTRIAL_RESEARCH_ID, EXPERIMENTAL_DEVELOPMENT_ID)) .withLeadApplicantTypes(asSet(RTO)) .withResearchRatio(50) .withResubmission(true) .withIncludeProjectGrowth(false) .withIncludeYourOrganisation(false) .withAssessorCount(3), grantCompetition() .withCompetitionType(SECTOR) .withName("Aerospace technology investment sector") .withResearchCategory(asSet(FEASIBILITY_STUDIES_ID, INDUSTRIAL_RESEARCH_ID, EXPERIMENTAL_DEVELOPMENT_ID)) .withResubmission(true) .withInnovationAreas(asSet(22L, 23L)), grantCompetition() .withCompetitionType(GENERIC) .withName("Generic innovation") .withLeadTechnologist(PETER_FREEMAN_ID), grantCompetition() .withName("Photonics for Research") .withLeadApplicantTypes(asSet(RESEARCH)) .withLeadTechnologist(PETER_FREEMAN_ID), grantCompetition() .withName("Photonics for Public") .withIncludeProjectGrowth(false) .withResearchCategory(asSet(FEASIBILITY_STUDIES_ID, INDUSTRIAL_RESEARCH_ID, EXPERIMENTAL_DEVELOPMENT_ID)) .withLeadTechnologist(PETER_FREEMAN_ID) .withLeadApplicantTypes(asSet(PUBLIC_SECTOR_OR_CHARITY)) .withResearchRatio(50), grantCompetition() .withName("Photonics for RTO and Business"), grantCompetition() .withName("Photonics for All") .withLeadTechnologist(PETER_FREEMAN_ID), grantCompetition() .withName("Expression of Interest: Quantum Computing algorithms for combating antibiotic resistance through simulation") .withCompetitionType(EXPRESSION_OF_INTEREST), grantCompetition() .withName("Low-cost propulsion mechanisms for subsonic travel") .withCompetitionType(ADVANCED_PROPULSION_CENTRE), grantCompetition() .withName("Reusability of waste material rocketry components") .withCompetitionType(AEROSPACE_TECHNOLOGY_INSTITUTE), investorPartnershipCompetition() .withName("Investor") .withCompetitionType(AEROSPACE_TECHNOLOGY_INSTITUTE), grantCompetition() .withName("Performance testing competition") .withLeadApplicantTypes(asSet(BUSINESS, RTO, RESEARCH, PUBLIC_SECTOR_OR_CHARITY)), procurementCompetition() .withName("Procurement Competition"), procurementCompetition() .withName("Procurement Competition"), loanCompetition() .withName("Loan Competition"), grantCompetition() .withName("H2020 Performance testing competition") .withCompetitionType(HORIZON_2020) .withInnovationAreas(null), grantCompetition() .withName("International Competition"), grantCompetition() .withName("596 Covid grants framework group") .withIncludeProjectGrowth(false) .withIncludeYourOrganisation(false) .withResubmission(true), grantCompetition() .withName("599 Covid de minimis round 2") .withResearchCategory(asSet(FEASIBILITY_STUDIES_ID, INDUSTRIAL_RESEARCH_ID, EXPERIMENTAL_DEVELOPMENT_ID)) .withResubmission(true) .withIncludeProjectGrowth(false) .withIncludeYourOrganisation(false), grantCompetition() .withName("Multiple choice open"), procurementCompetition() .withName("SBRI type one competition") .withCompetitionCompletionStage(CompetitionCompletionStage.COMPETITION_CLOSE), ktpCompetition() .withName("KTP new competition"), loanCompetition() .withName("Competition not submitted before the deadline") .withInnovationSector("Infrastructure systems") .withAssessorCount(5), loanCompetition() .withName("Competition for application submitted before competition closing time"), grantCompetition() .withName("Innovation continuity loan"), ktpCompetition() .withName("KTP Africa Comp") .withCompetitionType(AEROSPACE_TECHNOLOGY_INSTITUTE), ktpCompetition() .withName("No aid comp"), grantCompetition() .withName("Subsidy control competition") .withResubmission(true) .withFundingRules(FundingRules.SUBSIDY_CONTROL), grantCompetition() .withName("Always open competition") .withAlwaysOpen(true) .withResubmission(true), ktpCompetition() .withName("Always open ktp competition") .withAlwaysOpen(true) .withResubmission(true), ktpCompetition() .withName("FEC KTP competition"), grantCompetition() .withName("Improved organisation search performance competition"), ktpCompetition() .withName("KTP dashboard competition"), grantCompetition() .withName("Subsidy control t and c competition") .withFundingRules(FundingRules.SUBSIDY_CONTROL), grantCompetition() .withName("Subsidy control tactical competition") .withFundingRules(FundingRules.SUBSIDY_CONTROL), ktpCompetition() .withName("KTP new competition duplicate"), ktpCompetition() .withName("FEC KTP project competition"), ktpCompetition() .withName("FEC KTP competition duplicate") ) .stream() .map(competitionLineBuilder -> competitionLineBuilder.withCompetitionStatus(CompetitionStatus.OPEN)) .collect(Collectors.toList()); } private static List<CompetitionLineBuilder> getNonIfsLineBuilders() { return asList(nonIfsCompetition() .withName("Webtest Non IFS Comp 1"), nonIfsCompetition() .withName("Webtest Non IFS Comp 2"), nonIfsCompetition() .withName("Webtest Non IFS Comp 3"), nonIfsCompetition() .withName("Webtest Non IFS Comp 4"), nonIfsCompetition() .withName("Webtest Non IFS Comp 5"), nonIfsCompetition() .withName("Non IFS Comp 6"), nonIfsCompetition() .withName("Webtest Non IFS Comp 7"), nonIfsCompetition() .withName("Webtest Non IFS Comp 8"), nonIfsCompetition() .withName("Webtest Non IFS Comp 9"), nonIfsCompetition() .withName("Webtest Non IFS Comp 10"), nonIfsCompetition() .withName("Webtest Non IFS Comp 11"), nonIfsCompetition() .withName("Webtest Non IFS Comp 12"), nonIfsCompetition() .withName("Webtest Non IFS Comp 13"), nonIfsCompetition() .withName("Webtest Non IFS Comp 14"), nonIfsCompetition() .withName("Webtest Non IFS Comp 15"), nonIfsCompetition() .withName("Webtest Non IFS Comp 16"), nonIfsCompetition() .withName("Webtest Non IFS Comp 17"), nonIfsCompetition() .withName("Webtest Non IFS Comp 18"), nonIfsCompetition() .withName("Webtest Non IFS Comp 19"), nonIfsCompetition() .withName("Webtest Non IFS Comp 20"), nonIfsCompetition() .withName("Transforming big data") .withFundingType(FundingType.GRANT) .withInnovationAreas(asSet(5L)), nonIfsCompetition() .withName("Reducing carbon footprints") .withInnovationAreas(asSet(21L))); } private static CompetitionLineBuilder grantCompetition() { return anIfsCompetition() .withFundingType(FundingType.GRANT); } private static CompetitionLineBuilder procurementCompetition() { return anIfsCompetition() .withFundingType(FundingType.PROCUREMENT) .withInnovationSector("None") .withInnovationAreas(asSet(67L)) .withIncludeYourOrganisation(false) .withResearchRatio(100); } private static CompetitionLineBuilder ofGemCompetition() { return thirdPartyCompetition() .withCompetitionCompletionStage(CompetitionCompletionStage.RELEASE_FEEDBACK) .withTermsAndConditionsLabel("Strategic Innovation Fund Governance Document") .withTermsAndConditionsGuidance("<h2 class=\"govuk-heading-m\">A summary of the award terms and conditions</h2>" + "<p class=\"govuk-body\">The full terms and conditions are specific to this procurement competition. They will differ from any you have agreed to before. By submitting an application you are agreeing to the full terms and conditions pending the final contract if you are successful. It is your responsibility to make sure you read these terms.</p>" + "<p class=\"govuk-body\">They represent an agreement between the funding authority and your organisation and include details about your obligations and the administration of your project. They cover:</p>" + "<ul class=\"govuk-list govuk-list--bullet\">" + "<li>intellectual property rights</li>" + "<li>confidentiality</li>" + "<li>publicity</li>" + "<li>accounting and payments</li>" + "<li>monitoring and reporting</li>" + "<li>final report and evaluation</li>" + "<li>termination</li>" + "<li>warranties and insurance</li>" + "<li>resolution procedure</li>" + "</ul>" + "<p class=\"govuk-body\">This list is not exhaustive.</p>" + "<p class=\"govuk-body\">If you are successful in your application you must sign a final contract with the funding authority which may include additional details agreed between you and the funding authority.</p>" + "<p class=\"govuk-body\">If there is anything you do not understand, please <a href=\"/info/contact\">contact us</a>.</p>") .withProjectCostGuidanceUrl("https: .withTermsAndConditionsTemplate("third-party-terms-and-conditions"); } private static CompetitionLineBuilder thirdPartyCompetition() { return anIfsCompetition() .withFundingType(FundingType.PROCUREMENT) .withFundingRules(FundingRules.NOT_AID) .withInnovationSector("Infrastructure systems") .withInnovationAreas(asSet(NONE)) .withIncludeYourOrganisation(false) .withResearchRatio(100); } private static CompetitionLineBuilder investorPartnershipCompetition() { return anIfsCompetition() .withFundingType(FundingType.INVESTOR_PARTNERSHIPS) .withResearchRatio(100) .withResubmission(true); } private static CompetitionLineBuilder loanCompetition() { return anIfsCompetition() .withFundingType(FundingType.LOAN) .withResubmission(true); } private static CompetitionLineBuilder ktpCompetition() { return anIfsCompetition() .withFundingType(FundingType.KTP) .withResubmission(true); } private static CompetitionLineBuilder anIfsCompetition() { return aCompetitionLine() .withCompetitionType(PROGRAMME) .withInnovationAreas(asSet(DIGITAL_MANUFACTORING_ID)) .withInnovationSector("Materials and manufacturing") .withResearchCategory(asSet(FEASIBILITY_STUDIES_ID)) .withCollaborationLevel(CollaborationLevel.SINGLE_OR_COLLABORATIVE) .withLeadApplicantTypes(asSet(BUSINESS)) .withAssessorCount(5) .withResearchRatio(30) .withResubmission(false) .withMultiStream(false) .withHasAssessmentPanel(false) .withHasInterviewStage(false) .withLeadTechnologist(LEAD_TECHNOLOGIST_ID) .withCompExecutive(EXECUTIVE_ID) .withSetupComplete(true) .withPafCode("875") .withBudgetCode("DET1536/1537") .withActivityCode("16014") .withCode("2/1/1506") .withAssessorFinanceView(AssessorFinanceView.OVERVIEW) .withNonIfs(false) .withCompetitionCompletionStage(CompetitionCompletionStage.PROJECT_SETUP) .withIncludeJesForm(true) .withApplicationFinanceType(ApplicationFinanceType.STANDARD) .withIncludeProjectGrowth(true) .withIncludeYourOrganisation(true) .withFundingRules(FundingRules.STATE_AID) .withPublished(true) .withAlwaysOpen(false); } private static CompetitionLineBuilder nonIfsCompetition() { return aCompetitionLine() .withInnovationAreas(asSet(5L)) // Digital industries .withInnovationSector("Emerging and enabling") .withCompetitionStatus(CompetitionStatus.OPEN) .withAssessorFinanceView(AssessorFinanceView.OVERVIEW) .withFundingType(FundingType.GRANT) .withPublished(true) .withNonIfs(true) .withNonIfsUrl("https: .withCompetitionCompletionStage(CompetitionCompletionStage.PROJECT_SETUP) .withApplicationFinanceType(ApplicationFinanceType.STANDARD); } }
package <%=packageName%>.domain; import com.fasterxml.jackson.annotation.JsonIgnore;<% if (hibernateCache != 'no' && databaseType == 'sql') { %> import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy;<% } %> import org.hibernate.validator.constraints.Email; <% if (databaseType == 'nosql') { %>import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Field; <% } %><% if (databaseType == 'sql') { %> import javax.persistence.*;<% } %> import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.io.Serializable; import java.util.Set; /** * A user. */ <% if (databaseType == 'sql') { %>@Entity @Table(name = "T_USER")<% } %><% if (hibernateCache != 'no' && databaseType == 'sql') { %> @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)<% } %><% if (databaseType == 'nosql') { %> @Document(collection = "T_USER")<% } %> public class User extends AbstractAuditingEntity implements Serializable { @NotNull @Size(min = 0, max = 50) @Id<% if (databaseType == 'sql') { %> @Column(length = 50)<% } %> private String login; @JsonIgnore @Size(min = 0, max = 100)<% if (databaseType == 'sql') { %> @Column(length = 100)<% } %> private String password; @Size(min = 0, max = 50)<% if (databaseType == 'sql') { %> @Column(name = "first_name")<% } %><% if (databaseType == 'nosql') { %> @Field("first_name")<% } %> private String firstName; @Size(min = 0, max = 50)<% if (databaseType == 'sql') { %> @Column(name = "last_name")<% } %><% if (databaseType == 'nosql') { %> @Field("last_name")<% } %> private String lastName; @Email @Size(min = 0, max = 100) private String email; @NotNull private boolean activated = false; @Size(min = 2, max = 5)<% if (databaseType == 'sql') { %> @Column(name = "lang_key")<% } %><% if (databaseType == 'nosql') { %> @Field("lang_key")<% } %> private String langKey; @Size(min = 0, max = 20)<% if (databaseType == 'sql') { %> @Column(name = "activation_key")<% } %><% if (databaseType == 'nosql') { %> @Field("activation_key")<% } %> private String activationKey; @JsonIgnore<% if (databaseType == 'sql') { %> @ManyToMany @JoinTable( name = "T_USER_AUTHORITY", joinColumns = {@JoinColumn(name = "login", referencedColumnName = "login")}, inverseJoinColumns = {@JoinColumn(name = "name", referencedColumnName = "name")})<% } %><% if (hibernateCache != 'no' && databaseType == 'sql') { %> @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)<% } %> private Set<Authority> authorities; <% if (databaseType == 'sql') { %>@JsonIgnore @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "user")<% } %><% if (hibernateCache != 'no' && databaseType == 'sql') { %> @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)<% } %> private Set<PersistentToken> persistentTokens; public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public boolean getActivated() { return activated; } public void setActivated(boolean activated) { this.activated = activated; } public String getActivationKey() { return activationKey; } public void setActivationKey(String activationKey) { this.activationKey = activationKey; } public String getLangKey() { return langKey; } public void setLangKey(String langKey) { this.langKey = langKey; } public Set<Authority> getAuthorities() { return authorities; } public void setAuthorities(Set<Authority> authorities) { this.authorities = authorities; } <% if (databaseType == 'sql') { %> public Set<PersistentToken> getPersistentTokens() { return persistentTokens; } public void setPersistentTokens(Set<PersistentToken> persistentTokens) { this.persistentTokens = persistentTokens; }<% } %> @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } User user = (User) o; if (!login.equals(user.login)) { return false; } return true; } @Override public int hashCode() { return login.hashCode(); } @Override public String toString() { return "User{" + "login='" + login + '\'' + ", password='" + password + '\'' + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", email='" + email + '\'' + ", activated='" + activated + '\'' + ", langKey='" + langKey + '\'' + ", activationKey='" + activationKey + '\'' + "}"; } }
package org.ihtsdo.otf.mapping.jpa.handlers; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.log4j.Logger; import org.ihtsdo.otf.mapping.helpers.MapAdviceList; import org.ihtsdo.otf.mapping.helpers.ProjectSpecificAlgorithmHandler; import org.ihtsdo.otf.mapping.helpers.TreePositionList; import org.ihtsdo.otf.mapping.helpers.ValidationResult; import org.ihtsdo.otf.mapping.helpers.ValidationResultJpa; import org.ihtsdo.otf.mapping.helpers.WorkflowStatus; import org.ihtsdo.otf.mapping.jpa.MapRecordJpa; import org.ihtsdo.otf.mapping.jpa.services.ContentServiceJpa; import org.ihtsdo.otf.mapping.jpa.services.MappingServiceJpa; import org.ihtsdo.otf.mapping.model.MapAdvice; import org.ihtsdo.otf.mapping.model.MapEntry; import org.ihtsdo.otf.mapping.model.MapPrinciple; import org.ihtsdo.otf.mapping.model.MapProject; import org.ihtsdo.otf.mapping.model.MapRecord; import org.ihtsdo.otf.mapping.model.MapRelation; import org.ihtsdo.otf.mapping.model.MapUser; import org.ihtsdo.otf.mapping.rf2.Concept; import org.ihtsdo.otf.mapping.services.ContentService; import org.ihtsdo.otf.mapping.services.MappingService; import org.ihtsdo.otf.mapping.workflow.TrackingRecord; /** * Reference implementation of {@link ProjectSpecificAlgorithmHandler}. * * @author ${author} */ public class DefaultProjectSpecificAlgorithmHandler implements ProjectSpecificAlgorithmHandler { /** The map project. */ MapProject mapProject = null; /* * (non-Javadoc) * * @see * org.ihtsdo.otf.mapping.helpers.ProjectSpecificAlgorithmHandler#getMapProject * () */ @Override public MapProject getMapProject() { return this.mapProject; } /* * (non-Javadoc) * * @see * org.ihtsdo.otf.mapping.helpers.ProjectSpecificAlgorithmHandler#setMapProject * (org.ihtsdo.otf.mapping.model.MapProject) */ @Override public void setMapProject(MapProject mapProject) { this.mapProject = mapProject; } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.helpers.ProjectSpecificAlgorithmHandler# * isMapAdviceComputable(org.ihtsdo.otf.mapping.model.MapRecord) */ @Override public boolean isMapAdviceComputable(MapRecord mapRecord) { if (mapProject != null) { for (MapAdvice mapAdvice : mapProject.getMapAdvices()) { if (mapAdvice.isComputed() == true) return true; } } return false; } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.helpers.ProjectSpecificAlgorithmHandler# * isMapRelationComputable(org.ihtsdo.otf.mapping.model.MapRecord) */ @Override public boolean isMapRelationComputable(MapRecord mapRecord) { if (mapProject != null) { for (MapRelation mapRelation : mapProject.getMapRelations()) { if (mapRelation.isComputed() == true) return true; } } return false; } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.helpers.ProjectSpecificAlgorithmHandler# * computeMapAdvice (org.ihtsdo.otf.mapping.model.MapRecord, * org.ihtsdo.otf.mapping.model.MapEntry) */ @Override /** * Given a map record and a map entry, returns any computed advice. * This must be overwritten for each project specific handler. * @param mapRecord * @return */ public MapAdviceList computeMapAdvice(MapRecord mapRecord, MapEntry mapEntry) throws Exception { return null; } /** * Given a map record and a map entry, returns the computed map relation (if * applicable) This must be overwritten for each project specific handler. * * @param mapRecord the map record * @param mapEntry the map entry * @return computed map relation */ @Override public MapRelation computeMapRelation(MapRecord mapRecord, MapEntry mapEntry) { return null; } /* * (non-Javadoc) * * @see * org.ihtsdo.otf.mapping.helpers.ProjectSpecificAlgorithmHandler#validateRecord * (org.ihtsdo.otf.mapping.model.MapRecord) */ @Override public ValidationResult validateRecord(MapRecord mapRecord) throws Exception { ValidationResult validationResult = new ValidationResultJpa(); validationResult.merge(performUniversalValidationChecks(mapRecord)); validationResult.merge(validateTargetCodes(mapRecord)); return validationResult; } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.helpers.ProjectSpecificAlgorithmHandler# * validateTargetCodes(org.ihtsdo.otf.mapping.model.MapRecord) */ @Override /** * This must be overwritten for each project specific handler */ public ValidationResult validateTargetCodes(MapRecord mapRecord) throws Exception { return new ValidationResultJpa(); } /** * Perform universal validation checks. * * @param mapRecord the map record * @return the validation result */ public ValidationResult performUniversalValidationChecks(MapRecord mapRecord) { Map<Integer, List<MapEntry>> entryGroups = getEntryGroups(mapRecord); ValidationResult validationResult = new ValidationResultJpa(); // FATAL ERROR: map record has no entries if (mapRecord.getMapEntries().size() == 0) { validationResult.addError("Map record has no entries"); return validationResult; } // FATAL ERROR: multiple map groups present for a project without group // structure if (!mapProject.isGroupStructure() && entryGroups.keySet().size() > 1) { validationResult .addError("Project has no group structure but multiple map groups were found."); return validationResult; } // Validation Check: verify correct positioning of TRUE rules validationResult.merge(checkMapRecordTrueRules(mapRecord, entryGroups)); // Validation Check: very higher map groups do not have only NC nodes validationResult.merge(checkMapRecordNcNodes(mapRecord, entryGroups)); // Validation Check: verify entries are not duplicated validationResult.merge(checkMapRecordForDuplicateEntries(mapRecord)); // Validation Check: verify advice values are valid for the project // (this // entries) validationResult.merge(checkMapRecordAdvices(mapRecord, entryGroups)); // Validation Check: very that map entry targets OR relationIds are // valid /* * validationResult.merge(checkMapRecordTargets(mapRecord, entryGroups)); */ return validationResult; } // HELPER FUNCTIONS // // Map Record Validation Checks and Helper Functions /** * Function to check a map record for duplicate entries within map groups. * * @param mapRecord the map record * @return a list of errors detected */ @SuppressWarnings("static-method") public ValidationResult checkMapRecordForDuplicateEntries(MapRecord mapRecord) { // Logger.getLogger(DefaultProjectSpecificAlgorithmHandler.class) // .info(" Checking map record for duplicate entries within map groups..."); ValidationResult validationResult = new ValidationResultJpa(); List<MapEntry> entries = mapRecord.getMapEntries(); // cycle over all entries but last for (int i = 0; i < entries.size() - 1; i++) { // cycle over all entries after this one // NOTE: separated boolean checks for easier handling of possible null // relations for (int j = i + 1; j < entries.size(); j++) { // check if both targets are null OR if targets equal boolean targetIdsNull = entries.get(i).getTargetId() == null && entries.get(j).getTargetId() == null; boolean targetIdsEqual = false; if (!targetIdsNull) { targetIdsEqual = entries.get(i).getTargetId().equals(entries.get(j).getTargetId()); } // default: relations are not equal boolean mapRelationsNull = entries.get(i).getMapRelation() == null && entries.get(j).getMapRelation() == null; boolean mapRelationsEqual = false; if (!mapRelationsNull) { if (entries.get(i).getMapRelation() .equals(entries.get(j).getMapRelation())) mapRelationsEqual = true; } // if target ids are the same, add error if (!targetIdsNull && targetIdsEqual) { validationResult .addError("Duplicate entries (same target code) found: " + "Group " + Integer.toString(entries.get(i).getMapGroup()) + ", priority " + Integer.toString(i) + " and " + "Group " + Integer.toString(entries.get(j).getMapGroup()) + ", priority " + Integer.toString(j)); } // if target ids are null and map relations are equal, add error if (targetIdsNull && mapRelationsEqual) { validationResult .addError("Duplicate entries (null target code, same map relation) found: " + "Group " + Integer.toString(entries.get(i).getMapGroup()) + ", priority " + entries.get(i).getMapPriority() + " and " + "Group " + Integer.toString(entries.get(j).getMapGroup()) + ", priority " + entries.get(j).getMapPriority()); } } } for (String error : validationResult.getErrors()) { Logger.getLogger(DefaultProjectSpecificAlgorithmHandler.class).info( " " + error); } return validationResult; } /** * Function to check proper use of TRUE rules. * * @param mapRecord the map record * @param entryGroups the binned entry lists by group * @return a list of errors detected */ public ValidationResult checkMapRecordTrueRules(MapRecord mapRecord, Map<Integer, List<MapEntry>> entryGroups) { // Logger.getLogger(DefaultProjectSpecificAlgorithmHandler.class).info( // " Checking map record for proper use of TRUE rules..."); ValidationResult validationResult = new ValidationResultJpa(); // if not rule based, return empty validation result if (mapProject.isRuleBased() == false) return validationResult; // cycle over the groups for (Integer key : entryGroups.keySet()) { for (MapEntry mapEntry : entryGroups.get(key)) { Logger.getLogger(DefaultProjectSpecificAlgorithmHandler.class) .info( " Checking entry " + Integer.toString(mapEntry.getMapPriority())); // add message if TRUE rule found at non-terminating entry if (mapEntry.getMapPriority() != entryGroups.get(key).size() && mapEntry.getRule().equals("TRUE")) { validationResult .addError("Found non-terminating entry with TRUE rule." + " Entry:" + (mapProject.isGroupStructure() ? " group " + Integer.toString(mapEntry.getMapGroup()) + "," : "") + " map priority " + Integer.toString(mapEntry.getMapPriority())); // add message if terminating entry rule is not TRUE } else if (mapEntry.getMapPriority() == entryGroups.get(key).size() && !mapEntry.getRule().equals("TRUE")) { validationResult.addError("Terminating entry has non-TRUE rule." + " Entry:" + (mapProject.isGroupStructure() ? " group " + Integer.toString(mapEntry.getMapGroup()) + "," : "") + " map priority " + Integer.toString(mapEntry.getMapPriority())); } } } for (String error : validationResult.getErrors()) { Logger.getLogger(DefaultProjectSpecificAlgorithmHandler.class).info( " " + error); } return validationResult; } /** * Function to check higher level groups do not have only NC target codes. * * @param mapRecord the map record * @param entryGroups the binned entry lists by group * @return a list of errors detected */ @SuppressWarnings("static-method") public ValidationResult checkMapRecordNcNodes(MapRecord mapRecord, Map<Integer, List<MapEntry>> entryGroups) { // Logger.getLogger(DefaultProjectSpecificAlgorithmHandler.class) // .info(" Checking map record for high-level groups with only NC target codes..."); ValidationResult validationResult = new ValidationResultJpa(); // if only one group, return empty validation result (also covers // non-group-structure projects) if (entryGroups.keySet().size() == 1) return validationResult; // otherwise cycle over the high-level groups (i.e. all but first group) for (int group : entryGroups.keySet()) { if (group != 1) { List<MapEntry> entries = entryGroups.get(group); boolean isValidGroup = false; for (MapEntry entry : entries) { if (entry.getTargetId() != null && entry.getTargetId() != "") isValidGroup = true; } if (!isValidGroup) { validationResult.addError("High-level group " + Integer.toString(group) + " has no entries with targets"); } } } for (String error : validationResult.getErrors()) { Logger.getLogger(DefaultProjectSpecificAlgorithmHandler.class).info( " " + error); } return validationResult; } /** * Function to check that all advices attached are allowable by the project. * * @param mapRecord the map record * @param entryGroups the binned entry lists by group * @return a list of errors detected */ public ValidationResult checkMapRecordAdvices(MapRecord mapRecord, Map<Integer, List<MapEntry>> entryGroups) { // Logger.getLogger(DefaultProjectSpecificAlgorithmHandler.class).info( // " Checking map record for valid map advices..."); ValidationResult validationResult = new ValidationResultJpa(); for (MapEntry mapEntry : mapRecord.getMapEntries()) { for (MapAdvice mapAdvice : mapEntry.getMapAdvices()) { if (!mapProject.getMapAdvices().contains(mapAdvice)) { validationResult.addError("Invalid advice " + mapAdvice.getName() + "." + " Entry:" + (mapProject.isGroupStructure() ? " group " + Integer.toString(mapEntry.getMapGroup()) + "," : "") + " map priority " + Integer.toString(mapEntry.getMapPriority())); } } } for (String error : validationResult.getErrors()) { Logger.getLogger(DefaultProjectSpecificAlgorithmHandler.class).info( " " + error); } return validationResult; } /** * Helper function to sort a records entries into entry lists binned by group. * * @param mapRecord the map record * @return a map of group->entry list */ @SuppressWarnings("static-method") public Map<Integer, List<MapEntry>> getEntryGroups(MapRecord mapRecord) { Map<Integer, List<MapEntry>> entryGroups = new HashMap<>(); for (MapEntry entry : mapRecord.getMapEntries()) { // if no existing set for this group, create a blank set List<MapEntry> entryGroup = entryGroups.get(entry.getMapGroup()); if (entryGroup == null) { entryGroup = new ArrayList<>(); } // add this entry to group and put it in group map entryGroup.add(entry); entryGroups.put(entry.getMapGroup(), entryGroup); } return entryGroups; } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.helpers.ProjectSpecificAlgorithmHandler# * compareMapRecords(org.ihtsdo.otf.mapping.model.MapRecord, * org.ihtsdo.otf.mapping.model.MapRecord) */ @Override public ValidationResult compareMapRecords(MapRecord record1, MapRecord record2) { ValidationResult validationResult = new ValidationResultJpa(); // compare mapProjectId if (record1.getMapProjectId() != record2.getMapProjectId()) { validationResult .addError("Invalid comparison, map project ids do not match (" + record1.getMapProjectId() + ", " + record2.getMapProjectId() + ")."); return validationResult; } // compare conceptId if (!record1.getConceptId().equals(record2.getConceptId())) { validationResult .addError("Invalid comparison, map record concept ids do not match (" + record1.getConceptId() + ", " + record2.getConceptId() + ")."); return validationResult; } // compare mapPrinciples Comparator<Object> principlesComparator = new Comparator<Object>() { @Override public int compare(Object o1, Object o2) { String x1 = ((MapPrinciple) o1).getPrincipleId(); String x2 = ((MapPrinciple) o2).getPrincipleId(); if (!x1.equals(x2)) { return x1.compareTo(x2); } return 0; } }; List<MapPrinciple> principles1 = new ArrayList<>(record1.getMapPrinciples()); Collections.sort(principles1, principlesComparator); List<MapPrinciple> principles2 = new ArrayList<>(record2.getMapPrinciples()); Collections.sort(principles2, principlesComparator); if (principles1.size() != principles2.size()) { validationResult.addWarning("Differences in map principles."); } else { for (int i = 0; i < principles1.size(); i++) { if (!principles1.get(i).getPrincipleId() .equals(principles2.get(i).getPrincipleId())) validationResult.addWarning("Differences in map principles."); } } // check force map lead review flag if (record1.isFlagForMapLeadReview()) { validationResult.addError("The first record requests MAP LEAD REVIEW."); } if (record2.isFlagForMapLeadReview()) { validationResult.addError("The second record requests MAP LEAD REVIEW."); } // check consensus review flag if (record1.isFlagForConsensusReview()) { validationResult.addError("The first record requests CONSENSUS REVIEW."); } if (record2.isFlagForConsensusReview()) { validationResult.addError("The second record requests CONSENSUS REVIEW."); } // compare mapEntries // organize map entries by group Map<Integer, List<MapEntry>> groupToMapEntryList1 = new HashMap<>(); for (MapEntry entry : record1.getMapEntries()) { if (groupToMapEntryList1.containsKey(entry.getMapGroup())) { List<MapEntry> entryList = groupToMapEntryList1.get(entry.getMapGroup()); entryList.add(entry); } else { List<MapEntry> entryList = new ArrayList<>(); entryList.add(entry); groupToMapEntryList1.put(entry.getMapGroup(), entryList); } } Map<Integer, List<MapEntry>> groupToMapEntryList2 = new HashMap<>(); for (MapEntry entry : record2.getMapEntries()) { if (groupToMapEntryList2.containsKey(entry.getMapGroup())) { List<MapEntry> entryList = groupToMapEntryList2.get(entry.getMapGroup()); entryList.add(entry); } else { List<MapEntry> entryList = new ArrayList<>(); entryList.add(entry); groupToMapEntryList2.put(entry.getMapGroup(), entryList); } } // for each group for (int i = 1; i < Math.max(groupToMapEntryList1.size(), groupToMapEntryList2.size()) + 1; i++) { List<MapEntry> entries1 = groupToMapEntryList1.get(new Integer(i)); List<MapEntry> entries2 = groupToMapEntryList2.get(new Integer(i)); // error if different numbers of entries if (entries1 == null) { validationResult.addError("The first record has an empty group " + i + "."); continue; } else if (entries2 == null) { validationResult.addError("The second record has an empty group " + i + "."); continue; } else if (entries1.size() != entries2.size()) { validationResult .addError("The records have different numbers of entries for group " + i + "."); } // create string lists for entry comparison List<String> stringEntries1 = new ArrayList<>(); List<String> stringEntries2 = new ArrayList<>(); for (MapEntry entry1 : entries1) { stringEntries1.add(convertToString(entry1)); } for (MapEntry entry2 : entries2) { stringEntries2.add(convertToString(entry2)); } // check for matching entries in different order boolean outOfOrderFlag = false; boolean missingEntry = false; for (int d = 0; d < Math .min(stringEntries1.size(), stringEntries2.size()); d++) { if (stringEntries1.get(d).equals(stringEntries2.get(d))) continue; else if (stringEntries2.contains(stringEntries1.get(d))) outOfOrderFlag = true; else missingEntry = true; } if (!outOfOrderFlag && !missingEntry) { continue; // to next group for comparison } if (outOfOrderFlag && !missingEntry) { validationResult .addWarning("The records have the same entries for group " + i + ", but in a different order."); continue; // to next group for comparison } // check for details of missing entries boolean matchFound = false; for (int d = 0; d < entries1.size(); d++) { for (int f = 0; f < entries2.size(); f++) { if (isRulesEqual(entries1.get(d), entries2.get(f)) && isTargetIdsEqual(entries1.get(d), entries2.get(f)) && !isMapRelationsEqual(entries1.get(d), entries2.get(f))) matchFound = true; } if (matchFound) { validationResult .addError("Records have a matching entry but with different map relation: " + convertToString(entries1.get(d)) + "."); } matchFound = false; } for (int d = 0; d < entries1.size(); d++) { for (int f = 0; f < entries2.size(); f++) { if (isRulesEqual(entries1.get(d), entries2.get(f)) && isTargetIdsEqual(entries1.get(d), entries2.get(f)) && !entries1.get(d).getMapAdvices() .equals(entries2.get(f).getMapAdvices())) matchFound = true; } if (matchFound) { validationResult .addError("Records have a matching entry but with different advice: " + convertToString(entries1.get(d)) + "."); } matchFound = false; } for (int d = 0; d < entries1.size(); d++) { for (int f = 0; f < entries2.size(); f++) { if (isRulesEqual(entries1.get(d), entries2.get(f)) && !isTargetIdsEqual(entries1.get(d), entries2.get(f))) matchFound = true; } if (matchFound) { validationResult .addError("Records have an entry with the same rule but different target code: " + convertToString(entries1.get(d)) + "."); } matchFound = false; } for (int d = 0; d < entries1.size(); d++) { for (int f = 0; f < entries2.size(); f++) { if (isRulesEqual(entries1.get(d), entries2.get(f))) matchFound = true; } if (!matchFound) { validationResult.addError("Record entry does not match: " + convertToString(entries1.get(d)) + "."); } matchFound = false; } } return validationResult; } /** * Indicates whether or not rules are equal. * * @param entry1 the entry1 * @param entry2 the entry2 * @return <code>true</code> if so, <code>false</code> otherwise */ @SuppressWarnings("static-method") public boolean isRulesEqual(MapEntry entry1, MapEntry entry2) { // check null comparisons first if (entry1.getRule() == null && entry2.getRule() != null) return false; if (entry1.getRule() != null && entry2.getRule() == null) return false; if (entry1.getRule() == null && entry2.getRule() == null) return true; return entry1.getRule().equals(entry2.getRule()); } /** * Indicates whether or not target ids are equal. * * @param entry1 the entry1 * @param entry2 the entry2 * @return <code>true</code> if so, <code>false</code> otherwise */ @SuppressWarnings("static-method") public boolean isTargetIdsEqual(MapEntry entry1, MapEntry entry2) { // check null comparisons first if (entry1.getTargetId() == null && entry2.getTargetId() != null) return false; if (entry1.getTargetId() != null && entry2.getTargetId() == null) return false; if (entry1.getTargetId() == null && entry2.getTargetId() == null) return true; return entry1.getTargetId().equals(entry2.getTargetId()); } /** * Indicates whether or not map relations are equal. * * @param entry1 the entry1 * @param entry2 the entry2 * @return <code>true</code> if so, <code>false</code> otherwise */ @SuppressWarnings("static-method") public boolean isMapRelationsEqual(MapEntry entry1, MapEntry entry2) { // check null comparisons first if (entry1.getMapRelation() == null && entry2.getMapRelation() != null) return false; if (entry1.getMapRelation() != null && entry2.getMapRelation() == null) return false; if (entry1.getMapRelation() == null && entry2.getMapRelation() == null) return true; return entry1.getMapRelation().getId() .equals(entry2.getMapRelation().getId()); } /** * Convert to string. * * @param mapEntry the map entry * @return the string */ private String convertToString(MapEntry mapEntry) { // check map advices Comparator<Object> advicesComparator = new Comparator<Object>() { @Override public int compare(Object o1, Object o2) { String x1 = ((MapAdvice) o1).getName(); String x2 = ((MapAdvice) o2).getName(); if (!x1.equals(x2)) { return x1.compareTo(x2); } return 0; } }; List<MapAdvice> advices = new ArrayList<>(mapEntry.getMapAdvices()); Collections.sort(advices, advicesComparator); StringBuffer sb = new StringBuffer(); sb.append(mapEntry.getTargetId() + " " + mapEntry.getRule() + " " + (mapEntry.getMapRelation() != null ? mapEntry.getMapRelation() .getId() : "")); for (MapAdvice mapAdvice : advices) { sb.append(mapAdvice.getObjectId() + " "); } return sb.toString(); } /** * For default project, all target codes are considered valid. * * @param terminologyId the terminology id * @return true, if is target code valid * @throws Exception the exception */ @Override public boolean isTargetCodeValid(String terminologyId) throws Exception { return true; } /** * Assign a new map record from existing record, performing any necessary * workflow actions based on workflow status * * - READY_FOR_PUBLICATION, PUBLICATION -> FIX_ERROR_PATH: Create a new record * with origin ids set to the existing record (and its antecedents) - Add the * record to the tracking record - Return the tracking record. * * - NEW, EDITING_IN_PROGRESS, EDITING_DONE, CONFLICT_NEW, * CONFLICT_IN_PROGRESS Invalid workflow statuses, should never be called with * a record of this nature * * Expects the tracking record to be a detached Jpa entity. Does not modify * objects via services. * * @param trackingRecord the tracking record * @param mapRecords the map records * @param mapRecord the map record * @param mapUser the map user * @return the workflow tracking record * @throws Exception the exception */ @Override public Set<MapRecord> assignFromInitialRecord(TrackingRecord trackingRecord, Set<MapRecord> mapRecords, MapRecord mapRecord, MapUser mapUser) throws Exception { Set<MapRecord> newRecords = new HashSet<>(); switch (trackingRecord.getWorkflowPath()) { case FIX_ERROR_PATH: Logger.getLogger(DefaultProjectSpecificAlgorithmHandler.class).info( "assignFromInitialRecord: FIX_ERROR_PATH"); // case 1 : User claims a PUBLISHED or READY_FOR_PUBLICATION record to // fix error on. if (mapRecord.getWorkflowStatus().equals(WorkflowStatus.PUBLISHED) || mapRecord.getWorkflowStatus().equals( WorkflowStatus.READY_FOR_PUBLICATION)) { // check that only one record exists for this tracking record if (!(trackingRecord.getMapRecordIds().size() == 1)) { System.out.println(trackingRecord.toString()); throw new Exception( "DefaultProjectSpecificHandlerException - assignFromInitialRecord: More than one record exists for FIX_ERROR_PATH assignment."); } // deep copy the map record MapRecord newRecord = new MapRecordJpa(mapRecord, true); // set origin ids newRecord.addOrigin(mapRecord.getId()); newRecord.addOrigins(mapRecord.getOriginIds()); // set other relevant fields newRecord.setOwner(mapUser); newRecord.setLastModifiedBy(mapUser); newRecord.setWorkflowStatus(WorkflowStatus.NEW); // add the record to the list newRecords.add(newRecord); // set the workflow status of the old record to review and add it to // new records mapRecord.setWorkflowStatus(WorkflowStatus.REVISION); newRecords.add(mapRecord); System.out.println("fix_error_path record to add: " + mapRecord.toString()); } break; case CONSENSUS_PATH: break; case LEGACY_PATH: break; case NON_LEGACY_PATH: throw new Exception( "Invalid assignFromInitialRecord call for NON_LEGACY_PATH workflow"); case QA_PATH: break; default: throw new Exception( "assignFromInitialRecord called with invalid Workflow Path."); } return newRecords; } /** * Assign a map user to a concept for this project * * Conditions: - Only valid workflow paths: NON_LEGACY_PATH, LEGACY_PATH, and * CONSENSUS_PATH Note that QA_PATH and FIX_ERROR_PATH should never call this * method - Only valid workflow statuses: Any status preceding * CONFLICT_DETECTED and CONFLICT_DETECTED * * Default Behavior: - Create a record with workflow status based on current * workflow status - Add the record to the tracking record - Return the * tracking record. * * @param trackingRecord the tracking record * @param mapRecords the map records * @param concept the concept * @param mapUser the map user * @return the workflow tracking record * @throws Exception the exception */ @Override public Set<MapRecord> assignFromScratch(TrackingRecord trackingRecord, Set<MapRecord> mapRecords, Concept concept, MapUser mapUser) throws Exception { // the list of map records to return Set<MapRecord> newRecords = new HashSet<>(mapRecords); for (MapRecord mr : mapRecords) { System.out.println(mr.toString()); } // create new record MapRecord mapRecord = new MapRecordJpa(); mapRecord.setMapProjectId(mapProject.getId()); mapRecord.setConceptId(concept.getTerminologyId()); mapRecord.setConceptName(concept.getDefaultPreferredName()); mapRecord.setOwner(mapUser); mapRecord.setLastModifiedBy(mapUser); mapRecord.setWorkflowStatus(WorkflowStatus.NEW); // set additional record parameters based on workflow path and status switch (trackingRecord.getWorkflowPath()) { case NON_LEGACY_PATH: // if a "new" tracking record (i.e. prior to conflict detection), // add a NEW record if (getWorkflowStatus(mapRecords).compareTo( WorkflowStatus.CONFLICT_DETECTED) < 0) { // check that this record is valid to be assigned (i.e. no more // than // one other specialist assigned) if (getMapUsers(mapRecords).size() >= 2) { throw new Exception( "DefaultProjectSpecificHandlerException - assignFromScratch: Two users already assigned"); } mapRecord.setWorkflowStatus(WorkflowStatus.NEW); Logger.getLogger(DefaultProjectSpecificAlgorithmHandler.class).info( "NON_LEGACY_PATH: NEW"); // otherwise, if this is a tracking record with conflict // detected, add a CONFLICT_NEW record } else if (getWorkflowStatus(mapRecords).equals( WorkflowStatus.CONFLICT_DETECTED)) { mapRecord.setWorkflowStatus(WorkflowStatus.CONFLICT_NEW); // get the origin ids from the tracking record for (MapRecord mr : newRecords) { mapRecord.addOrigin(mr.getId()); } Logger.getLogger(DefaultProjectSpecificAlgorithmHandler.class).info( "NON_LEGACY_PATH: CONFLICT_NEW"); } break; case FIX_ERROR_PATH: // Case 1: A lead claims an error-fixed record for review if (getLowestWorkflowStatus(mapRecords).equals( WorkflowStatus.REVIEW_NEEDED)) { Logger.getLogger(DefaultProjectSpecificAlgorithmHandler.class).info( "FIX_ERROR_PATH: Lead claiming an error-fixed record"); // check that only two records exists for this tracking record if (!(trackingRecord.getMapRecordIds().size() == 2)) { System.out.println(trackingRecord.toString()); throw new Exception( "assignFromScratch: More than one record exists for FIX_ERROR_PATH assignment."); } // set origin id for (MapRecord mr : mapRecords) { mapRecord.addOrigin(mr.getId()); mapRecord.addOrigins(mr.getOriginIds()); } // set workflow status mapRecord.setWorkflowStatus(WorkflowStatus.REVIEW_NEW); Logger.getLogger("FIX_ERROR_PATH final record: " + mapRecord.toString()); } else { throw new Exception( "assignFromScratch called on FIX_ERROR_PATH but tracking record does not contain a record marked REVIEW_NEEDED"); } break; case CONSENSUS_PATH: break; case LEGACY_PATH: break; case QA_PATH: break; default: throw new Exception( "assignFromScratch called with erroneous Workflow Path."); } ContentService contentService = new ContentServiceJpa(); mapRecord.setCountDescendantConcepts(new Long( // get the tree positions for this concept contentService .getTreePositionsWithDescendants(trackingRecord.getTerminologyId(), trackingRecord.getTerminology(), trackingRecord.getTerminologyVersion()) .getTreePositions() // get the list of tree positions .get(0) // get the first tree position .getDescendantCount())); // get the descendant count contentService.close(); // add this record to the tracking record newRecords.add(mapRecord); // return the modified record set return newRecords; } /** * Unassigns a user from a concept, and performs any other necessary workflow * actions * * Conditions: - Valid workflow paths: All - Valid workflow status: All except * READY_FOR_PUBLICATION, PUBLISHED. * * @param trackingRecord the tracking record * @param mapRecords the map records * @param mapUser the map user * @return the workflow tracking record * @throws Exception the exception */ @Override public Set<MapRecord> unassign(TrackingRecord trackingRecord, Set<MapRecord> mapRecords, MapUser mapUser) throws Exception { Logger.getLogger(DefaultProjectSpecificAlgorithmHandler.class).info( "Unassign called along " + trackingRecord.getWorkflowPath() + " path"); Set<MapRecord> newRecords = new HashSet<>(mapRecords); // find the map record this user is assigned to MapRecord mapRecord = null; for (MapRecord mr : newRecords) { if (mr.getOwner().equals(mapUser)) { mapRecord = mr; } } // switch on workflow path switch (trackingRecord.getWorkflowPath()) { case NON_LEGACY_PATH: Logger.getLogger(DefaultProjectSpecificAlgorithmHandler.class).info( "Unassign: NON_LEGACY_PATH"); if (mapRecord == null) throw new Exception( "unassign called for concept that does not have specified user assigned"); // remove this record from the tracking record newRecords.remove(mapRecord); // determine action based on record's workflow status after removal // the unassigned record switch (mapRecord.getWorkflowStatus()) { // standard removal cases, no special action required case NEW: case EDITING_IN_PROGRESS: case EDITING_DONE: case CONFLICT_NEW: case CONFLICT_IN_PROGRESS: case REVIEW_NEEDED: case REVIEW_NEW: case REVIEW_IN_PROGRESS: Logger.getLogger(DefaultProjectSpecificAlgorithmHandler.class) .info( "Unassign: NON_LEGACY_PATH + mapRecord.getWorkflowStatus() + " -- No special action required"); break; // where a conflict is detected, two cases to handle // (1) any lead-claimed resolution record is now invalid, and should // be deleted (no conflict remaining) // (2) a specialist's record is now not in conflict, and should be // reverted to EDITING_DONE case CONFLICT_DETECTED: MapRecord recordToRemove = null; for (MapRecord mr : newRecords) { // if another specialist's record, revert to EDITING_DONE if (mr.getWorkflowStatus().equals( WorkflowStatus.CONFLICT_DETECTED)) { mr.setWorkflowStatus(WorkflowStatus.EDITING_DONE); } // if the lead's record, delete if (mr.getWorkflowStatus().equals(WorkflowStatus.CONFLICT_NEW)) { recordToRemove = mr; } } if (recordToRemove != null) newRecords.remove(recordToRemove); break; // consensus path not implemented case CONSENSUS_NEEDED: break; case CONSENSUS_IN_PROGRESS: break; // If REVISION is detected, something has gone horribly wrong for the // NON_LEGACY_PATH case REVISION: throw new Exception( "Unassign: A user has been improperly assigned to a review record"); // throw an exception if somehow an invalid workflow status is // found default: throw new Exception( "unassign found a map record with invalid workflow status"); } break; case LEGACY_PATH: break; // If unassignment for error fixing, need to reset the existing record // from REVIEW case FIX_ERROR_PATH: Logger.getLogger(DefaultProjectSpecificAlgorithmHandler.class).info( "Unassign: FIX_ERROR_PATH"); // get the REVISION record MapRecord revisionRecord = null; for (MapRecord mr : mapRecords) { if (mr.getWorkflowStatus().equals(WorkflowStatus.REVISION)) revisionRecord = mr; } if (revisionRecord == null) throw new Exception( "Attempted to unassign a published revision record, but no such previously published record exists!"); // Case 1: A user decides not to attempt to fix an error if (mapRecord.getWorkflowStatus().equals(WorkflowStatus.NEW) || mapRecord.getWorkflowStatus().equals( WorkflowStatus.EDITING_IN_PROGRESS)) { newRecords.remove(mapRecord); newRecords.remove(revisionRecord); newRecords .add(getPreviouslyPublishedVersionOfMapRecord(revisionRecord)); // Case 2: A lead unassigns themselves from reviewing a fixed error // delete the lead's record, no other action required } else if (mapRecord.getWorkflowStatus().equals( WorkflowStatus.REVIEW_NEW) || mapRecord.getWorkflowStatus().equals( WorkflowStatus.REVIEW_IN_PROGRESS)) { newRecords.remove(mapRecord); } else { throw new Exception( "Unexpected error attempt to unassign a Revision record. Contact an administrator."); } break; case QA_PATH: break; case CONSENSUS_PATH: break; default: break; } // return the modified record set\ System.out.println("DPSAH: New Records"); for (MapRecord mr : newRecords) System.out.println(mr.toString()); return newRecords; } /** * Updates workflow information when a specialist or lead clicks "Finished" * Expects the tracking record to be detached from persistence environment. * * @param trackingRecord the tracking record * @param mapRecords the map records * @param mapUser the map user * @return the workflow tracking record * @throws Exception the exception */ @Override public Set<MapRecord> finishEditing(TrackingRecord trackingRecord, Set<MapRecord> mapRecords, MapUser mapUser) throws Exception { Set<MapRecord> newRecords = new HashSet<>(mapRecords); // find the record assigned to this user MapRecord mapRecord = null; for (MapRecord mr : newRecords) { if (mr.getOwner().equals(mapUser)) { mapRecord = mr; } } if (mapRecord == null) throw new Exception("finishEditing: Record for user could not be found"); // switch on workflow path switch (trackingRecord.getWorkflowPath()) { case NON_LEGACY_PATH: // case 1: A specialist is finished with a record if (getWorkflowStatus(mapRecords).compareTo( WorkflowStatus.CONFLICT_DETECTED) < 0) { Logger .getLogger(DefaultProjectSpecificAlgorithmHandler.class) .info( "NON_LEGACY_PATH - New finished record, checking for other records"); // set this record to EDITING_DONE mapRecord.setWorkflowStatus(WorkflowStatus.EDITING_DONE); // check if two specialists have completed work if (getLowestWorkflowStatus(mapRecords).equals( WorkflowStatus.EDITING_DONE) && mapRecords.size() == 2) { Logger.getLogger(DefaultProjectSpecificAlgorithmHandler.class) .info("NON_LEGACY_PATH - Two records found"); java.util.Iterator<MapRecord> record_iter = mapRecords.iterator(); MapRecord mapRecord1 = record_iter.next(); MapRecord mapRecord2 = record_iter.next(); ValidationResult validationResult = compareMapRecords(mapRecord1, mapRecord2); // if map records validation is successful if (validationResult.isValid() == true) { Logger.getLogger(DefaultProjectSpecificAlgorithmHandler.class) .info("NON_LEGACY_PATH - No conflicts detected."); // deep copy the record and mark the new record // READY_FOR_PUBLICATION MapRecord newRecord = new MapRecordJpa(mapRecord, true); newRecord.setOwner(mapUser); newRecord.setLastModifiedBy(mapUser); mapRecord.setWorkflowStatus(WorkflowStatus.READY_FOR_PUBLICATION); // construct and set the new origin ids Set<Long> originIds = new HashSet<>(); originIds.add(mapRecord1.getId()); originIds.add(mapRecord2.getId()); originIds.addAll(mapRecord1.getOriginIds()); originIds.addAll(mapRecord2.getOriginIds()); newRecord.setOriginIds(originIds); // clear the records and add a single record owned by this user newRecords.clear(); newRecords.add(newRecord); } else { Logger.getLogger(DefaultProjectSpecificAlgorithmHandler.class) .info("NON_LEGACY_PATH - Conflicts detected"); // conflict detected, change workflow status of all // records and // update records for (MapRecord mr : newRecords) { mr.setWorkflowStatus(WorkflowStatus.CONFLICT_DETECTED); } } // otherwise, only one specialist has finished work, do // nothing else } else { Logger .getLogger(DefaultProjectSpecificAlgorithmHandler.class) .info( "NON_LEGACY_PATH - Only this specialist has completed work"); } // case 2: A lead is finished with a conflict resolution // Determined by workflow status of: // CONFLICT_NEW (i.e. conflict was resolved immediately) // CONFLICT_IN_PROGRESS (i.e. conflict had been previously saved // for later) } else if (getWorkflowStatus(mapRecords).equals( WorkflowStatus.CONFLICT_NEW) || getWorkflowStatus(mapRecords).equals( WorkflowStatus.CONFLICT_IN_PROGRESS)) { Logger.getLogger(DefaultProjectSpecificAlgorithmHandler.class).info( "NON_LEGACY_PATH - Conflict resolution detected"); // cycle over the previously existing records for (MapRecord mr : mapRecords) { // remove the CONFLICT_DETECTED records from the revised set if (mr.getWorkflowStatus().equals(WorkflowStatus.CONFLICT_DETECTED)) { newRecords.remove(mr); // set the CONFLICT_NEW or CONFLICT_IN_PROGRESS record // READY_FOR_PUBLICATION // and update } else { mr.setWorkflowStatus(WorkflowStatus.READY_FOR_PUBLICATION); } } // case 3: A lead is finished reviewing a record with no conflicts } else if (getWorkflowStatus(mapRecords).equals( WorkflowStatus.REVIEW_NEW) || getWorkflowStatus(mapRecords).equals( WorkflowStatus.REVIEW_IN_PROGRESS)) { // do nothing } else { throw new Exception( "finishEditing failed! Invalid workflow status combination on record(s)"); } break; case FIX_ERROR_PATH: for (MapRecord mr : mapRecords) System.out.println(mr.getWorkflowStatus().toString()); Logger.getLogger(DefaultProjectSpecificAlgorithmHandler.class).info( "FIX_ERROR_PATH"); // case 1: A user has finished correcting an error on a previously // published record // requires a workflow state to exist below that of REVEW_NEW (in this // case, NEW, EDITING_IN_PROGRESS if (mapRecords.size() == 2) { Logger.getLogger(DefaultProjectSpecificAlgorithmHandler.class).info( " User has finished correcting an error"); // assumption check: should only be 2 records // 1) The original record (now marked REVISION) // 2) The modified record (NEW or EDITING_IN_PROGRESS boolean foundOriginalRecord = false; boolean foundModifiedRecord = false; for (MapRecord mr : mapRecords) { if (mr.getWorkflowStatus().equals(WorkflowStatus.REVISION)) foundOriginalRecord = true; if (mr.getWorkflowStatus().equals(WorkflowStatus.NEW) || mr.getWorkflowStatus().equals( WorkflowStatus.EDITING_IN_PROGRESS)) foundModifiedRecord = true; } if (!foundOriginalRecord) throw new Exception( "FIX_ERROR_PATH: Specialist finished work, but could not find previously published record"); if (!foundModifiedRecord) throw new Exception( "FIX_ERROR_PATH: Specialist finished work, but could not find their record"); // cycle over the records for (MapRecord mr : mapRecords) { // two records, one marked REVISION, one marked with NEW, // EDITING_IN_PROGRESS if (!mr.getWorkflowStatus().equals(WorkflowStatus.REVISION)) { mr.setWorkflowStatus(WorkflowStatus.REVIEW_NEEDED); } } // Case 2: A lead has finished reviewing a corrected error and is // ready to send it to publication status } else if (mapRecords.size() == 3) { // assumption check: should be exactly three records // 1) original published record, marked REVISION // 2) specialist's record, marked REVIEW_NEEDED // 3) lead's record, marked REVIEW_NEW or REVIEW_IN_PROGRESS boolean foundOriginalRecord = false; boolean foundModifiedRecord = false; boolean foundLeadRecord = false; for (MapRecord mr : mapRecords) { if (mr.getWorkflowStatus().equals(WorkflowStatus.REVISION)) foundOriginalRecord = true; if (mr.getWorkflowStatus().equals(WorkflowStatus.REVIEW_NEEDED)) foundModifiedRecord = true; if (mr.getWorkflowStatus().equals(WorkflowStatus.REVIEW_NEW) || mr.getWorkflowStatus().equals( WorkflowStatus.REVIEW_IN_PROGRESS)) foundLeadRecord = true; } if (!foundOriginalRecord) throw new Exception( "FIX_ERROR_PATH: Lead finished reviewing work, but could not find previously published record"); if (!foundModifiedRecord) throw new Exception( "FIX_ERROR_PATH: Lead finished reviewing work, but could not find the specialist's record record"); if (!foundLeadRecord) throw new Exception( "FIX_ERROR_PATH: Lead finished reviewing work, but could not find their record."); // set the record to ready for publication for (MapRecord mr : mapRecords) { // remove the REVIEW_NEEDED and REVISION records if (mr.getWorkflowStatus().equals(WorkflowStatus.REVIEW_NEEDED) || mr.getWorkflowStatus().equals(WorkflowStatus.REVISION)) { newRecords.remove(mr); // set the finished record to READY_FOR_PUBLICATION } else { mr.setWorkflowStatus(WorkflowStatus.READY_FOR_PUBLICATION); } } } else { throw new Exception( "Unexpected error along FIX_ERROR_PATH, invalid number of records passed in"); } break; case LEGACY_PATH: Logger.getLogger(DefaultProjectSpecificAlgorithmHandler.class).info( "LEGACY_PATH"); break; case QA_PATH: Logger.getLogger(DefaultProjectSpecificAlgorithmHandler.class).info( "QA_PATH"); break; case CONSENSUS_PATH: Logger.getLogger(DefaultProjectSpecificAlgorithmHandler.class).info( "CONSENSUS_PATH"); break; default: throw new Exception("finishEditing: Unexpected workflow path"); } return newRecords; } /* * (non-Javadoc) * * @see * org.ihtsdo.otf.mapping.helpers.ProjectSpecificAlgorithmHandler#saveForLater * (org.ihtsdo.otf.mapping.workflow.TrackingRecord, * org.ihtsdo.otf.mapping.model.MapUser) */ @Override public Set<MapRecord> saveForLater(TrackingRecord trackingRecord, Set<MapRecord> mapRecords, MapUser mapUser) throws Exception { Set<MapRecord> newRecords = new HashSet<>(mapRecords); // find the record assigned to this user MapRecord mapRecord = null; for (MapRecord mr : newRecords) { // find using mapping service instead of workflow service? if (mr.getOwner().equals(mapUser)) { mapRecord = mr; } } if (mapRecord == null) throw new Exception("finishEditing: Record for user could not be found"); switch (trackingRecord.getWorkflowPath()) { case CONSENSUS_PATH: break; case FIX_ERROR_PATH: if (mapRecord.getWorkflowStatus().equals(WorkflowStatus.NEW)) mapRecord.setWorkflowStatus(WorkflowStatus.EDITING_IN_PROGRESS); if (mapRecord.getWorkflowStatus().equals(WorkflowStatus.REVIEW_NEW)) mapRecord.setWorkflowStatus(WorkflowStatus.REVIEW_IN_PROGRESS); break; case LEGACY_PATH: break; case NON_LEGACY_PATH: if (mapRecord.getWorkflowStatus().equals(WorkflowStatus.NEW)) mapRecord.setWorkflowStatus(WorkflowStatus.EDITING_IN_PROGRESS); if (mapRecord.getWorkflowStatus().equals(WorkflowStatus.CONFLICT_NEW)) mapRecord.setWorkflowStatus(WorkflowStatus.CONFLICT_IN_PROGRESS); break; case QA_PATH: break; default: break; } return newRecords; } /** * Cancel work on a map record. * * Only use-case is for the FIX_ERROR_PATH where a new map record has been * assigned due to editing a published record. * * @param trackingRecord the tracking record * @param mapRecords the map records * @param mapUser the map user * @return the sets the * @throws Exception the exception */ @Override public Set<MapRecord> cancelWork(TrackingRecord trackingRecord, Set<MapRecord> mapRecords, MapUser mapUser) throws Exception { // copy the map records into a new array Set<MapRecord> newRecords = new HashSet<>(mapRecords); switch (trackingRecord.getWorkflowPath()) { case FIX_ERROR_PATH: MapRecord reviewRecord = null; MapRecord newRecord = null; // check for the appropriate map records for (MapRecord mr : mapRecords) { if (mr.getOwner().equals(mapUser)) { newRecord = mr; } else if (mr.getWorkflowStatus().equals(WorkflowStatus.REVISION)) { reviewRecord = mr; } } // check assumption: user has an assigned record if (newRecord == null) throw new Exception("Cancel work called for user " + mapUser.getName() + " and " + trackingRecord.getTerminology() + " concept " + trackingRecord.getTerminologyId() + ", but could not retrieve assigned record."); // check assumption: a REVIEW record exists if (reviewRecord == null) throw new Exception( "Cancel work called for user " + mapUser.getName() + " and " + trackingRecord.getTerminology() + " concept " + trackingRecord.getTerminologyId() + ", but could not retrieve the previously published or ready-for-publication record."); // perform action only if the user's record is NEW // if editing has occured (EDITING_IN_PROGRESS or above), null-op if (newRecord.getWorkflowStatus().equals(WorkflowStatus.NEW)) { newRecords = unassign(trackingRecord, mapRecords, mapUser); } break; default: // do nothing break; } // return the modified records return newRecords; } /** * Returns the previously published/ready-for-publicatoin version of map * record. * * @param mapRecord the map record * @return the previously publication-ready version of map record * @throws Exception the exception */ @SuppressWarnings("static-method") public MapRecord getPreviouslyPublishedVersionOfMapRecord(MapRecord mapRecord) throws Exception { MappingService mappingService = new MappingServiceJpa(); // get the record revisions List<MapRecord> revisions = mappingService.getMapRecordRevisions(mapRecord.getId()).getMapRecords(); // ensure revisions are sorted by descending timestamp Collections.sort(revisions, new Comparator<MapRecord>() { @Override public int compare(MapRecord mr1, MapRecord mr2) { return mr1.getTimestamp().compareTo(mr2.getTimestamp()); } }); // check assumption: last revision exists, at least two records must be // present if (revisions.size() < 2) throw new Exception( "Attempted to get the previously published version of map record with id " + mapRecord.getId() + ", " + mapRecord.getOwner().getName() + ", and concept id " + mapRecord.getConceptId() + ", but no previous revisions exist."); // cycle over records until the previously published/ready-for-publication // state record is found for (MapRecord revision : revisions) { System.out.println("Previous record = " + revision.toString()); if (revision.getWorkflowStatus().equals(WorkflowStatus.PUBLISHED) || revision.getWorkflowStatus().equals( WorkflowStatus.READY_FOR_PUBLICATION)) return revision; } throw new Exception( "Could not retrieve previously published state of map record for concept " + mapRecord.getConceptId() + ", " + mapRecord.getConceptName()); } /** * Returns the workflow status. * * @param mapRecords the map records * @return the workflow status */ @SuppressWarnings("static-method") public WorkflowStatus getWorkflowStatus(Set<MapRecord> mapRecords) { WorkflowStatus workflowStatus = WorkflowStatus.NEW; for (MapRecord mr : mapRecords) { System.out.println(mr.getWorkflowStatus()); if (mr.getWorkflowStatus().compareTo(workflowStatus) > 0) workflowStatus = mr.getWorkflowStatus(); } return workflowStatus; } /** * Returns the lowest workflow status. * * @param mapRecords the map records * @return the lowest workflow status */ @SuppressWarnings("static-method") public WorkflowStatus getLowestWorkflowStatus(Set<MapRecord> mapRecords) { WorkflowStatus workflowStatus = WorkflowStatus.REVISION; for (MapRecord mr : mapRecords) { if (mr.getWorkflowStatus().compareTo(workflowStatus) < 0) workflowStatus = mr.getWorkflowStatus(); } return workflowStatus; } /** * Returns the map users. * * @param mapRecords the map records * @return the map users */ @SuppressWarnings("static-method") public Set<MapUser> getMapUsers(Set<MapRecord> mapRecords) { Set<MapUser> mapUsers = new HashSet<>(); for (MapRecord mr : mapRecords) { mapUsers.add(mr.getOwner()); } return mapUsers; } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.helpers.ProjectSpecificAlgorithmHandler# * computeTargetTerminologyNotes * (org.ihtsdo.otf.mapping.helpers.TreePositionList) */ @Override public void computeTargetTerminologyNotes(TreePositionList treePositions) throws Exception { // DO NOTHING -- Override in project specific handlers if necessary } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.helpers.ProjectSpecificAlgorithmHandler# * isRecordEditableByUser(org.ihtsdo.otf.mapping.model.MapRecord, * org.ihtsdo.otf.mapping.model.MapUser) */ @Override public boolean isRecordEditableByUser(MapRecord mapRecord, MapUser mapUser) throws Exception { // check that this user is on this project if (!mapProject.getMapSpecialists().contains(mapUser) && !mapProject.getMapLeads().contains(mapUser)) { return false; } switch (mapRecord.getWorkflowStatus()) { // neither lead nor specialist can modify a CONFLICT_DETECTED record case CONFLICT_DETECTED: return false; // the following cases can only be edited by an owner who is a lead // for this project case CONFLICT_IN_PROGRESS: case CONFLICT_NEW: if (mapRecord.getOwner().equals(mapUser) && mapProject.getMapLeads().contains(mapUser)) return true; else return false; case REVIEW_NEEDED: return false; // review editing can only be done by the lead who owns this record case REVIEW_NEW: case REVIEW_IN_PROGRESS: if (mapRecord.getOwner().equals(mapUser) && mapProject.getMapLeads().contains(mapUser)) return true; else return false; // consensus record handling - Phase 2 case CONSENSUS_NEEDED: case CONSENSUS_NEW: case CONSENSUS_IN_PROGRESS: return false; // initial editing stages can be edited only by owner case EDITING_DONE: case EDITING_IN_PROGRESS: case NEW: if (mapRecord.getOwner().equals(mapUser)) return true; else return false; // published and ready_for_publication records are available to // either specialists or leads case PUBLISHED: case READY_FOR_PUBLICATION: return true; // review records are not editable case REVISION: return false; // if a non-specified case, throw error default: throw new Exception("Invalid Workflow Status " + mapRecord.getWorkflowStatus().toString() + " when checking editable for map record"); } } }
package com.ksa.web.struts2.action.finance.charge; import java.util.Date; import java.util.List; import com.ksa.context.ServiceContextUtils; import com.ksa.model.finance.Account; import com.ksa.model.finance.Charge; import com.ksa.model.logistics.BookingNote; import com.ksa.model.security.User; import com.ksa.service.bd.CurrencyRateService; import com.ksa.service.finance.AccountService; import com.ksa.service.finance.ChargeService; import com.ksa.service.logistics.BookingNoteService; import com.ksa.service.security.util.SecurityUtils; import com.ksa.util.StringUtils; import com.opensymphony.xwork2.ModelDriven; public class ChargeEditAction extends ChargeAction implements ModelDriven<BookingNote> { private static final long serialVersionUID = -2776151163922960571L; @Override protected String doExecute() throws Exception { BookingNoteService service = ServiceContextUtils.getService( BookingNoteService.class ); bookingNote = service.loadBookingNoteById( bookingNote.getId() ); if( StringUtils.hasText( template ) ) { ChargeService chargeService = ServiceContextUtils.getService( ChargeService.class ); List<Charge> charges = chargeService.loadBookingNoteCharges( template, incomes, expenses ); User currentUser = SecurityUtils.getCurrentUser(); for( Charge charge : charges ) { charge.setId( "" ); charge.setCreatedDate( new Date() ); charge.setCreator( currentUser ); } } else /* if( ! BookingNoteState.isNone( bookingNote.getState() ) ) */{ // BookingNote ChargeService chargeService = ServiceContextUtils.getService( ChargeService.class ); chargeService.loadBookingNoteCharges( bookingNote.getId(), incomes, expenses ); } // bookingNote.creator bookingNote.setCreator( SecurityUtils.getCurrentUser() ); if( bookingNote.getChargeDate() == null ) { bookingNote.setChargeDate( new Date() ); } return SUCCESS; } @Override public String getJsonRates() { if( rates == null ) { Account account = null; if( incomes != null && !incomes.isEmpty() ) { for( Charge income : incomes ) { if( income.getAccountState() >= 0 ) { account = income.getAccount(); } } } if( account != null ) { rates = ServiceContextUtils.getService( AccountService.class ).loadAccountCurrencyRates( account ); } else { CurrencyRateService rateService = ServiceContextUtils.getService( CurrencyRateService.class ); rates = rateService.loadLatestCurrencyRates(bookingNote.getChargeDate()); } } return serializeList( rates ); } }
package org.languagetool.tokenizers.de; import com.google.common.base.Suppliers; import de.danielnaber.jwordsplitter.EmbeddedGermanDictionary; import de.danielnaber.jwordsplitter.GermanWordSplitter; import de.danielnaber.jwordsplitter.InputTooLongException; import gnu.trove.THashSet; import org.languagetool.tokenizers.Tokenizer; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.function.Supplier; import static java.util.Arrays.asList; /** * Split German nouns using the jWordSplitter library. * * @author Daniel Naber */ public class GermanCompoundTokenizer implements Tokenizer { private static final Supplier<GermanCompoundTokenizer> strictInstance = Suppliers.memoize(() -> { try { return new GermanCompoundTokenizer(true); } catch (IOException e) { throw new RuntimeException(e); } }); private static final Supplier<GermanCompoundTokenizer> nonStrictInstance = Suppliers.memoize(() -> { try { return new GermanCompoundTokenizer(false); } catch (IOException e) { throw new RuntimeException(e); } }); private final ExtendedGermanWordSplitter wordSplitter; public GermanCompoundTokenizer() throws IOException { this(true); } static class ExtendedGermanWordSplitter extends GermanWordSplitter { ExtendedGermanWordSplitter(boolean hideInterfixCharacters) throws IOException { super(hideInterfixCharacters, extendedList()); } static Set<String> extendedList() { THashSet<String> words = new THashSet<>(EmbeddedGermanDictionary.getWords()); // add compound parts here so we don't need to update JWordSplitter for every missing word we find: words.add("synonym"); words.trimToSize(); return words; } } public GermanCompoundTokenizer(boolean strictMode) throws IOException { wordSplitter = new ExtendedGermanWordSplitter(false); // add exceptions here so we don't need to update JWordSplitter for every exception we find: //wordSplitter.addException("Maskerade", Collections.singletonList("Maskerade")); //wordSplitter.addException("Sportshorts", asList("Sport", "shorts")); wordSplitter.addException("Reinigungstab", asList("Reinigungs", "tab")); wordSplitter.addException("Reinigungstabs", asList("Reinigungs", "tabs")); wordSplitter.addException("Tauschwerte", asList("Tausch", "werte")); wordSplitter.addException("Tauschwertes", asList("Tausch", "wertes")); wordSplitter.addException("Kinderspielen", asList("Kinder", "spielen")); wordSplitter.setStrictMode(strictMode); wordSplitter.setMinimumWordLength(3); } @Override public List<String> tokenize(String word) { try { return wordSplitter.splitWord(word); } catch (InputTooLongException e) { return Collections.singletonList(word); } } public static GermanCompoundTokenizer getStrictInstance() { return strictInstance.get(); } public static GermanCompoundTokenizer getNonStrictInstance() { return nonStrictInstance.get(); } public static void main(String[] args) throws IOException { if (args.length == 0) { System.out.println("Usage: " + GermanCompoundTokenizer.class.getSimpleName() + " <wordsToSplit..>"); System.exit(1); } GermanCompoundTokenizer tokenizer = new GermanCompoundTokenizer(); for (String arg : args) { System.out.println(tokenizer.tokenize(arg)); } } }
import java.net.DatagramPacket; import java.net.InetSocketAddress; import java.nio.ByteBuffer; public class RequestFromUIControllerToGetaResource extends RequestFromUIController implements Runnable { /** * * Miguel Velez * April 29, 2015 * * This class is a request from ui controller to get a resource * * Class variables: * * boolean[] responses; * the part numbers that correspond to responses of this request * * Constructors: * * public RequestFromUIControllerToGetaResource(ID id) * create a request to find resources from peers * * Methods: * * public void updateRequest(UDPMessage udpMessage); * update the request * * public void run() * Process packets from the UI and community * * public Thread startAsThread() * Start this class as a thread * * * Modification History: * * May 7, 2015 * Original version. * * May 13, 2015 * Implemented getting a part number and sending to UI. * * May 14, 2015 * Using a thread to synchronize the sending and receiving. * */ private boolean[] responses; private ID resourceID; public RequestFromUIControllerToGetaResource(ID id, ID resourceId, InetSocketAddress uiController, OutgoingPacketQueue outgoingPacket, int numberOfParts) { // Create a request to find resources from peers // Call the super constructor super(id, uiController, outgoingPacket); this.resourceID = resourceId; this.responses = new boolean[numberOfParts]; // System.out.println(this.responses.length); } @Override public void updateRequest(UDPMessage udpMessage) { // Send the datagram packet to the UI controller // Check if null if(udpMessage == null) { throw new IllegalArgumentException("The UDP message that you provided is null"); } // Get the request part byte[] partRequested = new byte[PartNumbers.getLengthInBytes()]; System.arraycopy(udpMessage.getMessage(), ID.getLengthInBytes(), partRequested, 0, PartNumbers.getLengthInBytes()); // System.out.println(partRequested[0] + " - " + partRequested[1] + " - " + partRequested[2] + " - " + partRequested[3]); // Get the integer representation of the part int partNumberRequested = ByteBuffer.wrap(partRequested).getInt(); // // Get an int from a byte array // for(int i = 0; i < PartNumbers.getLengthInBytes(); i++) { // partNumberRequested = partNumberRequested | ((partRequested[i] & 0xFF) << ((PartNumbers.getLengthInBytes() - 1 - i) * 8)); // System.out.println("Part requested: " + partNumberRequested); // System.out.println("Before synchronize"); // Synchronize the responses array synchronized(this.responses) { // System.out.println("Have we seen this part: " + partNumberRequested + " - " + this.responses[partNumberRequested]); // Check if we have seen this response before if(!this.responses[partNumberRequested]) { // System.out.println("Part not seen before"); // Add a response with the part number this.responses[partNumberRequested] = new Boolean(true); // Get the response packet byte[] responseMessage = udpMessage.getMessage(); // Get the bytes that we requested byte[] bytesToSend = new byte[488]; // Pass the resource id System.arraycopy(udpMessage.getID1().getBytes(), 0, bytesToSend, 0, ID.getLengthInBytes()); // Get the starting byte long startByte = partNumberRequested * (UDPMessage.getMaximumPacketSizeInBytes() - ID.getLengthInBytes() - (4)); // System.out.println("start bytes: " + startByte); byte[] byteNumber = ByteBuffer.allocate(8).putLong(startByte).array(); // System.out.println(byteNumber[0] + " - " + byteNumber[1] + " - " + byteNumber[2] + " - " + byteNumber[3] + " - " + byteNumber[4] + " - " + byteNumber[5] + " - " + byteNumber[6] + " - " + byteNumber[7]); // Put the 4 bytes of the starting byte at the 16 slot to send System.arraycopy(byteNumber, 0, bytesToSend, ID.getLengthInBytes(), 8); // Get the end byte long endByte = startByte + (UDPMessage.getMaximumPacketSizeInBytes() - ID.getLengthInBytes() - (4)); // System.out.println("End bytes: " + endByte); byteNumber = ByteBuffer.allocate(8).putLong(endByte).array(); // System.out.println(byteNumber[0] + " - " + byteNumber[1] + " - " + byteNumber[2] + " - " + byteNumber[3] + " - " + byteNumber[4] + " - " + byteNumber[5] + " - " + byteNumber[6] + " - " + byteNumber[7]); // Put the 4 bytes of the end byte in spot 20 of the bytes to send System.arraycopy(byteNumber, 0, bytesToSend, (8) + ID.getLengthInBytes(), (8)); // Copy the bytes to send System.arraycopy(responseMessage, ID.getLengthInBytes() + 4, bytesToSend, (16) + ID.getLengthInBytes(), 456); // System.out.println("Sending bytes to UI: " + bytesToSend.length); // Create a new datagram DatagramPacket resourceBytes = new DatagramPacket(bytesToSend, bytesToSend.length); // Set the address of the UICOntroller resourceBytes.setAddress(this.getUIControllerAddress().getAddress()); // Set the port of the UIController resourceBytes.setPort(this.getUIControllerAddress().getPort()); resourceBytes.setData(bytesToSend); //System.out.println(new String(bytesToSend)); // Send the bytes as start, end, bytes this.getQueue().enQueue(resourceBytes); // System.out.println("Sent to ui part:" + partNumberRequested); // Notify to get a new part this.responses.notify(); } } } @Override public void run() { for (int i = 0; i < this.responses.length; i++) { // Synchronize the responses array synchronized(this.responses) { // Get a byte array from the part number byte[] partNumber = new byte[4]; // for(int j = 0; j < PartNumbers.getLengthInBytes(); j++) { // partNumber[j] = (byte) (i >> ((PartNumbers.getLengthInBytes() - 1 - j) * 8)); int temp = i; // System.out.println("\n" + i); for(int j = PartNumbers.getLengthInBytes() - 1; j >= 0; j partNumber[j] = (byte) (temp & 0xFF); temp = temp >>> 8; // System.out.println(">>>> "+ (int)partNumber[j]); } // partNumber = ByteBuffer.allocate(4).putInt(i).array(); // System.out.println(i+":"+ByteBuffer.wrap(partNumber).getInt()); byte[] message = new byte[ID.getLengthInBytes() + PartNumbers.getLengthInBytes()]; // new String(ID.idFactory().getBytes()) + new String(partNumber) System.arraycopy(ID.idFactory().getBytes(), 0, message, 0, ID.getLengthInBytes()); System.arraycopy(partNumber, 0, message, ID.getLengthInBytes(), PartNumbers.getLengthInBytes()); // Create a UDP message with format RequestID, ResourceID, TTL, RandomID, partNumber UDPMessage getMessage = new UDPMessage(this.getID(), this.resourceID, new TimeToLive(), message); // Send to peers GossipPartners.getInstance().send(getMessage); // System.out.println("Requested part: " + i); // While we have not receive the part number that we requested while(!this.responses[i]) { try { // Wait this.responses.wait(); } catch (InterruptedException ei) { } } } } } public Thread startAsThread() { Thread thread = new Thread(); thread = new Thread(this); // Execute the run method thread.start(); return thread; } }
package finvoice2csv; import static org.junit.Assert.*; import java.io.File; import java.math.BigDecimal; import org.junit.Before; import org.junit.Test; import org.niklas.finvoice2csv.model.Finvoice; import org.niklas.finvoice2csv.util.mappers.Xml2ModelMapper; import org.niklas.finvoice2csv.util.mappers.Xml2ModelMapperImpl; public class Xml2ModelMapperTest { private Finvoice finvoice; @Before public void setUp() { Xml2ModelMapper mapper = new Xml2ModelMapperImpl(); finvoice = mapper.getFinvoiceFromXml(new File("test/res/lasku.xml")); } @Test public void testBuyerPartyIdentifier() { assertTrue(finvoice.getBuyerPartyDetails().getBuyerPartyIdentifier() .equals("0836922-4")); } @Test public void testBuyerOrganisationName() { assertTrue(finvoice.getBuyerPartyDetails().getBuyerOrganisationName() .equals("ProCountor International Oy")); } @Test public void testBuyerStreetName() { assertTrue(finvoice.getBuyerPartyDetails() .getBuyerPostalAddressDetails().getBuyerStreetName() .equals("Maapallonkuja 1 A")); } @Test public void testBuyerTownName() { assertTrue(finvoice.getBuyerPartyDetails() .getBuyerPostalAddressDetails().getBuyerTownName() .equals("ESPOO")); } @Test public void testBuyerPostcodeIdentifier() { assertTrue(finvoice.getBuyerPartyDetails() .getBuyerPostalAddressDetails().getBuyerPostCodeIdentifier() .equals("02150")); } @Test public void testBuyerCountryCode() { assertTrue(finvoice.getBuyerPartyDetails() .getBuyerPostalAddressDetails().getCountryCode().equals("FI")); } @Test public void testDeliveryOrganisationName() { assertTrue(finvoice.getDeliveryPartyDetails() .getDeliveryOrganisationName() .equals("ProCountor International Oy")); } @Test public void testDeliveryStreetName() { assertTrue(finvoice.getDeliveryPartyDetails() .getDeliveryPostalAddressDetails().getDeliveryStreetName() .equals("Keilaranta 8")); } @Test public void testDeliveryTownName() { assertTrue(finvoice.getDeliveryPartyDetails() .getDeliveryPostalAddressDetails().getDeliveryTownName() .equals("ESPOO")); } @Test public void testDeliveryPostcodeIdentifier() { assertTrue(finvoice.getDeliveryPartyDetails() .getDeliveryPostalAddressDetails() .getDeliveryPostCodeIdentifier().equals("02150")); } @Test public void testDeliveryCountryCode() { assertTrue(finvoice.getDeliveryPartyDetails() .getDeliveryPostalAddressDetails().getCountryCode() .equals("FI")); } // TODO TEST DATES!!!! @Test public void testInvoiceTypeCode() { assertTrue(finvoice.getInvoiceDetails().getInvoiceTypeCode() .equals("M")); } @Test public void testInvoiceTotalVatExcludedAmount() { assertTrue(finvoice.getInvoiceDetails() .getInvoiceTotalVatExcludedAmount() .equals(new BigDecimal("2450.00"))); } @Test public void testInvoiceTotalVatAmount() { assertTrue(finvoice.getInvoiceDetails().getInvoiceTotalVatAmount() .equals(new BigDecimal("563.50"))); } @Test public void testPaymentOverDueFinePercent() { assertTrue(finvoice.getInvoiceDetails().getPaymentTermsDetails() .getPaymentOverDueFineDetails().getPaymentOverDueFinePercent() .equals(new BigDecimal("10.5"))); } @Test public void testInvoiceRowArticleIdentifier() { assertTrue(finvoice.getInvoiceRow().get(1).getArticleIdentifier() .equals("SA2")); } @Test public void testInvoiceRowArticleName() { assertTrue(finvoice.getInvoiceRow().get(1).getArticleName() .equals("Premium Saula Cafe espressonapit")); } @Test public void testInvoiceRowOrderedQuantity() { assertTrue(finvoice.getInvoiceRow().get(1).getOrderedQuantity() == 1000); } @Test public void testInvoiceRowUnitPrice() { assertTrue(finvoice.getInvoiceRow().get(1).getUnitPriceAmount() .equals(new BigDecimal("0.15"))); } @Test public void testInvoiceRowVatPercent() { assertTrue(finvoice.getInvoiceRow().get(1).getRowVatRatePercent() == 23); } @Test public void testInvoiceRowVatAmount() { assertTrue(finvoice.getInvoiceRow().get(1).getRowVatAmount() .equals(new BigDecimal("34.50"))); } @Test public void testInvoiceRowVatExcludedAmount() { assertTrue(finvoice.getInvoiceRow().get(1).getRowVatExcludedAmount() .equals(new BigDecimal("150.00"))); } @Test public void testInvoiceRowAmount() { assertTrue(finvoice.getInvoiceRow().get(1).getRowAmount() .equals(new BigDecimal("184.50"))); } }
package memorymeasurer; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.base.Supplier; import com.google.common.base.Throwables; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.HashBiMap; import com.google.common.collect.HashMultimap; import com.google.common.collect.HashMultiset; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.MapMaker; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.google.common.collect.TreeMultimap; import com.google.common.collect.TreeMultiset; import java.lang.reflect.Constructor; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.Map; import java.util.PriorityQueue; import java.util.TreeMap; import java.util.TreeSet; import java.util.WeakHashMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.DelayQueue; import java.util.concurrent.Delayed; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.PriorityBlockingQueue; import java.util.concurrent.TimeUnit; import objectexplorer.MemoryMeasurer; import objectexplorer.ObjectGraphMeasurer; import objectexplorer.ObjectGraphMeasurer.Footprint; public class ElementCostOfDataStructures { public static void main(String[] args) throws Exception { ImmutableList.Builder<Analyzer> builder = ImmutableList.builder(); builder.add(Analyzer.createCollection("ArrayList", defaultSupplierFor(ArrayList.class))); builder.add(Analyzer.createCollection("LinkedList", defaultSupplierFor(LinkedList.class))); builder.add(Analyzer.createCollection("ArrayDeque", defaultSupplierFor(ArrayDeque.class))); builder.add(Analyzer.createCollection("HashSet", defaultSupplierFor(HashSet.class))); builder.add(Analyzer.createCollection("LinkedHashSet", defaultSupplierFor(LinkedHashSet.class))); builder.add(Analyzer.createCollection("PriorityQueue", defaultSupplierFor(PriorityQueue.class), Analyzer.ElementType.COMPARABLE)); builder.add(Analyzer.createCollection("PriorityBlockingQueue", defaultSupplierFor(PriorityBlockingQueue.class), Analyzer.ElementType.DELAYED)); builder.add(Analyzer.createCollection("TreeSet", defaultSupplierFor(TreeSet.class), Analyzer.ElementType.COMPARABLE)); builder.add(Analyzer.createCollection("ConcurrentSkipListSet", defaultSupplierFor(ConcurrentSkipListSet.class), Analyzer.ElementType.COMPARABLE)); builder.add(Analyzer.createCollection("CopyOnWriteArrayList", defaultSupplierFor(CopyOnWriteArrayList.class))); builder.add(Analyzer.createCollection("CopyOnWriteArraySet", defaultSupplierFor(CopyOnWriteArraySet.class))); builder.add(Analyzer.createCollection("DelayQueue", defaultSupplierFor(DelayQueue.class), Analyzer.ElementType.DELAYED)); builder.add(Analyzer.createCollection("LinkedBlockingQueue", defaultSupplierFor(LinkedBlockingQueue.class))); builder.add(Analyzer.createCollection("LinkedBlockingDeque", defaultSupplierFor(LinkedBlockingDeque.class))); builder.add(Analyzer.createMap("HashMap", defaultSupplierFor(HashMap.class))); builder.add(Analyzer.createMap("LinkedHashMap", defaultSupplierFor(LinkedHashMap.class))); builder.add(Analyzer.createMap("TreeMap", defaultSupplierFor(TreeMap.class), Analyzer.ElementType.COMPARABLE)); builder.add(Analyzer.createMap("WeakHashMap", defaultSupplierFor(WeakHashMap.class))); builder.add(Analyzer.createMap("ConcurrentHashMap", defaultSupplierFor(ConcurrentHashMap.class))); builder.add(Analyzer.createMap("MapMaker", new Supplier<Map>() { public Map get() { return new MapMaker().makeMap(); } })); builder.add(Analyzer.createMap("MapMaker_Expires", new Supplier<Map>() { public Map get() { return new MapMaker().expiration(5, TimeUnit.DAYS).makeMap(); } })); builder.add(Analyzer.createMap("MapMaker_Evicts", new Supplier<Map>() { public Map get() { return new MapMaker().maximumSize(1000000).makeMap(); } })); builder.add(Analyzer.createMap("MapMaker_Expires", new Supplier<Map>() { public Map get() { return new MapMaker().expiration(5, TimeUnit.DAYS).makeMap(); } })); builder.add(Analyzer.createMap("MapMaker_Expires", new Supplier<Map>() { public Map get() { return new MapMaker().expiration(5, TimeUnit.DAYS).makeMap(); } })); builder.add(Analyzer.createMap("MapMaker_Expires", new Supplier<Map>() { public Map get() { return new MapMaker().expiration(5, TimeUnit.DAYS).makeMap(); } })); builder.add(Analyzer.createMap("MapMaker_ExpiresEvicts", new Supplier<Map>() { public Map get() { return new MapMaker().maximumSize(1000000).expiration(3, TimeUnit.DAYS).makeMap(); } })); builder.add(Analyzer.createMap("MapMaker_SoftKeys", new Supplier<Map>() { public Map get() { return new MapMaker().softKeys().makeMap(); } })); builder.add(Analyzer.createMap("MapMaker_SoftValues", new Supplier<Map>() { public Map get() { return new MapMaker().softValues().makeMap(); } })); builder.add(Analyzer.createMap("MapMaker_SoftKeysValues", new Supplier<Map>() { public Map get() { return new MapMaker().softKeys().softValues().makeMap(); } })); builder.add(Analyzer.createMap("MapMaker_Evicts_SoftKeys", new Supplier<Map>() { public Map get() { return new MapMaker().maximumSize(1000000).softKeys().makeMap(); } })); builder.add(Analyzer.createMap("MapMaker_Evicts_SoftValues", new Supplier<Map>() { public Map get() { return new MapMaker().maximumSize(1000000).softValues().makeMap(); } })); builder.add(Analyzer.createMap("MapMaker_Evicts_SoftKeysValues", new Supplier<Map>() { public Map get() { return new MapMaker().maximumSize(1000000).softKeys().softValues().makeMap(); } })); builder.add(Analyzer.createMap("MapMaker_Expires_SoftKeys", new Supplier<Map>() { public Map get() { return new MapMaker().expiration(3, TimeUnit.DAYS).softKeys().makeMap(); } })); builder.add(Analyzer.createMap("MapMaker_Expires_SoftValues", new Supplier<Map>() { public Map get() { return new MapMaker().expiration(3, TimeUnit.DAYS).softValues().makeMap(); } })); builder.add(Analyzer.createMap("MapMaker_Expires_SoftKeysValues", new Supplier<Map>() { public Map get() { return new MapMaker().expiration(3, TimeUnit.DAYS).softKeys().softValues().makeMap(); } })); builder.add(Analyzer.createMap("MapMaker_ExpiresEvicts_SoftKeys", new Supplier<Map>() { public Map get() { return new MapMaker().maximumSize(1000000).expiration(3, TimeUnit.DAYS).softKeys().makeMap(); } })); builder.add(Analyzer.createMap("MapMaker_ExpiresEvicts_SoftValues", new Supplier<Map>() { public Map get() { return new MapMaker().maximumSize(1000000).expiration(3, TimeUnit.DAYS).softValues().makeMap(); } })); builder.add(Analyzer.createMap("MapMaker_ExpiresEvicts_SoftKeysValues", new Supplier<Map>() { public Map get() { return new MapMaker().maximumSize(1000000).expiration(3, TimeUnit.DAYS).softKeys().softValues().makeMap(); } })); builder.add(Analyzer.createCollection("HashMultiset (frequency=1)", new Supplier<Collection>() { public Collection get() { return HashMultiset.create(); } })); builder.add(Analyzer.createCollection("TreeMultiset (frequency=1)", new Supplier<Collection>() { public Collection get() { return TreeMultiset.create(); } }, Analyzer.ElementType.COMPARABLE)); builder.add(Analyzer.createMap("HashBiMap", new Supplier<Map>() { public Map get() { return HashBiMap.create(); } })); builder.add(Analyzer.createMultimapWorst("HashMultimap (Worst)", new Supplier<Multimap>() { public Multimap get() { return HashMultimap.create(); } })); builder.add(Analyzer.createMultimapBest("HashMultimap (Best)", new Supplier<Multimap>() { public Multimap get() { return HashMultimap.create(); } })); builder.add(Analyzer.createMultimapWorst("ArrayListMultimap (Worst)", new Supplier<Multimap>() { public Multimap get() { return ArrayListMultimap.create(); } })); builder.add(Analyzer.createMultimapBest("ArrayListMultimap (Best)", new Supplier<Multimap>() { public Multimap get() { return ArrayListMultimap.create(); } })); builder.add(Analyzer.createMultimapWorst("TreeMultimap (Worst)", new Supplier<Multimap>() { public Multimap get() { return TreeMultimap.create(); } }, Analyzer.ElementType.COMPARABLE)); builder.add(Analyzer.createMultimapBest("TreeMultimap (Best)", new Supplier<Multimap>() { public Multimap get() { return TreeMultimap.create(); } }, Analyzer.ElementType.COMPARABLE)); //immutable collections ImmutableList<Analyzer> analyzers = builder.build(); for (Analyzer analyzer : analyzers) { AvgEntryCost cost = analyzer.averageEntryCost(16, 1024 * 31); System.out.printf("%40s -- Bytes = %6.2f, Objects = %5.2f Refs = %5.2f Primitives = %s%n", analyzer.getDescription(), cost.bytes, cost.objects, cost.refs, cost.primitives); } } private static class DefaultConstructorSupplier<C> implements Supplier<C> { private final Constructor<C> constructor; DefaultConstructorSupplier(Class<C> clazz) throws NoSuchMethodException { this.constructor = clazz.getConstructor(); } public C get() { try { return constructor.newInstance(); } catch (Exception e) { throw Throwables.propagate(e); } } } static <C> DefaultConstructorSupplier<C> defaultSupplierFor(Class<C> clazz) throws NoSuchMethodException { return new DefaultConstructorSupplier(clazz); } } interface Populator<C> { Class<?> entryType(); void addEntry(C target); } class Analyzer { private final String description; private final SupplierAndPopulator<?> supplierAndPopulator; Analyzer(String description, SupplierAndPopulator<?> supplierAndPopulator) { this.description = description; this.supplierAndPopulator = supplierAndPopulator; } static <C> Analyzer newAnalyzer(String description, Supplier<C> supplier, Populator<? super C> populator) { return new Analyzer(description, new SupplierAndPopulator<C>(supplier, populator)); } private static class Element { } private static class ComparableElement extends Element implements Comparable { public int compareTo(Object o) { return 1; } } private static class DelayedElement extends Element implements Delayed { public long getDelay(TimeUnit unit) { return 0; } public int compareTo(Delayed o) { return 1; } } enum ElementType { REGULAR { Class<?> getElementClass() { return Element.class; } Object createElement() { return new Element(); } }, COMPARABLE { Class<?> getElementClass() { return ComparableElement.class; } Object createElement() { return new ComparableElement(); } }, DELAYED { Class<?> getElementClass() { return DelayedElement.class; } Object createElement() { return new DelayedElement(); } }; abstract Class<?> getElementClass(); abstract Object createElement(); } //the purpose of this class is to not unnecessarily expose the parameter type in the outer class interface static class SupplierAndPopulator<C> { final Supplier<? extends C> supplier; final Populator<? super C> populator; SupplierAndPopulator(Supplier<? extends C> supplier, Populator<? super C> populator) { this.supplier = supplier; this.populator = populator; } class Population { C target = supplier.get(); void addEntry() { populator.addEntry(target); } } } AvgEntryCost averageEntryCost(int initialEntries, int entriesToAdd) { Preconditions.checkArgument(initialEntries >= 0, "initialEntries negative"); Preconditions.checkArgument(entriesToAdd > 0, "entriesToAdd negative or zero"); SupplierAndPopulator.Population population = supplierAndPopulator.new Population(); for (int i = 1; i <= initialEntries; i++) { population.addEntry(); } Predicate<Object> predicate = Predicates.not(Predicates.instanceOf( supplierAndPopulator.populator.entryType())); Footprint initialCost = ObjectGraphMeasurer.measure(population.target, predicate); long bytes1 = MemoryMeasurer.measureBytes(population.target, predicate); for (int i = 0; i < entriesToAdd; i++) { population.addEntry(); } Footprint finalCost = ObjectGraphMeasurer.measure(population.target, predicate); long bytes2 = MemoryMeasurer.measureBytes(population.target, predicate); double objects = (finalCost.getObjects() - initialCost.getObjects()) / (double) entriesToAdd; double refs = (finalCost.getReferences() - initialCost.getReferences()) / (double) entriesToAdd; double bytes = (bytes2 - bytes1) / (double)entriesToAdd; Map<Class<?>, Double> primitives = Maps.newHashMap(); for (Class<?> primitiveType : primitiveTypes) { int initial = initialCost.getPrimitives().count(primitiveType); int ending = finalCost.getPrimitives().count(primitiveType); if (initial != ending) { primitives.put(primitiveType, (ending - initial) / (double) entriesToAdd); } } return new AvgEntryCost(objects, refs, primitives, bytes); } private static final ImmutableSet<Class<?>> primitiveTypes = ImmutableSet.<Class<?>>of( boolean.class, byte.class, char.class, short.class, int.class, float.class, long.class, double.class); String getDescription() { return description; } static Analyzer createMap(String description, Supplier<? extends Map> supplier) { return createMap(description, supplier, ElementType.REGULAR); } static Analyzer createMap(String description, Supplier<? extends Map> supplier, final ElementType elementType) { return new Analyzer(description, new SupplierAndPopulator<Map>(supplier, new Populator<Map>() { public Class<?> entryType() { return elementType.getElementClass(); } public void addEntry(Map target) { Object x = elementType.createElement(); target.put(x, x); } })); } static Analyzer createCollection(String description, Supplier<? extends Collection> supplier) { return createCollection(description, supplier, ElementType.REGULAR); } static Analyzer createCollection(String description, Supplier<? extends Collection> supplier, final ElementType elementType) { return new Analyzer(description, new SupplierAndPopulator<Collection>(supplier, new Populator<Collection>() { public Class<?> entryType() { return elementType.getElementClass(); } public void addEntry(Collection target) { target.add(elementType.createElement()); } })); } static Analyzer createMultimapWorst(String description, Supplier<? extends Multimap> supplier) { return createMultimapWorst(description, supplier, ElementType.REGULAR); } static Analyzer createMultimapWorst(String description, Supplier<? extends Multimap> supplier, final ElementType elementType) { return new Analyzer(description, new SupplierAndPopulator<Multimap>(supplier, new Populator<Multimap>() { public Class<?> entryType() { return elementType.getElementClass(); } public void addEntry(Multimap target) { Object x = elementType.createElement(); target.put(x, x); } })); } static Analyzer createMultimapBest(String description, Supplier<? extends Multimap> supplier) { return createMultimapBest(description, supplier, ElementType.REGULAR); } static Analyzer createMultimapBest(String description, Supplier<? extends Multimap> supplier, final ElementType elementType) { return new Analyzer(description, new SupplierAndPopulator<Multimap>(supplier, new Populator<Multimap>() { public Class<?> entryType() { return elementType.getElementClass(); } final Object key = elementType.createElement(); public void addEntry(Multimap target) { target.put(key, elementType.createElement()); } })); } } class AvgEntryCost { final double objects; final double refs; final ImmutableMap<Class<?>, Double> primitives; final double bytes; AvgEntryCost(double objects, double refs, Map<Class<?>, Double> primitives, double bytes) { this.objects = objects; this.refs = refs; this.primitives = ImmutableMap.copyOf(primitives); this.bytes = bytes; } }
package hudson.scm; import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException; import com.gargoylesoftware.htmlunit.html.HtmlAnchor; import com.gargoylesoftware.htmlunit.html.HtmlButton; import com.gargoylesoftware.htmlunit.html.HtmlForm; import com.gargoylesoftware.htmlunit.html.HtmlPage; import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; import hudson.model.Result; import org.dom4j.Document; import org.dom4j.io.DOMReader; import org.jvnet.hudson.test.Bug; import org.jvnet.hudson.test.HudsonHomeLoader.CopyExisting; import org.jvnet.hudson.test.HudsonTestCase; import org.jvnet.hudson.test.Email; import org.jvnet.hudson.test.recipes.PresetData; import static org.jvnet.hudson.test.recipes.PresetData.DataSet.ANONYMOUS_READONLY; import java.io.File; /** * @author Kohsuke Kawaguchi */ public class SubversionSCMTest extends HudsonTestCase { @PresetData(ANONYMOUS_READONLY) @Bug(2380) public void testTaggingPermission() throws Exception { // create a build File svnRepo = new CopyExisting(getClass().getResource("/svn-repo.zip")).allocate(); FreeStyleProject p = createFreeStyleProject(); p.setScm(new SubversionSCM( new String[]{"file://"+svnRepo+"/trunk/a"}, new String[]{null}, true, null )); FreeStyleBuild b = p.scheduleBuild2(0).get(); System.out.println(b.getLog()); assertBuildStatus(Result.SUCCESS,b); SubversionTagAction action = b.getAction(SubversionTagAction.class); assertFalse(b.hasPermission(action.getPermission())); WebClient wc = new WebClient(); HtmlPage html = wc.getPage(b); // make sure there's no link to the 'tag this build' Document dom = new DOMReader().read(html); assertNull(dom.selectSingleNode("//A[text()='Tag this build']")); for( HtmlAnchor a : html.getAnchors() ) assertFalse(a.getHrefAttribute().contains("/tagBuild/")); // and that tagging would fail html = wc.getPage(b,"tagBuild/"); HtmlForm form = html.getFormByName("tag"); try { form.submit((HtmlButton)last(form.getHtmlElementsByTagName("button"))); fail("should have been denied"); } catch (FailingHttpStatusCodeException e) { // make sure the request is denied assertEquals(e.getResponse().getStatusCode(),403); } // now login as alice and make sure that the tagging would succeed wc = new WebClient(); wc.login("alice","alice"); html = wc.getPage(b,"tagBuild/"); form = html.getFormByName("tag"); form.submit((HtmlButton)last(form.getHtmlElementsByTagName("button"))); } @Email("http: public void testHttpsCheckOut() throws Exception { FreeStyleProject p = createFreeStyleProject(); p.setScm(new SubversionSCM( new String[]{"https://svn.dev.java.net/svn/hudson/trunk/hudson/test-projects/trivial-ant"}, new String[]{null}, true, null )); FreeStyleBuild b = p.scheduleBuild2(0).get(); System.out.println(b.getLog()); assertBuildStatus(Result.SUCCESS,b); assertTrue(p.getWorkspace().child("trivial-ant/build.xml").exists()); } @Email("http: public void testHttpCheckOut() throws Exception { FreeStyleProject p = createFreeStyleProject(); p.setScm(new SubversionSCM( new String[]{"http://svn.codehaus.org/plexus/tags/JASF_INIT/plexus-avalon-components/jasf/"}, new String[]{null}, true, null )); FreeStyleBuild b = p.scheduleBuild2(0).get(); System.out.println(b.getLog()); assertBuildStatus(Result.SUCCESS,b); assertTrue(p.getWorkspace().child("jasf/maven.xml").exists()); } }
package edu.utexas.cycic; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.embed.swing.SwingFXUtils; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.HPos; import javafx.geometry.Insets; import javafx.scene.SnapshotParameters; import javafx.scene.control.Button; import javafx.scene.control.ButtonBar.ButtonData; import javafx.scene.control.ButtonType; import javafx.scene.control.ColorPicker; import javafx.scene.control.ComboBox; import javafx.scene.control.ContextMenu; import javafx.scene.control.Dialog; import javafx.scene.control.Label; import javafx.scene.control.Menu; import javafx.scene.control.MenuItem; import javafx.scene.control.RadioButton; import javafx.scene.control.ScrollPane; import javafx.scene.control.SeparatorMenuItem; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.control.ToggleGroup; import javafx.scene.control.Tooltip; import javafx.scene.image.WritableImage; import javafx.scene.input.ClipboardContent; import javafx.scene.input.DragEvent; import javafx.scene.input.Dragboard; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; import javafx.scene.input.TransferMode; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.stage.FileChooser; import javafx.stage.Window; import javax.imageio.ImageIO; import org.apache.log4j.Logger; import edu.utah.sci.cyclist.Cyclist; import edu.utah.sci.cyclist.core.controller.CyclistController; import edu.utah.sci.cyclist.core.event.dnd.DnD; import edu.utah.sci.cyclist.core.model.CyclusJob; import edu.utah.sci.cyclist.core.model.CyclusJob.Status; import edu.utah.sci.cyclist.core.model.Preferences; import edu.utah.sci.cyclist.core.ui.components.ViewBase; import edu.utah.sci.cyclist.core.util.AwesomeIcon; import edu.utah.sci.cyclist.core.util.GlyphRegistry; public class Cycic extends ViewBase{ static Logger log = Logger.getLogger(Cycic.class); /** * Function for building the CYCIC Pane and GridPane of this view. */ public Cycic(){ super(); if (monthList.size() == 0){ months(); } if (CycicScenarios.cycicScenarios.size() < 1){ DataArrays scenario = new DataArrays(); workingScenario = scenario; CycicScenarios.cycicScenarios.add(scenario); } init(); } public static final String TITLE = "Cycic"; static Pane pane = new Pane(); Pane nodesPane = new Pane(); static facilityNode workingNode = null; static DataArrays workingScenario; static boolean marketHideBool = true; static Window window; static ToggleGroup opSwitch = new ToggleGroup(); static CyclusJob _remoteDashA; private static Object monitor = new Object(); static String currentSkin = "Default Skin"; static String currentServer = ""; static TextField duration = VisFunctions.numberField(); static ComboBox<String> startMonth = new ComboBox<String>(); static TextField startYear = VisFunctions.numberField(); static TextArea description = new TextArea(); static ComboBox<String> decay = new ComboBox<String>(); static TextField simHandle = new TextField(); static GridPane simInfo = new GridPane(){ { setHgap(4); setVgap(4); setPadding(new Insets(10, 10, 10, 10)); } }; static VBox simDetailBox = new VBox(){ { getChildren().add(simInfo); setStyle("-fx-border-style: solid;" + "-fx-border-width: 1;" + "-fx-border-color: black"); } }; static GridPane commodGrid = new GridPane(){ { setVgap(5); setHgap(5); } }; static Button addNewCommod = new Button(){ { setOnAction(new EventHandler<ActionEvent>(){ public void handle(ActionEvent e){ addNewCommodity(); } }); setText("+"); setStyle("-fx-font-size: 12;"); } }; static VBox commodBox = new VBox(){ { getChildren().add(new HBox(){ { getChildren().add(new Label(){ { setText("Simulation Commodities"); setTooltip(new Tooltip("Commodities facilitate the transfer of materials from one facility to another." + "Facilities with the same commodities are allowed to trade with each other.")); setFont(new Font("Times", 16)); } }); getChildren().add(addNewCommod); setSpacing(5); } }); getChildren().add(commodGrid); setPadding(new Insets(10, 10, 10, 10)); setSpacing(5); setStyle("-fx-border-style: solid;" + "-fx-border-width: 1;" + "-fx-border-color: black"); } }; GridPane archetypeGrid = new GridPane(){ { add(new Label(){ { setText("Add Available Archetypes"); setTooltip(new Tooltip("Use the drop down menu to select archetypes to add to the simulation.")); setFont(new Font("Times", 16)); } }, 0, 0); setStyle("-fx-border-style: solid;" + "-fx-border-width: 1;" + "-fx-border-color: black"); setVgap(5); setHgap(10); setPadding(new Insets(10, 10, 10, 10)); } }; private void updateLinkColor(){ ColorPicker cP = new ColorPicker(); cP.setOnAction(new EventHandler<ActionEvent>(){ public void handle(ActionEvent e){ for(nodeLink node: DataArrays.Links){ node.line.updateColor(cP.getValue()); } } }); Dialog dg = new Dialog(); ButtonType loginButtonType = new ButtonType("Ok", ButtonData.OK_DONE); dg.getDialogPane().setContent(cP); dg.getDialogPane().getButtonTypes().addAll(loginButtonType, ButtonType.CANCEL); dg.setResizable(true); dg.show(); } private void updateBgColor(){ ColorPicker cP = new ColorPicker(); cP.setOnAction(new EventHandler<ActionEvent>(){ public void handle(ActionEvent e){ String background = "-fx-background-color: background += cP.getValue().toString().substring(2, 8); pane.setStyle(background); } }); Dialog dg = new Dialog(); ButtonType loginButtonType = new ButtonType("Ok", ButtonData.OK_DONE); dg.getDialogPane().setContent(cP); dg.getDialogPane().getButtonTypes().addAll(loginButtonType, ButtonType.CANCEL); dg.setResizable(true); dg.show(); } private void setSkin() { if(currentSkin.equalsIgnoreCase("Default Skin")){ for(int j = 0; j < DataArrays.FacilityNodes.size(); j++){ DataArrays.FacilityNodes.get(j).cycicCircle.image.setVisible(false); DataArrays.FacilityNodes.get(j).cycicCircle.setOpacity(100); } } else { for(int i = 0; i < DataArrays.visualizationSkins.size(); i++){ skinSet skin = DataArrays.visualizationSkins.get(i); if(skin.name.equalsIgnoreCase(currentSkin)){ for(int j = 0; j < DataArrays.FacilityNodes.size(); j++){ DataArrays.FacilityNodes.get(j).cycicCircle.image.setImage(skin.images.getOrDefault(DataArrays.FacilityNodes.get(j).niche, skin.images.get("facility"))); DataArrays.FacilityNodes.get(j).cycicCircle.image.setVisible(true); DataArrays.FacilityNodes.get(j).cycicCircle.setOpacity(0); } } } } } /** * Initiates the Pane and GridPane. */ private void init(){ DataArrays.cycicInitLoader(); final ContextMenu paneMenu = new ContextMenu(); MenuItem linkColor = new MenuItem("Change Link Color..."); linkColor.setOnAction(new EventHandler<ActionEvent>(){ public void handle(ActionEvent e){ updateLinkColor(); } }); MenuItem bgColor = new MenuItem("Change Background Color..."); bgColor.setOnAction(new EventHandler<ActionEvent>(){ public void handle(ActionEvent e){ updateBgColor(); } }); Menu skinMenu = new Menu("Change skin"); MenuItem defSkin = new MenuItem("Default Skin"); defSkin.setOnAction(new EventHandler<ActionEvent>(){ public void handle(ActionEvent e){ currentSkin = "Default Skin"; setSkin(); } }); skinMenu.getItems().add(defSkin); for(int i = 0; i < DataArrays.visualizationSkins.size(); i++){ final String skinName = DataArrays.visualizationSkins.get(i).name; if (skinName.equals("DSARR")) { currentSkin = skinName; } MenuItem item = new MenuItem(skinName); item.setOnAction(new EventHandler<ActionEvent>(){ public void handle(ActionEvent e){ currentSkin = skinName; setSkin(); } }); skinMenu.getItems().add(item); } MenuItem imageExport = new MenuItem("Save fuel cycle diagram"); imageExport.setOnAction(new EventHandler<ActionEvent>(){ public void handle(ActionEvent e){ export(); } }); paneMenu.getItems().addAll(linkColor,bgColor,skinMenu,new SeparatorMenuItem(), imageExport); pane.setOnMouseClicked(new EventHandler<MouseEvent>(){ public void handle(MouseEvent e){ if(e.getButton().equals(MouseButton.SECONDARY)){ paneMenu.show(pane,e.getScreenX(),e.getScreenY()); } } }); pane.setOnDragOver(new EventHandler <DragEvent>(){ public void handle(DragEvent event){ event.acceptTransferModes(TransferMode.ANY); } }); pane.setOnDragDropped(new EventHandler<DragEvent>(){ public void handle(DragEvent event){ if(event.getDragboard().hasContent(DnD.VALUE_FORMAT)){ facilityNode facility = new facilityNode(); facility.facilityType = event.getDragboard().getContent(DnD.VALUE_FORMAT).toString(); facility.facilityType.trim(); for (int i = 0; i < DataArrays.simFacilities.size(); i++){ if(DataArrays.simFacilities.get(i).facilityName.equalsIgnoreCase(facility.facilityType)){ facility.facilityStructure = DataArrays.simFacilities.get(i).facStruct; facility.niche = DataArrays.simFacilities.get(i).niche; facility.doc = DataArrays.simFacilities.get(i).doc; facility.archetype = DataArrays.simFacilities.get(i).facilityArch; } } event.consume(); facility.name = ""; facility.facLifetime = ""; facility.cycicCircle = CycicCircles.addNode((String)facility.name, facility); facility.cycicCircle.setCenterX(event.getX()); facility.cycicCircle.setCenterY(event.getY()); VisFunctions.placeTextOnCircle(facility.cycicCircle, "middle"); for(int i = 0; i < DataArrays.visualizationSkins.size(); i++){ if(DataArrays.visualizationSkins.get(i).name.equalsIgnoreCase(currentSkin)){ facility.cycicCircle.image.setImage(DataArrays.visualizationSkins.get(i).images.getOrDefault(facility.niche,DataArrays.visualizationSkins.get(i).images.get("facility"))); facility.cycicCircle.image.setVisible(true); facility.cycicCircle.setOpacity(0); facility.cycicCircle.setRadius(DataArrays.visualizationSkins.get(i).radius); VisFunctions.placeTextOnCircle(facility.cycicCircle, DataArrays.visualizationSkins.get(i).textPlacement); } } facility.cycicCircle.image.setLayoutX(facility.cycicCircle.getCenterX()-60); facility.cycicCircle.image.setLayoutY(facility.cycicCircle.getCenterY()-60); facility.sorterCircle = SorterCircles.addNode((String)facility.name, facility, facility); FormBuilderFunctions.formArrayBuilder(facility.facilityStructure, facility.facilityData); } else { event.consume(); } } }); setTitle(TITLE); setOnMousePressed(new EventHandler<MouseEvent>(){ public void handle(MouseEvent e){ CycicScenarios.workingCycicScenario = workingScenario; } }); VBox cycicBox = new VBox(); cycicBox.autosize(); pane.autosize(); pane.setId("cycicPane"); pane.setPrefSize(1000, 600); pane.setStyle("-fx-background-color: white;"); // Temp Toolbar // final GridPane grid = new GridPane(); grid.setStyle("-fx-background-color: #d6d6d6;" + "-fx-font-size: 14;"); grid.setHgap(10); grid.setVgap(5); createArchetypeBar(grid); // Adding a new Facility // Label scenetitle1 = new Label("Add Prototype"); grid.add(scenetitle1, 0, 0); Label facName = new Label("Name"); grid.add(facName, 1, 0); // Name Field final TextField facNameField = new TextField(); grid.add(facNameField, 2, 0); // Facility Type final ComboBox<String> structureCB = new ComboBox<String>(); structureCB.setOnMousePressed(new EventHandler<MouseEvent>(){ public void handle(MouseEvent m){ structureCB.getItems().clear(); for(int i = 0; i < DataArrays.simFacilities.size(); i++){ structureCB.getItems().add((String) DataArrays.simFacilities.get(i).facilityName); } } }); structureCB.setPromptText("Select Facility Archetype"); grid.add(structureCB, 3, 0); //Submit Button Button submit1 = new Button("Add"); submit1.setOnAction(new EventHandler<ActionEvent>(){ @Override public void handle(ActionEvent event){ if (structureCB.getValue() == null){ return; } facilityNode facility = new facilityNode(); facility.facilityType = structureCB.getValue(); facility.facilityType.trim(); addArcheToBar(facility.facilityType); for (int i = 0; i < DataArrays.simFacilities.size(); i++){ if(DataArrays.simFacilities.get(i).facilityName.equalsIgnoreCase(facility.facilityType)){ facility.facilityStructure = DataArrays.simFacilities.get(i).facStruct; facility.niche = DataArrays.simFacilities.get(i).niche; facility.doc = DataArrays.simFacilities.get(i).doc; facility.archetype = DataArrays.simFacilities.get(i).facilityArch; } } event.consume(); facility.name = facNameField.getText(); facility.facLifetime = ""; facility.cycicCircle = CycicCircles.addNode((String)facility.name, facility); facility.cycicCircle.setCenterX(80); facility.cycicCircle.setCenterY(80); VisFunctions.placeTextOnCircle(facility.cycicCircle, "middle"); for(int i = 0; i < DataArrays.visualizationSkins.size(); i++){ if(DataArrays.visualizationSkins.get(i).name.equalsIgnoreCase(currentSkin)){ facility.cycicCircle.image.setImage(DataArrays.visualizationSkins.get(i).images.getOrDefault(facility.niche,DataArrays.visualizationSkins.get(i).images.get("facility"))); facility.cycicCircle.image.setVisible(true); facility.cycicCircle.setOpacity(0); facility.cycicCircle.setRadius(DataArrays.visualizationSkins.get(i).radius); VisFunctions.placeTextOnCircle(facility.cycicCircle, DataArrays.visualizationSkins.get(i).textPlacement); } } facility.cycicCircle.image.setLayoutX(facility.cycicCircle.getCenterX()-60); facility.cycicCircle.image.setLayoutY(facility.cycicCircle.getCenterY()-60); facility.sorterCircle = SorterCircles.addNode((String)facility.name, facility, facility); FormBuilderFunctions.formArrayBuilder(facility.facilityStructure, facility.facilityData); } }); grid.add(submit1, 4, 0); ScrollPane scroll = new ScrollPane(); scroll.setMinHeight(120); scroll.setContent(nodesPane); // opSwitch.getToggles().clear(); // opSwitch.getToggles().addAll(localToggle, remoteToggle); // try { // Process readproc = Runtime.getRuntime().exec("cyclus -V"); // new BufferedReader(new InputStreamReader(readproc.getInputStream())); // localToggle.setSelected(true); // } catch (RuntimeException | IOException e) { // localToggle.setSelected(false); // remoteToggle.setSelected(true); cycicBox.getChildren().addAll(grid, scroll, pane); HBox mainView = new HBox(){ { setSpacing(5); } }; details(); VBox sideView = new VBox(){ { setSpacing(5); setStyle("-fx-border-style: solid;" + "-fx-border-width: 1;" + "-fx-border-color: black"); } }; sideView.getChildren().addAll(simDetailBox, archetypeGrid, commodBox); mainView.getChildren().addAll(sideView, cycicBox); setContent(mainView); } /** * * @param circle * @param i * @param name */ public void buildDnDCircle(FacilityCircle circle, int i, String name){ circle.setRadius(40); circle.setStroke(Color.BLACK); circle.rgbColor=VisFunctions.stringToColor(name); circle.setFill(VisFunctions.pastelize(Color.rgb(circle.rgbColor.get(0),circle.rgbColor.get(1),circle.rgbColor.get(2)))); circle.setCenterX(45+(i*90)); circle.setCenterY(50); circle.text.setText(name.split(" ")[2] + " (" + name.split(" ")[1] + ")"); VisFunctions.placeTextOnCircle(circle, "middle"); circle.setOnDragDetected(new EventHandler<MouseEvent>(){ public void handle(MouseEvent e){ Dragboard db = circle.startDragAndDrop(TransferMode.COPY); ClipboardContent content = new ClipboardContent(); content.put(DnD.VALUE_FORMAT, name); db.setContent(content); e.consume(); } }); } public static void buildCommodPane(){ commodGrid.getChildren().clear(); for (int i = 0; i < Cycic.workingScenario.CommoditiesList.size(); i++){ CommodityNode commod = Cycic.workingScenario.CommoditiesList.get(i); TextField commodity = new TextField(); commodity.setText(commod.name.getText()); commodGrid.add(commodity, 0, i ); final int index = i; commodity.setPromptText("Enter Commodity Name"); commodity.textProperty().addListener(new ChangeListener<String>(){ public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue){ commod.name.setText(newValue); } }); commodGrid.add(new Label("Priority"), 1, index); TextField priority = VisFunctions.numberField(); priority.textProperty().addListener(new ChangeListener<String>(){ public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue){ commod.priority = Double.parseDouble(newValue); } }); priority.setPromptText("Enter Commodity Prioirty"); priority.setText("1"); commodGrid.add(priority, 2, index); Button removeCommod = new Button(); removeCommod.setGraphic(GlyphRegistry.get(AwesomeIcon.TRASH_ALT, "10px")); removeCommod.setOnAction(new EventHandler<ActionEvent>(){ public void handle(ActionEvent e){ String commod = Cycic.workingScenario.CommoditiesList.get(index).name.getText(); Cycic.workingScenario.CommoditiesList.remove(index); for(facilityNode facility: DataArrays.FacilityNodes){ for(int i =0; i < facility.cycicCircle.incommods.size(); i++){ if(facility.cycicCircle.incommods.get(i) == commod){ facility.cycicCircle.incommods.remove(i); } } for(int i =0; i < facility.cycicCircle.outcommods.size(); i++){ if(facility.cycicCircle.outcommods.get(i) == commod){ facility.cycicCircle.outcommods.remove(i); } } } VisFunctions.redrawPane(); buildCommodPane(); } }); commodGrid.add(removeCommod, 3, index); } } /** * Adds a new TextField to the commodity GridPane tied to a new commodity in the * simulation. */ static public void addNewCommodity(){ CommodityNode commodity = new CommodityNode(); commodity.name.setText(""); Cycic.workingScenario.CommoditiesList.add(commodity); TextField newCommod = new TextField(); newCommod.autosize(); newCommod.setPromptText("Enter Commodity Name"); newCommod.textProperty().addListener(new ChangeListener<String>(){ public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue){ commodity.name.setText(newValue); } }); buildCommodPane(); } HashMap<String, String> months = new HashMap<String, String>(); ArrayList<String> monthList = new ArrayList<String>(); /** * Quick hack to convert months into their integer values. * i.e. January = 0, Feb = 1, etc... */ public void months(){ monthList.add("January"); monthList.add("February"); monthList.add("March"); monthList.add("April"); monthList.add("May"); monthList.add("June"); monthList.add("July"); monthList.add("August"); monthList.add("September"); monthList.add("October"); monthList.add("November"); monthList.add("December"); months.put("January", "1"); months.put("Febuary", "2"); months.put("March", "3"); months.put("April", "4"); months.put("May", "5"); months.put("June", "6"); months.put("July", "7"); months.put("August", "8"); months.put("September", "9"); months.put("October", "10"); months.put("November", "11"); months.put("December", "12"); } public void details(){ Label simDets = new Label("Simulation Details"); simDets.setTooltip(new Tooltip("The top level details of the simulation.")); simDets.setFont(new Font("Times", 16)); simInfo.add(simDets, 0, 0, 2, 1); duration.setMaxWidth(150); duration.setPromptText("Length of Simulation"); duration.setText(Cycic.workingScenario.simulationData.duration); Cycic.workingScenario.simulationData.duration = "0"; duration.textProperty().addListener(new ChangeListener<String>(){ public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue){ Cycic.workingScenario.simulationData.duration = newValue; } }); simInfo.add(new Label("Duration (Months)"), 0, 1, 2, 1); simInfo.add(duration, 2, 1); for(int i = 0; i < 12; i++ ){ startMonth.getItems().add(monthList.get(i)); } Cycic.workingScenario.simulationData.startMonth = "1"; startMonth.setValue(monthList.get(Integer.parseInt(Cycic.workingScenario.simulationData.startMonth)-1)); startMonth.valueProperty().addListener(new ChangeListener<String>(){ public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue){ Cycic.workingScenario.simulationData.startMonth = months.get(newValue); } }); startMonth.setPromptText("Select Month"); simInfo.add(new Label("Start Month"), 0, 2, 2, 1); simInfo.add(startMonth, 2, 2); startYear.setText(Cycic.workingScenario.simulationData.startYear); Cycic.workingScenario.simulationData.startYear = "0"; startYear.textProperty().addListener(new ChangeListener<String>(){ public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue){ Cycic.workingScenario.simulationData.startYear = newValue; } }); startYear.setPromptText("Starting Year"); startYear.setMaxWidth(150); simInfo.add(new Label("Start Year"), 0, 3, 2, 1); simInfo.add(startYear, 2, 3); decay.getItems().addAll("manual", "never"); decay.setValue("Never"); Cycic.workingScenario.simulationData.decay = "never"; decay.setOnAction(new EventHandler<ActionEvent>(){ public void handle(ActionEvent e){ Cycic.workingScenario.simulationData.decay = decay.getValue(); } }); simInfo.add(new Label("Decay"), 0, 4); simInfo.add(decay, 2, 4); simHandle.setPromptText("Optional Simulation Name"); simHandle.textProperty().addListener(new ChangeListener<String>(){ public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue){ Cycic.workingScenario.simulationData.simHandle = newValue; } }); simInfo.add(new Label("Simulation Handle"), 0, 5, 2, 1); simInfo.add(simHandle, 2, 5); description.setMaxSize(250, 50); description.setWrapText(true); description.textProperty().addListener(new ChangeListener<String>(){ public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue){ Cycic.workingScenario.simulationData.notes = newValue; } }); simInfo.add(new Label("Description"), 0, 6, 2, 1); simInfo.add(description, 2, 6); // Prints the Cyclus input associated with this simulator. Button output = new Button("Generate"); output.setOnAction(new EventHandler<ActionEvent>(){ public void handle(ActionEvent event){ if(OutPut.inputTest()){ FileChooser fileChooser = new FileChooser(); //Set extension filter FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("XML files (*.xml)", "*.xml"); fileChooser.getExtensionFilters().add(extFilter); fileChooser.setTitle("Save Cyclus input file"); fileChooser.setInitialFileName("*.xml"); //Show save file dialog File file = fileChooser.showSaveDialog(window); OutPut.output(file); } } }); simInfo.add(output, 0, 7, 2, 1); Button load = new Button("Load Scenario"); load.setOnAction(new EventHandler<ActionEvent>(){ public void handle(ActionEvent e){ FileChooser fileChooser = new FileChooser(); //Set extension filter FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("XML files (*.xml)", "*.xml"); fileChooser.getExtensionFilters().add(extFilter); fileChooser.setTitle("Select input file to load."); fileChooser.setInitialFileName("*.xml"); //Show save file dialog File file = fileChooser.showOpenDialog(window); OutPut.loadFile(file); } }); simInfo.add(load, 2, 7); Button runCyclus = new Button("Execute"); simInfo.add(runCyclus, 0, 8, 1, 1); final List<String> serversList = FXCollections.observableArrayList(Preferences.getInstance().servers()); serversList.add(0, "-- add new --"); ComboBox<String> serverBox = new ComboBox<>(); serverBox.getItems().addAll(serversList); serverBox.setVisibleRowCount(Math.min(6, serverBox.getItems().size())); int currentIndex = Preferences.getInstance().getCurrentServerIndex()+1; currentServer = serversList.get(currentIndex); serverBox.setPromptText("server"); serverBox.setEditable(true); serverBox.getSelectionModel().select(currentIndex); serverBox.valueProperty().addListener( (ov, from, to)-> { int idx = serverBox.getSelectionModel().getSelectedIndex(); if (idx-1 != Preferences.getInstance().getCurrentServerIndex()) { Preferences.getInstance().setCurrentServerIndex(idx-1); } else if (Preferences.LOCAL_SERVER.equals(from)) { serverBox.getSelectionModel().select(idx); } else if ("".equals(to)) { serverBox.getItems().remove(from); Preferences.getInstance().servers().remove(from); } else if (serverBox.getItems().indexOf(to) == -1) { serverBox.getItems().add(to); Preferences.getInstance().servers().add(to); Preferences.getInstance().setCurrentServerIndex(serverBox.getItems().size()-2); serverBox.setVisibleRowCount(Math.min(6, serverBox.getItems().size())); } currentServer = serverBox.getValue(); }); Label serverLabel = new Label("Server:"); GridPane.setHalignment(serverLabel, HPos.RIGHT); simInfo.add(serverLabel, 1, 8, 1, 1); simInfo.add(serverBox, 2, 8); runCyclus.setOnAction(new EventHandler<ActionEvent>(){ public void handle(ActionEvent e){ if(!OutPut.inputTest()){ log.error("Cyclus Input Not Well Formed!"); return; // safety dance } String server = serverBox.getValue(); if (Preferences.LOCAL_SERVER.equals(server)) { // local execution String tempHash = Integer.toString(OutPut.xmlStringGen().hashCode()); String prefix = "cycic" + tempHash; String infile = prefix + ".xml"; String outfile = prefix + ".sqlite"; try { File temp = new File(infile); log.trace("Writing file " + temp.getName()); log.trace("lines:\n" + OutPut.xmlStringGen()); BufferedWriter output = new BufferedWriter(new FileWriter(temp)); output.write(OutPut.xmlStringGen()); output.close(); Process p = Runtime.getRuntime().exec("cyclus -o " + outfile + " " + infile); p.waitFor(); String line = null; BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream())); while ((line = input.readLine()) != null) { log.info(line); } input.close(); input = new BufferedReader(new InputStreamReader(p.getErrorStream())); while ((line = input.readLine()) != null) { log.warn(line); } input.close(); log.info("Cyclus run complete"); } catch (Exception e1) { // e1.printStackTrace(); log.error(e1.getMessage()); } } else { // remote execution String cycicXml = OutPut.xmlStringGen(); CyclistController._cyclusService.submit(cycicXml, server); } } });; } public void addArcheToBar(String archeType){ for(int i = 0; i < DataArrays.simFacilities.size(); i++){ if(DataArrays.simFacilities.get(i).facilityName.equalsIgnoreCase(archeType)){ if(DataArrays.simFacilities.get(i).loaded == true){ return; } facilityStructure test = DataArrays.simFacilities.get(i); try { test.loaded = true; FacilityCircle circle = new FacilityCircle(); int pos = 0; for(int k = 0; k < DataArrays.simFacilities.size(); k++){ if(DataArrays.simFacilities.get(k).loaded == true){ pos+=1; } } buildDnDCircle(circle, pos-1, test.facilityName); nodesPane.getChildren().addAll(circle, circle.text); } catch (Exception eq) { } } } } public void createArchetypeBar(GridPane grid){ ComboBox<String> archetypes = new ComboBox<String>(); for(int i = 0; i < DataArrays.simFacilities.size(); i++){ archetypes.getItems().add(DataArrays.simFacilities.get(i).facilityName); } archetypes.setOnMousePressed(new EventHandler<MouseEvent>(){ public void handle(MouseEvent e){ archetypes.getItems().clear(); for(int i = 0; i < DataArrays.simFacilities.size(); i++){ archetypes.getItems().add(DataArrays.simFacilities.get(i).facilityName); } } }); archetypes.setOnAction(new EventHandler<ActionEvent>(){ public void handle(ActionEvent e){ addArcheToBar(archetypes.getValue()); } }); Button cyclusDashM = new Button("Discover Archetypes"); cyclusDashM.setTooltip(new Tooltip("Use this button to search for all local Cyclus modules.")); cyclusDashM.setOnAction(new EventHandler<ActionEvent>(){ public void handle(ActionEvent e){ if (Preferences.LOCAL_SERVER.equals(currentServer)) { // Local metadata collection try { Process readproc = Runtime.getRuntime().exec("cyclus -m"); BufferedReader metaBuf = new BufferedReader(new InputStreamReader(readproc.getInputStream())); String line=null; String metadata = new String(); while ((line = metaBuf.readLine()) != null) {metadata += line;} metaBuf.close(); DataArrays.retrieveSchema(metadata); } catch (IOException ex) { log.error(ex.getMessage()); // ex.printStackTrace(); } } else { // Remote metadata collection _remoteDashA = CyclistController._cyclusService.submitCmdToRemote(currentServer, "cyclus", "-m"); // _remoteDashA = CyclistController._cyclusService.latestJob(); CyclusJob job = _remoteDashA; if (_remoteDashA.getStatus() == Status.FAILED) { // TODO: an error msg was already sent to the console. Do we want to pop up an error msg? } else { _remoteDashA.statusProperty() .addListener(new ChangeListener<CyclusJob.Status>() { @Override public void changed(ObservableValue<? extends Status> observable, Status oldValue, Status newValue) { if (newValue == Status.READY) { DataArrays.retrieveSchema(_remoteDashA.getStdout()); } } }); } } } }); archetypeGrid.add(cyclusDashM, 1, 0); archetypeGrid.add(new Label("Add Archetype to Simulation"), 0, 1); archetypeGrid.add(archetypes, 1, 1); } private void export() { FileChooser chooser = new FileChooser(); chooser.getExtensionFilters().add( new FileChooser.ExtensionFilter("Image file (png, jpg, gif)", "*.png", "*.jpg", "'*.gif") ); File file = chooser.showSaveDialog(Cyclist.cyclistStage); if (file != null) { WritableImage image = pane.snapshot(new SnapshotParameters(), null); String name = file.getName(); String ext = name.substring(name.indexOf(".")+1, name.length()); try { ImageIO.write(SwingFXUtils.fromFXImage(image, null), ext, file); } catch (IOException e) { log.error("Error writing image to file: "+e.getMessage()); } } else { log.error("File did not generate correctly."); System.out.println("File did not generate correctly."); } } }
package com.jme3.renderer; import com.jme3.bounding.BoundingBox; import com.jme3.bounding.BoundingVolume; import com.jme3.export.*; import com.jme3.math.*; import com.jme3.util.TempVars; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; /** * <code>Camera</code> is a standalone, purely mathematical class for doing * camera-related computations. * * <p> * Given input data such as location, orientation (direction, left, up), * and viewport settings, it can compute data necessary to render objects * with the graphics library. Two matrices are generated, the view matrix * transforms objects from world space into eye space, while the projection * matrix transforms objects from eye space into clip space. * </p> * <p>Another purpose of the camera class is to do frustum culling operations, * defined by six planes which define a 3D frustum shape, it is possible to * test if an object bounded by a mathematically defined volume is inside * the camera frustum, and thus to avoid rendering objects that are outside * the frustum * </p> * * @author Mark Powell * @author Joshua Slack */ public class Camera implements Savable, Cloneable { private static final Logger logger = Logger.getLogger(Camera.class.getName()); /** * The <code>FrustumIntersect</code> enum is returned as a result * of a culling check operation, * see {@link #contains(com.jme3.bounding.BoundingVolume) } */ public enum FrustumIntersect { /** * defines a constant assigned to spatials that are completely outside * of this camera's view frustum. */ Outside, /** * defines a constant assigned to spatials that are completely inside * the camera's view frustum. */ Inside, /** * defines a constant assigned to spatials that are intersecting one of * the six planes that define the view frustum. */ Intersects; } /** * LEFT_PLANE represents the left plane of the camera frustum. */ private static final int LEFT_PLANE = 0; /** * RIGHT_PLANE represents the right plane of the camera frustum. */ private static final int RIGHT_PLANE = 1; /** * BOTTOM_PLANE represents the bottom plane of the camera frustum. */ private static final int BOTTOM_PLANE = 2; /** * TOP_PLANE represents the top plane of the camera frustum. */ private static final int TOP_PLANE = 3; /** * FAR_PLANE represents the far plane of the camera frustum. */ private static final int FAR_PLANE = 4; /** * NEAR_PLANE represents the near plane of the camera frustum. */ private static final int NEAR_PLANE = 5; /** * FRUSTUM_PLANES represents the number of planes of the camera frustum. */ private static final int FRUSTUM_PLANES = 6; /** * MAX_WORLD_PLANES holds the maximum planes allowed by the system. */ private static final int MAX_WORLD_PLANES = 6; /** * Camera's location */ protected Vector3f location; /** * The orientation of the camera. */ protected Quaternion rotation; /** * Distance from camera to near frustum plane. */ protected float frustumNear; /** * Distance from camera to far frustum plane. */ protected float frustumFar; /** * Distance from camera to left frustum plane. */ protected float frustumLeft; /** * Distance from camera to right frustum plane. */ protected float frustumRight; /** * Distance from camera to top frustum plane. */ protected float frustumTop; /** * Distance from camera to bottom frustum plane. */ protected float frustumBottom; //Temporary values computed in onFrustumChange that are needed if a //call is made to onFrameChange. protected float[] coeffLeft; protected float[] coeffRight; protected float[] coeffBottom; protected float[] coeffTop; //view port coordinates /** * Percent value on display where horizontal viewing starts for this camera. * Default is 0. */ protected float viewPortLeft; /** * Percent value on display where horizontal viewing ends for this camera. * Default is 1. */ protected float viewPortRight; /** * Percent value on display where vertical viewing ends for this camera. * Default is 1. */ protected float viewPortTop; /** * Percent value on display where vertical viewing begins for this camera. * Default is 0. */ protected float viewPortBottom; /** * Array holding the planes that this camera will check for culling. */ protected Plane[] worldPlane; /** * A mask value set during contains() that allows fast culling of a Node's * children. */ private int planeState; protected int width; protected int height; protected boolean viewportChanged = true; /** * store the value for field parallelProjection */ private boolean parallelProjection = true; protected Matrix4f projectionMatrixOverride; protected Matrix4f viewMatrix = new Matrix4f(); protected Matrix4f projectionMatrix = new Matrix4f(); protected Matrix4f viewProjectionMatrix = new Matrix4f(); private BoundingBox guiBounding = new BoundingBox(); /** The camera's name. */ protected String name; /** * Serialization only. Do not use. */ public Camera() { worldPlane = new Plane[MAX_WORLD_PLANES]; for (int i = 0; i < MAX_WORLD_PLANES; i++) { worldPlane[i] = new Plane(); } } /** * Constructor instantiates a new <code>Camera</code> object. All * values of the camera are set to default. */ public Camera(int width, int height) { this(); location = new Vector3f(); rotation = new Quaternion(); frustumNear = 1.0f; frustumFar = 2.0f; frustumLeft = -0.5f; frustumRight = 0.5f; frustumTop = 0.5f; frustumBottom = -0.5f; coeffLeft = new float[2]; coeffRight = new float[2]; coeffBottom = new float[2]; coeffTop = new float[2]; viewPortLeft = 0.0f; viewPortRight = 1.0f; viewPortTop = 1.0f; viewPortBottom = 0.0f; this.width = width; this.height = height; onFrustumChange(); onViewPortChange(); onFrameChange(); logger.log(Level.FINE, "Camera created (W: {0}, H: {1})", new Object[]{width, height}); } @Override public Camera clone() { try { Camera cam = (Camera) super.clone(); cam.viewportChanged = true; cam.planeState = 0; cam.worldPlane = new Plane[MAX_WORLD_PLANES]; for (int i = 0; i < worldPlane.length; i++) { cam.worldPlane[i] = worldPlane[i].clone(); } cam.coeffLeft = new float[2]; cam.coeffRight = new float[2]; cam.coeffBottom = new float[2]; cam.coeffTop = new float[2]; cam.location = location.clone(); cam.rotation = rotation.clone(); if (projectionMatrixOverride != null) { cam.projectionMatrixOverride = projectionMatrixOverride.clone(); } cam.viewMatrix = viewMatrix.clone(); cam.projectionMatrix = projectionMatrix.clone(); cam.viewProjectionMatrix = viewProjectionMatrix.clone(); cam.guiBounding = (BoundingBox) guiBounding.clone(); cam.update(); return cam; } catch (CloneNotSupportedException ex) { throw new AssertionError(); } } /** * This method copies the settings of the given camera. * * @param cam * the camera we copy the settings from */ public void copyFrom(Camera cam) { location.set(cam.location); rotation.set(cam.rotation); frustumNear = cam.frustumNear; frustumFar = cam.frustumFar; frustumLeft = cam.frustumLeft; frustumRight = cam.frustumRight; frustumTop = cam.frustumTop; frustumBottom = cam.frustumBottom; coeffLeft[0] = cam.coeffLeft[0]; coeffLeft[1] = cam.coeffLeft[1]; coeffRight[0] = cam.coeffRight[0]; coeffRight[1] = cam.coeffRight[1]; coeffBottom[0] = cam.coeffBottom[0]; coeffBottom[1] = cam.coeffBottom[1]; coeffTop[0] = cam.coeffTop[0]; coeffTop[1] = cam.coeffTop[1]; viewPortLeft = cam.viewPortLeft; viewPortRight = cam.viewPortRight; viewPortTop = cam.viewPortTop; viewPortBottom = cam.viewPortBottom; this.width = cam.width; this.height = cam.height; this.planeState = 0; this.viewportChanged = true; for (int i = 0; i < MAX_WORLD_PLANES; ++i) { worldPlane[i].setNormal(cam.worldPlane[i].getNormal()); worldPlane[i].setConstant(cam.worldPlane[i].getConstant()); } this.parallelProjection = cam.parallelProjection; if (cam.projectionMatrixOverride != null) { if (this.projectionMatrixOverride == null) { this.projectionMatrixOverride = cam.projectionMatrixOverride.clone(); } else { this.projectionMatrixOverride.set(cam.projectionMatrixOverride); } } else { this.projectionMatrixOverride = null; } this.viewMatrix.set(cam.viewMatrix); this.projectionMatrix.set(cam.projectionMatrix); this.viewProjectionMatrix.set(cam.viewProjectionMatrix); this.guiBounding.setXExtent(cam.guiBounding.getXExtent()); this.guiBounding.setYExtent(cam.guiBounding.getYExtent()); this.guiBounding.setZExtent(cam.guiBounding.getZExtent()); this.guiBounding.setCenter(cam.guiBounding.getCenter()); this.guiBounding.setCheckPlane(cam.guiBounding.getCheckPlane()); this.name = cam.name; } /** * This method sets the cameras name. * @param name the cameras name */ public void setName(String name) { this.name = name; } /** * This method returns the cameras name. * @return the cameras name */ public String getName() { return name; } public void setClipPlane(Plane clipPlane, Plane.Side side) { float sideFactor = 1; if (side == Plane.Side.Negative) { sideFactor = -1; } //we are on the other side of the plane no need to clip anymore. if (clipPlane.whichSide(location) == side) { return; } TempVars vars = TempVars.get(); try { Matrix4f p = projectionMatrix.clone(); Matrix4f ivm = viewMatrix; Vector3f point = clipPlane.getNormal().mult(clipPlane.getConstant(), vars.vect1); Vector3f pp = ivm.mult(point, vars.vect2); Vector3f pn = ivm.multNormal(clipPlane.getNormal(), vars.vect3); Vector4f clipPlaneV = vars.vect4f1.set(pn.x * sideFactor, pn.y * sideFactor, pn.z * sideFactor, -(pp.dot(pn)) * sideFactor); Vector4f v = vars.vect4f2.set(0, 0, 0, 0); v.x = (Math.signum(clipPlaneV.x) + p.m02) / p.m00; v.y = (Math.signum(clipPlaneV.y) + p.m12) / p.m11; v.z = -1.0f; v.w = (1.0f + p.m22) / p.m23; float dot = clipPlaneV.dot(v);//clipPlaneV.x * v.x + clipPlaneV.y * v.y + clipPlaneV.z * v.z + clipPlaneV.w * v.w; Vector4f c = clipPlaneV.multLocal(2.0f / dot); p.m20 = c.x - p.m30; p.m21 = c.y - p.m31; p.m22 = c.z - p.m32; p.m23 = c.w - p.m33; setProjectionMatrix(p); } finally { vars.release(); } } public void setClipPlane(Plane clipPlane) { setClipPlane(clipPlane, clipPlane.whichSide(location)); } /** * Resizes this camera's view with the given width and height. This is * similar to constructing a new camera, but reusing the same Object. This * method is called by an associated {@link RenderManager} to notify the camera of * changes in the display dimensions. * * @param width the view width * @param height the view height * @param fixAspect If true, the camera's aspect ratio will be recomputed. * Recomputing the aspect ratio requires changing the frustum values. */ public void resize(int width, int height, boolean fixAspect) { this.width = width; this.height = height; onViewPortChange(); if (fixAspect /*&& !parallelProjection*/) { frustumRight = frustumTop * ((float) width / height); frustumLeft = -frustumRight; onFrustumChange(); } } /** * <code>getFrustumBottom</code> returns the value of the bottom frustum * plane. * * @return the value of the bottom frustum plane. */ public float getFrustumBottom() { return frustumBottom; } /** * <code>setFrustumBottom</code> sets the value of the bottom frustum * plane. * * @param frustumBottom the value of the bottom frustum plane. */ public void setFrustumBottom(float frustumBottom) { this.frustumBottom = frustumBottom; onFrustumChange(); } /** * <code>getFrustumFar</code> gets the value of the far frustum plane. * * @return the value of the far frustum plane. */ public float getFrustumFar() { return frustumFar; } /** * <code>setFrustumFar</code> sets the value of the far frustum plane. * * @param frustumFar the value of the far frustum plane. */ public void setFrustumFar(float frustumFar) { this.frustumFar = frustumFar; onFrustumChange(); } /** * <code>getFrustumLeft</code> gets the value of the left frustum plane. * * @return the value of the left frustum plane. */ public float getFrustumLeft() { return frustumLeft; } /** * <code>setFrustumLeft</code> sets the value of the left frustum plane. * * @param frustumLeft the value of the left frustum plane. */ public void setFrustumLeft(float frustumLeft) { this.frustumLeft = frustumLeft; onFrustumChange(); } /** * <code>getFrustumNear</code> gets the value of the near frustum plane. * * @return the value of the near frustum plane. */ public float getFrustumNear() { return frustumNear; } /** * <code>setFrustumNear</code> sets the value of the near frustum plane. * * @param frustumNear the value of the near frustum plane. */ public void setFrustumNear(float frustumNear) { this.frustumNear = frustumNear; onFrustumChange(); } /** * <code>getFrustumRight</code> gets the value of the right frustum plane. * * @return frustumRight the value of the right frustum plane. */ public float getFrustumRight() { return frustumRight; } /** * <code>setFrustumRight</code> sets the value of the right frustum plane. * * @param frustumRight the value of the right frustum plane. */ public void setFrustumRight(float frustumRight) { this.frustumRight = frustumRight; onFrustumChange(); } /** * <code>getFrustumTop</code> gets the value of the top frustum plane. * * @return the value of the top frustum plane. */ public float getFrustumTop() { return frustumTop; } /** * <code>setFrustumTop</code> sets the value of the top frustum plane. * * @param frustumTop the value of the top frustum plane. */ public void setFrustumTop(float frustumTop) { this.frustumTop = frustumTop; onFrustumChange(); } /** * <code>getLocation</code> retrieves the location vector of the camera. * * @return the position of the camera. * @see Camera#getLocation() */ public Vector3f getLocation() { return location; } /** * <code>getRotation</code> retrieves the rotation quaternion of the camera. * * @return the rotation of the camera. */ public Quaternion getRotation() { return rotation; } /** * <code>getDirection</code> retrieves the direction vector the camera is * facing. * * @return the direction the camera is facing. * @see Camera#getDirection() */ public Vector3f getDirection() { return rotation.getRotationColumn(2); } /** * <code>getLeft</code> retrieves the left axis of the camera. * * @return the left axis of the camera. * @see Camera#getLeft() */ public Vector3f getLeft() { return rotation.getRotationColumn(0); } /** * <code>getUp</code> retrieves the up axis of the camera. * * @return the up axis of the camera. * @see Camera#getUp() */ public Vector3f getUp() { return rotation.getRotationColumn(1); } /** * <code>getDirection</code> retrieves the direction vector the camera is * facing. * * @return the direction the camera is facing. * @see Camera#getDirection() */ public Vector3f getDirection(Vector3f store) { return rotation.getRotationColumn(2, store); } /** * <code>getLeft</code> retrieves the left axis of the camera. * * @return the left axis of the camera. * @see Camera#getLeft() */ public Vector3f getLeft(Vector3f store) { return rotation.getRotationColumn(0, store); } /** * <code>getUp</code> retrieves the up axis of the camera. * * @return the up axis of the camera. * @see Camera#getUp() */ public Vector3f getUp(Vector3f store) { return rotation.getRotationColumn(1, store); } /** * <code>setLocation</code> sets the position of the camera. * * @param location the position of the camera. */ public void setLocation(Vector3f location) { this.location.set(location); onFrameChange(); } /** * <code>setRotation</code> sets the orientation of this camera. This will * be equivalent to setting each of the axes: * <code><br> * cam.setLeft(rotation.getRotationColumn(0));<br> * cam.setUp(rotation.getRotationColumn(1));<br> * cam.setDirection(rotation.getRotationColumn(2));<br> * </code> * * @param rotation the rotation of this camera */ public void setRotation(Quaternion rotation) { this.rotation.set(rotation); onFrameChange(); } /** * <code>lookAtDirection</code> sets the direction the camera is facing * given a direction and an up vector. * * @param direction the direction this camera is facing. */ public void lookAtDirection(Vector3f direction, Vector3f up) { this.rotation.lookAt(direction, up); onFrameChange(); } /** * <code>setAxes</code> sets the axes (left, up and direction) for this * camera. * * @param left the left axis of the camera. * @param up the up axis of the camera. * @param direction the direction the camera is facing. * * @see Camera#setAxes(com.jme3.math.Quaternion) */ public void setAxes(Vector3f left, Vector3f up, Vector3f direction) { this.rotation.fromAxes(left, up, direction); onFrameChange(); } /** * <code>setAxes</code> uses a rotational matrix to set the axes of the * camera. * * @param axes the matrix that defines the orientation of the camera. */ public void setAxes(Quaternion axes) { this.rotation.set(axes); onFrameChange(); } /** * normalize normalizes the camera vectors. */ public void normalize() { this.rotation.normalizeLocal(); onFrameChange(); } /** * <code>setFrustum</code> sets the frustum of this camera object. * * @param near the near plane. * @param far the far plane. * @param left the left plane. * @param right the right plane. * @param top the top plane. * @param bottom the bottom plane. * @see Camera#setFrustum(float, float, float, float, * float, float) */ public void setFrustum(float near, float far, float left, float right, float top, float bottom) { frustumNear = near; frustumFar = far; frustumLeft = left; frustumRight = right; frustumTop = top; frustumBottom = bottom; onFrustumChange(); } /** * <code>setFrustumPerspective</code> defines the frustum for the camera. This * frustum is defined by a viewing angle, aspect ratio, and near/far planes * * @param fovY Frame of view angle along the Y in degrees. * @param aspect Width:Height ratio * @param near Near view plane distance * @param far Far view plane distance */ public void setFrustumPerspective(float fovY, float aspect, float near, float far) { if (Float.isNaN(aspect) || Float.isInfinite(aspect)) { // ignore. logger.log(Level.WARNING, "Invalid aspect given to setFrustumPerspective: {0}", aspect); return; } float h = FastMath.tan(fovY * FastMath.DEG_TO_RAD * .5f) * near; float w = h * aspect; frustumLeft = -w; frustumRight = w; frustumBottom = -h; frustumTop = h; frustumNear = near; frustumFar = far; // Camera is no longer parallel projection even if it was before parallelProjection = false; onFrustumChange(); } /** * <code>setFrame</code> sets the orientation and location of the camera. * * @param location the point position of the camera. * @param left the left axis of the camera. * @param up the up axis of the camera. * @param direction the facing of the camera. * @see Camera#setFrame(com.jme3.math.Vector3f, * com.jme3.math.Vector3f, com.jme3.math.Vector3f, com.jme3.math.Vector3f) */ public void setFrame(Vector3f location, Vector3f left, Vector3f up, Vector3f direction) { this.location = location; this.rotation.fromAxes(left, up, direction); onFrameChange(); } /** * <code>lookAt</code> is a convenience method for auto-setting the frame * based on a world position the user desires the camera to look at. It * repoints the camera towards the given position using the difference * between the position and the current camera location as a direction * vector and the worldUpVector to compute up and left camera vectors. * * @param pos where to look at in terms of world coordinates * @param worldUpVector a normalized vector indicating the up direction of the world. * (typically {0, 1, 0} in jME.) */ public void lookAt(Vector3f pos, Vector3f worldUpVector) { TempVars vars = TempVars.get(); Vector3f newDirection = vars.vect1; Vector3f newUp = vars.vect2; Vector3f newLeft = vars.vect3; newDirection.set(pos).subtractLocal(location).normalizeLocal(); newUp.set(worldUpVector).normalizeLocal(); if (newUp.equals(Vector3f.ZERO)) { newUp.set(Vector3f.UNIT_Y); } newLeft.set(newUp).crossLocal(newDirection).normalizeLocal(); if (newLeft.equals(Vector3f.ZERO)) { if (newDirection.x != 0) { newLeft.set(newDirection.y, -newDirection.x, 0f); } else { newLeft.set(0f, newDirection.z, -newDirection.y); } } newUp.set(newDirection).crossLocal(newLeft).normalizeLocal(); this.rotation.fromAxes(newLeft, newUp, newDirection); this.rotation.normalizeLocal(); vars.release(); onFrameChange(); } /** * <code>setFrame</code> sets the orientation and location of the camera. * * @param location * the point position of the camera. * @param axes * the orientation of the camera. */ public void setFrame(Vector3f location, Quaternion axes) { this.location = location; this.rotation.set(axes); onFrameChange(); } /** * <code>update</code> updates the camera parameters by calling * <code>onFrustumChange</code>,<code>onViewPortChange</code> and * <code>onFrameChange</code>. * * @see Camera#update() */ public void update() { onFrustumChange(); onViewPortChange(); //...this is always called by onFrustumChange() //onFrameChange(); } /** * <code>getPlaneState</code> returns the state of the frustum planes. So * checks can be made as to which frustum plane has been examined for * culling thus far. * * @return the current plane state int. */ public int getPlaneState() { return planeState; } /** * <code>setPlaneState</code> sets the state to keep track of tested * planes for culling. * * @param planeState the updated state. */ public void setPlaneState(int planeState) { this.planeState = planeState; } /** * <code>getViewPortLeft</code> gets the left boundary of the viewport * * @return the left boundary of the viewport */ public float getViewPortLeft() { return viewPortLeft; } /** * <code>setViewPortLeft</code> sets the left boundary of the viewport * * @param left the left boundary of the viewport */ public void setViewPortLeft(float left) { viewPortLeft = left; onViewPortChange(); } /** * <code>getViewPortRight</code> gets the right boundary of the viewport * * @return the right boundary of the viewport */ public float getViewPortRight() { return viewPortRight; } /** * <code>setViewPortRight</code> sets the right boundary of the viewport * * @param right the right boundary of the viewport */ public void setViewPortRight(float right) { viewPortRight = right; onViewPortChange(); } /** * <code>getViewPortTop</code> gets the top boundary of the viewport * * @return the top boundary of the viewport */ public float getViewPortTop() { return viewPortTop; } /** * <code>setViewPortTop</code> sets the top boundary of the viewport * * @param top the top boundary of the viewport */ public void setViewPortTop(float top) { viewPortTop = top; onViewPortChange(); } /** * <code>getViewPortBottom</code> gets the bottom boundary of the viewport * * @return the bottom boundary of the viewport */ public float getViewPortBottom() { return viewPortBottom; } /** * <code>setViewPortBottom</code> sets the bottom boundary of the viewport * * @param bottom the bottom boundary of the viewport */ public void setViewPortBottom(float bottom) { viewPortBottom = bottom; onViewPortChange(); } /** * <code>setViewPort</code> sets the boundaries of the viewport * * @param left the left boundary of the viewport (default: 0) * @param right the right boundary of the viewport (default: 1) * @param bottom the bottom boundary of the viewport (default: 0) * @param top the top boundary of the viewport (default: 1) */ public void setViewPort(float left, float right, float bottom, float top) { this.viewPortLeft = left; this.viewPortRight = right; this.viewPortBottom = bottom; this.viewPortTop = top; onViewPortChange(); } /** * Returns the pseudo distance from the given position to the near * plane of the camera. This is used for render queue sorting. * @param pos The position to compute a distance to. * @return Distance from the far plane to the point. */ public float distanceToNearPlane(Vector3f pos) { return worldPlane[NEAR_PLANE].pseudoDistance(pos); } /** * <code>contains</code> tests a bounding volume against the planes of the * camera's frustum. The frustum's planes are set such that the normals all * face in towards the viewable scene. Therefore, if the bounding volume is * on the negative side of the plane is can be culled out. * * NOTE: This method is used internally for culling, for public usage, * the plane state of the bounding volume must be saved and restored, e.g: * <code>BoundingVolume bv;<br/> * Camera c;<br/> * int planeState = bv.getPlaneState();<br/> * bv.setPlaneState(0);<br/> * c.contains(bv);<br/> * bv.setPlaneState(plateState);<br/> * </code> * * @param bound the bound to check for culling * @return See enums in <code>FrustumIntersect</code> */ public FrustumIntersect contains(BoundingVolume bound) { if (bound == null) { return FrustumIntersect.Inside; } int mask; FrustumIntersect rVal = FrustumIntersect.Inside; for (int planeCounter = FRUSTUM_PLANES; planeCounter >= 0; planeCounter if (planeCounter == bound.getCheckPlane()) { continue; // we have already checked this plane at first iteration } int planeId = (planeCounter == FRUSTUM_PLANES) ? bound.getCheckPlane() : planeCounter; // int planeId = planeCounter; mask = 1 << (planeId); if ((planeState & mask) == 0) { Plane.Side side = bound.whichSide(worldPlane[planeId]); if (side == Plane.Side.Negative) { //object is outside of frustum bound.setCheckPlane(planeId); return FrustumIntersect.Outside; } else if (side == Plane.Side.Positive) { //object is visible on *this* plane, so mark this plane //so that we don't check it for sub nodes. planeState |= mask; } else { rVal = FrustumIntersect.Intersects; } } } return rVal; } /** * <code>containsGui</code> tests a bounding volume against the ortho * bounding box of the camera. A bounding box spanning from * 0, 0 to Width, Height. Constrained by the viewport settings on the * camera. * * @param bound the bound to check for culling * @return True if the camera contains the gui element bounding volume. */ public boolean containsGui(BoundingVolume bound) { if (bound == null) { return true; } return guiBounding.intersects(bound); } /** * @return the view matrix of the camera. * The view matrix transforms world space into eye space. * This matrix is usually defined by the position and * orientation of the camera. */ public Matrix4f getViewMatrix() { return viewMatrix; } /** * Overrides the projection matrix used by the camera. Will * use the matrix for computing the view projection matrix as well. * Use null argument to return to normal functionality. * * @param projMatrix */ public void setProjectionMatrix(Matrix4f projMatrix) { projectionMatrixOverride = projMatrix; updateViewProjection(); } /** * @return the projection matrix of the camera. * The view projection matrix transforms eye space into clip space. * This matrix is usually defined by the viewport and perspective settings * of the camera. */ public Matrix4f getProjectionMatrix() { if (projectionMatrixOverride != null) { return projectionMatrixOverride; } return projectionMatrix; } /** * Updates the view projection matrix. */ public void updateViewProjection() { if (projectionMatrixOverride != null) { viewProjectionMatrix.set(projectionMatrixOverride).multLocal(viewMatrix); } else { //viewProjectionMatrix.set(viewMatrix).multLocal(projectionMatrix); viewProjectionMatrix.set(projectionMatrix).multLocal(viewMatrix); } } /** * @return The result of multiplying the projection matrix by the view * matrix. This matrix is required for rendering an object. It is * precomputed so as to not compute it every time an object is rendered. */ public Matrix4f getViewProjectionMatrix() { return viewProjectionMatrix; } /** * @return True if the viewport (width, height, left, right, bottom, up) * has been changed. This is needed in the renderer so that the proper * viewport can be set-up. */ public boolean isViewportChanged() { return viewportChanged; } /** * Clears the viewport changed flag once it has been updated inside * the renderer. */ public void clearViewportChanged() { viewportChanged = false; } /** * Called when the viewport has been changed. */ public void onViewPortChange() { viewportChanged = true; setGuiBounding(); } private void setGuiBounding() { float sx = width * viewPortLeft; float ex = width * viewPortRight; float sy = height * viewPortBottom; float ey = height * viewPortTop; float xExtent = Math.max(0f, (ex - sx) / 2f); float yExtent = Math.max(0f, (ey - sy) / 2f); guiBounding.setCenter(sx + xExtent, sy + yExtent, 0); guiBounding.setXExtent(xExtent); guiBounding.setYExtent(yExtent); guiBounding.setZExtent(Float.MAX_VALUE); } /** * <code>onFrustumChange</code> updates the frustum to reflect any changes * made to the planes. The new frustum values are kept in a temporary * location for use when calculating the new frame. The projection * matrix is updated to reflect the current values of the frustum. */ public void onFrustumChange() { if (!isParallelProjection()) { float nearSquared = frustumNear * frustumNear; float leftSquared = frustumLeft * frustumLeft; float rightSquared = frustumRight * frustumRight; float bottomSquared = frustumBottom * frustumBottom; float topSquared = frustumTop * frustumTop; float inverseLength = FastMath.invSqrt(nearSquared + leftSquared); coeffLeft[0] = -frustumNear * inverseLength; coeffLeft[1] = -frustumLeft * inverseLength; inverseLength = FastMath.invSqrt(nearSquared + rightSquared); coeffRight[0] = frustumNear * inverseLength; coeffRight[1] = frustumRight * inverseLength; inverseLength = FastMath.invSqrt(nearSquared + bottomSquared); coeffBottom[0] = frustumNear * inverseLength; coeffBottom[1] = -frustumBottom * inverseLength; inverseLength = FastMath.invSqrt(nearSquared + topSquared); coeffTop[0] = -frustumNear * inverseLength; coeffTop[1] = frustumTop * inverseLength; } else { coeffLeft[0] = 1; coeffLeft[1] = 0; coeffRight[0] = -1; coeffRight[1] = 0; coeffBottom[0] = 1; coeffBottom[1] = 0; coeffTop[0] = -1; coeffTop[1] = 0; } projectionMatrix.fromFrustum(frustumNear, frustumFar, frustumLeft, frustumRight, frustumTop, frustumBottom, parallelProjection); // projectionMatrix.transposeLocal(); // The frame is effected by the frustum values // update it as well onFrameChange(); } /** * <code>onFrameChange</code> updates the view frame of the camera. */ public void onFrameChange() { TempVars vars = TempVars.get(); Vector3f left = getLeft(vars.vect1); Vector3f direction = getDirection(vars.vect2); Vector3f up = getUp(vars.vect3); float dirDotLocation = direction.dot(location); // left plane Vector3f leftPlaneNormal = worldPlane[LEFT_PLANE].getNormal(); leftPlaneNormal.x = left.x * coeffLeft[0]; leftPlaneNormal.y = left.y * coeffLeft[0]; leftPlaneNormal.z = left.z * coeffLeft[0]; leftPlaneNormal.addLocal(direction.x * coeffLeft[1], direction.y * coeffLeft[1], direction.z * coeffLeft[1]); worldPlane[LEFT_PLANE].setConstant(location.dot(leftPlaneNormal)); // right plane Vector3f rightPlaneNormal = worldPlane[RIGHT_PLANE].getNormal(); rightPlaneNormal.x = left.x * coeffRight[0]; rightPlaneNormal.y = left.y * coeffRight[0]; rightPlaneNormal.z = left.z * coeffRight[0]; rightPlaneNormal.addLocal(direction.x * coeffRight[1], direction.y * coeffRight[1], direction.z * coeffRight[1]); worldPlane[RIGHT_PLANE].setConstant(location.dot(rightPlaneNormal)); // bottom plane Vector3f bottomPlaneNormal = worldPlane[BOTTOM_PLANE].getNormal(); bottomPlaneNormal.x = up.x * coeffBottom[0]; bottomPlaneNormal.y = up.y * coeffBottom[0]; bottomPlaneNormal.z = up.z * coeffBottom[0]; bottomPlaneNormal.addLocal(direction.x * coeffBottom[1], direction.y * coeffBottom[1], direction.z * coeffBottom[1]); worldPlane[BOTTOM_PLANE].setConstant(location.dot(bottomPlaneNormal)); // top plane Vector3f topPlaneNormal = worldPlane[TOP_PLANE].getNormal(); topPlaneNormal.x = up.x * coeffTop[0]; topPlaneNormal.y = up.y * coeffTop[0]; topPlaneNormal.z = up.z * coeffTop[0]; topPlaneNormal.addLocal(direction.x * coeffTop[1], direction.y * coeffTop[1], direction.z * coeffTop[1]); worldPlane[TOP_PLANE].setConstant(location.dot(topPlaneNormal)); if (isParallelProjection()) { worldPlane[LEFT_PLANE].setConstant(worldPlane[LEFT_PLANE].getConstant() + frustumLeft); worldPlane[RIGHT_PLANE].setConstant(worldPlane[RIGHT_PLANE].getConstant() - frustumRight); worldPlane[TOP_PLANE].setConstant(worldPlane[TOP_PLANE].getConstant() - frustumTop); worldPlane[BOTTOM_PLANE].setConstant(worldPlane[BOTTOM_PLANE].getConstant() + frustumBottom); } // far plane worldPlane[FAR_PLANE].setNormal(left); worldPlane[FAR_PLANE].setNormal(-direction.x, -direction.y, -direction.z); worldPlane[FAR_PLANE].setConstant(-(dirDotLocation + frustumFar)); // near plane worldPlane[NEAR_PLANE].setNormal(direction.x, direction.y, direction.z); worldPlane[NEAR_PLANE].setConstant(dirDotLocation + frustumNear); viewMatrix.fromFrame(location, direction, up, left); vars.release(); // viewMatrix.transposeLocal(); updateViewProjection(); } /** * @return true if parallel projection is enable, false if in normal perspective mode * @see #setParallelProjection(boolean) */ public boolean isParallelProjection() { return this.parallelProjection; } /** * Enable/disable parallel projection. * * @param value true to set up this camera for parallel projection is enable, false to enter normal perspective mode */ public void setParallelProjection(final boolean value) { this.parallelProjection = value; onFrustumChange(); } public float getViewToProjectionZ(float viewZPos) { float far = getFrustumFar(); float near = getFrustumNear(); float a = far / (far - near); float b = far * near / (near - far); return a + b / viewZPos; } public Vector3f getWorldCoordinates(Vector2f screenPos, float projectionZPos) { return getWorldCoordinates(screenPos, projectionZPos, null); } /** * @see Camera#getWorldCoordinates */ public Vector3f getWorldCoordinates(Vector2f screenPosition, float projectionZPos, Vector3f store) { if (store == null) { store = new Vector3f(); } Matrix4f inverseMat = new Matrix4f(viewProjectionMatrix); inverseMat.invertLocal(); store.set( (screenPosition.x / getWidth() - viewPortLeft) / (viewPortRight - viewPortLeft) * 2 - 1, (screenPosition.y / getHeight() - viewPortBottom) / (viewPortTop - viewPortBottom) * 2 - 1, projectionZPos * 2 - 1); float w = inverseMat.multProj(store, store); store.multLocal(1f / w); return store; } /** * Converts the given position from world space to screen space. * * @see Camera#getScreenCoordinates */ public Vector3f getScreenCoordinates(Vector3f worldPos) { return getScreenCoordinates(worldPos, null); } /** * Converts the given position from world space to screen space. * * @see Camera#getScreenCoordinates(Vector3f, Vector3f) */ public Vector3f getScreenCoordinates(Vector3f worldPosition, Vector3f store) { if (store == null) { store = new Vector3f(); } // TempVars vars = vars.lock(); // Quaternion tmp_quat = vars.quat1; // tmp_quat.set( worldPosition.x, worldPosition.y, worldPosition.z, 1 ); // viewProjectionMatrix.mult(tmp_quat, tmp_quat); // tmp_quat.multLocal( 1.0f / tmp_quat.getW() ); // store.x = ( ( tmp_quat.getX() + 1 ) * ( viewPortRight - viewPortLeft ) / 2 + viewPortLeft ) * getWidth(); // store.y = ( ( tmp_quat.getY() + 1 ) * ( viewPortTop - viewPortBottom ) / 2 + viewPortBottom ) * getHeight(); // store.z = ( tmp_quat.getZ() + 1 ) / 2; // vars.release(); float w = viewProjectionMatrix.multProj(worldPosition, store); store.divideLocal(w); store.x = ((store.x + 1f) * (viewPortRight - viewPortLeft) / 2f + viewPortLeft) * getWidth(); store.y = ((store.y + 1f) * (viewPortTop - viewPortBottom) / 2f + viewPortBottom) * getHeight(); store.z = (store.z + 1f) / 2f; return store; } /** * @return the width/resolution of the display. */ public int getWidth() { return width; } /** * @return the height/resolution of the display. */ public int getHeight() { return height; } @Override public String toString() { return "Camera[location=" + location + "\n, direction=" + getDirection() + "\n" + "res=" + width + "x" + height + ", parallel=" + parallelProjection + "\n" + "near=" + frustumNear + ", far=" + frustumFar + "]"; } public void write(JmeExporter e) throws IOException { OutputCapsule capsule = e.getCapsule(this); capsule.write(location, "location", Vector3f.ZERO); capsule.write(rotation, "rotation", Quaternion.DIRECTION_Z); capsule.write(frustumNear, "frustumNear", 1); capsule.write(frustumFar, "frustumFar", 2); capsule.write(frustumLeft, "frustumLeft", -0.5f); capsule.write(frustumRight, "frustumRight", 0.5f); capsule.write(frustumTop, "frustumTop", 0.5f); capsule.write(frustumBottom, "frustumBottom", -0.5f); capsule.write(coeffLeft, "coeffLeft", new float[2]); capsule.write(coeffRight, "coeffRight", new float[2]); capsule.write(coeffBottom, "coeffBottom", new float[2]); capsule.write(coeffTop, "coeffTop", new float[2]); capsule.write(viewPortLeft, "viewPortLeft", 0); capsule.write(viewPortRight, "viewPortRight", 1); capsule.write(viewPortTop, "viewPortTop", 1); capsule.write(viewPortBottom, "viewPortBottom", 0); capsule.write(width, "width", 0); capsule.write(height, "height", 0); capsule.write(name, "name", null); } public void read(JmeImporter e) throws IOException { InputCapsule capsule = e.getCapsule(this); location = (Vector3f) capsule.readSavable("location", Vector3f.ZERO.clone()); rotation = (Quaternion) capsule.readSavable("rotation", Quaternion.DIRECTION_Z.clone()); frustumNear = capsule.readFloat("frustumNear", 1); frustumFar = capsule.readFloat("frustumFar", 2); frustumLeft = capsule.readFloat("frustumLeft", -0.5f); frustumRight = capsule.readFloat("frustumRight", 0.5f); frustumTop = capsule.readFloat("frustumTop", 0.5f); frustumBottom = capsule.readFloat("frustumBottom", -0.5f); coeffLeft = capsule.readFloatArray("coeffLeft", new float[2]); coeffRight = capsule.readFloatArray("coeffRight", new float[2]); coeffBottom = capsule.readFloatArray("coeffBottom", new float[2]); coeffTop = capsule.readFloatArray("coeffTop", new float[2]); viewPortLeft = capsule.readFloat("viewPortLeft", 0); viewPortRight = capsule.readFloat("viewPortRight", 1); viewPortTop = capsule.readFloat("viewPortTop", 1); viewPortBottom = capsule.readFloat("viewPortBottom", 0); width = capsule.readInt("width", 1); height = capsule.readInt("height", 1); name = capsule.readString("name", null); onFrustumChange(); onViewPortChange(); onFrameChange(); } }
package jodd.util; import org.junit.Test; import java.text.DateFormatSymbols; import java.util.Locale; import static org.junit.Assert.*; public class LocaleUtilTest { @Test public void testLocaleUtil() { Locale locale1 = LocaleUtil.getLocale("fr", "FR"); Locale locale2 = LocaleUtil.getLocale("fr_FR"); assertSame(locale1, locale2); DateFormatSymbolsEx dfs = LocaleUtil.getDateFormatSymbols(locale2); DateFormatSymbols dfsJava = new DateFormatSymbols(locale2); assertEquals(dfs.getMonth(0), dfsJava.getMonths()[0]); assertEquals(dfs.getWeekday(1), dfsJava.getWeekdays()[1]); assertEquals(dfs.getShortMonth(2), dfsJava.getShortMonths()[2]); locale1 = LocaleUtil.getLocale("en"); locale2 = LocaleUtil.getLocale("en_EN"); assertNotSame(locale1, locale2); dfs = LocaleUtil.getDateFormatSymbols(locale2); dfsJava = new DateFormatSymbols(locale2); assertEquals(dfs.getMonth(0), dfsJava.getMonths()[0]); assertEquals(dfs.getWeekday(1), dfsJava.getWeekdays()[1]); assertEquals(dfs.getShortMonth(2), dfsJava.getShortMonths()[2]); } }
package org.jpos.apps.qsp.config; import java.util.Properties; import org.jpos.util.Logger; import org.jpos.util.LogEvent; import org.jpos.util.LogSource; import org.jpos.util.NameRegistrar; import org.jpos.core.SimpleConfiguration; import org.jpos.core.Configurable; import org.jpos.core.ReConfigurable; import org.jpos.core.ConfigurationException; import org.jpos.apps.qsp.QSP; import org.jpos.apps.qsp.QSPConfigurator; import org.jpos.apps.qsp.QSPReConfigurator; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * Configure User defined Tasks * @author <a href="mailto:apr@cs.com.uy">Alejandro P. Revilla</a> * @version $Revision$ $Date$ */ public class ConfigTask implements QSPReConfigurator { public static final String NAMEREGISTRAR_PREFIX = "qsp.task."; public void config (QSP qsp, Node node) throws ConfigurationException { String className = node.getAttributes().getNamedItem ("class").getNodeValue(); String name = getValue (node, "name"); LogEvent evt = new LogEvent (qsp, "config-task", className); try { Class c = Class.forName(className); Runnable task = (Runnable) c.newInstance(); if (task instanceof LogSource) { ((LogSource)task).setLogger ( ConfigLogger.getLogger (node), ConfigLogger.getRealm (node) ); } if (task instanceof Configurable) configureTask ((Configurable) task, node, evt); if (name != null) NameRegistrar.register (NAMEREGISTRAR_PREFIX+name, task); Thread thread = new Thread(task); thread.setName ("qsp-task-"+name); thread.start(); } catch (ClassNotFoundException e) { throw new ConfigurationException ("config-task:"+className, e); } catch (InstantiationException e) { throw new ConfigurationException ("config-task:"+className, e); } catch (IllegalAccessException e) { throw new ConfigurationException ("config-task:"+className, e); } Logger.log (evt); } public void reconfig (QSP qsp, Node node) throws ConfigurationException { String name = getValue (node, "name"); if (name == null) return; // nothing to do LogEvent evt = new LogEvent (qsp, "re-config-task", name); try { Object task = NameRegistrar.get (NAMEREGISTRAR_PREFIX + name); if (task instanceof ReConfigurable) configureTask ((Configurable) task, node, evt); } catch (NameRegistrar.NotFoundException e) { evt.addMessage ("<task-not-found/>"); } Logger.log (evt); } private void configureTask (Configurable task, Node node, LogEvent evt) throws ConfigurationException { String [] attributeNames = { "connection-pool" }; Properties props = ConfigUtil.addAttributes ( node, attributeNames, null, evt ); task.setConfiguration (new SimpleConfiguration ( ConfigUtil.addProperties (node, props, evt) ) ); } private String getValue (Node node, String tagName) { Node n = node.getAttributes().getNamedItem (tagName); return n != null ? n.getNodeValue() : null; } }
package cpw.mods.fml.client.registry; import java.util.List; import java.util.Map; import net.minecraft.block.Block; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.entity.*; import net.minecraft.entity.Entity; import net.minecraft.world.IBlockAccess; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.ObjectArrays; import cpw.mods.fml.client.TextureFXManager; /** * @author cpw * */ public class RenderingRegistry { private static final RenderingRegistry INSTANCE = new RenderingRegistry(); private int nextRenderId = 40; private Map<Integer, ISimpleBlockRenderingHandler> blockRenderers = Maps.newHashMap(); private List<EntityRendererInfo> entityRenderers = Lists.newArrayList(); /** * Add a new armour prefix to the RenderPlayer * * @param armor */ public static int addNewArmourRendererPrefix(String armor) { RenderPlayer.field_77110_j = ObjectArrays.concat(RenderPlayer.field_77110_j, armor); RenderBiped.field_82424_k = RenderPlayer.field_77110_j; return RenderPlayer.field_77110_j.length - 1; } /** * Register an entity rendering handler. This will, after mod initialization, be inserted into the main * render map for entities * * @param entityClass * @param renderer */ public static void registerEntityRenderingHandler(Class<? extends Entity> entityClass, Render renderer) { instance().entityRenderers.add(new EntityRendererInfo(entityClass, renderer)); } /** * Register a simple block rendering handler * * @param handler */ public static void registerBlockHandler(ISimpleBlockRenderingHandler handler) { instance().blockRenderers.put(handler.getRenderId(), handler); } /** * Register the simple block rendering handler * This version will not call getRenderId on the passed in handler, instead using the supplied ID, so you * can easily re-use the same rendering handler for multiple IDs * * @param renderId * @param handler */ public static void registerBlockHandler(int renderId, ISimpleBlockRenderingHandler handler) { instance().blockRenderers.put(renderId, handler); } /** * Get the next available renderId from the block render ID list */ public static int getNextAvailableRenderId() { return instance().nextRenderId++; } /** * Add a texture override for the given path and return the used index * * @param fileToOverride * @param fileToAdd */ @Deprecated public static int addTextureOverride(String fileToOverride, String fileToAdd) { return -1; } /** * Add a texture override for the given path and index * * @param path * @param overlayPath * @param index */ public static void addTextureOverride(String path, String overlayPath, int index) { // TextureFXManager.instance().addNewTextureOverride(path, overlayPath, index); } /** * Get and reserve a unique texture index for the supplied path * * @param path */ @Deprecated public static int getUniqueTextureIndex(String path) { return -1; } @Deprecated public static RenderingRegistry instance() { return INSTANCE; } private static class EntityRendererInfo { public EntityRendererInfo(Class<? extends Entity> target, Render renderer) { this.target = target; this.renderer = renderer; } private Class<? extends Entity> target; private Render renderer; } public boolean renderWorldBlock(RenderBlocks renderer, IBlockAccess world, int x, int y, int z, Block block, int modelId) { if (!blockRenderers.containsKey(modelId)) { return false; } ISimpleBlockRenderingHandler bri = blockRenderers.get(modelId); return bri.renderWorldBlock(world, x, y, z, block, modelId, renderer); } public void renderInventoryBlock(RenderBlocks renderer, Block block, int metadata, int modelID) { if (!blockRenderers.containsKey(modelID)) { return; } ISimpleBlockRenderingHandler bri = blockRenderers.get(modelID); bri.renderInventoryBlock(block, metadata, modelID, renderer); } public boolean renderItemAsFull3DBlock(int modelId) { ISimpleBlockRenderingHandler bri = blockRenderers.get(modelId); return bri != null && bri.shouldRender3DInInventory(); } public void loadEntityRenderers(Map<Class<? extends Entity>, Render> rendererMap) { for (EntityRendererInfo info : entityRenderers) { rendererMap.put(info.target, info.renderer); info.renderer.func_76976_a(RenderManager.field_78727_a); } } }
// FileStitcher.java package loci.formats; import java.awt.image.BufferedImage; import java.io.*; import java.lang.reflect.InvocationTargetException; import java.util.*; /** * Logic to stitch together files with similar names. * Assumes that all files have the same dimensions. */ public class FileStitcher implements IFormatReader { // -- Fields -- /** FormatReader to use as a template for constituent readers. */ private IFormatReader reader; /** * Whether string ids given should be treated * as file patterns rather than single file paths. */ private boolean patternIds = false; /** Current file pattern string. */ private String currentId; /** File pattern object used to build the list of files. */ private FilePattern fp; /** Axis guesser object used to guess which dimensional axes are which. */ private AxisGuesser[] ag; /** The matching files. */ private String[] files; /** Used files list. */ private String[] usedFiles; /** Reader used for each file. */ private IFormatReader[] readers; /** Blank buffered image, for use when image counts vary between files. */ private BufferedImage[] blankImage; /** Blank image bytes, for use when image counts vary between files. */ private byte[][] blankBytes; /** Blank buffered thumbnail, for use when image counts vary between files. */ private BufferedImage[] blankThumb; /** Blank thumbnail bytes, for use when image counts vary between files. */ private byte[][] blankThumbBytes; /** Number of images per file. */ private int[] imagesPerFile; /** Dimensional axis lengths per file. */ private int[] sizeZ, sizeC, sizeT; /** Component lengths for each axis type. */ private int[][] lenZ, lenC, lenT; /** Core metadata. */ private CoreMetadata core; // -- Constructors -- /** Constructs a FileStitcher around a new image reader. */ public FileStitcher() { this(new ImageReader()); } /** * Constructs a FileStitcher around a new image reader. * @param patternIds Whether string ids given should be treated as file * patterns rather than single file paths. */ public FileStitcher(boolean patternIds) { this(new ImageReader(), patternIds); } /** * Constructs a FileStitcher with the given reader. * @param r The reader to use for reading stitched files. */ public FileStitcher(IFormatReader r) { this(r, false); } /** * Constructs a FileStitcher with the given reader. * @param r The reader to use for reading stitched files. * @param patternIds Whether string ids given should be treated as file * patterns rather than single file paths. */ public FileStitcher(IFormatReader r, boolean patternIds) { reader = r; this.patternIds = patternIds; } // -- FileStitcher API methods -- /** Gets the wrapped reader prototype. */ public IFormatReader getReader() { return reader; } /** * Gets the axis type for each dimensional block. * @return An array containing values from the enumeration: * <ul> * <li>AxisGuesser.Z_AXIS: focal planes</li> * <li>AxisGuesser.T_AXIS: time points</li> * <li>AxisGuesser.C_AXIS: channels</li> * </ul> */ public int[] getAxisTypes() { FormatTools.assertId(currentId, true, 2); return ag[getSeries()].getAxisTypes(); } /** * Sets the axis type for each dimensional block. * @param axes An array containing values from the enumeration: * <ul> * <li>AxisGuesser.Z_AXIS: focal planes</li> * <li>AxisGuesser.T_AXIS: time points</li> * <li>AxisGuesser.C_AXIS: channels</li> * </ul> */ public void setAxisTypes(int[] axes) throws FormatException { FormatTools.assertId(currentId, true, 2); ag[getSeries()].setAxisTypes(axes); computeAxisLengths(); } /** Gets the file pattern object used to build the list of files. */ public FilePattern getFilePattern() { FormatTools.assertId(currentId, true, 2); return fp; } /** * Gets the axis guesser object used to guess * which dimensional axes are which. */ public AxisGuesser getAxisGuesser() { FormatTools.assertId(currentId, true, 2); return ag[getSeries()]; } /** * Finds the file pattern for the given ID, based on the state of the file * stitcher. Takes both ID map entries and the patternIds flag into account. */ public FilePattern findPattern(String id) { FormatTools.assertId(currentId, true, 2); if (!patternIds) { // find the containing pattern Hashtable map = Location.getIdMap(); String pattern = null; if (map.containsKey(id)) { // search ID map for pattern, rather than files on disk String[] idList = new String[map.size()]; Enumeration en = map.keys(); for (int i=0; i<idList.length; i++) { idList[i] = (String) en.nextElement(); } pattern = FilePattern.findPattern(id, null, idList); } else { // id is an unmapped file path; look to similar files on disk pattern = FilePattern.findPattern(new Location(id)); } if (pattern != null) id = pattern; } return new FilePattern(id); } // -- IFormatReader API methods -- /* @see IFormatReader#isThisType(byte[]) */ public boolean isThisType(byte[] block) { return reader.isThisType(block); } /* @see IFormatReader#setId(String) */ public void setId(String id) throws FormatException, IOException { if (!id.equals(currentId)) initFile(id); } /* @see IFormatReader#setId(String, boolean) */ public void setId(String id, boolean force) throws FormatException, IOException { if (!id.equals(currentId) || force) initFile(id); } /* @see IFormatReader#getImageCount() */ public int getImageCount() { FormatTools.assertId(currentId, true, 2); return core.imageCount[getSeries()]; } /* @see IFormatReader#isRGB() */ public boolean isRGB() { FormatTools.assertId(currentId, true, 2); return core.rgb[getSeries()]; } /* @see IFormatReader#getSizeX() */ public int getSizeX() { FormatTools.assertId(currentId, true, 2); return core.sizeX[getSeries()]; } /* @see IFormatReader#getSizeY() */ public int getSizeY() { FormatTools.assertId(currentId, true, 2); return core.sizeY[getSeries()]; } /* @see IFormatReader#getSizeZ() */ public int getSizeZ() { FormatTools.assertId(currentId, true, 2); return core.sizeZ[getSeries()]; } /* @see IFormatReader#getSizeC() */ public int getSizeC() { FormatTools.assertId(currentId, true, 2); return core.sizeC[getSeries()]; } /* @see IFormatReader#getSizeT() */ public int getSizeT() { FormatTools.assertId(currentId, true, 2); return core.sizeT[getSeries()]; } /* @see IFormatReader#getPixelType() */ public int getPixelType() { FormatTools.assertId(currentId, true, 2); return core.pixelType[getSeries()]; } /* @see IFormatReader#getEffectiveSizeC() */ public int getEffectiveSizeC() { FormatTools.assertId(currentId, true, 2); return getImageCount() / (getSizeZ() * getSizeT()); } /* @see IFormatReader#getRGBChannelCount() */ public int getRGBChannelCount() { FormatTools.assertId(currentId, true, 2); return getSizeC() / getEffectiveSizeC(); } /* @see IFormatReader#getChannelDimLengths() */ public int[] getChannelDimLengths() { FormatTools.assertId(currentId, true, 1); return core.cLengths[getSeries()]; } /* @see IFormatReader#getChannelDimTypes() */ public String[] getChannelDimTypes() { FormatTools.assertId(currentId, true, 1); return core.cTypes[getSeries()]; } /* @see IFormatReader#getThumbSizeX() */ public int getThumbSizeX() { FormatTools.assertId(currentId, true, 2); return reader.getThumbSizeX(); } /* @see IFormatReader#getThumbSizeY() */ public int getThumbSizeY() { FormatTools.assertId(currentId, true, 2); return reader.getThumbSizeY(); } /* @see IFormatReader#isLittleEndian() */ public boolean isLittleEndian() { FormatTools.assertId(currentId, true, 2); return reader.isLittleEndian(); } /* @see IFormatReader#getDimensionOrder() */ public String getDimensionOrder() { FormatTools.assertId(currentId, true, 2); return core.currentOrder[getSeries()]; } /* @see IFormatReader#isOrderCertain() */ public boolean isOrderCertain() { FormatTools.assertId(currentId, true, 2); return core.orderCertain[getSeries()]; } /* @see IFormatReader#isInterleaved() */ public boolean isInterleaved() { FormatTools.assertId(currentId, true, 2); return reader.isInterleaved(); } /* @see IFormatReader#isInterleaved(int) */ public boolean isInterleaved(int subC) { FormatTools.assertId(currentId, true, 2); return reader.isInterleaved(subC); } /* @see IFormatReader#openImage(int) */ public BufferedImage openImage(int no) throws FormatException, IOException { FormatTools.assertId(currentId, true, 2); int[] q = computeIndices(no); int fno = q[0], ino = q[1]; if (ino < readers[fno].getImageCount()) { return readers[fno].openImage(ino); } // return a blank image to cover for the fact that // this file does not contain enough image planes int sno = getSeries(); if (blankImage[sno] == null) { blankImage[sno] = ImageTools.blankImage(core.sizeX[sno], core.sizeY[sno], sizeC[sno], getPixelType()); } return blankImage[sno]; } /* @see IFormatReader#openBytes(int) */ public byte[] openBytes(int no) throws FormatException, IOException { FormatTools.assertId(currentId, true, 2); int[] q = computeIndices(no); int fno = q[0], ino = q[1]; if (ino < readers[fno].getImageCount()) { return readers[fno].openBytes(ino); } // return a blank image to cover for the fact that // this file does not contain enough image planes int sno = getSeries(); if (blankBytes[sno] == null) { int bytes = FormatTools.getBytesPerPixel(getPixelType()); blankBytes[sno] = new byte[core.sizeX[sno] * core.sizeY[sno] * bytes * getRGBChannelCount()]; } return blankBytes[sno]; } /* @see IFormatReader#openBytes(int, byte[]) */ public byte[] openBytes(int no, byte[] buf) throws FormatException, IOException { FormatTools.assertId(currentId, true, 2); int[] q = computeIndices(no); int fno = q[0], ino = q[1]; if (ino < readers[fno].getImageCount()) { return readers[fno].openBytes(ino, buf); } // return a blank image to cover for the fact that // this file does not contain enough image planes Arrays.fill(buf, (byte) 0); return buf; } /* @see IFormatReader#openThumbImage(int) */ public BufferedImage openThumbImage(int no) throws FormatException, IOException { FormatTools.assertId(currentId, true, 2); int[] q = computeIndices(no); int fno = q[0], ino = q[1]; if (ino < readers[fno].getImageCount()) { return readers[fno].openThumbImage(ino); } // return a blank image to cover for the fact that // this file does not contain enough image planes int sno = getSeries(); if (blankThumb[sno] == null) { blankThumb[sno] = ImageTools.blankImage(getThumbSizeX(), getThumbSizeY(), sizeC[sno], getPixelType()); } return blankThumb[sno]; } /* @see IFormatReader#openThumbBytes(int) */ public byte[] openThumbBytes(int no) throws FormatException, IOException { FormatTools.assertId(currentId, true, 2); int[] q = computeIndices(no); int fno = q[0], ino = q[1]; if (ino < readers[fno].getImageCount()) { return readers[fno].openThumbBytes(ino); } // return a blank image to cover for the fact that // this file does not contain enough image planes int sno = getSeries(); if (blankThumbBytes[sno] == null) { int bytes = FormatTools.getBytesPerPixel(getPixelType()); blankThumbBytes[sno] = new byte[getThumbSizeX() * getThumbSizeY() * bytes * getRGBChannelCount()]; } return blankThumbBytes[sno]; } /* @see IFormatReader#close(boolean) */ public void close(boolean fileOnly) throws IOException { if (readers == null) reader.close(fileOnly); else { for (int i=0; i<readers.length; i++) readers[i].close(fileOnly); } if (!fileOnly) { readers = null; blankImage = null; blankBytes = null; currentId = null; } } /* @see IFormatReader#close() */ public void close() throws IOException { if (readers == null) reader.close(); else { for (int i=0; i<readers.length; i++) readers[i].close(); } readers = null; blankImage = null; blankBytes = null; currentId = null; } /* @see IFormatReader#getSeriesCount() */ public int getSeriesCount() { FormatTools.assertId(currentId, true, 2); return reader.getSeriesCount(); } /* @see IFormatReader#setSeries(int) */ public void setSeries(int no) throws FormatException { FormatTools.assertId(currentId, true, 2); reader.setSeries(no); } /* @see IFormatReader#getSeries() */ public int getSeries() { FormatTools.assertId(currentId, true, 2); return reader.getSeries(); } /* @see IFormatReader#setNormalized(boolean) */ public void setNormalized(boolean normalize) { FormatTools.assertId(currentId, false, 2); if (readers == null) reader.setNormalized(normalize); else { for (int i=0; i<readers.length; i++) { readers[i].setNormalized(normalize); } } } /* @see IFormatReader#isNormalized() */ public boolean isNormalized() { return reader.isNormalized(); } /* @see IFormatReader#setMetadataCollected(boolean) */ public void setMetadataCollected(boolean collect) { FormatTools.assertId(currentId, false, 2); if (readers == null) reader.setMetadataCollected(collect); else { for (int i=0; i<readers.length; i++) { readers[i].setMetadataCollected(collect); } } } /* @see IFormatReader#isMetadataCollected() */ public boolean isMetadataCollected() { return reader.isMetadataCollected(); } /* @see IFormatReader#getUsedFiles() */ public String[] getUsedFiles() { FormatTools.assertId(currentId, true, 2); // returning the files list directly here is fast, since we do not // have to call initFile on each constituent file; but we can only do so // when each constituent file does not itself have multiple used files if (reader.getUsedFiles().length > 1) { // each constituent file has multiple used files; we must build the list // this could happen with, e.g., a stitched collection of ICS/IDS pairs // we have no datasets structured this way, so this logic is untested if (usedFiles == null) { String[][] used = new String[files.length][]; int total = 0; for (int i=0; i<files.length; i++) { try { readers[i].setId(files[i]); } catch (FormatException exc) { exc.printStackTrace(); return null; } catch (IOException exc) { exc.printStackTrace(); return null; } used[i] = readers[i].getUsedFiles(); total += used[i].length; } usedFiles = new String[total]; for (int i=0, off=0; i<used.length; i++) { System.arraycopy(used[i], 0, usedFiles, off, used[i].length); off += used[i].length; } } return usedFiles; } // assume every constituent file has no other used files // this logic could fail if the first constituent has no extra used files, // but later constituents do; in practice, this scenario seems unlikely return files; } /* @see IFormatReader#getCurrentFile() */ public String getCurrentFile() { return currentId; } /* @see IFormatReader#getIndex(int, int, int) */ public int getIndex(int z, int c, int t) throws FormatException { return FormatTools.getIndex(this, z, c, t); } /* @see IFormatReader#getZCTCoords(int) */ public int[] getZCTCoords(int index) throws FormatException { return FormatTools.getZCTCoords(this, index); } /* @see IFormatReader#getMetadataValue(String) */ public Object getMetadataValue(String field) { FormatTools.assertId(currentId, true, 2); return reader.getMetadataValue(field); } /* @see IFormatReader#getMetadata() */ public Hashtable getMetadata() { FormatTools.assertId(currentId, true, 2); return reader.getMetadata(); } /* @see IFormatReader#getCoreMetadata() */ public CoreMetadata getCoreMetadata() { FormatTools.assertId(currentId, true, 2); return core; } /* @see IFormatReader#setMetadataFiltered(boolean) */ public void setMetadataFiltered(boolean filter) { FormatTools.assertId(currentId, false, 2); reader.setMetadataFiltered(filter); } /* @see IFormatReader#isMetadataFiltered() */ public boolean isMetadataFiltered() { return reader.isMetadataFiltered(); } /* @see IFormatReader#setMetadataStore(MetadataStore) */ public void setMetadataStore(MetadataStore store) { FormatTools.assertId(currentId, false, 2); reader.setMetadataStore(store); } /* @see IFormatReader#getMetadataStore() */ public MetadataStore getMetadataStore() { FormatTools.assertId(currentId, true, 2); return reader.getMetadataStore(); } /* @see IFormatReader#getMetadataStoreRoot() */ public Object getMetadataStoreRoot() { FormatTools.assertId(currentId, true, 2); return reader.getMetadataStoreRoot(); } /* @see IFormatReader#testRead(String[]) */ public boolean testRead(String[] args) throws FormatException, IOException { return FormatTools.testRead(this, args); } // -- IFormatHandler API methods -- /* @see IFormatHandler#isThisType(String) */ public boolean isThisType(String name) { return reader.isThisType(name); } /* @see IFormatHandler#isThisType(String, boolean) */ public boolean isThisType(String name, boolean open) { return reader.isThisType(name, open); } /* @see IFormatHandler#getFormat() */ public String getFormat() { FormatTools.assertId(currentId, true, 2); return reader.getFormat(); } /* @see IFormatHandler#getSuffixes() */ public String[] getSuffixes() { return reader.getSuffixes(); } // -- StatusReporter API methods -- /* @see IFormatHandler#addStatusListener(StatusListener) */ public void addStatusListener(StatusListener l) { if (readers == null) reader.addStatusListener(l); else { for (int i=0; i<readers.length; i++) readers[i].addStatusListener(l); } } /* @see IFormatHandler#removeStatusListener(StatusListener) */ public void removeStatusListener(StatusListener l) { if (readers == null) reader.removeStatusListener(l); else { for (int i=0; i<readers.length; i++) readers[i].removeStatusListener(l); } } /* @see IFormatHandler#getStatusListeners() */ public StatusListener[] getStatusListeners() { return reader.getStatusListeners(); } // -- Helper methods -- /** Initializes the given file. */ protected void initFile(String id) throws FormatException, IOException { if (FormatHandler.debug) { System.out.println("calling FileStitcher.initFile(" + id + ")"); } currentId = id; fp = findPattern(id); // verify that file pattern is valid and matches existing files String msg = " Please rename your files or disable file stitching."; if (!fp.isValid()) { throw new FormatException("Invalid " + (patternIds ? "file pattern" : "filename") + " (" + currentId + "): " + fp.getErrorMessage() + msg); } files = fp.getFiles(); if (files == null) { throw new FormatException("No files matching pattern (" + fp.getPattern() + "). " + msg); } for (int i=0; i<files.length; i++) { if (!new Location(files[i]).exists()) { throw new FormatException("File " (" + files[i] + ") does not exist."); } } // determine reader type for these files; assume all are the same type Vector classes = new Vector(); IFormatReader r = reader; while (r instanceof ReaderWrapper) { classes.add(r.getClass()); r = ((ReaderWrapper) r).getReader(); } if (r instanceof ImageReader) r = ((ImageReader) r).getReader(files[0]); classes.add(r.getClass()); // construct list of readers for all files readers = new IFormatReader[files.length]; readers[0] = reader; for (int i=1; i<readers.length; i++) { // use crazy reflection to instantiate a reader of the proper type try { r = null; for (int j=classes.size()-1; j>=0; j Class c = (Class) classes.elementAt(j); if (r == null) r = (IFormatReader) c.newInstance(); else { r = (IFormatReader) c.getConstructor( new Class[] {IFormatReader.class}).newInstance(new Object[] {r}); } } readers[i] = (IFormatReader) r; } catch (InstantiationException exc) { exc.printStackTrace(); } catch (IllegalAccessException exc) { exc.printStackTrace(); } catch (NoSuchMethodException exc) { exc.printStackTrace(); } catch (InvocationTargetException exc) { exc.printStackTrace(); } } // sync reader configurations with original reader boolean normalized = reader.isNormalized(); boolean metadataFiltered = reader.isMetadataFiltered(); boolean metadataCollected = reader.isMetadataCollected(); StatusListener[] statusListeners = reader.getStatusListeners(); for (int i=1; i<readers.length; i++) { readers[i].setNormalized(normalized); readers[i].setMetadataFiltered(metadataFiltered); readers[i].setMetadataCollected(metadataCollected); for (int j=0; j<statusListeners.length; j++) { readers[i].addStatusListener(statusListeners[j]); } } reader.setId(files[0]); int seriesCount = reader.getSeriesCount(); ag = new AxisGuesser[seriesCount]; blankImage = new BufferedImage[seriesCount]; blankBytes = new byte[seriesCount][]; blankThumb = new BufferedImage[seriesCount]; blankThumbBytes = new byte[seriesCount][]; imagesPerFile = new int[seriesCount]; sizeZ = new int[seriesCount]; sizeC = new int[seriesCount]; sizeT = new int[seriesCount]; boolean[] certain = new boolean[seriesCount]; lenZ = new int[seriesCount][]; lenC = new int[seriesCount][]; lenT = new int[seriesCount][]; // analyze first file; assume each file has the same parameters core = new CoreMetadata(seriesCount); int oldSeries = reader.getSeries(); for (int i=0; i<seriesCount; i++) { reader.setSeries(i); core.sizeX[i] = reader.getSizeX(); core.sizeY[i] = reader.getSizeY(); // NB: core.sizeZ populated in computeAxisLengths below // NB: core.sizeC populated in computeAxisLengths below // NB: core.sizeT populated in computeAxisLengths below core.pixelType[i] = reader.getPixelType(); imagesPerFile[i] = reader.getImageCount(); core.imageCount[i] = files.length * imagesPerFile[i]; core.thumbSizeX[i] = reader.getThumbSizeX(); core.thumbSizeY[i] = reader.getThumbSizeY(); // NB: core.cLengths[i] populated in computeAxisLengths below // NB: core.cTypes[i] populated in computeAxisLengths below core.currentOrder[i] = reader.getDimensionOrder(); // NB: core.orderCertain[i] populated below core.rgb[i] = reader.isRGB(); core.littleEndian[i] = reader.isLittleEndian(); core.interleaved[i] = reader.isInterleaved(); core.seriesMetadata[i] = reader.getMetadata(); sizeZ[i] = reader.getSizeZ(); sizeC[i] = reader.getSizeC(); sizeT[i] = reader.getSizeT(); certain[i] = reader.isOrderCertain(); } reader.setSeries(oldSeries); // guess at dimensions corresponding to file numbering for (int i=0; i<seriesCount; i++) { ag[i] = new AxisGuesser(fp, core.currentOrder[i], sizeZ[i], sizeT[i], sizeC[i], certain[i]); } // order may need to be adjusted for (int i=0; i<seriesCount; i++) { setSeries(i); core.currentOrder[i] = ag[i].getAdjustedOrder(); core.orderCertain[i] = ag[i].isCertain(); computeAxisLengths(); } setSeries(oldSeries); // initialize used files list only when requested usedFiles = null; } /** Computes axis length arrays, and total axis lengths. */ protected void computeAxisLengths() throws FormatException { int sno = getSeries(); int[] count = fp.getCount(); int[] axes = ag[sno].getAxisTypes(); int numZ = ag[sno].getAxisCountZ(); int numC = ag[sno].getAxisCountC(); int numT = ag[sno].getAxisCountT(); core.sizeZ[sno] = sizeZ[sno]; core.sizeC[sno] = sizeC[sno]; core.sizeT[sno] = sizeT[sno]; lenZ[sno] = new int[numZ + 1]; lenC[sno] = new int[numC + 1]; lenT[sno] = new int[numT + 1]; lenZ[sno][0] = sizeZ[sno]; lenC[sno][0] = sizeC[sno]; lenT[sno][0] = sizeT[sno]; for (int i=0, z=1, c=1, t=1; i<axes.length; i++) { switch (axes[i]) { case AxisGuesser.Z_AXIS: core.sizeZ[sno] *= count[i]; lenZ[sno][z++] = count[i]; break; case AxisGuesser.C_AXIS: core.sizeC[sno] *= count[i]; lenC[sno][c++] = count[i]; break; case AxisGuesser.T_AXIS: core.sizeT[sno] *= count[i]; lenT[sno][t++] = count[i]; break; default: throw new FormatException("Unknown axis type for axis i + ": " + axes[i]); } } int[] cLengths = reader.getChannelDimLengths(); String[] cTypes = reader.getChannelDimTypes(); int cCount = 0; for (int i=0; i<cLengths.length; i++) { if (cLengths[i] > 1) cCount++; } for (int i=1; i<lenC[sno].length; i++) { if (lenC[sno][i] > 1) cCount++; } if (cCount == 0) { core.cLengths[sno] = new int[] {1}; core.cTypes[sno] = new String[] {FormatTools.CHANNEL}; } else { core.cLengths[sno] = new int[cCount]; core.cTypes[sno] = new String[cCount]; } int c = 0; for (int i=0; i<cLengths.length; i++) { if (cLengths[i] == 1) continue; core.cLengths[sno][c] = cLengths[i]; core.cTypes[sno][c] = cTypes[i]; c++; } for (int i=1; i<lenC[sno].length; i++) { if (lenC[sno][i] == 1) continue; core.cLengths[sno][c] = lenC[sno][i]; core.cTypes[sno][c] = FormatTools.CHANNEL; } // populate metadata store int pixelType = getPixelType(); boolean little = reader.isLittleEndian(); MetadataStore s = reader.getMetadataStore(); s.setPixels(new Integer(core.sizeX[sno]), new Integer(core.sizeY[sno]), new Integer(core.sizeZ[sno]), new Integer(core.sizeC[sno]), new Integer(core.sizeT[sno]), new Integer(pixelType), new Boolean(!little), core.currentOrder[sno], new Integer(sno), null); } /** * Gets the file index, and image index into that file, * corresponding to the given global image index. * * @return An array of size 2, dimensioned {file index, image index}. */ protected int[] computeIndices(int no) throws FormatException, IOException { int sno = getSeries(); int[] axes = ag[sno].getAxisTypes(); int[] count = fp.getCount(); // get Z, C and T positions int[] zct = getZCTCoords(no); int[] posZ = FormatTools.rasterToPosition(lenZ[sno], zct[0]); int[] posC = FormatTools.rasterToPosition(lenC[sno], zct[1]); int[] posT = FormatTools.rasterToPosition(lenT[sno], zct[2]); // convert Z, C and T position lists into file index and image index int[] pos = new int[axes.length]; int z = 1, c = 1, t = 1; for (int i=0; i<axes.length; i++) { if (axes[i] == AxisGuesser.Z_AXIS) pos[i] = posZ[z++]; else if (axes[i] == AxisGuesser.C_AXIS) pos[i] = posC[c++]; else if (axes[i] == AxisGuesser.T_AXIS) pos[i] = posT[t++]; else { throw new FormatException("Unknown axis type for axis i + ": " + axes[i]); } } int fno = FormatTools.positionToRaster(count, pos); // configure the reader, in case we haven't done this one yet readers[fno].setId(files[fno]); readers[fno].setSeries(reader.getSeries()); int ino; if (posZ[0] < readers[fno].getSizeZ() && posC[0] < readers[fno].getSizeC() && posT[0] < readers[fno].getSizeT()) { ino = FormatTools.getIndex(readers[fno], posZ[0], posC[0], posT[0]); } else ino = Integer.MAX_VALUE; // coordinates out of range return new int[] {fno, ino}; } /** * Gets a list of readers to include in relation to the given C position. * @return Array with indices corresponding to the list of readers, and * values indicating the internal channel index to use for that reader. */ protected int[] getIncludeList(int theC) throws FormatException, IOException { int[] include = new int[readers.length]; Arrays.fill(include, -1); for (int t=0; t<sizeT[getSeries()]; t++) { for (int z=0; z<sizeZ[getSeries()]; z++) { int no = getIndex(z, theC, t); int[] q = computeIndices(no); int fno = q[0], ino = q[1]; include[fno] = ino; } } return include; } // -- Deprecated FileStitcher API methods -- /** @deprecated Replaced by {@link #getAxisTypes()} */ public int[] getAxisTypes(String id) throws FormatException, IOException { setId(id); return getAxisTypes(); } /** @deprecated Replaced by {@link #setAxisTypes(int[])} */ public void setAxisTypes(String id, int[] axes) throws FormatException, IOException { setId(id); setAxisTypes(axes); } /** @deprecated Replaced by {@link #getFilePattern()} */ public FilePattern getFilePattern(String id) throws FormatException, IOException { setId(id); return getFilePattern(); } /** @deprecated Replaced by {@link #getAxisGuesser()} */ public AxisGuesser getAxisGuesser(String id) throws FormatException, IOException { setId(id); return getAxisGuesser(); } // -- Deprecated IFormatReader API methods -- /** @deprecated Replaced by {@link #getImageCount()} */ public int getImageCount(String id) throws FormatException, IOException { setId(id); return getImageCount(); } /** @deprecated Replaced by {@link #isRGB()} */ public boolean isRGB(String id) throws FormatException, IOException { setId(id); return isRGB(); } /** @deprecated Replaced by {@link #getSizeX()} */ public int getSizeX(String id) throws FormatException, IOException { setId(id); return getSizeX(); } /** @deprecated Replaced by {@link #getSizeY()} */ public int getSizeY(String id) throws FormatException, IOException { setId(id); return getSizeY(); } /** @deprecated Replaced by {@link #getSizeZ()} */ public int getSizeZ(String id) throws FormatException, IOException { setId(id); return getSizeZ(); } /** @deprecated Replaced by {@link #getSizeC()} */ public int getSizeC(String id) throws FormatException, IOException { setId(id); return getSizeC(); } /** @deprecated Replaced by {@link #getSizeT()} */ public int getSizeT(String id) throws FormatException, IOException { setId(id); return getSizeT(); } /** @deprecated Replaced by {@link #getPixelType()} */ public int getPixelType(String id) throws FormatException, IOException { setId(id); return getPixelType(); } /** @deprecated Replaced by {@link #getEffectiveSizeC()} */ public int getEffectiveSizeC(String id) throws FormatException, IOException { setId(id); return getEffectiveSizeC(); } /** @deprecated Replaced by {@link #getRGBChannelCount()} */ public int getRGBChannelCount(String id) throws FormatException, IOException { setId(id); return getSizeC() / getEffectiveSizeC(); } /** @deprecated Replaced by {@link #getChannelDimLengths()} */ public int[] getChannelDimLengths(String id) throws FormatException, IOException { setId(id); return getChannelDimLengths(); } /** @deprecated Replaced by {@link #getChannelDimTypes()} */ public String[] getChannelDimTypes(String id) throws FormatException, IOException { setId(id); return getChannelDimTypes(); } /** @deprecated Replaced by {@link #getThumbSizeX()} */ public int getThumbSizeX(String id) throws FormatException, IOException { setId(id); return getThumbSizeX(); } /** @deprecated Replaced by {@link #getThumbSizeY()} */ public int getThumbSizeY(String id) throws FormatException, IOException { setId(id); return getThumbSizeY(); } /** @deprecated Replaced by {@link #isLittleEndian()} */ public boolean isLittleEndian(String id) throws FormatException, IOException { setId(id); return isLittleEndian(); } /** @deprecated Replaced by {@link #getDimensionOrder()} */ public String getDimensionOrder(String id) throws FormatException, IOException { setId(id); return getDimensionOrder(); } /** @deprecated Replaced by {@link #isOrderCertain()} */ public boolean isOrderCertain(String id) throws FormatException, IOException { setId(id); return isOrderCertain(); } /** @deprecated Replaced by {@link #isInterleaved()} */ public boolean isInterleaved(String id) throws FormatException, IOException { setId(id); return isInterleaved(); } /** @deprecated Replaced by {@link #isInterleaved(int)} */ public boolean isInterleaved(String id, int subC) throws FormatException, IOException { setId(id); return isInterleaved(subC); } /** @deprecated Replaced by {@link #openImage(int)} */ public BufferedImage openImage(String id, int no) throws FormatException, IOException { setId(id); return openImage(no); } /** @deprecated Replaced by {@link #openBytes(int)} */ public byte[] openBytes(String id, int no) throws FormatException, IOException { setId(id); return openBytes(no); } /** @deprecated Replaced by {@link #openBytes(int, byte[])} */ public byte[] openBytes(String id, int no, byte[] buf) throws FormatException, IOException { setId(id); return openBytes(no, buf); } /** @deprecated Replaced by {@link #openThumbImage(int)} */ public BufferedImage openThumbImage(String id, int no) throws FormatException, IOException { setId(id); return openThumbImage(no); } /** @deprecated Replaced by {@link #openThumbImage(int)} */ public byte[] openThumbBytes(String id, int no) throws FormatException, IOException { setId(id); return openThumbBytes(no); } /** @deprecated Replaced by {@link #getSeriesCount()} */ public int getSeriesCount(String id) throws FormatException, IOException { setId(id); return getSeriesCount(); } /** @deprecated Replaced by {@link #setSeries(int)} */ public void setSeries(String id, int no) throws FormatException, IOException { setId(id); setSeries(no); } /** @deprecated Replaced by {@link #getSeries()} */ public int getSeries(String id) throws FormatException, IOException { setId(id); return getSeries(); } /** @deprecated Replaced by {@link #getUsedFiles()} */ public String[] getUsedFiles(String id) throws FormatException, IOException { setId(id); return getUsedFiles(); } /** @deprecated Replaced by {@link #getIndex(int, int, int)} */ public int getIndex(String id, int z, int c, int t) throws FormatException, IOException { setId(id); return getIndex(z, c, t); } /** @deprecated Replaced by {@link #getZCTCoords(int)} */ public int[] getZCTCoords(String id, int index) throws FormatException, IOException { setId(id); return getZCTCoords(index); } /** @deprecated Replaced by {@link #getMetadataValue(String)} */ public Object getMetadataValue(String id, String field) throws FormatException, IOException { setId(id); return getMetadataValue(field); } /** @deprecated Replaced by {@link #getMetadata()} */ public Hashtable getMetadata(String id) throws FormatException, IOException { setId(id); return getMetadata(); } /** @deprecated Replaced by {@link #getCoreMetadata()} */ public CoreMetadata getCoreMetadata(String id) throws FormatException, IOException { setId(id); return getCoreMetadata(); } /** @deprecated Replaced by {@link #getMetadataStore()} */ public MetadataStore getMetadataStore(String id) throws FormatException, IOException { setId(id); return getMetadataStore(); } /** @deprecated Replaced by {@link #getMetadataStoreRoot()} */ public Object getMetadataStoreRoot(String id) throws FormatException, IOException { setId(id); return getMetadataStoreRoot(); } }
// LIFReader.java package loci.formats.in; import java.awt.image.BufferedImage; import java.io.*; import java.text.*; import java.util.*; import javax.xml.parsers.*; import loci.formats.*; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * LIFReader is the file format reader for Leica LIF files. * * @author Melissa Linkert linkert at wisc.edu */ public class LIFReader extends FormatReader { // -- Constants -- /** Factory for generating SAX parsers. */ public static final SAXParserFactory SAX_FACTORY = SAXParserFactory.newInstance(); // -- Fields -- /** Offsets to memory blocks, paired with their corresponding description. */ protected Vector offsets; /** Bits per pixel. */ private int[] bitsPerPixel; /** Extra dimensions. */ private int[] extraDimensions; private int bpp; private Vector xcal; private Vector ycal; private Vector zcal; private Vector seriesNames; private Vector containerNames; private Vector containerCounts; // -- Constructor -- /** Constructs a new Leica LIF reader. */ public LIFReader() { super("Leica Image File Format", "lif"); } // -- IFormatReader API methods -- /* @see loci.formats.IFormatReader#isThisType(byte[]) */ public boolean isThisType(byte[] block) { return block[0] == 0x70; } /* @see loci.formats.IFormatReader#isMetadataComplete() */ public boolean isMetadataComplete() { return true; } /* @see loci.formats.IFormatReader#openBytes(int) */ public byte[] openBytes(int no) throws FormatException, IOException { FormatTools.assertId(currentId, true, 1); bpp = bitsPerPixel[series]; while (bpp % 8 != 0) bpp++; byte[] buf = new byte[core.sizeX[series] * core.sizeY[series] * (bpp / 8) * getRGBChannelCount()]; return openBytes(no, buf); } /* @see loci.formats.IFormatReader#openBytes(int, byte[]) */ public byte[] openBytes(int no, byte[] buf) throws FormatException, IOException { FormatTools.assertId(currentId, true, 1); if (no < 0 || no >= getImageCount()) { throw new FormatException("Invalid image number: " + no); } bpp = bitsPerPixel[series]; while (bpp % 8 != 0) bpp++; int bytes = bpp / 8; if (buf.length < core.sizeX[series] * core.sizeY[series] * bytes * getRGBChannelCount()) { throw new FormatException("Buffer too small."); } long offset = ((Long) offsets.get(series)).longValue(); in.seek(offset + core.sizeX[series] * core.sizeY[series] * bytes * no * getRGBChannelCount()); in.read(buf); return buf; } /* @see loci.formats.IFormatReader#openImage(int) */ public BufferedImage openImage(int no) throws FormatException, IOException { return ImageTools.makeImage(openBytes(no), core.sizeX[series], core.sizeY[series], getRGBChannelCount(), false, bpp / 8, core.littleEndian[series]); } // -- Internal FormatReader API methods -- /* @see loci.formats.FormatReader#initFile(String) */ protected void initFile(String id) throws FormatException, IOException { if (debug) debug("LIFReader.initFile(" + id + ")"); super.initFile(id); in = new RandomAccessStream(id); offsets = new Vector(); core.littleEndian[0] = true; in.order(core.littleEndian[0]); xcal = new Vector(); ycal = new Vector(); zcal = new Vector(); // read the header status("Reading header"); byte checkOne = (byte) in.read(); in.skipBytes(2); byte checkTwo = (byte) in.read(); if (checkOne != 0x70 && checkTwo != 0x70) { throw new FormatException(id + " is not a valid Leica LIF file"); } in.skipBytes(4); // read and parse the XML description if (in.read() != 0x2a) { throw new FormatException("Invalid XML description"); } // number of Unicode characters in the XML block int nc = in.readInt(); String xml = DataTools.stripString(in.readString(nc * 2)); status("Finding image offsets"); while (in.getFilePointer() < in.length()) { if (in.readInt() != 0x70) { throw new FormatException("Invalid Memory Block"); } in.skipBytes(4); if (in.read() != 0x2a) { throw new FormatException("Invalid Memory Description"); } int blockLength = in.readInt(); if (in.read() != 0x2a) { in.skipBytes(3); if (in.read() != 0x2a) { throw new FormatException("Invalid Memory Description"); } } int descrLength = in.readInt(); in.skipBytes(descrLength * 2); if (blockLength > 0) { offsets.add(new Long(in.getFilePointer())); } in.skipBytes(blockLength); } initMetadata(xml); } // -- Helper methods -- /** Parses a string of XML and puts the values in a Hashtable. */ private void initMetadata(String xml) throws FormatException, IOException { // parse raw key/value pairs - adapted from FlexReader containerNames = new Vector(); containerCounts = new Vector(); seriesNames = new Vector(); LIFHandler handler = new LIFHandler(); xml = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><LEICA>" + xml + "</LEICA>"; // strip out invalid characters for (int i=0; i<xml.length(); i++) { char c = xml.charAt(i); if (Character.isISOControl(c) || !Character.isDefined(c)) { xml = xml.replace(c, ' '); } } try { SAXParser parser = SAX_FACTORY.newSAXParser(); parser.parse(new ByteArrayInputStream(xml.getBytes()), handler); } catch (ParserConfigurationException exc) { throw new FormatException(exc); } catch (SAXException exc) { throw new FormatException(exc); } Vector elements = new Vector(); status("Populating native metadata"); // first parse each element in the XML string StringTokenizer st = new StringTokenizer(xml, ">"); while (st.hasMoreTokens()) { String token = st.nextToken(); elements.add(token.substring(1)); } // the first element contains version information String token = (String) elements.get(0); String key = token.substring(0, token.indexOf("\"")); String value = token.substring(token.indexOf("\"") + 1, token.length()-1); addMeta(key, value); // what we have right now is a vector of XML elements, which need to // be parsed into the appropriate image dimensions int ndx = 1; // the image data we need starts with the token "ElementName='blah'" and // ends with the token "/ImageDescription" int numDatasets = 0; Vector widths = new Vector(); Vector heights = new Vector(); Vector zs = new Vector(); Vector ts = new Vector(); Vector channels = new Vector(); Vector bps = new Vector(); Vector extraDims = new Vector(); String prefix = ""; while (ndx < elements.size()) { token = (String) elements.get(ndx); // if the element contains a key/value pair, parse it and put it in // the metadata hashtable if (token.startsWith("ScannerSettingRecord")) { if (token.indexOf("csScanMode") != -1) { int index = token.indexOf("Variant") + 7; String ordering = token.substring(index + 2, token.indexOf("\"", index + 3)); ordering = ordering.toLowerCase(); if (ordering.indexOf("x") == -1 || ordering.indexOf("y") == -1 || ordering.indexOf("xy") == -1) { int xPos = ordering.indexOf("x"); int yPos = ordering.indexOf("y"); int zPos = ordering.indexOf("z"); int tPos = ordering.indexOf("t"); if (xPos < 0) xPos = 0; if (yPos < 0) yPos = 1; if (zPos < 0) zPos = 2; if (tPos < 0) tPos = 3; int x = ((Integer) widths.get(widths.size() - 1)).intValue(); int y = ((Integer) heights.get(widths.size() - 1)).intValue(); int z = ((Integer) zs.get(widths.size() - 1)).intValue(); int t = ((Integer) ts.get(widths.size() - 1)).intValue(); int[] dimensions = {x, y, z, t}; x = dimensions[xPos]; y = dimensions[yPos]; z = dimensions[zPos]; t = dimensions[tPos]; widths.setElementAt(new Integer(x), widths.size() - 1); heights.setElementAt(new Integer(y), heights.size() - 1); zs.setElementAt(new Integer(z), zs.size() - 1); ts.setElementAt(new Integer(t), ts.size() - 1); } } else if (token.indexOf("dblVoxel") != -1) { int index = token.indexOf("Variant") + 7; String size = token.substring(index + 2, token.indexOf("\"", index + 3)); float cal = Float.parseFloat(size) * 1000000; if (token.indexOf("X") != -1) xcal.add(new Float(cal)); else if (token.indexOf("Y") != -1) ycal.add(new Float(cal)); else if (token.indexOf("Z") != -1) zcal.add(new Float(cal)); } } else if (token.startsWith("Element Name")) { // loop until we find "/ImageDescription" //seriesNames.add(token.substring(token.indexOf("=") + 2, // token.length() - 1)); numDatasets++; int numChannels = 0; int extras = 1; while (token.indexOf("/ImageDescription") == -1) { if (token.indexOf("=") != -1) { // create a small hashtable to store just this element's data if (token.startsWith("Element Name")) { // hack to override first series name //seriesNames.setElementAt(token.substring(token.indexOf("=") + 2, // token.length() - 1), seriesNames.size() - 1); //prefix = (String) seriesNames.get(seriesNames.size() - 1); prefix = (String) seriesNames.get(numDatasets - 1); } Hashtable tmp = new Hashtable(); while (token.length() > 2) { key = token.substring(0, token.indexOf("\"") - 1); value = token.substring(token.indexOf("\"") + 1, token.indexOf("\"", token.indexOf("\"") + 1)); token = token.substring(key.length() + value.length() + 3); key = key.trim(); value = value.trim(); tmp.put(key, value); } if (tmp.get("ChannelDescription DataType") != null) { // found channel description block numChannels++; if (numChannels == 1) { bps.add(new Integer((String) tmp.get("Resolution"))); } } else if (tmp.get("DimensionDescription DimID") != null) { // found dimension description block int w = Integer.parseInt((String) tmp.get("NumberOfElements")); int id = Integer.parseInt((String) tmp.get("DimensionDescription DimID")); switch (id) { case 1: widths.add(new Integer(w)); break; case 2: heights.add(new Integer(w)); break; case 3: zs.add(new Integer(w)); break; case 4: ts.add(new Integer(w)); break; default: extras *= w; } } } ndx++; if (elements != null && ndx < elements.size()) { token = (String) elements.get(ndx); } else break; } extraDims.add(new Integer(extras)); if (numChannels == 0) numChannels++; channels.add(new Integer(numChannels)); if (widths.size() < numDatasets && heights.size() < numDatasets) { numDatasets } else { if (widths.size() < numDatasets) widths.add(new Integer(1)); if (heights.size() < numDatasets) heights.add(new Integer(1)); if (zs.size() < numDatasets) zs.add(new Integer(1)); if (ts.size() < numDatasets) ts.add(new Integer(1)); if (bps.size() < numDatasets) bps.add(new Integer(8)); } } ndx++; } numDatasets = widths.size(); bitsPerPixel = new int[numDatasets]; extraDimensions = new int[numDatasets]; // Populate metadata store status("Populating metadata"); // The metadata store we're working with. MetadataStore store = getMetadataStore(); core = new CoreMetadata(numDatasets); Arrays.fill(core.orderCertain, true); for (int i=0; i<numDatasets; i++) { core.sizeX[i] = ((Integer) widths.get(i)).intValue(); core.sizeY[i] = ((Integer) heights.get(i)).intValue(); core.sizeZ[i] = ((Integer) zs.get(i)).intValue(); core.sizeC[i] = ((Integer) channels.get(i)).intValue(); core.sizeT[i] = ((Integer) ts.get(i)).intValue(); core.currentOrder[i] = (core.sizeZ[i] > core.sizeT[i]) ? "XYCZT" : "XYCTZ"; bitsPerPixel[i] = ((Integer) bps.get(i)).intValue(); extraDimensions[i] = ((Integer) extraDims.get(i)).intValue(); if (extraDimensions[i] > 1) { if (core.sizeZ[i] == 1) core.sizeZ[i] = extraDimensions[i]; else core.sizeT[i] *= extraDimensions[i]; extraDimensions[i] = 1; } core.littleEndian[i] = true; core.rgb[i] = core.sizeC[i] > 1 && core.sizeC[i] < 4; core.interleaved[i] = true; core.imageCount[i] = core.sizeZ[i] * core.sizeT[i]; if (!core.rgb[i]) core.imageCount[i] *= core.sizeC[i]; while (bitsPerPixel[i] % 8 != 0) bitsPerPixel[i]++; switch (bitsPerPixel[i]) { case 8: core.pixelType[i] = FormatTools.UINT8; break; case 16: core.pixelType[i] = FormatTools.UINT16; break; case 32: core.pixelType[i] = FormatTools.FLOAT; break; } Integer ii = new Integer(i); String seriesName = (String) seriesNames.get(i); if (seriesName == null || seriesName.trim().length() == 0) { seriesName = "Series " + (i + 1); } store.setImage(seriesName, null, null, ii); store.setPixels( new Integer(core.sizeX[i]), // SizeX new Integer(core.sizeY[i]), // SizeY new Integer(core.sizeZ[i]), // SizeZ new Integer(core.sizeC[i]), // SizeC new Integer(core.sizeT[i]), // SizeT new Integer(core.pixelType[i]), // PixelType new Boolean(!core.littleEndian[i]), // BigEndian core.currentOrder[i], // DimensionOrder ii, // Image index null); // Pixels index Float xf = i < xcal.size() ? (Float) xcal.get(i) : null; Float yf = i < ycal.size() ? (Float) ycal.get(i) : null; Float zf = i < zcal.size() ? (Float) zcal.get(i) : null; store.setDimensions(xf, yf, zf, null, null, ii); for (int j=0; j<core.sizeC[i]; j++) { store.setLogicalChannel(j, null, null, null, null, null, null, ii); } String zoom = (String) getMeta(seriesName + " - dblZoom"); store.setDisplayOptions(zoom == null ? null : new Float(zoom), new Boolean(core.sizeC[i] > 1), new Boolean(core.sizeC[i] > 1), new Boolean(core.sizeC[i] > 2), new Boolean(isRGB()), null, null, null, null, null, ii, null, null, null, null, null); Enumeration keys = metadata.keys(); while (keys.hasMoreElements()) { String k = (String) keys.nextElement(); boolean use = true; for (int j=0; j<seriesNames.size(); j++) { if (j != i && k.startsWith((String) seriesNames.get(j))) { use = false; break; } } if (use) core.seriesMetadata[i].put(k, metadata.get(k)); } } } // -- Helper class -- /** SAX handler for parsing XML. */ class LIFHandler extends DefaultHandler { private String series; private String fullSeries; private int count = 0; private boolean firstElement = true; private boolean dcroiOpen = false; public void endElement(String uri, String localName, String qName) { if (qName.equals("Element")) { if (dcroiOpen) { dcroiOpen = false; return; } if (fullSeries.indexOf("/") != -1) { fullSeries = fullSeries.substring(0, fullSeries.lastIndexOf("/")); } else fullSeries = ""; } } public void startElement(String uri, String localName, String qName, Attributes attributes) { if (qName.equals("Element")) { if (!attributes.getValue("Name").equals("DCROISet") && !firstElement) { series = attributes.getValue("Name"); containerNames.add(series); if (fullSeries == null || fullSeries.equals("")) fullSeries = series; else fullSeries += "/" + series; } else if (firstElement) firstElement = false; if (attributes.getValue("Name").equals("DCROISet")) { dcroiOpen = true; } } else if (qName.equals("Experiment")) { for (int i=0; i<attributes.getLength(); i++) { addMeta(attributes.getQName(i), attributes.getValue(i)); } } else if (qName.equals("Image")) { containerNames.remove(series); if (containerCounts.size() < containerNames.size()) { containerCounts.add(new Integer(1)); } else if (containerCounts.size() > 0) { int ndx = containerCounts.size() - 1; int n = ((Integer) containerCounts.get(ndx)).intValue(); containerCounts.setElementAt(new Integer(n + 1), ndx); } if (fullSeries == null || fullSeries.equals("")) fullSeries = series; seriesNames.add(fullSeries); } else if (qName.equals("ChannelDescription")) { String prefix = fullSeries + " - Channel " + count + " - "; addMeta(prefix + "Min", attributes.getValue("Min")); addMeta(prefix + "Max", attributes.getValue("Max")); addMeta(prefix + "Resolution", attributes.getValue("Resolution")); addMeta(prefix + "LUTName", attributes.getValue("LUTName")); addMeta(prefix + "IsLUTInverted", attributes.getValue("IsLUTInverted")); count++; } else if (qName.equals("DimensionDescription")) { String prefix = fullSeries + " - Dimension " + count + " - "; addMeta(prefix + "NumberOfElements", attributes.getValue("NumberOfElements")); addMeta(prefix + "Length", attributes.getValue("Length")); addMeta(prefix + "Origin", attributes.getValue("Origin")); addMeta(prefix + "DimID", attributes.getValue("DimID")); } else if (qName.equals("ScannerSettingRecord")) { String key = attributes.getValue("Identifier") + " - " + attributes.getValue("Description"); addMeta(fullSeries + " - " + key, attributes.getValue("Variant")); } else if (qName.equals("FilterSettingRecord")) { String key = attributes.getValue("ObjectName") + " - " + attributes.getValue("Description") + " - " + attributes.getValue("Attribute"); addMeta(fullSeries + " - " + key, attributes.getValue("Variant")); } else if (qName.equals("ATLConfocalSettingDefinition")) { if (fullSeries.endsWith(" - Master sequential setting")) { fullSeries = fullSeries.replaceAll(" - Master sequential setting", " - Sequential Setting 0"); } if (fullSeries.indexOf("- Sequential Setting ") == -1) { fullSeries += " - Master sequential setting"; } else { int ndx = fullSeries.indexOf(" - Sequential Setting ") + 22; int n = Integer.parseInt(fullSeries.substring(ndx)); n++; fullSeries = fullSeries.substring(0, ndx) + String.valueOf(n); } for (int i=0; i<attributes.getLength(); i++) { addMeta(fullSeries + " - " + attributes.getQName(i), attributes.getValue(i)); } } else if (qName.equals("Wheel")) { String prefix = fullSeries + " - Wheel " + count + " - "; addMeta(prefix + "Qualifier", attributes.getValue("Qualifier")); addMeta(prefix + "FilterIndex", attributes.getValue("FilterIndex")); addMeta(prefix + "FilterSpectrumPos", attributes.getValue("FilterSpectrumPos")); addMeta(prefix + "IsSpectrumTurnMode", attributes.getValue("IsSpectrumTurnMode")); addMeta(prefix + "IndexChanged", attributes.getValue("IndexChanged")); addMeta(prefix + "SpectrumChanged", attributes.getValue("SpectrumChanged")); count++; } else if (qName.equals("WheelName")) { String prefix = fullSeries + " - Wheel " + (count - 1) + " - WheelName "; int ndx = 0; while (getMeta(prefix + ndx) != null) ndx++; addMeta(prefix + ndx, attributes.getValue("FilterName")); } else if (qName.equals("MultiBand")) { String prefix = fullSeries + " - MultiBand Channel " + attributes.getValue("Channel") + " - "; addMeta(prefix + "LeftWorld", attributes.getValue("LeftWorld")); addMeta(prefix + "RightWorld", attributes.getValue("RightWorld")); addMeta(prefix + "DyeName", attributes.getValue("DyeName")); } else if (qName.equals("LaserLineSetting")) { String prefix = fullSeries + " - LaserLine " + attributes.getValue("LaserLine") + " - "; addMeta(prefix + "IntensityDev", attributes.getValue("IntensityDev")); addMeta(prefix + "IntensityLowDev", attributes.getValue("IntensityLowDev")); addMeta(prefix + "AOBSIntensityDev", attributes.getValue("AOBSIntensityDev")); addMeta(prefix + "AOBSIntensityLowDev", attributes.getValue("AOBSIntensityLowDev")); addMeta(prefix + "EnableDoubleMode", attributes.getValue("EnableDoubleMode")); addMeta(prefix + "LineIndex", attributes.getValue("LineIndex")); addMeta(prefix + "Qualifier", attributes.getValue("Qualifier")); addMeta(prefix + "SequenceIndex", attributes.getValue("SequenceIndex")); } else if (qName.equals("Detector")) { String prefix = fullSeries + " - Detector Channel " + attributes.getValue("Channel") + " - "; addMeta(prefix + "IsActive", attributes.getValue("IsActive")); addMeta(prefix + "IsReferenceUnitActivatedForCorrection", attributes.getValue("IsReferenceUnitActivatedForCorrection")); addMeta(prefix + "Gain", attributes.getValue("Gain")); addMeta(prefix + "Offset", attributes.getValue("Offset")); } else if (qName.equals("Laser")) { String prefix = fullSeries + " Laser " + attributes.getValue("LaserName") + " - "; addMeta(prefix + "CanDoLinearOutputPower", attributes.getValue("CanDoLinearOutputPower")); addMeta(prefix + "OutputPower", attributes.getValue("OutputPower")); addMeta(prefix + "Wavelength", attributes.getValue("Wavelength")); } else if (qName.equals("TimeStamp")) { long high = Long.parseLong(attributes.getValue("HighInteger")); long low = Long.parseLong(attributes.getValue("LowInteger")); long stamp = 0; high <<= 32; if ((int) low < 0) { low &= 0xffffffffL; } stamp = high + low; // Near as I can figure, this timestamp represents the number of // 100-nanosecond ticks since the ANSI/COBOL epoch (Jan 1, 1601). // Note that the following logic does not handle negative timestamp // values, so if the file in question was acquired prior to Jan 1 1601, // the timestamp will not be parsed correctly. long ms = stamp / 10000; // subtract number of seconds until Unix epoch (Jan 1, 1970) ms -= 11644444800000L; Date d = new Date(ms); SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); StringBuffer sb = new StringBuffer(); fmt.format(d, sb, new FieldPosition(0)); String n = String.valueOf(count); while (n.length() < 4) n = "0" + n; addMeta(fullSeries + " - TimeStamp " + n, sb.toString()); count++; } else if (qName.equals("ChannelScalingInfo")) { String prefix = fullSeries + " - ChannelScalingInfo " + count + " - "; addMeta(prefix + "WhiteValue", attributes.getValue("WhiteValue")); addMeta(prefix + "BlackValue", attributes.getValue("BlackValue")); addMeta(prefix + "GammaValue", attributes.getValue("GammaValue")); addMeta(prefix + "Automatic", attributes.getValue("Automatic")); } else if (qName.equals("RelTimeStamp")) { addMeta(fullSeries + " RelTimeStamp " + attributes.getValue("Frame"), attributes.getValue("Time")); } else count = 0; } } }
// LociUploader.java package loci.plugins; import java.awt.TextField; import java.util.Vector; import ij.*; import ij.gui.GenericDialog; import ij.plugin.PlugIn; import ij.process.*; import ij.io.FileInfo; import loci.formats.*; import loci.formats.ome.*; /** * ImageJ plugin for uploading images to an OME server. * * @author Melissa Linkert linket at wisc.edu */ public class LociUploader implements PlugIn { // -- Fields -- private String server; private String user; private String pass; // -- PlugIn API methods -- public synchronized void run(String arg) { // check that we can safely execute the plugin if (Util.checkVersion() && Util.checkLibraries(true, true, true, false)) { promptForLogin(); uploadStack(); } else { } } // -- Helper methods -- /** Open a dialog box that prompts for a username, password, and server. */ private void promptForLogin() { GenericDialog prompt = new GenericDialog("Login to OME"); prompt.addStringField("Server: ", Prefs.get("uploader.server", ""), 60); prompt.addStringField("Username: ", Prefs.get("uploader.user", ""), 60); prompt.addStringField("Password: ", "", 60); ((TextField) prompt.getStringFields().get(2)).setEchoChar('*'); prompt.showDialog(); server = prompt.getNextString(); user = prompt.getNextString(); pass = prompt.getNextString(); Prefs.set("uploader.server", server); Prefs.set("uploader.user", user); } /** Log in to the OME server and upload the current image stack. */ private void uploadStack() { try { IJ.showStatus("Starting upload..."); OMEUploader ul = new OMEUploader(server, user, pass); ImagePlus imp = WindowManager.getCurrentImage(); if (imp == null) { IJ.error("No open images!"); IJ.showStatus(""); return; } ImageStack is = imp.getImageStack(); Vector pixels = new Vector(); FileInfo fi = imp.getOriginalFileInfo(); OMEXMLMetadataStore store = new OMEXMLMetadataStore(); // if we opened this stack with the Bio-Formats importer, then the // appropriate OME-XML is in fi.description if (fi != null && fi.description != null && fi.description.endsWith("</OME>")) { store.createRoot(fi.description); } else { store.createRoot(); int pixelType = FormatTools.UINT8; switch (imp.getBitDepth()) { case 16: pixelType = FormatTools.UINT16; break; case 32: pixelType = FormatTools.FLOAT; break; } store.setPixels( new Integer(imp.getWidth()), new Integer(imp.getHeight()), new Integer(imp.getNSlices()), new Integer(imp.getNChannels()), new Integer(imp.getNFrames()), new Integer(pixelType), fi == null ? Boolean.TRUE : new Boolean(!fi.intelByteOrder), "XYCZT", // TODO : figure out a way to calculate the dimension order null, null); String name = fi == null ? imp.getTitle() : fi.fileName; store.setImage(name, null, fi == null ? null : fi.info, null); } if (is.getProcessor(1) instanceof ColorProcessor) { store.setPixels(null, null, null, null, null, new Integer(FormatTools.UINT8), null, null, null, null); } boolean little = !store.getBigEndian(null).booleanValue(); for (int i=0; i<is.getSize(); i++) { IJ.showStatus("Reading plane " + (i+1) + "/" + is.getSize()); Object pix = is.getProcessor(i + 1).getPixels(); if (pix instanceof byte[]) { pixels.add((byte[]) pix); } else if (pix instanceof short[]) { short[] s = (short[]) pix; byte[] b = new byte[s.length * 2]; for (int j=0; j<s.length; j++) { b[j*2] = little ? (byte) (s[j] & 0xff) : (byte) ((s[j] >>> 8) & 0xff); b[j*2 + 1] = little ? (byte) ((s[j] >>> 8) & 0xff): (byte) (s[j] & 0xff); } pixels.add(b); } else if (pix instanceof int[]) { if (is.getProcessor(i+1) instanceof ColorProcessor) { byte[][] rgb = new byte[3][((int[]) pix).length]; ((ColorProcessor) is.getProcessor(i+1)).getRGB(rgb[0], rgb[1], rgb[2]); int channels = store.getSizeC(null).intValue(); if (channels > 3) channels = 3; for (int j=0; j<channels; j++) { pixels.add(rgb[j]); } } else { int[] p = (int[]) pix; byte[] b = new byte[4 * p.length]; for (int j=0; j<p.length; j++) { b[j*4] = little ? (byte) (p[j] & 0xff) : (byte) ((p[j] >> 24) & 0xff); b[j*4 + 1] = little ? (byte) ((p[j] >> 8) & 0xff) : (byte) ((p[j] >> 16) & 0xff); b[j*4 + 2] = little ? (byte) ((p[j] >> 16) & 0xff) : (byte) ((p[j] >> 8) & 0xff); b[j*4 + 3] = little ? (byte) ((p[j] >> 24) & 0xff) : (byte) (p[j] & 0xff); } } } else if (pix instanceof float[]) { float[] f = (float[]) pix; byte[] b = new byte[f.length * 4]; for (int j=0; j<f.length; j++) { int k = Float.floatToIntBits(f[j]); b[j*4] = little ? (byte) (k & 0xff) : (byte) ((k >> 24) & 0xff); b[j*4 + 1] = little ? (byte) ((k >> 8) & 0xff) : (byte) ((k >> 16) & 0xff); b[j*4 + 2] = little ? (byte) ((k >> 16) & 0xff) : (byte) ((k >> 8) & 0xff); b[j*4 + 3] = little ? (byte) ((k >> 24) & 0xff) : (byte) (k & 0xff); } pixels.add(b); } } byte[][] planes = new byte[pixels.size()][]; for (int i=0; i<pixels.size(); i++) { planes[i] = (byte[]) pixels.get(i); } IJ.showStatus("Sending data to server..."); ul.uploadPlanes(planes, 0, planes.length - 1, 1, store, true); ul.logout(); IJ.showStatus("Upload finished."); } catch (UploadException e) { IJ.error("Upload failed:\n" + e); e.printStackTrace(); } } }
package powerups.core.feedpowerup; import com.avaje.ebean.Ebean; import com.fasterxml.jackson.databind.JsonNode; import models.*; import play.Logger; import play.mvc.Result; import play.mvc.Results; import play.twirl.api.Html; import powerups.Powerup; import utils.Context; import utils.FeedSorter; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class FeedPowerup extends Powerup { private List<Feed> feedList; private List<Feed> userFeedList; private List<Feed> adminList; private static final String MESSAGE = "message"; private static final String MESSAGETITLE = "messageTitle"; private static final int MAXFEEDSIZE = 3; private User user = null; public FeedPowerup(Club club, PowerupModel model){ super(club, model); if(club != null && model != null){ /* * Find all feeds from club, sort them by date, and copy * the first 3 into new lists to be rendered by view. * */ feedList = Feed.findByClub(club); adminList = new ArrayList<>(); userFeedList = new ArrayList<>(); user = Context.getContext(getClub()).getSender(); if(user == null){ Logger.warn("user in FeedPowerup was null"); return; } if(feedList != null){ feedList.sort(new FeedSorter()); Collections.reverse(feedList); for(int i = 0; i < feedList.size(); i++){ if(i < MAXFEEDSIZE){ adminList.add(feedList.get(i)); userFeedList.add(feedList.get(i)); }else{ break; } } }else{ Logger.warn("feedList in FeedPowerup is null"); } } } @Override public Html renderAdmin(){ return powerups.core.feedpowerup.html.admin.render(adminList); } @Override public Html render() { return powerups.core.feedpowerup.html.powerup.render(userFeedList); } @Override public void activate() { } @Override public Result update(JsonNode updateContent) { if(updateContent != null && !updateContent.isNull()){ String message = updateContent.get(MESSAGE).asText(); String messageTitle = updateContent.get(MESSAGETITLE).asText(); if(message.equalsIgnoreCase("") || messageTitle.equalsIgnoreCase("")){ return Results.badRequest("Vennligst fyll ut både tittel og innhold for FeedPost"); } Logger.info("jsonNode in Feed found the following: " + "message : " + message + ", \n" + "messagetitle : " + messageTitle + ", \n" + "clubname : " + getClub().name + ", \n" + "user firstName : " + user.firstName + "."); Feed feed = new Feed(getClub(), user, messageTitle, message); Ebean.save(feed); }else{ Logger.info("Json in update for FeedPowerup was null"); } return Results.ok(); } }
package com.googlecode.goclipse.builder; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.QualifiedName; import org.eclipse.core.runtime.SubMonitor; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.util.Util; import com.googlecode.goclipse.Activator; import com.googlecode.goclipse.Environment; import com.googlecode.goclipse.go.lang.lexer.Lexer; import com.googlecode.goclipse.go.lang.lexer.Tokenizer; import com.googlecode.goclipse.go.lang.model.Import; import com.googlecode.goclipse.go.lang.parser.ImportParser; import com.googlecode.goclipse.preferences.PreferenceConstants; import com.googlecode.goclipse.utils.ObjectUtils; /** * GoCompiler provides the GoClipse interface to the go build tool. */ public class GoCompiler { private static final QualifiedName COMPILER_VERSION_QN = new QualifiedName(Activator.PLUGIN_ID, "compilerVersion"); /** environment for build */ private Map<String, String> env; private String version; private long versionLastUpdated = 0; public GoCompiler() {} /** * Returns the current compiler version (ex. "6g version release.r58 8787"). * Returns null if we were unable to recover the compiler version. The * returned string should be treated as an opaque token. * * @return the current compiler version */ public static String getCompilerVersion() { String version = null; IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore(); String compilerPath = preferenceStore.getString(PreferenceConstants.GO_TOOL_PATH); if (compilerPath == null || compilerPath.length() == 0) { return null; } try { String[] cmd = { compilerPath, GoConstants.GO_VERSION_COMMAND }; Runtime runtime = Runtime.getRuntime(); Process p = runtime.exec(cmd); try { p.waitFor(); } catch (InterruptedException e) { Activator.logInfo(e); } InputStream is = p.getInputStream(); InputStream es = p.getErrorStream(); StreamAsLines output = new StreamAsLines(); StreamAsLines errors = new StreamAsLines(); output.process(is); errors.process(es); final String GO_VERSION = "go version "; for (String line : output.getLines()) { if (line != null && line.startsWith(GO_VERSION)) { version = line.substring(GO_VERSION.length()); break; } } } catch (IOException e) { Activator.logInfo(e); } return version; } /** * TODO this needs to be centralized into a common index... * * @param file * @return * @throws IOException */ private List<Import> getImports(File file) throws IOException { Lexer lexer = new Lexer(); Tokenizer tokenizer = new Tokenizer(lexer); ImportParser importParser = new ImportParser(tokenizer); BufferedReader reader = new BufferedReader(new FileReader(file)); String temp = ""; StringBuilder builder = new StringBuilder(); while( (temp = reader.readLine()) != null ) { builder.append(temp); builder.append("\n"); } reader.close(); lexer.scan(builder.toString()); List<Import> imports = importParser.getImports(); return imports; } /** * @param project * @param target */ public void goGetDependencies(final IProject project, IProgressMonitor monitor, java.io.File target) { final IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore(); final IPath projectLocation = project.getLocation(); final String compilerPath = preferenceStore.getString(PreferenceConstants.GO_TOOL_PATH); final IFile file = project.getFile(target.getAbsolutePath().replace(projectLocation.toOSString(), "")); try { /** * TODO Allow the user to set the go get locations * manually. */ List<Import> imports = getImports(target); List<String> cmd = new ArrayList<String>(); List<Import> extImports = new ArrayList<Import>(); monitor.beginTask("Importing external libraries for "+file.getName()+":", 5); for (Import imp: imports) { if (imp.getName().startsWith("code.google.com") || imp.getName().startsWith("github.com") || imp.getName().startsWith("bitbucket.org") || imp.getName().startsWith("launchpad.net") || imp.getName().contains(".git") || imp.getName().contains(".svn") || imp.getName().contains(".hg") || imp.getName().contains(".bzr") ){ cmd.add(imp.getName()); extImports.add(imp); } } monitor.worked(1); //String[] cmd = { compilerPath, GoConstants.GO_GET_COMMAND, "-u" }; cmd.add(0, "-u"); cmd.add(0, "-fix"); cmd.add(0, GoConstants.GO_GET_COMMAND); cmd.add(0, compilerPath); String goPath = buildGoPath(projectLocation); String PATH = System.getenv("PATH"); Runtime runtime = Runtime.getRuntime(); Process p = runtime.exec(cmd.toArray(new String[]{}), new String[] { "GOPATH=" + goPath, "PATH="+PATH }, target.getParentFile()); monitor.worked(3); try { p.waitFor(); } catch (InterruptedException e) { Activator.logInfo(e); } InputStream is = p.getInputStream(); InputStream es = p.getErrorStream(); StreamAsLines sal = new StreamAsLines(); sal.setCombineLines(true); sal.process(is); sal.process(es); Activator.logInfo(sal.getLinesAsString()); boolean exMsg = true; try { project.deleteMarkers(MarkerUtilities.MARKER_ID, false, IResource.DEPTH_ZERO); } catch (CoreException e1) { Activator.logError(e1); } clearErrorMessages(file); if (sal.getLines().size() > 0) { for (String line : sal.getLines()) { if (line.startsWith("package")) { String impt = line.substring(0,line.indexOf(" -")); impt = impt.replaceFirst("package ", ""); for (Import i:extImports) { if (i.path.equals(impt)) { MarkerUtilities.addMarker(file, i.getLine(), line.substring(line.indexOf(" -")+2), IMarker.SEVERITY_ERROR); } } } else if (line.contains(".go:")) { try { String[] split = line.split(":"); String path = "GOPATH/"+split[0].substring(split[0].indexOf("/src/")+5); IFile extfile = project.getFile(path); int lineNumber = Integer.parseInt(split[1]); String msg = split[3]; IPath pp = extfile.getFullPath(); if(extfile!=null && extfile.exists()){ MarkerUtilities.addMarker(extfile, lineNumber, msg, IMarker.SEVERITY_ERROR); } else if (exMsg) { exMsg = false; MarkerUtilities.addMarker(file, "There are problems with the external imports in this file.\n" + "You may want to attempt to resolve them outside of eclipse.\n" + "Here is the GOPATH to use: \n\t"+goPath); } } catch (Exception e){ Activator.logError(e); } } } } monitor.worked(1); } catch (IOException e1) { Activator.logInfo(e1); } } /** * @param projectLocation * @return */ public static String buildGoPath(final IPath projectLocation) { String goPath = projectLocation.toOSString(); final String SYSTEM_GO_PATH = System.getenv("GOPATH"); if (SYSTEM_GO_PATH != null) { goPath = SYSTEM_GO_PATH + ":" + goPath; } return goPath; } /** * @param project * @param pmonitor * @param fileList */ public void compileCmd(final IProject project, IProgressMonitor pmonitor, java.io.File target) { final IPath projectLocation = project.getLocation(); final IFile file = project.getFile(target.getAbsolutePath().replace(projectLocation.toOSString(), "")); final String pkgPath = target.getParentFile().getAbsolutePath().replace(projectLocation.toOSString(), ""); final IPath binFolder = Environment.INSTANCE.getBinOutputFolder(project); clearErrorMessages(file); /* * This isn't really a good idea here */ //goGetDependencies(project, target); final IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore(); final String compilerPath = preferenceStore.getString(PreferenceConstants.GO_TOOL_PATH); final String outExtension = (Util.isWindows() ? ".exe" : ""); final String outPath = projectLocation.toOSString() + File.separator + binFolder + File.separator + target.getName().replace(GoConstants.GO_SOURCE_FILE_EXTENSION, outExtension); String PATH = System.getenv("PATH"); try { String[] cmd = { compilerPath, GoConstants.GO_BUILD_COMMAND, GoConstants.COMPILER_OPTION_O, outPath, file.getName() }; String goPath = buildGoPath(projectLocation); ProcessBuilder builder = new ProcessBuilder(cmd).directory(target.getParentFile()); builder.environment().put("GOPATH", goPath); builder.environment().put("PATH", PATH); Process p = builder.start(); try { p.waitFor(); } catch (InterruptedException e) { Activator.logInfo(e); } try { project.refreshLocal(IResource.DEPTH_INFINITE, pmonitor); } catch (CoreException e) { Activator.logInfo(e); } InputStream is = p.getInputStream(); InputStream es = p.getErrorStream(); StreamAsLines sal = new StreamAsLines(); sal.setCombineLines(true); sal.process(is); sal.process(es); if (sal.getLines().size() > 0) { processCompileOutput(sal, project, pkgPath, file); } } catch (IOException e1) { Activator.logInfo(e1); } } /** * @param file */ private void clearErrorMessages(final IFile file) { MarkerUtilities.deleteFileMarkers(file); } /** * * @param output * @param project * @param relativeTargetDir */ private void processCompileOutput(final StreamAsLines output, final IProject project, final String relativeTargetDir, final IFile file) { boolean iswindows = Util.isWindows(); for (String line : output.getLines()) { if (line.startsWith(" continue; } int goPos = line.indexOf(GoConstants.GO_SOURCE_FILE_EXTENSION); if (goPos > 0) { int fileNameLength = goPos + GoConstants.GO_SOURCE_FILE_EXTENSION.length(); // Strip the prefix off the error message String fileName = line.substring(0, fileNameLength); fileName = fileName.replace(project.getLocation().toOSString(), ""); fileName = iswindows?fileName:fileName.substring(fileName.indexOf(":") + 1).trim(); // Determine the type of error message if (fileName.startsWith(File.separator)) { fileName = fileName.substring(1); } else if (fileName.startsWith("." + File.separator)) { fileName = relativeTargetDir.substring(1) + File.separator + fileName.substring(2); } else if (line.startsWith("can't")) { fileName = relativeTargetDir.substring(1); } else { fileName = relativeTargetDir.substring(1) + File.separator + fileName; } // find the resource if possible IResource resource = project.findMember(fileName); if (resource == null && file != null) { resource = file; } else { resource = project; } // Create the error message String msg = line.substring(fileNameLength + 1); String[] str = msg.split(":", 3); int location = -1; // marker for trouble int messageStart = msg.indexOf(": "); try { location = Integer.parseInt(str[0]); } catch (NumberFormatException nfe) {} // Determine how to mark the message if (location != -1 && messageStart != -1) { String message = msg.substring(messageStart + 2); MarkerUtilities.addMarker(resource, location, message, IMarker.SEVERITY_ERROR); } else { // play safe. to show something in UI MarkerUtilities.addMarker(resource, 1, line, IMarker.SEVERITY_ERROR); } } else { // runtime.main: undefined: main.main MarkerUtilities.addMarker(file, 1, line, IMarker.SEVERITY_ERROR); } } } /** * @param project * @param pmonitor * @param fileList */ public String compilePkg(final IProject project, IProgressMonitor pmonitor, String pkgpath, java.io.File target) { final IPath projectLocation = project.getLocation(); final IFile file = project.getFile(target.getAbsolutePath().replace(projectLocation.toOSString(), "")); final String pkgPath = target.getParentFile().getAbsolutePath().replace(projectLocation.toOSString(), ""); final IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore(); final String compilerPath = preferenceStore.getString(PreferenceConstants.GO_TOOL_PATH); try { String[] cmd = { compilerPath, GoConstants.GO_BUILD_COMMAND, GoConstants.COMPILER_OPTION_O, pkgpath, "." }; String goPath = buildGoPath(projectLocation); String PATH = System.getenv("PATH"); Runtime runtime = Runtime.getRuntime(); Process p = runtime.exec(cmd, new String[] { "GOPATH=" + goPath, "PATH="+PATH }, target.getParentFile()); try { p.waitFor(); } catch (InterruptedException e) { Activator.logInfo(e); } try { project.refreshLocal(IResource.DEPTH_INFINITE, pmonitor); } catch (CoreException e) { Activator.logInfo(e); } clearErrorMessages(file); InputStream is = p.getInputStream(); InputStream es = p.getErrorStream(); StreamAsLines sal = new StreamAsLines(); sal.process(is); sal.process(es); if (sal.getLines().size() > 0) { processCompileOutput(sal, project, pkgPath, file); } } catch (IOException e1) { Activator.logInfo(e1); } return pkgpath; } /** * * @param project * @param pmonitor * @param target * @param dependencies */ public void compile(final IProject project, IProgressMonitor pmonitor, String target, String... dependencies) { final IFile file = project.getFile(new File(target).getAbsolutePath().replace( project.getLocation().toOSString(), "")); if (!dependenciesExist(project, dependencies)) { Activator.logWarning("Missing dependency for '" + target + "' not compiling"); return; } SubMonitor monitor = SubMonitor.convert(pmonitor, 130); Activator.logInfo("compile():" + dependencies); final IPath prjLoc = project.getLocation(); IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore(); String compilerPath = preferenceStore.getString(PreferenceConstants.GO_TOOL_PATH); // String goarch = // preferenceStore.getString(PreferenceConstants.GOARCH); IPath pkgPath = Environment.INSTANCE.getPkgOutputFolder(project); final ExternalCommand compilePackageCmd = new ExternalCommand(compilerPath); compilePackageCmd.setEnvironment(env); // get the architecture // Arch arch = Arch.getArch(goarch); StreamAsLines output = new StreamAsLines(); output.setCombineLines(true); compilePackageCmd.setResultsFilter(output); Activator.logInfo("building " + target); List<String> args = new ArrayList<String>(); args.clear(); // show all errors option args.add(GoConstants.COMPILER_OPTION_E); // include folder args.add(GoConstants.COMPILER_OPTION_I); args.add(prjLoc.append(pkgPath).toOSString()); // output file option args.add(GoConstants.COMPILER_OPTION_O); // output file args.add(target); compilePackageCmd.setWorkingFolder(prjLoc.toOSString()); IResource firstDependency = null; //errorMessages.clear(); for (String dependency : dependencies) { if (dependency.endsWith(GoConstants.GO_SOURCE_FILE_EXTENSION)) { IResource resource = project.findMember(dependency); if (firstDependency == null) { firstDependency = resource; } MarkerUtilities.deleteFileMarkers(resource); args.add(dependency); } } String result = compilePackageCmd.execute(args); if (result != null) { MarkerUtilities.addMarker(firstDependency, -1, result, IMarker.SEVERITY_ERROR); } processCompileOutput(output, project, "", file); try { project.refreshLocal(IResource.DEPTH_INFINITE, monitor); } catch (CoreException e) { Activator.logInfo(e); } } /** * * @param goEnv */ public void setEnvironment(Map<String, String> goEnv) { this.env = goEnv; } /** * * @return */ public String getVersion() { // The getCompilerVersion() call takes about ~30 msec to compute. // Because it's expensive, // we cache the value for a short time. final long TEN_SECONDS = 10 * 1000; if ((System.currentTimeMillis() - versionLastUpdated) > TEN_SECONDS) { version = getCompilerVersion(); versionLastUpdated = System.currentTimeMillis(); } return version; } /** * * @param project * @param dependencies * @return */ private boolean dependenciesExist(IProject project, String[] dependencies) { ArrayList<String> sourceDependencies = new ArrayList<String>(); for (String dependency : dependencies) { if (dependency.endsWith(GoConstants.GO_SOURCE_FILE_EXTENSION)) { sourceDependencies.add(dependency); } } return GoBuilder.dependenciesExist(project, sourceDependencies.toArray(new String[] {})); } /** * * @param project */ public void updateVersion(IProject project) { try { project.setPersistentProperty(COMPILER_VERSION_QN, getVersion()); } catch (CoreException ex) { Activator.logError(ex); } } /** * * @param project * @return */ public boolean requiresRebuild(IProject project) { String storedVersion; try { storedVersion = project.getPersistentProperty(COMPILER_VERSION_QN); } catch (CoreException ex) { storedVersion = null; } String currentVersion = getVersion(); if (currentVersion == null) { // We were not able to get the latest compiler version - don't force // a rebuild. return false; } else { return !ObjectUtils.objectEquals(storedVersion, currentVersion); } } }
package app.hongs.serv.bundle; import app.hongs.Core; import app.hongs.CoreConfig; import app.hongs.CoreLocale; import app.hongs.CoreLogger; import app.hongs.HongsException; import app.hongs.action.ActionHelper; import app.hongs.action.anno.Action; import app.hongs.dh.IAction; import app.hongs.util.Synt; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Comparator; import java.util.ArrayList; import java.util.HashMap; import java.util.TreeSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.activation.MimetypesFileTypeMap; /** * * @author Hongs */ @Action("bundle/file") public class FileAction implements IAction { private static final Map<String, Byte> TYPE_SORT = new HashMap(); static { TYPE_SORT.put("dir", (byte) 0); TYPE_SORT.put("txt", (byte) 1); TYPE_SORT.put("bin", (byte) 2); } private static final List ROOT_LIST = new ArrayList(); static { ROOT_LIST.add(Synt.mapOf( "path", "/BASE", "name", "", "type", "dir", "size", "1" )); ROOT_LIST.add(Synt.mapOf( "path", "/CONF", "name", "", "type", "dir", "size", "1" )); ROOT_LIST.add(Synt.mapOf( "path", "/DATA", "name", "", "type", "dir", "size", "1" )); } @Override @Action("search") public void search(ActionHelper helper) throws HongsException { MimetypesFileTypeMap nmap = new MimetypesFileTypeMap( ); CoreLocale lang = CoreLocale.getInstance("bundle_serv"); String type = helper.getParameter("type"); String path = helper.getParameter("path"); String pxth = path; File file; if ("".equals(path) || "/".equals(path)) { if ("file".equals(type)) { helper.reply(Synt.mapOf("page" , Synt.mapOf( "ern" , 1 ), "list" , new ArrayList() )); } else { helper.reply(Synt.mapOf("page" , Synt.mapOf( "ern" , 0 ), "list" , ROOT_LIST )); } return; } if ( path == null ) { helper.fault(lang.translate("core.serv.bundle.file.path.required")); return; } path = realPath(path); if ( path == null ) { helper.fault(lang.translate("core.serv.bundle.file.path.is.error")); return; } file = new File(path); if (!file.exists()) { helper.fault(lang.translate("core.serv.bundle.file.path.is.not.exist")); return; } byte t = 0; if ( "dir".equals(type)) { t = 1; } else if ("file".equals(type)) { t = 2; } if ( file.isDirectory()) { File[ ] files = file.listFiles(); Set<Map> filez; final boolean ds; String ob = helper.getParameter("ob"); if (ob != null && ob.startsWith("-")) { ob = ob.substring(1); ds = true ; } else { ds = false ; } if ("type".equals(ob)) { filez = new TreeSet(new Comparator<Map>() { @Override public int compare(Map f1, Map f2) { String t1 = (String) f1.get("type"); String t2 = (String) f2.get("type"); byte s1 = Synt.declare(TYPE_SORT.get(t1), (byte) 0); byte s2 = Synt.declare(TYPE_SORT.get(t2), (byte) 0); if (s1 != s2) if (ds) return s1 < s2 ? 1 : -1; else return s1 > s2 ? 1 : -1; String n1 = (String) f1.get("name"); String n2 = (String) f2.get("name"); if (ds) return n2.compareTo(n1); else return n1.compareTo(n2); }; }); } else if ("size".equals(ob)) { filez = new TreeSet(new Comparator<Map>() { @Override public int compare(Map f1, Map f2) { long s1 = Synt.declare(f1.get("size") , 0L); long s2 = Synt.declare(f2.get("size") , 0L); if (s1 != s2) if (ds) return s1 < s2 ? 1 : -1; else return s1 > s2 ? 1 : -1; String n1 = (String) f1.get("name"); String n2 = (String) f2.get("name"); if (ds) return n2.compareTo(n1); else return n1.compareTo(n2); }; }); } else { filez = new TreeSet(new Comparator<Map>() { @Override public int compare(Map f1, Map f2) { String n1 = (String) f1.get("name"); String n2 = (String) f2.get("name"); if (ds) return n2.compareTo(n1); else return n1.compareTo(n2); }; }); } for (File item : files) { if (t == 1) { if ( ! item.isDirectory()) { continue; } } else if (t == 2) { if ( ! item.isFile()) { continue; } } String name = item.getName(); String extn = name.replaceFirst("^.*/",""); String mime = nmap.getContentType ( extn ); Map xxxx = new HashMap(); xxxx.put("path" , pxth + "/" + name); xxxx.put("name" , name ); xxxx.put("mime" , mime ); xxxx.put("type" , item.isDirectory() ? "dir" : (isTextFile(item) ? "txt" : "bin")); xxxx.put("size" , item.isDirectory() ? item.list( ).length : item.length( ) ); xxxx.put("mtime", item.lastModified()); filez.add(xxxx ); } Map rsp = new HashMap(); rsp.put("list", filez ); rsp.put("page", Synt.mapOf( "ern", filez.size() > 0 ? 0 : 1 )); helper.reply(rsp); } else if (isTextFile(file)) { String name = file.getName(); String extn = name.replaceFirst("^.*/",""); String mime = nmap.getContentType ( extn ); Map xxxx = new HashMap(); xxxx.put("path" , pxth ); xxxx.put("name" , name ); xxxx.put("mime" , mime ); xxxx.put("type" , "txt"); xxxx.put("size" , file.length( )); xxxx.put("text" , readFile(file)); xxxx.put("mtime", file.lastModified()); helper.reply( "", xxxx ); } else { helper.fault(lang.translate("core.serv.bundle.file.unsupported")); } } @Override @Action("create") public void create(ActionHelper helper) throws HongsException { CoreLocale lang = CoreLocale.getInstance("bundle_serv"); String path = helper.getParameter("path"); String type = helper.getParameter("type"); String text = helper.getParameter("text"); File file; if ( path == null ) { helper.fault(lang.translate("core.serv.bundle.file.path.required")); return; } path = realPath(path); if ( path == null ) { helper.fault(lang.translate("core.serv.bundle.file.path.is.error")); return; } file = new File(path); if ( file.exists()) { helper.fault(lang.translate("core.serv.bundle.file.path.is.exist")); return; } if (isDenyFile(file)) { helper.fault(lang.translate("core.serv.bundle.file.interdicted" )); return; } if ("dir".equals(type)) { new File(path).mkdirs(); helper.reply(""); return; } try { saveFile(file, text); } catch ( Exception ex ) { CoreLogger.error(ex); helper.fault(lang.translate("core.serv.bundle.file.create.failed")); return; } helper.reply(""); } @Override @Action("update") public void update(ActionHelper helper) throws HongsException { CoreLocale lang = CoreLocale.getInstance("bundle_serv"); String path = helper.getParameter("path"); String dist = helper.getParameter("dist"); String text = helper.getParameter("text"); File file; File dizt; if ( dist != null && dist.equals ( path )) { dist = null ; } if ( path == null ) { helper.fault(lang.translate("core.serv.bundle.file.path.required")); return; } path = realPath(path); if ( path == null ) { helper.fault(lang.translate("core.serv.bundle.file.path.is.error")); return; } file = new File(path); if (!file.exists()) { helper.fault(lang.translate("core.serv.bundle.file.path.is.not.exist")); return; } if (isDenyFile(file)) { helper.fault(lang.translate("core.serv.bundle.file.interdicted" )); return; } if ( dist != null ) { dist = realPath(dist); if ( dist == null ) { helper.fault(lang.translate("core.serv.bundle.file.path.is.error")); return; } dizt = new File(dist); if ( dizt.exists()) { helper.fault(lang.translate("core.serv.bundle.file.dist.is.exist")); return; } if (isDenyFile(file)) { helper.fault(lang.translate("core.serv.bundle.file.interdicted" )); return; } if (!file.renameTo(dizt)) { helper.fault(lang.translate("core.serv.bundle.file.rename.failed")); return; } if ( text == null ) { return; } file = dizt; } try { saveFile(file, text); } catch ( Exception ex ) { CoreLogger.error(ex); helper.fault(lang.translate("core.serv.bundle.file.update.failed")); return; } helper.reply(""); } @Override @Action("delete") public void delete(ActionHelper helper) throws HongsException { CoreLocale lang = CoreLocale.getInstance("bundle_serv"); String path = helper.getParameter("path"); File file; if ( path == null ) { helper.fault(lang.translate("core.serv.bundle.file.path.required")); return; } path = realPath(path); if ( path == null ) { helper.fault(lang.translate("core.serv.bundle.file.path.is.error")); return; } file = new File(path); if (!file.exists()) { helper.fault(lang.translate("core.serv.bundle.file.path.is.not.exist")); return; } if (isDenyDire(file)) { helper.fault(lang.translate("core.serv.bundle.file.path.is.not.empty")); return; } if (isDenyFile(file)) { helper.fault(lang.translate("core.serv.bundle.file.interdicted" )); return; } if (!file.delete()) { helper.fault(lang.translate("core.serv.bundle.file.delete.failed")); return; } helper.reply(""); } private String realPath(String path) { if (path == null) { return null; } if (path.matches(".*/\\.{1,2}/.*")) { return null; } if (path.startsWith("/BASE")) { path = Core.BASE_PATH+"/"+path.substring(5); } else if (path.startsWith("/CONF")) { path = Core.CONF_PATH+"/"+path.substring(5); } else if (path.startsWith("/DATA")) { path = Core.DATA_PATH+"/"+path.substring(5); } else { return null; } if (path.endsWith("/")) { path = path.substring(0 , path.length() - 1); } return path; } private String readFile(File file) { try ( FileInputStream fi = new FileInputStream(file); InputStreamReader is = new InputStreamReader( fi , "utf-8"); BufferedReader br = new BufferedReader( is ); ) { StringBuilder sb = new StringBuilder ( ); char[] bs; int bn; while (true) { bs = new char [1024]; if((bn = br.read(bs)) < 0) { break; } sb.append(bs, 0, bn); } return sb.toString(); } catch (FileNotFoundException ex) { throw new RuntimeException("Can not find " + file.getAbsolutePath(), ex); } catch (IOException ex) { throw new RuntimeException("Can not read " + file.getAbsolutePath(), ex); } } private void saveFile(File file, String text) { try ( FileOutputStream fo = new FileOutputStream(file); OutputStreamWriter os = new OutputStreamWriter( fo , "utf-8"); BufferedWriter bw = new BufferedWriter( os ); ) { bw.write(text); } catch (IOException ex) { throw new RuntimeException("Can not save " + file.getAbsolutePath(), ex); } } private boolean isDenyDire(File file) { return file.isDirectory ( ) && file.list().length > 0; } private boolean isDenyFile(File file) { if (file.isDirectory()) { return true ; } String serv = System.getProperty("bundle.serv.file"); if ( "no".equals(serv)) { return true ; } if ("all".equals(serv)) { return false; } String name = file.getName( ); String extn = name.replaceFirst("^.*\\.", ""); CoreConfig conf = CoreConfig.getInstance( ); Set<String> extz = Synt.toTerms(conf.getProperty("fore.upload.deny.extns" )); Set<String> exts = Synt.toTerms(conf.getProperty("fore.upload.allow.extns")); return (null != extz && extz.contains(extn)) || (null != exts && !exts.contains(extn)); } private boolean isTextFile(File file) { boolean isBinary = false; try { FileInputStream fin = new FileInputStream(file); long len = file.length(); for (int j = 0; j < (int) len; j++) { int t = fin.read(); if (t < 32 && t != 9 && t != 10 && t != 13) { isBinary = true; break; } } } catch (IOException ex) { throw new RuntimeException("Can not close "+ file.getAbsolutePath(), ex); } return !isBinary; } }
package app.hongs.serv.common; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author Hongs */ public class XsrfFilter implements Filter { private static final Pattern DMN_PAT = Pattern.compile("^\\w+: @Override public void init(FilterConfig fc) throws ServletException { // Nothing todo. } @Override public void doFilter(ServletRequest rxq, ServletResponse rxp, FilterChain fc) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest ) rxq; HttpServletResponse rsp = (HttpServletResponse) rxp; // X-Requested-With AJAX APP String ret = req.getHeader("X-Requested-With" ); if (ret != null && ret.length() != 0) { fc.doFilter(rxq, rxp); return; } // Referer URL String ref = req.getHeader("Referer"); String dmn = req.getServerName( ); Matcher ma = DMN_PAT.matcher(ref); if (ma.find( ) && ! ma.group( 1 ).equals(dmn) ) { fc.doFilter(rxq, rxp); return; } rsp.setStatus(HttpServletResponse.SC_FORBIDDEN); rsp.getWriter().print("XSRF Access Forbidden!"); } @Override public void destroy() { // Nothing todo. } }
package algorithms.imageProcessing; import algorithms.imageProcessing.Sky.SkyObject; import algorithms.imageProcessing.features.mser.Canonicalizer; import algorithms.imageProcessing.features.mser.Canonicalizer.RegionGeometry; import algorithms.imageProcessing.features.mser.MSEREdges; import algorithms.imageProcessing.features.mser.Region; import algorithms.misc.MiscMath; import algorithms.util.OneDIntArray; import algorithms.util.PairInt; import algorithms.util.VeryLongBitString; import java.awt.Color; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.logging.Logger; /** * NOT READY FOR USE. * rewriting most of it. * * class with methods to find a rainbow within an image and to create a hull * to encapsulate it for various methods. * * @author nichole */ public class RainbowFinder { private Logger log = Logger.getLogger(this.getClass().getName()); static class Hull { float[] xHull; float[] yHull; } private Hull rainbowHull = null; public RainbowFinder() { } /** * find rainbows in the blob detector results of MSER. * NOTE that the method needs more testing. * * @param mserEdges * @return */ public SkyObject[] findRainbows(MSEREdges mserEdges) { ImageExt img = mserEdges.getClrImg(); List<Region> polarThetaPositive = mserEdges.getOrigGsPtRegions().get(2); /* segments of rainbows in two test images are found as elongated thin ellipses in the polar theta positive images, and those then have adjacent thin elongated regions in the polar theta negative images where the brighter arcs of the rainbow are. NOTE: once a rainbow is found, could look for others fainter in the image. */ List<Set<PairInt>> listOfSets0 = new ArrayList<Set<PairInt>>(); List<OneDIntArray> hists0 = new ArrayList<OneDIntArray>(); List<RegionGeometry> rgs0 = new ArrayList<RegionGeometry>(); //mserEdges._debugOrigRegions(2, "_PT_"); findPositivePT(img, polarThetaPositive, listOfSets0, hists0, rgs0); // TODO: for complete rainbows, sometimes the entire arc is present // in an MSER region and separate segments of it are // in other smaller MSER regions, // so look for that here // paused here List<Region> polarThetaNegative = mserEdges.getOrigGsPtRegions().get(3); List<Set<PairInt>> listOfSets1 = new ArrayList<Set<PairInt>>(); List<OneDIntArray> hists1 = new ArrayList<OneDIntArray>(); List<RegionGeometry> rgs1 = new ArrayList<RegionGeometry>(); findNegativePT(img, polarThetaNegative, listOfSets1, hists1, rgs1); // points from the same rainbow in the positive image // should have similar hue histograms. // gathered those into groups here. List<VeryLongBitString> lists = clusterByIntersection(hists0, 0.9f); for (int i = 0; i < lists.size(); ++i) { VeryLongBitString bs = lists.get(i); int[] histIdxs = bs.getSetBits(); List<Set<PairInt>> setsI = new ArrayList<Set<PairInt>>(histIdxs.length); List<RegionGeometry> rgsI = new ArrayList<RegionGeometry>(histIdxs.length); System.out.println("hs=" + Arrays.toString(histIdxs)); for (int hIdx : histIdxs) { //int idx = indexes.get(hIdx); setsI.add(listOfSets0.get(hIdx)); RegionGeometry rg = rgs0.get(hIdx); rgsI.add(rg); System.out.println( i + ") " + " xy=(" + rg.xC + "," + rg.yC + ") " + " angle=" + (rg.orientation*180./Math.PI) + " ecc=" + rg.eccentricity ); } // there may be more than one rainbow in this set. // for example, a test image has 1 strong rainbow and 2 fainter ones. // combine these positive mser w/ the complementary MSER regions found in the // negative polar theta image here. for the strong mser regions // in the positive image that are rainbow arcs, there are // complementary arcs which appear in the // negative image near them. // add the negative sets for (int j = 0; j < listOfSets1.size(); ++j) { setsI.add(listOfSets1.get(j)); RegionGeometry rg = rgs1.get(j); rgsI.add(rg); } /* either: (1) fit setsI in combinations to find the best fitting sets or (2) */ // TODO: paused here } /*can use a clustering based on intersection limit to get clusters of points and fit ellipses to them. because of the eccentricity limit, the individual point set mser regions already have elliptical fits. */ //SkyObject obj = new SkyObject(); //obj.points = listOfSets2.get(0); //obj.xyCenter = ehs.get(0).getXYCenter(); //return obj; throw new UnsupportedOperationException("not yet implemented"); } private int[] extractHues(ImageExt img, Set<PairInt> set) { int[] hues = new int[10]; float[] hsb = new float[3]; for (PairInt p : set) { int r = img.getR(p); int g = img.getG(p); int b = img.getB(p); Color.RGBtoHSB(r, g, b, hsb); // TODO: consider satudation and brightness limits int bin = (int)(hsb[0]/0.1f); if (bin == 10) { bin } hues[bin]++; } return hues; } private Set<PairInt> extractOffRegion(ImageExt img, Region r, RegionGeometry rg) { // region orientation is the direction that the minor axis points // to, so is the direction needed for an offset patch // and so is 180 from that. int eAngle = (int)Math.round(rg.orientation * 180./Math.PI); // put into 0 to 180 ref frame if (eAngle > 179) { eAngle -= 180; } // put into ref frame of dominant orientations (major axis direction) eAngle -= 90; if (eAngle < 0) { eAngle += 180; } double d = eAngle * Math.PI/180.; int x = rg.xC; int y = rg.yC; int delta = (int)((rg.minor + rg.major)/2.); int x2 = (int)Math.round(x + 2.f * delta * Math.cos(d)); int y2 = (int)Math.round(y + 2.f * delta * Math.sin(d)); int w = img.getWidth(); int h = img.getHeight(); Set<PairInt> out = new HashSet<PairInt>(); if (isWithinBounds(x2, y2, w, h)) { Set<PairInt> points = new HashSet<PairInt>(); for (int i = (x2 - delta); i < (x2 + delta); ++i) { for (int j = (y2 - delta); j < (y2 + delta); ++j) { if (isWithinBounds(i, j, w, h)) { points.add(new PairInt(i, j)); } } } out.addAll(points); } int x3 = (int)Math.round(x - 2.f * delta * Math.cos(d)); int y3 = (int)Math.round(y - 2.f * delta * Math.sin(d)); if (isWithinBounds(x3, y3, w, h)) { Set<PairInt> points = new HashSet<PairInt>(); for (int i = (x3 - delta); i < (x3 + delta); ++i) { for (int j = (y3 - delta); j < (y3 + delta); ++j) { if (isWithinBounds(i, j, w, h)) { points.add(new PairInt(i, j)); } } } out.addAll(points); } return out; } private void extractHSBProperties(ImageExt img, Set<PairInt> points, int[] hues, float[] sbAvg) { float sum0 = 0; float sum1 = 0; float[] hsb = new float[3]; for (PairInt p : points) { int r = img.getR(p); int g = img.getG(p); int b = img.getB(p); Color.RGBtoHSB(r, g, b, hsb); sum0 += hsb[1]; sum1 += hsb[2]; // TODO: consider satudation and brightness limits int bin = (int)(hsb[0]/0.1f); if (bin == 10) { bin } hues[bin]++; } sum0 /= (float)points.size(); sum1 /= (float)points.size(); sbAvg[0] = sum0; sbAvg[1] = sum1; } private boolean isWithinBounds(int x, int y, int width, int height) { if (x < 0 || y < 0 || (x >= width) || (y >= height)) { return false; } return true; } private float[] normalize(int[] hues) { float[] norm0 = new float[hues.length]; int n0 = 0; for (int h : hues) { n0 += h; } for (int i = 0; i < hues.length; ++i) { norm0[i] = (float)hues[i]/(float)n0; } return norm0; } private int[] subtractNormalized(int[] hues, int[] offRegion) { float[] h = normalize(hues); float[] bck = normalize(offRegion); /*System.out.println( "hues=" + Arrays.toString(hues) + " off=" + Arrays.toString(offRegion) + " h=" + Arrays.toString(h) + " bck=" + Arrays.toString(bck)); */ float tot = 0; for (int i = 0; i < h.length; ++i) { h[i] -= bck[i]; if (h[i] < 0) { h[i] = 0; } tot += h[i]; } float factor = 100.f/tot; int[] out = new int[hues.length]; for (int i = 0; i < h.length; ++i) { out[i] = Math.round(factor * h[i]); } return out; } private boolean isEmpty(int[] hues) { for (int h : hues) { if (h != 0) { return false; } } return true; } private List<VeryLongBitString> clusterByIntersection(List<OneDIntArray> hists, float minIntersection) { ColorHistogram ch = new ColorHistogram(); List<VeryLongBitString> out = new ArrayList<VeryLongBitString>(); for (int i = 0; i < hists.size(); ++i) { OneDIntArray h = hists.get(i); VeryLongBitString indexes = new VeryLongBitString(hists.size()); boolean didSet = false; for (int j = (i + 1); j < hists.size(); ++j) { OneDIntArray h2 = hists.get(j); float intersection = ch.intersection(h.a, h2.a); if (intersection >= minIntersection) { indexes.setBit(j); didSet = true; } } if (didSet) { indexes.setBit(i); // if this bitstring is not a subset of an existing in out, add boolean doNotAdd = false; for (int j = 0; j < i; ++j) { VeryLongBitString bs = out.get(j); VeryLongBitString intersectionBS = bs.and(indexes); if (intersectionBS.getNSetBits() == indexes.getNSetBits()) { doNotAdd = true; break; } } if (!doNotAdd) { out.add(indexes); } } } // add entries for the sets by themselves for (int i = 0; i < hists.size(); ++i) { OneDIntArray h = hists.get(i); VeryLongBitString indexes = new VeryLongBitString(hists.size()); indexes.setBit(i); out.add(indexes); } return out; } private void findPositivePT(ImageExt img, List<Region> polarThetaPositive, List<Set<PairInt>> listOfSets, List<OneDIntArray> hists, List<RegionGeometry> rgs) { for (int rIdx = 0; rIdx < polarThetaPositive.size(); ++rIdx) { Region r = polarThetaPositive.get(rIdx); Set<PairInt> set1 = null; for (int i = 0; i < r.accX.size(); ++i) { int x = r.accX.get(i); int y = r.accY.get(i); PairInt p = new PairInt(x, y); int pixIdx = img.getInternalIndex(p); if (set1 == null) { set1 = new HashSet<PairInt>(); } set1.add(p); } if (set1 != null) { RegionGeometry rg = Canonicalizer.calculateEllipseParams( r, img.getWidth(), img.getHeight()); System.out.format( "%d : xy=(%d,%d) angle=%.2f " + " ecc=%.3f minor=%.3f major=%.3f n=%d\n", rIdx, rg.xC, rg.yC, (rg.orientation * 180. / Math.PI), (float) rg.eccentricity, (float) rg.minor, (float) rg.major, set1.size()); if (rg.eccentricity >= 0.95) { int[] hues = extractHues(img, set1); System.out.println(" " + rIdx + " hues=" + Arrays.toString(hues)); if (isEmpty(hues)) { continue; } //Set<PairInt> offRegionPoints = extractOffRegion(img, r, rg); int[] offRegion = new int[hues.length]; float[] sbAvg = new float[2]; extractHSBProperties(img, set1, offRegion, sbAvg); if (Float.isNaN(sbAvg[0])) { continue; } int[] hues2 = subtractNormalized(hues, offRegion); /* bright sky: sAvg=0.23 vAvg=0.75 rnbw hues peak is 2nd bin dark sky: sAvg=0.5 bck vAvg=0.43 rnbw hues peak is 1st peak */ int maxPeakIdx = MiscMath.findYMaxIndex(hues); int hIdx = -1; //NOTE: this may need to be revised if (sbAvg[1] < 0.55) { if (maxPeakIdx == 0) { hIdx = hists.size(); listOfSets.add(set1); hists.add(new OneDIntArray(hues2)); rgs.add(rg); } } else { if (maxPeakIdx == 1) { hIdx = hists.size(); listOfSets.add(set1); hists.add(new OneDIntArray(hues2)); rgs.add(rg); } } System.out.println( " " + rIdx + " xy=(" + rg.xC + "," + rg.yC + ") " + " maxIdx=" + maxPeakIdx + " hists.idx=" + hIdx + " angle=" + (rg.orientation*180./Math.PI) + " ecc=" + rg.eccentricity + "\n sAvg=" + sbAvg[0] + " vAvg=" + sbAvg[1] + " hues hist=" + Arrays.toString(hues2) + "\n bck=" + Arrays.toString(offRegion) ); } } } } private void findNegativePT(ImageExt img, List<Region> polarThetaNegative, List<Set<PairInt>> listOfSets, List<OneDIntArray> hists, List<RegionGeometry> rgs) { for (int rIdx = 0; rIdx < polarThetaNegative.size(); ++rIdx) { Region r = polarThetaNegative.get(rIdx); Set<PairInt> set1 = null; for (int i = 0; i < r.accX.size(); ++i) { int x = r.accX.get(i); int y = r.accY.get(i); PairInt p = new PairInt(x, y); int pixIdx = img.getInternalIndex(p); if (set1 == null) { set1 = new HashSet<PairInt>(); } set1.add(p); } if (set1 != null) { RegionGeometry rg = Canonicalizer.calculateEllipseParams( r, img.getWidth(), img.getHeight()); //System.out.println("negative xy=" // + rg.xC + "," + rg.yC // + " ecc=" + rg.eccentricity); if (rg.eccentricity >= 0.95) { int[] hues = extractHues(img, set1); if (isEmpty(hues)) { continue; } //Set<PairInt> offRegionPoints = extractOffRegion(img, r, rg); int[] offRegion = new int[hues.length]; float[] sbAvg = new float[2]; extractHSBProperties(img, set1, offRegion, sbAvg); if (Float.isNaN(sbAvg[0])) { continue; } int[] hues2 = subtractNormalized(hues, offRegion); /* bright sky: sAvg=0.07 vAvg=0.86 hues hist=[0, 0, 0, 0, 3, 36, 0, 0, 0, 0] rnbw hues peak is bin dark sky: sAvg= vAvg= hues hist= rnbw hues */ int maxPeakIdx = MiscMath.findYMaxIndex(hues); //NOTE: this may need to be revised if (maxPeakIdx == 5) { listOfSets.add(set1); hists.add(new OneDIntArray(hues2)); rgs.add(rg); } System.out.println("negative xy=(" + rg.xC + "," + rg.yC + ") " + " angle=" + (rg.orientation*180./Math.PI) + " ecc=" + rg.eccentricity + "\n sAvg=" + sbAvg[0] + "\n vAvg=" + sbAvg[1] + "\n hues hist=" + Arrays.toString(hues) + "\n bck=" + Arrays.toString(offRegion) ); } } } } }
package algorithms.imageProcessing.transform; import algorithms.imageProcessing.transform.Camera.CameraExtrinsicParameters; import algorithms.imageProcessing.transform.Camera.CameraIntrinsicParameters; import algorithms.matrix.MatrixUtil; import algorithms.util.FormatArray; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import no.uib.cipr.matrix.NotConvergedException; /** * iterative non-linear optimization using Levenberg-Marquardt algorithm * to minimize the re-projection error of perspective projection * in "perspective-n-point". * * L-M is guaranteed to converge to eventually find an improvement, * because an update with a sufficiently small magnitude and a negative scalar * product with the gradient is guaranteed to do so. * * TODO: consider implementing the Szeliski 2010 chapter 6 equations (6.44)-(6.47) * * NOTE: this implementation uses euler rotation angles and singularity safe * updates, but future versions could consider using quaternions. * This from Szeliski 2010: "Quaternions, on the other hand, are better if you want to keep track of a smoothly moving camera, since there are no discontinuities in the representation. It is also easier to interpolate between rotations and to chain rigid transformations (Murray, Li, and Sastry 1994; Bregler and Malik 1998). My usual preference is to use quaternions, but to update their estimates using an incremental rotation, as described in Section 6.2.2." * @author nichole */ public class PNP { public static List<CameraExtrinsicParameters> solveForPose(double[][] imageC, double[][] worldC, CameraIntrinsicParameters kIntr, List<CameraExtrinsicParameters> kExtrs, double[] kRadial, final int nMaxIter, boolean useR2R4) throws NotConvergedException, Exception { if (imageC.length != 3) { throw new IllegalArgumentException("imageC.length must be 3 for the x,y,z dimensions"); } if (worldC.length != 3) { throw new IllegalArgumentException("worldC.length must be 3 for the x,y,z dimensions"); } int nFeatures = worldC[0].length; if (nFeatures < 4) { throw new IllegalArgumentException("worldC[0].length must be at least 4"); } if ((imageC[0].length % nFeatures) != 0) { throw new IllegalArgumentException("imageC[0].length must be an integer multiple of worldC[0].length"); } int nImages = imageC[0].length/nFeatures; if (kExtrs.size() != nImages) { throw new IllegalArgumentException("from imageC[0].length, " + "nImages is expected to be " + nImages + " therefore kExtrs.size() should be " + nImages + " also."); } List<CameraExtrinsicParameters> refined = new ArrayList<CameraExtrinsicParameters>(); double[][] imageCI = MatrixUtil.zeros(3, nFeatures); CameraExtrinsicParameters r; for (int i = 0; i < nImages; ++i) { MatrixUtil.copySubMatrix(imageC, 0, 2, i*nFeatures, i*nFeatures+nFeatures-1, imageCI); r = solveForPose(imageCI, worldC, kIntr, kExtrs.get(i), kRadial, nMaxIter, useR2R4); refined.add(r); } return refined; } public static List<CameraExtrinsicParameters> solveForPose(double[][] imageC, double[][] worldC, List<CameraIntrinsicParameters> kIntrs, List<CameraExtrinsicParameters> kExtrs, double[] kRadial, final int nMaxIter, boolean useR2R4) throws NotConvergedException, Exception { if (kIntrs.size() != kExtrs.size()) { throw new IllegalArgumentException("the sizes of Kintrs and kExtrs must be the same"); } if (imageC.length != 3) { throw new IllegalArgumentException("imageC.length must be 3 for the x,y,z dimensions"); } if (worldC.length != 3) { throw new IllegalArgumentException("worldC.length must be 3 for the x,y,z dimensions"); } int nFeatures = worldC[0].length; if (nFeatures < 4) { throw new IllegalArgumentException("worldC[0].length must be at least 4"); } if ((imageC[0].length % nFeatures) != 0) { throw new IllegalArgumentException("imageC[0].length must be an integer multiple of worldC[0].length"); } int nImages = imageC[0].length/nFeatures; if (kExtrs.size() != nImages) { throw new IllegalArgumentException("from imageC[0].length, " + "nImages is expected to be " + nImages + " therefore kExtrs.size() should be " + nImages + " also."); } if (kIntrs.size() != nImages) { throw new IllegalArgumentException("from imageC[0].length, " + "nImages is expected to be " + nImages + " therefore kIntrs.size() should be " + nImages + " also."); } List<CameraExtrinsicParameters> refined = new ArrayList<CameraExtrinsicParameters>(); double[][] imageCI = MatrixUtil.zeros(3, nFeatures); CameraExtrinsicParameters r; for (int i = 0; i < nImages; ++i) { MatrixUtil.copySubMatrix(imageC, 0, 2, i*nFeatures, i*nFeatures+nFeatures-1, imageCI); r = solveForPose(imageCI, worldC, kIntrs.get(i), kExtrs.get(i), kRadial, nMaxIter, useR2R4); refined.add(r); } return refined; } public static CameraExtrinsicParameters solveForPose(double[][] imageC, double[][] worldC, CameraIntrinsicParameters kIntr, CameraExtrinsicParameters kExtr, double[] kRadial, final int nMaxIter, boolean useR2R4) throws NotConvergedException, Exception { if (imageC.length != 3) { throw new IllegalArgumentException("imageC.length must be 3 for the x,y,z dimensions"); } if (worldC.length != 3) { throw new IllegalArgumentException("worldC.length must be 3 for the x,y,z dimensions"); } // number of features int n = worldC[0].length; if (n < 4) { throw new IllegalArgumentException("worldC[0].length must be at least 4"); } if (imageC[0].length != n) { throw new IllegalArgumentException("imageC[0].length must equal worldC[0].length"); } double[] b = new double[2*n]; final double[][] xn = Camera.pixelToCameraCoordinates(imageC, kIntr, kRadial, useR2R4); for (int i = 0; i < n; ++i) { xn[0][i] /= xn[2][i]; xn[1][i] /= xn[2][i]; //TODO: follow up on signs from pixelToCameraCoordinates. b[2*i] = xn[0][i]; b[2*i + 1] = xn[1][i]; } //TODO: consider adding constraints suggested in Seliski 2010: // u_0 and v_0 are close to half the image lengths and widths, respectively. // the angle between 2 image axes is close to 90. // the focal lengths along both axes are greater than 0. // extract pose as (theta_x, theta_y, theta_z, t_x, t_y, t_z) double[][] rTest = MatrixUtil.copy(kExtr.getRotation()); double[] thetasTest = Rotation.extractThetaFromZYX(rTest); double[] tTest = Arrays.copyOf(kExtr.getTranslation(), 4); CameraExtrinsicParameters outExtr = new CameraExtrinsicParameters(); outExtr.setRotation(MatrixUtil.copy(kExtr.getRotation())); outExtr.setTranslation(Arrays.copyOf(kExtr.getTranslation(), 4)); //TODO: check the signs of the last row. wetzsteinuses a convention of looking down //the negative z-axis. // equation (19). size is 1 X 9 double[] h = new double[9]; populateHWithRT(h, rTest, tTest); // eqn (20) of Wetzstein. length is 2*N // project the world coordinates to the camera coord frame, using R and T in h: double[] fgp = map(worldC, h); // in camera reference frame, subtract the projected world points from the observations: // length is 2*N double[] bMinusFGP = MatrixUtil.subtract(b, fgp); // the projected x and y have opposite signs than they should System.out.printf("observed in camera ref frame=\n%s\n", FormatArray.toString(b, "%.3e")); System.out.printf("world feature projected to camera ref frame=\n%s\n", FormatArray.toString(fgp, "%.3e")); System.out.printf("(observed-projected) in camera ref frame=\n%s\n", FormatArray.toString(bMinusFGP, "%.3e")); // sum the squares to evalute the re-projection error: double fPrev = evaluateObjective(bMinusFGP); double fTest = Double.POSITIVE_INFINITY; // size is (2N) X 6 double[][] j = calculateJ(worldC, h, thetasTest); // size is 6 X (2N) double[][] jT = MatrixUtil.transpose(j); // size is 6 X 6 double[][] jTJ = MatrixUtil.multiply(jT, j); double lambda = maxDiag(jTJ); //factor to raise or lower lambda. // consider using the eigenvalue spacing of J^T*J (Transtrum & Sethna, "Improvements to the Levenberg-Marquardt algorithm for nonlinear least-squares minimization") final double lambdaF = 2; // deltaP is the array of length 6 holding the steps of change for theta and translation. double[] deltaP = new double[6]; // deltaTheta is used to extract the 1st 3 elements of deltaPM double[] deltaTheta = new double[3]; // deltaT is used to extract the last 3 elements of deltaPLM double[] deltaT = new double[3]; double eps = 1E-12; double gainRatio; double[] gradient = MatrixUtil.multiplyMatrixByColumnVector(jT, bMinusFGP); final double tolP = 1.e-3; final double tolG = 1.e-3; int nIter = 0; //begin loop of tentative changes while ((nIter < nMaxIter) && (Math.abs(fPrev - fTest) >= eps)) { if (nIter == 0) { initDeltaPWithQu(deltaP); } else { calculateDeltaPLMSzeliski(jTJ, lambda, gradient, deltaP); } nIter++; // p is (theta_x, theta_y, theta_z, t_x, t_y, t_z) System.arraycopy(deltaP, 0, deltaTheta, 0, 3); System.arraycopy(deltaP, 3, deltaT, 0, 3); updateT(tTest, deltaT); updateRTheta(rTest, thetasTest, deltaTheta); populateHWithRT(h, rTest, tTest); // eqn (20) of Wetzstein. length is 2*N // project the world coordinates to the camera coord frame, using R and T in h: fgp = map(worldC, h); // in camera reference frame, subtract the projected world points from the observations: bMinusFGP = MatrixUtil.subtract(b, fgp); // sum the squares: fTest = evaluateObjective(bMinusFGP); System.out.printf("nIter=%d) fPrev=%.11e, fTest=%.11e diff=%.11e\n", nIter, fPrev, fTest, (fPrev-fTest)); System.out.flush(); // eqns (24-34) of Wetzstein j = calculateJ(worldC, h, thetasTest); // 2NX6 jT = MatrixUtil.transpose(j); // 6X2N jTJ = MatrixUtil.multiply(jT, j); // 6X6 //gradient is the local direction of steepest ascent // 6X1 gradient = MatrixUtil.multiplyMatrixByColumnVector(jT, bMinusFGP); System.out.printf("\nj^T*(b-fgp)=%s\n", FormatArray.toString(gradient, "%.3e")); System.out.printf("deltaP=%s\n", FormatArray.toString(deltaP, "%.3e")); gainRatio = calculateGainRatio(fTest, fPrev, deltaP, lambda, gradient, eps); if (gainRatio <= Double.NEGATIVE_INFINITY) { break; } System.out.printf("lambda=%.6e\ngainRatio=%.6e\nfPrev=%.11e, fTest=%.11e\n", lambda, gainRatio, fPrev, fTest); System.out.flush(); if (gainRatio > 0) { // near the minimimum, which is good. // decrease lambda lambda /= lambdaF; assert(fTest < fPrev); fPrev = fTest; System.out.printf("fPrev updated to fTest: fPrev=%.11e fTest=%.11e\n", fPrev, fTest); System.out.flush(); System.out.printf("elementwise diff in rotation:\n%s\n", FormatArray.toString(MatrixUtil.elementwiseSubtract(outExtr.getRotation(), rTest), "%.11e")); outExtr.setRotation(MatrixUtil.copy(rTest)); outExtr.setTranslation(Arrays.copyOf(tTest, 3)); // step length vanishes: deltaPLM --> 0 // gradient of f(x) vanishes: -J^T * (b - fgp) --> 0 //MatrixUtil.multiply(gradientCheck, -1.); if (isNegligible(deltaP, tolP) || isNegligible(gradient, tolG)) { break; } } else { // increase lambda to reduce step length and get closer to // steepest descent direction lambda *= lambdaF; } System.out.printf("new lambda=%.6e\n", lambda); } return outExtr; } /** * map the homography matrix to the projected 2D point coordinates of the * world reference points eqn (20). * @param worldC * @param h * @return */ static double[] map(double[][] worldC, double[] h) { int n = worldC[0].length; double[] f = new double[2*n]; int i, j; double X, Y, s; for (i = 0; i < n; ++i) { X = worldC[0][i]; Y = worldC[1][i]; s = h[6]*X + h[7]*Y + h[8]; f[2*i] = (h[0]*X + h[1]*Y + h[2])/s; f[2*i+1] = ((h[3]*X + h[4]*Y + h[5])/s); } return f; } static double evaluateObjective(double[] bMinusFGP) { int n = bMinusFGP.length; double sum = 0; int i; for (i = 0; i < n; ++i) { sum += (bMinusFGP[i] * bMinusFGP[i]); } return sum; } /** * calculate J for extrinsic parameters in solving pose <pre> Sect 6.1 of George Wetzstein Stanford Course Notes for EE 267 Virtual Reality, 6-DOF Pose Tracking with the VRduino </pre> <pre> J = J_f * J_g where p is the parameter vector [thetas, translations] where J_g = dh/dp where h is the 2-D projection matrix of size 3x3 as 2 columns of rotation and last column is translation and where J_f = df/dh where f is the world point transformed by the homography h. J = df/dp </pre> * @param worldC * @param h * @param thetas * @return matrix size (2N) X 6 */ static double[][] calculateJ(double[][] worldC, double[] h, double[] thetas) { //(2N) X 9 double[][] jF = calculateJF(worldC, h); //9 X 6 double[][] jG = calculateJG(thetas); // (2N)X6) double[][] j = MatrixUtil.multiply(jF, jG); return j; } /** <pre> J_f = df/dh where f is the world point transformed by the homography h. </pre> <pre> Sect 6.1 of George Wetzstein Stanford Course Notes for EE 267 Virtual Reality, 6-DOF Pose Tracking with the VRduino </pre> * @param worldC * @param h * @return a (2*n)X9 matrix */ static double[][] calculateJF(double[][] worldC, double[] h) { int n = worldC[0].length; if (n < 4) { throw new IllegalArgumentException("need at least 4 features in worldC"); } //TODO: assert worldC[2][*] = 1 for local device frame assert(Math.abs(worldC[2][0] - 1.) < 1e-5); // (2*n) X 9 double[][] jF = MatrixUtil.zeros(2*n, 9); int i, j; double x, y, s1, s2, d, dsq; for (i = 0; i < n; ++i) { x = worldC[0][i]; y = worldC[1][i]; d = h[6] * x + h[7] * y + h[8]; s1 = h[0] * x + h[1] * y + h[2]; s2 = h[3] * x + h[4] * y + h[5]; dsq = s1*s1; jF[2*i][0] = x/d; jF[2*i][1] = y/d; jF[2*i][2] = 1./d; jF[2*i][6] = -(s1/dsq)*x; jF[2*i][7] = -(s1/dsq)*y; jF[2*i][8] = -(s1/dsq); jF[2*i + 1][3] = x/d; jF[2*i + 1][4] = y/d; jF[2*i + 1][5] = 1./d; jF[2*i + 1][6] = -(s2/dsq)*x; jF[2*i + 1][7] = -(s2/dsq)*y; jF[2*i + 1][8] = -(s2/dsq); } return jF; } /** <pre> J_g = dh/dp where h is the 2-D projection matrix of size 3x3 as 2 columns of rotation and last column is translation </pre> <pre> Sect 6.1 of George Wetzstein Stanford Course Notes for EE 267 Virtual Reality, 6-DOF Pose Tracking with the VRduino </pre> * @param thetas * @return 9X6 matrix */ static double[][] calculateJG(double[] thetas) { // 9 X 9 double[][] jG = new double[9][6];//MatrixUtil.zeros(9, 6); double cx, cy, cz, sx, sy, sz; cx = Math.cos(thetas[0]); cy = Math.cos(thetas[1]); cz = Math.cos(thetas[2]); sx = Math.sin(thetas[0]); sy = Math.sin(thetas[1]); sz = Math.sin(thetas[2]); jG[0] = new double[]{-cx*sy*sz, -sy*cz-sx*cy*sz, -cy*sz-sx*sy*cz, 0, 0, 0}; jG[1] = new double[]{sx*sz, 0, -cx*cz, 0, 0, 0}; jG[2] = new double[]{0, 0, 0, 1, 0, 0}; jG[3] = new double[]{cx*sy*cz, -sy*sz+sx*cy*cz, cy*cz-sx*sy*sz, 0, 0, 0}; jG[4] = new double[]{-sx*cz, 0, -cx*sz, 0, 0, 0}; jG[5] = new double[]{0, 0, 0, 0, 1, 0}; jG[6] = new double[]{-sx*sy, cx*cy, 0, 0, 0, 0}; jG[7] = new double[]{-cx, 0, 0, 0, 0, 0}; jG[8] = new double[]{0, 0, 0, 0, 0, -1}; return jG; } /** * following Szeliski 2010, Chap 6, eqn (6.18) * @param jTJ J^T * J. size is 6X6. * @param lambda * @param jTBFG J^T * (B-F(g(p))). size is 6X1 * @param outDeltaP calculated step length * @throws no.uib.cipr.matrix.NotConvergedException */ private static void calculateDeltaPLMSzeliski(double[][] jTJ, double lambda, double[] jTBFG, double[] outDeltaP) throws NotConvergedException { // [6X6] * [6X1] = [6X1] //delta p = pseudoInv(J^T*J + lambda*diag(J^T*J)) * J^T*BFG int i, j; // [6X6] double[][] a = MatrixUtil.copy(jTJ); for (i = 0; i < 6; ++i) { a[i][i] += (lambda*(jTJ[i][i])); } //[6X6] double[][] aInv = MatrixUtil.pseudoinverseRankDeficient(a); //[6X6] * [6X1] = [6X1] MatrixUtil.multiplyMatrixByColumnVector(aInv, jTBFG, outDeltaP); } private static double[] calculateDeltaPLM(double[][] jTJ, double lambda, double[] jTBF) throws NotConvergedException { // (J^T*J + lambda*I)^-1 * J^T * (b-f(g(p)) double[][] identity = MatrixUtil.createIdentityMatrix(6); MatrixUtil.multiply(identity, lambda); // 6 X 6 double[][] a = MatrixUtil.elementwiseAdd(jTJ, identity); double[][] aInv = MatrixUtil.pseudoinverseFullRank(a); double[] step = MatrixUtil.multiplyMatrixByColumnVector(aInv, jTBF); return step; } /** * gain = (f(p) - f(p + delta p)) / ell(delta p) where ell(delta p) is (delta p)^T * (lambda * (delta p)) + J^T * ( b - fgp)) gain = (f - fPrev) / ( (delta p)^T * (lambda * (delta p) + J^T * ( b - fgp)) ) * @param fNew * @param fPrev * @param deltaP * @param lambda * @param jTBFG j^T*(b-f(g(p))). size is 6X1 * @return */ private static double calculateGainRatio(double fNew, double fPrev, double[] deltaP, double lambda, double[] jTBFG, double eps) { // (M. Lourakis, A. Argyros: SBA: A Software Package For Generic // Sparse Bundle Adjustment. ACM Trans. Math. Softw. 36(1): (2009)) // gain ratio = ( fPrev - fNew) / ( deltaP^T * (lambda * deltaP + J^T*fPrev) ) // 1X6 * ([1X1]*[6X1] + [6X1]) = [1X1] //(delta p LM)^T * (lambda * (delta p LM) + J^T * (b - fgp)) // 1X6 * ( 6X1 + 6 X (2N) * (2NX1) ) // 1X6 6X1 // 1X1 //(delta p LM)^T * (lambda * (delta p LM) + J^T * (b - fgp)) double[] denom = Arrays.copyOf(deltaP, deltaP.length); for (int i = 0; i < denom.length; ++i) { denom[i] *= lambda; } denom = MatrixUtil.add(denom, jTBFG); double d = MatrixUtil.innerProduct(deltaP, denom); if (Math.abs(d) < eps) { return Double.NEGATIVE_INFINITY; } double gain = (fPrev - fNew)/d; return gain; } private static boolean isNegligible(double[] c, double eps) { for (int i = 0; i < c.length; ++i) { if (Math.abs(c[i]) > eps) { return false; } } return true; } private static void populateHWithRT(double[] h, double[][] r, double[] t) { h[0] = r[0][0]; h[1] = r[0][1]; h[2] = t[0]; h[3] = r[1][0]; h[4] = r[1][1]; h[5] = t[1]; // TODO: review the code for right-handedness vs left-handedness. // Wetzstein convention looks down the negative z-axis. // (see Rotation.java notes). may need transposition... //h[6] = -r[2][0]; //h[7] = -r[2][1]; //h[8] = -t[2]; h[6] = r[2][0]; h[7] = r[2][1]; h[8] = t[2]; } /** * * @param h input and output variable homography to be updated with given * rotation angles and translations. * @param thetas * @param t */ private static void updateHWithThetaT(double[] h, double[] thetas, double[] t) { // equation (19). size is 1 X 9 double cx = Math.cos(thetas[0]); double cy = Math.cos(thetas[1]); double cz = Math.cos(thetas[2]); double sx = Math.sin(thetas[0]); double sy = Math.sin(thetas[1]); double sz = Math.sin(thetas[2]); h[0] = cy*cz - sx*sy*sz; h[1] = -cx*sz; h[2] = t[0]; h[3] = cy*sz + sx*sy*cz; h[4] = cx*cz; h[5] = t[1]; h[6] = cx*sy; h[7] = -sx; h[9] = -t[2]; } /** * update translation t by deltaT */ private static void updateT(double[] t, double[] deltaT) { // from Danping Zou lecture notes, Shanghai Jiao Tong University, // parameter perturbations for a vector are // x + delta x int i; // vector perturbation for translation: for (i = 0; i < 3; ++i) { t[i] += deltaT[i]; } } private static void updateT(double[] t, double[] deltaT, double[][] r) { // t_local(t + deltaT) = t + r*deltaT int i; double[] rdt = MatrixUtil.multiplyMatrixByColumnVector(r, deltaT); // vector perturbation for translation: for (i = 0; i < 3; ++i) { t[i] += rdt[i]; } } /** * update rotation matrix r with deltaTheta. * the approach used avoids singularities and the need to restore * the constraint afterwards (i.e., constraint restoration is built in). * * @param r * @param thetas input and output array holding euler rotation angles * theta_x, theta_y, theta_ * @param deltaTheta */ private static void updateRTheta(double[][] r, double[] thetas, double[] deltaTheta) { // from Danping Zou lecture notes, Shanghai Jiao Tong University, // parameter perturbations for a Lie group such as rotation are: // R * (I - [delta x]_x) where [delta x]_x is the skew-symetric matrix of delta_x // T. Barfoot, et al. 2010, // Pose estimation using linearized rotations and quaternion algebra, // Acta Astronautica (2010), doi:10.1016/j.actaastro.2010.06.049 // eqn (31) for updating rotation: // C(theta) = C(deltaPhi) * previous C // where C is rotation matrix r // calculated as C(theta) = // and deltaPhi = sTheta * deltaTheta //double[][] out;// = MatrixUtil.zeros(3, 3); double[] qUpdated = Rotation.applySingularitySafeRotationPerturbationQuaternion(thetas, deltaTheta); // [4X4] double[][] qR = Rotation.createRotationMatrixFromQuaternion4(qUpdated); qR = MatrixUtil.transpose(qR); // rotation is [0:2, 0:2] of qR // update in-out variable r for (int i = 0; i < 3; ++i) { System.arraycopy(qR[i], 0, r[i], 0, 3); } //extracting theta from the updated rotation would keep the theta // vector consistent with the rotation matrix, // but the value is a little different that updating theta with delta theta // by addition. double[] thetaExtracted = Rotation.extractThetaFromZYX(r); System.arraycopy(thetaExtracted, 0, thetas, 0, thetas.length); /* for (int i = 0; i < 3; ++i) { thetas[i] += deltaTheta[i]; }*/ } /** * initialize the first parameter steps with small values suggested * by Qu. * @param deltaP */ private static void initDeltaPWithQu(double[] deltaP) { /*Qu thesis eqn (3.38) delta thetas ~ 1e-8 delta translation ~1e-5 delta focus ~ 1 delta kRadial ~ 1e-3 delta x ~ 1e-8 */ int i; for (i = 0; i < 3; ++i) { // delta theta deltaP[i] = 1e-8; } for (i = 0; i < 3; ++i) { // delta translation deltaP[3+i] = 1e-5; } } private static double maxDiag(double[][] jTJ) { double max = Double.NEGATIVE_INFINITY; //Arrays.fill(max, Double.NEGATIVE_INFINITY); for (int i = 0; i < jTJ.length; ++i) { if (jTJ[i][i] > max) { max = jTJ[i][i]; } } return max; } }
package pylos.controller; import pylos.Pylos; import pylos.model.Ball; import pylos.model.Model; import pylos.model.Position; import pylos.view.View; /** * The Pylos Controller. * Implements the singleton pattern by having everything static and no instance (the object is the class). */ public abstract class Controller { static View view; public static void initialize(View view) { Controller.view = view; initTurn(); } public static void updateView() { view.board.drawBalls(); view.updatePositionBalls(); } public static void initTurn() { Model.currentPlayer.resetAction(); } public static void finishTurn() { if (Model.isWinner()) { updateView(); Pylos.logger.info(Model.currentPlayer + " won"); } else { nextTurn(); } } public static void placePlayerBall(Position position) { Model.currentPlayer.putBallOnBoard(position); finishTurn(); } private static void nextTurn() { Model.currentPlayer = (Model.currentPlayer == Model.player1) ? Model.player2 : Model.player1; initTurn(); updateView(); } public static void risePlayerBall(Ball ball) { if (Model.getPositionsToRise(ball).isEmpty()) { System.err.println("Can not rise ball, there is no place to rise it."); } else { Model.currentPlayer.riseBall(ball); view.updatePositionsToRise(ball); updateView(); } } }
// $Id: ConnectStressTest.java,v 1.20 2007/11/07 12:12:29 belaban Exp $ package org.jgroups.tests; import junit.framework.TestCase; import junit.framework.Test; import junit.framework.TestSuite; import org.jgroups.*; import org.jgroups.util.Util; import java.util.Vector; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.BrokenBarrierException; /** * Creates 1 channel, then creates NUM channels, all try to join the same channel concurrently. * @author Bela Ban Nov 20 2003 * @version $Id: ConnectStressTest.java,v 1.20 2007/11/07 12:12:29 belaban Exp $ */ public class ConnectStressTest extends TestCase { static CyclicBarrier start_connecting=null; static CyclicBarrier connected=null; static CyclicBarrier received_all_views=null; static CyclicBarrier start_disconnecting=null; static CyclicBarrier disconnected=null; static final int NUM=20; static final MyThread[] threads=new MyThread[NUM]; static JChannel channel=null; static String groupname="ConcurrentTestDemo"; static String props="udp.xml"; public ConnectStressTest(String name) { super(name); } static void log(String msg) { System.out.println("-- [" + Thread.currentThread().getName() + "] " + msg); } public void testConcurrentJoins() throws Exception { start_connecting=new CyclicBarrier(NUM +1); connected=new CyclicBarrier(NUM +1); received_all_views=new CyclicBarrier(NUM +1); start_disconnecting=new CyclicBarrier(NUM +1); disconnected=new CyclicBarrier(NUM +1); long start, stop; // create main channel - will be coordinator for JOIN requests channel=new JChannel(props); channel.setOpt(Channel.AUTO_RECONNECT, Boolean.TRUE); start=System.currentTimeMillis(); channel.connect(groupname); stop=System.currentTimeMillis(); log(channel.getLocalAddress() + " connected in " + (stop-start) + " msecs (" + channel.getView().getMembers().size() + " members). VID=" + channel.getView().getVid()); assertEquals(1, channel.getView().getMembers().size()); for(int i=0; i < threads.length; i++) { threads[i]=new MyThread(i); threads[i].start(); } // signal the threads to start connecting to their channels start_connecting.await(); start=System.currentTimeMillis(); try { connected.await(); stop=System.currentTimeMillis(); System.out.println("-- took " + (stop-start) + " msecs for all " + NUM + " threads to connect"); received_all_views.await(); stop=System.currentTimeMillis(); System.out.println("-- took " + (stop-start) + " msecs for all " + NUM + " threads to see all views"); int num_members=-1; for(int i=0; i < 10; i++) { View v=channel.getView(); num_members=v.getMembers().size(); System.out.println("*--* number of members connected: " + num_members + ", (expected: " +(NUM+1) + "), v=" + v); if(num_members == NUM+1) break; Util.sleep(500); } assertEquals((NUM+1), num_members); } catch(Exception ex) { fail(ex.toString()); } } public void testConcurrentLeaves() throws Exception { start_disconnecting.await(); long start, stop; start=System.currentTimeMillis(); disconnected.await(); stop=System.currentTimeMillis(); System.out.println("-- took " + (stop-start) + " msecs for " + NUM + " threads to disconnect"); int num_members=0; for(int i=0; i < 10; i++) { View v=channel.getView(); Vector mbrs=v != null? v.getMembers() : null; if(mbrs != null) { num_members=mbrs.size(); System.out.println("*--* number of members connected: " + num_members + ", (expected: 1), view=" + v); if(num_members <= 1) break; } Util.sleep(3000); } assertEquals(1, num_members); log("closing all channels"); for(int i=0; i < threads.length; i++) { MyThread t=threads[i]; t.closeChannel(); } channel.close(); } public static class MyThread extends Thread { int index=-1; long total_connect_time=0, total_disconnect_time=0; private JChannel ch=null; private Address my_addr=null; public MyThread(int i) { super("thread index=i; } public void closeChannel() { if(ch != null) { ch.close(); } } public void run() { View view; try { ch=new JChannel(props); ch.setOpt(Channel.AUTO_RECONNECT, true); start_connecting.await(); long start=System.currentTimeMillis(), stop; ch.connect(groupname); stop=System.currentTimeMillis(); total_connect_time=stop-start; view=ch.getView(); my_addr=ch.getLocalAddress(); log(my_addr + " connected in " + total_connect_time + " msecs (" + view.getMembers().size() + " members). VID=" + view.getVid()); connected.await(); int num_members=0; while(true) { View v=ch.getView(); Vector mbrs=v != null? v.getMembers() : null; if(mbrs == null) { System.err.println("mbrs is null, v=" + v); } else { num_members=mbrs.size(); log("num_members=" + num_members); if(num_members == NUM+1) // all threads (NUM) plus the first channel (1) break; } Util.sleep(2000); } log("reached " + num_members + " members"); received_all_views.await(); start_disconnecting.await(); start=System.currentTimeMillis(); ch.disconnect(); stop=System.currentTimeMillis(); log(my_addr + " disconnected in " + (stop-start) + " msecs"); disconnected.await(); } catch(BrokenBarrierException e) { e.printStackTrace(); } catch(ChannelException e) { e.printStackTrace(); } catch(InterruptedException e) { e.printStackTrace(); } } } public static Test suite() { TestSuite s=new TestSuite(); // we're adding the tests manually, because they need to be run in *this exact order* s.addTest(new ConnectStressTest("testConcurrentJoins")); s.addTest(new ConnectStressTest("testConcurrentLeaves")); return s; } public static void main(String[] args) { String[] testCaseName={ConnectStressTest.class.getName()}; junit.textui.TestRunner.main(testCaseName); } }
package VASSAL.build.module; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import VASSAL.Info; import VASSAL.build.GameModule; import VASSAL.build.module.metadata.AbstractMetaData; import VASSAL.build.module.metadata.ExtensionMetaData; import VASSAL.build.module.metadata.MetaDataFactory; import VASSAL.tools.ReadErrorDialog; import VASSAL.tools.WriteErrorDialog; /** * Convenience class for managing extensions relative to a module file. * Create extension directory as lazily as possible. * * @author rodneykinney * */ public class ExtensionsManager { private File moduleFile; private File extensionsDir; private File inactiveDir; /** * Tests if the specified file should be accepted as an module extension * file. Currently we disallow any files that are hidden or "files" that * are directories. */ private final FilenameFilter filter = new FilenameFilter() { public boolean accept(File dir, String name) { final File fileCandidate = new File(dir, name); return !fileCandidate.isHidden() && !fileCandidate.isDirectory(); } }; public ExtensionsManager(File moduleFile) { this.moduleFile = moduleFile; } public ExtensionsManager(GameModule module) { this.moduleFile = new File(GameModule.getGameModule().getDataArchive().getName()); } /** * Manage global extensions */ public ExtensionsManager(String dir) { extensionsDir = ensureExists(new File(Info.getHomeDir(), dir)); } public File getExtensionsDirectory(boolean mustExist) { if (extensionsDir == null) { File dir; String dirName = moduleFile.getPath(); int index = dirName.lastIndexOf('.'); if (index > 0) { dirName = dirName.substring(0, index); } dir = new File(dirName + "_ext"); if (mustExist) { dir = ensureExists(dir); } extensionsDir = dir; if (extensionsDir == null) { return null; } } if (mustExist && !extensionsDir.exists()) { extensionsDir = ensureExists(extensionsDir); } return extensionsDir; } public void setExtensionsDirectory(File dir) { extensionsDir = dir == null ? null : ensureExists(dir); } /** * Ensure a directory exists. * @param dir Directory * @return Directory as <code>File</code> object; otherwise <code>null</code> if an error occurs. */ protected File ensureExists(File dir) { if (dir.exists() && !dir.isDirectory()) { WriteErrorDialog.error(new IOException(dir + "is not a directory"), dir); return null; } else if (!dir.exists() && !dir.mkdirs()) { WriteErrorDialog.error(new IOException("Could not create " + dir), dir); return null; } return dir; } public File getInactiveExtensionsDirectory(boolean mustExist) { if (inactiveDir == null) { File extDir = getExtensionsDirectory(mustExist); if (extDir == null) { return null; } inactiveDir = new File(extDir, "inactive"); if (mustExist) { inactiveDir = ensureExists(inactiveDir); if ( inactiveDir == null ) { return null; } } } if (mustExist && !inactiveDir.exists()) { inactiveDir = ensureExists(inactiveDir); } return inactiveDir; } public File setActive(File extension, boolean active) { File newExt; if (active) { final File extensionsDirectory = getExtensionsDirectory(true); if (extensionsDirectory == null) { return extension; } newExt = new File(extensionsDirectory, extension.getName()); } else { final File inactiveExtensionsDirectory = getInactiveExtensionsDirectory(true); if (inactiveExtensionsDirectory == null) { return extension; } newExt = new File(inactiveExtensionsDirectory, extension.getName()); } extension.renameTo(newExt); return newExt; } private List<File> getExtensions(File dir) { final List<File> extensions = new ArrayList<File>(0); if (dir != null && dir.exists()) { File[] files = dir.listFiles(filter); if (files == null) { ReadErrorDialog.error(new IOException(), dir); } else { for (File file : files) { final AbstractMetaData metadata = MetaDataFactory.buildMetaData(file); if (metadata != null && metadata instanceof ExtensionMetaData) { extensions.add(file); } } } } return extensions; } public List<File> getActiveExtensions() { return getExtensions(getExtensionsDirectory(false)); } public List<File> getInactiveExtensions() { return getExtensions(getInactiveExtensionsDirectory(false)); } public boolean isExtensionActive(File extension) { for (File f : getActiveExtensions()) { if (f.getName().equals(extension.getName())) { return true; } } return false; } }
package com.bouye.gw2.sab.query; import api.web.gw2.mapping.core.JsonpContext; import api.web.gw2.mapping.core.PageResult; import api.web.gw2.mapping.v1.guilddetails.GuildDetails; import api.web.gw2.mapping.v2.account.Account; import api.web.gw2.mapping.v2.guild.id.log.LogEvent; import api.web.gw2.mapping.v2.guild.id.members.Member; import api.web.gw2.mapping.v2.tokeninfo.TokenInfo; import api.web.gw2.mapping.v2.worlds.World; import api.web.gw2.mapping.v2.wvw.matches.Match; import com.bouye.gw2.sab.SABConstants; import com.bouye.gw2.sab.demo.DemoSupport; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Optional; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; public enum WebQuery { INSTANCE; public String encodeURLParameter(final String value) throws UnsupportedEncodingException { String result = URLEncoder.encode(value, "utf-8"); // NOI18N. result = result.replaceAll("\\+", "%20"); // NOI18N. return result; } /** * Return the language code to be used when doing queries that return localized values. * <br>If the user's current language is not supported, the default locale will be used instead. * @return A {@code String} instance, never {@code null}. */ private String getLanguageCode() { final Set<String> supportedLanguages = SABConstants.INSTANCE.getSupportedWebApiLanguages(); final String currentLanguage = Locale.getDefault().getLanguage(); return supportedLanguages.contains(currentLanguage) ? currentLanguage : SABConstants.DEFAULT_WEBAPI_LANGUAGE; } /** * Convert given {@code int} ids into a {@code String} for the query. * @param ids the ids. * @return A {@code String}, never {@code null}. * <br>Contains {@code "all"} no id provided. */ public String idsToString(final int... ids) { String result = "all"; // NOI18N. if (ids.length > 0) { final StringBuilder builder = new StringBuilder(); for (final int id : ids) { builder.append(id); builder.append(','); // NOI18N. } // Remove last comma. builder.replace(builder.length() - 1, builder.length(), ""); // NOI18N. result = builder.toString(); } return result; } /** * Convert given {@code String} ids into a {@code String} for the query. * @param ids the ids. * @return A {@code String}, never {@code null}. * <br>Contains {@code "all"} no id provided. */ public String idsToString(final String... ids) { String result = "all"; // NOI18N. if (ids.length > 0) { final StringBuilder builder = new StringBuilder(); for (final String id : ids) { builder.append(id); builder.append(','); // NOI18N. } // Remove last comma. builder.replace(builder.length() - 1, builder.length(), ""); // NOI18N. result = builder.toString(); } return result; } /** * Do a simply web query that returns a simple object. * @param <T> The type to use. * @param targetClass The target class. * @param path The path to query. * @return An {@code Optional<T>} instance, never {@code null}. */ private <T> Optional<T> objectWebQuery(final Class<T> targetClass, final String path) { Logger.getLogger(WebQuery.class.getName()).log(Level.INFO, "objectWebQuery " + path); // NOI18N. Optional<T> result = Optional.empty(); try { final URL url = new URL(path); final T value = JsonpContext.SAX.loadObject(targetClass, url); result = Optional.ofNullable(value); } catch (NullPointerException | IOException ex) { Logger.getLogger(WebQuery.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); } return result; } /** * Do a simple web query that returns a list of object. * @param <T> The type to use. * @param targetClass The target class. * @param path The path to query. * @return A {@code List<T>} instance, never {@code null}. */ private <T> List<T> arrayWebQuery(final Class<T> targetClass, final String path) { Logger.getLogger(WebQuery.class.getName()).log(Level.INFO, "arrayWebQuery " + path); // NOI18N. List<T> result = Collections.EMPTY_LIST; try { final URL url = new URL(path); final Collection<T> value = JsonpContext.SAX.loadObjectArray(targetClass, url); result = new ArrayList<>(value); result = Collections.unmodifiableList(result); } catch (NullPointerException | IOException ex) { Logger.getLogger(WebQuery.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); } return result; } private <T> PageResult<T> pageWebQuery(final Class<T> targetClass, final String path) { Logger.getLogger(WebQuery.class.getName()).log(Level.INFO, "arrayWebQuery " + path); // NOI18N. PageResult<T> result = PageResult.EMPTY; try { final URL url = new URL(path); result = JsonpContext.SAX.loadPage(targetClass, url);; } catch (NullPointerException | IOException ex) { Logger.getLogger(WebQuery.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); } return result; } public Optional<TokenInfo> queryTokenInfo(final boolean demo, final String appKey) { Optional<TokenInfo> result = Optional.empty(); if (demo) { result = Optional.ofNullable(DemoSupport.INSTANCE.loadTokenInfo()); } else { final String path = String.format("https://api.guildwars2.com/v2/tokeninfo?access_token=%s", appKey); // NOI18N. result = objectWebQuery(TokenInfo.class, path); } return result; } public Optional<Account> queryAccount(final boolean demo, final String appKey) { Optional<Account> result = Optional.empty(); if (demo) { result = Optional.ofNullable(DemoSupport.INSTANCE.loadAccount()); } else { final String path = String.format("https://api.guildwars2.com/v2/account?access_token=%s", appKey); // NOI18N. result = objectWebQuery(Account.class, path); } return result; } public List<World> queryWorlds(final boolean demo, final int... ids) { List<World> result = Collections.EMPTY_LIST; if (demo) { result = DemoSupport.INSTANCE.loadWorlds(ids); } else { final String path = String.format("https://api.guildwars2.com/v2/worlds?lang=%s&ids=%s", getLanguageCode(), idsToString(ids)); // NOI18N. result = arrayWebQuery(World.class, path); } return result; } public List<GuildDetails> queryGuildDetails(final boolean demo, final String... ids) { // V1 endpoint: can only query one guild at a time. List<GuildDetails> result = Collections.EMPTY_LIST; if (demo) { result = DemoSupport.INSTANCE.loadGuilds(ids); } else { result = new ArrayList(ids.length); for (final String id : ids) { final String path = String.format("https://api.guildwars2.com/v1/guild_details.php?guild_id=%s", id); // NOI18N. final Optional<GuildDetails> value = objectWebQuery(GuildDetails.class, path); if (value.isPresent()) { result.add(value.get()); } } result = Collections.unmodifiableList(result); } return result; } public List<Member> queryGuildMembers(final boolean demo, final String appKey, final String id) { List<Member> result = Collections.EMPTY_LIST; if (demo) { result = DemoSupport.INSTANCE.loadGuildRoster(id); } else { final String path = String.format("https://api.guildwars2.com/v2/guild/%s/members?access_token=%s", id, appKey); // NOI18N. result = arrayWebQuery(Member.class, path); } return result; } public List<LogEvent> queryGuildLogs(final boolean demo, final String appKey, final String id) { List<LogEvent> result = Collections.EMPTY_LIST; if (demo) { result = DemoSupport.INSTANCE.loadGuildLogs(id); } else { final String path = String.format("https://api.guildwars2.com/v2/guild/%s/log?access_token=%s", id, appKey); // NOI18N. result = arrayWebQuery(LogEvent.class, path); } return result; } public Optional<Match> queryWvwMatch(final boolean demo, final int id) { Optional<Match> result = Optional.empty(); if (demo) { } else { final String path = String.format("https://api.guildwars2.com/v2/wvw/matches?world=%d", id); // NOI18N. result = objectWebQuery(Match.class, path); } return result; } }
package org.jetel.data.parser; import java.io.IOException; import java.io.InputStream; import java.nio.BufferOverflowException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CoderResult; import org.jetel.data.DataRecord; import org.jetel.data.Defaults; import org.jetel.exception.BadDataFormatException; import org.jetel.exception.ComponentNotReadyException; import org.jetel.exception.IParserExceptionHandler; import org.jetel.exception.JetelException; import org.jetel.exception.PolicyType; import org.jetel.metadata.DataFieldMetadata; import org.jetel.metadata.DataRecordMetadata; import org.jetel.util.string.StringUtils; /** * Parsing plain text data. * * Known bugs: * - Method skip() doesn't recognize records without final delimiter/recordDelimiter, * for example last record in file without termination enter. * That's why skip() doesn't count unfinished records. * * @author Martin Zatopek, David Pavlis * @since September 29, 2005 * @see Parser * @see org.jetel.data.Defaults * @revision $Revision: 1.9 $ */ public class DataParser implements Parser { private static final int RECORD_DELIMITER_IDENTIFIER = -1; private static final int DEFAULT_FIELD_DELIMITER_IDENTIFIER = -2; private IParserExceptionHandler exceptionHandler; private DataRecordMetadata metadata; private ReadableByteChannel reader; private CharBuffer charBuffer; private ByteBuffer byteBuffer; private StringBuilder fieldBuffer; private CharBuffer recordBuffer; private CharsetDecoder decoder; private int fieldLengths[]; private int recordCounter; private AhoCorasick delimiterSearcher; private boolean skipLeadingBlanks = true; private boolean quotedStrings = false; private StringBuilder tempReadBuffer; private boolean treatMultipleDelimitersAsOne = false; private Boolean trim = null; private boolean[] isAutoFilling; private boolean[] isSkipBlanks; private boolean releaseInputSource = true; private boolean hasRecordDelimiter = false; private boolean hasDefaultFieldDelimiter = false; public DataParser() { decoder = Charset.forName(Defaults.DataParser.DEFAULT_CHARSET_DECODER).newDecoder(); reader = null; } public DataParser(String charset) { decoder = Charset.forName(charset).newDecoder(); reader = null; } /** * @see org.jetel.data.parser.Parser#getNext() */ public DataRecord getNext() throws JetelException { DataRecord record = new DataRecord(metadata); record.init(); record = parseNext(record); if(exceptionHandler != null ) { //use handler only if configured while(exceptionHandler.isExceptionThrowed()) { exceptionHandler.setRawRecord(getLastRawRecord()); exceptionHandler.handleException(); record = parseNext(record); } } return record; } /** * @see org.jetel.data.parser.Parser#getNext(org.jetel.data.DataRecord) */ public DataRecord getNext(DataRecord record) throws JetelException { record = parseNext(record); if(exceptionHandler != null ) { //use handler only if configured while(exceptionHandler.isExceptionThrowed()) { exceptionHandler.setRawRecord(getLastRawRecord()); exceptionHandler.handleException(); record = parseNext(record); } } return record; } /* (non-Javadoc) * @see org.jetel.data.parser.Parser#init(org.jetel.metadata.DataRecordMetadata) */ public void init(DataRecordMetadata metadata) throws ComponentNotReadyException { //init private variables byteBuffer = ByteBuffer.allocateDirect(Defaults.DEFAULT_INTERNAL_IO_BUFFER_SIZE); charBuffer = CharBuffer.allocate(Defaults.DEFAULT_INTERNAL_IO_BUFFER_SIZE); charBuffer.flip(); // initially empty fieldBuffer = new StringBuilder(Defaults.DEFAULT_INTERNAL_IO_BUFFER_SIZE); recordBuffer = CharBuffer.allocate(Defaults.DEFAULT_INTERNAL_IO_BUFFER_SIZE); tempReadBuffer = new StringBuilder(Defaults.DEFAULT_INTERNAL_IO_BUFFER_SIZE); isAutoFilling = new boolean[metadata.getNumFields()]; isSkipBlanks = new boolean[metadata.getNumFields()]; //save metadata this.metadata = metadata; //aho-corasick initialize delimiterSearcher = new AhoCorasick(); // create array of delimiters & initialize them String[] delimiters; for (int i = 0; i < metadata.getNumFields(); i++) { if(metadata.getField(i).isDelimited()) { delimiters = metadata.getField(i).getDelimiters(); for(int j = 0; j < delimiters.length; j++) { delimiterSearcher.addPattern(delimiters[j], i); } } isAutoFilling[i] = metadata.getField(i).getAutoFilling() != null; isSkipBlanks[i] = skipLeadingBlanks || trim == Boolean.TRUE || (trim == null && metadata.getField(i).isTrim()); } //aho-corasick initialize if(metadata.isSpecifiedRecordDelimiter()) { hasRecordDelimiter = true; delimiters = metadata.getRecordDelimiters(); for(int j = 0; j < delimiters.length; j++) { delimiterSearcher.addPattern(delimiters[j], RECORD_DELIMITER_IDENTIFIER); } } if(metadata.isSpecifiedFieldDelimiter()) { hasDefaultFieldDelimiter = true; delimiters = metadata.getFieldDelimiters(); for(int j = 0; j < delimiters.length; j++) { delimiterSearcher.addPattern(delimiters[j], DEFAULT_FIELD_DELIMITER_IDENTIFIER); } } delimiterSearcher.compile(); // create array of field sizes & initialize them fieldLengths = new int[metadata.getNumFields()]; for (int i = 0; i < metadata.getNumFields(); i++) { if(metadata.getField(i).isFixed()) { fieldLengths[i] = metadata.getField(i).getSize(); } } } /* (non-Javadoc) * @see org.jetel.data.parser.Parser#setDataSource(java.lang.Object) */ public void setReleaseDataSource(boolean releaseInputSource) { this.releaseInputSource = releaseInputSource; } /* (non-Javadoc) * @see org.jetel.data.parser.Parser#setDataSource(java.lang.Object) */ public void setDataSource(Object inputDataSource) { if (releaseInputSource) releaseDataSource(); fieldBuffer = new StringBuilder(Defaults.DEFAULT_INTERNAL_IO_BUFFER_SIZE); recordBuffer = CharBuffer.allocate(Defaults.DEFAULT_INTERNAL_IO_BUFFER_SIZE); tempReadBuffer = new StringBuilder(Defaults.DEFAULT_INTERNAL_IO_BUFFER_SIZE); decoder.reset();// reset CharsetDecoder byteBuffer.clear(); charBuffer.clear(); charBuffer.flip(); fieldBuffer.setLength(0); recordBuffer.clear(); tempReadBuffer.setLength(0); recordCounter = 0;// reset record counter if (inputDataSource == null) { reader = null; } else { if (inputDataSource instanceof ReadableByteChannel) { reader = ((ReadableByteChannel)inputDataSource); } else { reader = Channels.newChannel((InputStream)inputDataSource); } } } /** * Release data source * */ private void releaseDataSource() { if (reader == null) { return; } try { reader.close(); } catch (IOException e) { e.printStackTrace(); } reader = null; } /** * @see org.jetel.data.parser.Parser#close() */ public void close() { if(reader != null && reader.isOpen()) { try { reader.close(); } catch(IOException ex) { ex.printStackTrace(); } } } private DataRecord parseNext(DataRecord record) { int fieldCounter; int character = -1; int mark; boolean inQuote; boolean skipBlanks; char type; recordCounter++; recordBuffer.clear(); for (fieldCounter = 0; fieldCounter < metadata.getNumFields(); fieldCounter++) { // skip all fields that are internally filled if (isAutoFilling[fieldCounter]) { continue; } skipBlanks = isSkipBlanks[fieldCounter]; if (metadata.getField(fieldCounter).isDelimited()) { //delimited data field // field // read data till we reach field delimiter, record delimiter, // end of file or exceed buffer size // exceeded buffer is indicated by BufferOverflowException fieldBuffer.setLength(0); inQuote = false; try { while ((character = readChar()) != -1) { //end of file if (character == -1) { break; } //delimiter update delimiterSearcher.update((char) character); //skip leading blanks if (skipBlanks && !Character.isWhitespace(character)) { skipBlanks = false; } //quotedStrings type = metadata.getField(fieldCounter).getType(); if (quotedStrings && type != DataFieldMetadata.BYTE_FIELD && type != DataFieldMetadata.BYTE_FIELD_COMPRESSED){ if (fieldBuffer.length() == 0) { if (StringUtils.isQuoteChar((char) character)) { inQuote = true; continue; } } else { if (inQuote && StringUtils.isQuoteChar((char) character)) { if (!followFieldDelimiter(fieldCounter)) { //after ending quote can i find delimiter findFirstRecordDelimiter(); return parsingErrorFound("Bad quote format", record, fieldCounter); } break; } } } //fieldDelimiter update if(!skipBlanks) { fieldBuffer.append((char) character); } //test field delimiter if (!inQuote) { if(delimiterSearcher.isPattern(fieldCounter)) { if(!skipBlanks) { fieldBuffer.setLength(fieldBuffer.length() - delimiterSearcher.getMatchLength()); } if ((trim == Boolean.TRUE || (trim == null && metadata.getField(fieldCounter).isTrim()))) { StringUtils.trimTrailing(fieldBuffer); } if(treatMultipleDelimitersAsOne) while(followFieldDelimiter(fieldCounter)); break; } //test default field delimiter if(defaultFieldDelimiterFound()) { findFirstRecordDelimiter(); return parsingErrorFound("Unexpected default field delimiter, probably record has too many fields.", record, fieldCounter); } //test record delimiter if(recordDelimiterFound()) { return parsingErrorFound("Unexpected record delimiter, probably record has too little fields.", record, fieldCounter); } } } } catch (Exception ex) { throw new RuntimeException(getErrorMessage(ex.getMessage(), null, fieldCounter), ex); } } else { //fixlen data field mark = 0; fieldBuffer.setLength(0); try { for(int i = 0; i < fieldLengths[fieldCounter]; i++) { //end of file if ((character = readChar()) == -1) { break; } //skip leading blanks if (skipBlanks) if(Character.isWhitespace(character)) continue; else skipBlanks = false; //keep track of trailing blanks if(!Character.isWhitespace(character)) { mark = i; } fieldBuffer.append((char) character); } if(character != -1 && fieldBuffer.length() > 0) { fieldBuffer.setLength(fieldBuffer.length() - (fieldLengths[fieldCounter] - mark - 1)); } } catch (Exception ex) { throw new RuntimeException(getErrorMessage(ex.getMessage(), null, fieldCounter)); } } // did we have EOF situation ? if (character == -1) { try { //hack for data files without last row delimiter (for example last record without new-line character) if(fieldCounter + 1 == metadata.getNumFields()) { populateField(record, fieldCounter, fieldBuffer); if((fieldCounter != 0 || recordBuffer.position() > 0)) { //hack for hack for one column table //reader.close(); return record; } } if(recordBuffer.position() == 0) { reader.close(); return null; } else { return parsingErrorFound("Unexpected end of file", record, fieldCounter); } } catch (IOException e) { e.printStackTrace(); } } //populate field populateField(record, fieldCounter, fieldBuffer); } // if(metadata.isSpecifiedRecordDelimiter() && !recordDelimiterFound) { // if(!followRecordDelimiter()) { //record delimiter is not found // return parsingErrorFound("Too fields in record found", record, fieldCounter); return record; } private DataRecord parsingErrorFound(String exceptionMessage, DataRecord record, int fieldNum) { if(exceptionHandler != null) { exceptionHandler.populateHandler("Parsing error: " + exceptionMessage, record, recordCounter, fieldNum + 1, null, new BadDataFormatException("Parsing error: " + exceptionMessage)); return record; } else { throw new RuntimeException("Parsing error: " + exceptionMessage + " when parsing record #" + recordCounter + " and " + (fieldNum + 1) + ". field (" + recordBuffer.toString() + ")"); } } private int readChar() throws IOException { int size; char character; CoderResult decodingResult; if(tempReadBuffer.length() > 0) { character = tempReadBuffer.charAt(0); tempReadBuffer.deleteCharAt(0); return character; } if (!charBuffer.hasRemaining()) { byteBuffer.clear(); size = reader.read(byteBuffer); // if no more data, return -1 if (size == -1) { return -1; } try { byteBuffer.flip(); charBuffer.clear(); decodingResult = decoder.decode(byteBuffer, charBuffer, true); decodingResult.throwException(); charBuffer.flip(); } catch (Exception ex) { throw new IOException("Exception when decoding characters: " + ex.getMessage()); } } character = charBuffer.get(); try { recordBuffer.put(character); } catch (BufferOverflowException e) { throw new RuntimeException("Parse error: The size of data buffer for data record is only " + recordBuffer.limit() + ". Set appropriate parameter in defautProperties file.", e); } return character; } /** * Assembles error message when exception occures during parsing * * @param exceptionMessage * message from exception getMessage() call * @param recNo * recordNumber * @param fieldNo * fieldNumber * @return error message * @since September 19, 2002 */ private String getErrorMessage(String exceptionMessage, CharSequence value, int fieldNo) { StringBuffer message = new StringBuffer(); message.append(exceptionMessage); message.append(" when parsing record message.append(recordCounter); message.append(" field "); message.append(metadata.getField(fieldNo).getName()); if (value != null) { message.append(" value \"").append(value).append("\""); } return message.toString(); } /** * Finish incomplete fields <fieldNumber, metadata.getNumFields()>. * * @param record * incomplete record * @param fieldNumber * first incomlete field in record */ // private void finishRecord(DataRecord record, int fieldNumber) { // for(int i = fieldNumber; i < metadata.getNumFields(); i++) { // record.getField(i).setToDefaultValue(); /** * Populate field. * * @param record * @param fieldNum * @param data */ private void populateField(DataRecord record, int fieldNum, StringBuilder data) { try { record.getField(fieldNum).fromString(data); } catch(BadDataFormatException bdfe) { if(exceptionHandler != null) { exceptionHandler.populateHandler(bdfe.getMessage(), record, recordCounter, fieldNum + 1, data.toString(), bdfe); } else { bdfe.setRecordNumber(recordCounter); bdfe.setFieldNumber(fieldNum); bdfe.setOffendingValue(data); throw bdfe; } } catch(Exception ex) { throw new RuntimeException(getErrorMessage(ex.getMessage(), null, fieldNum)); } } /** * Find first record delimiter in input channel. */ private boolean findFirstRecordDelimiter() { if(!metadata.isSpecifiedRecordDelimiter()) { return false; } int character; try { while ((character = readChar()) != -1) { delimiterSearcher.update((char) character); //test record delimiter if (recordDelimiterFound()) { return true; } } } catch (IOException e) { throw new RuntimeException(getErrorMessage(e.getMessage(), null, -1)); } //end of file return false; } /** * Find end of record for metadata without record delimiter specified. */ private boolean findEndOfRecord(int fieldNum) { int character = 0; try { for(int i = fieldNum + 1; i < metadata.getNumFields(); i++) { if (isAutoFilling[i]) continue; while((character = readChar()) != -1) { delimiterSearcher.update((char) character); if(delimiterSearcher.isPattern(i)) { break; } } } } catch (IOException e) { throw new RuntimeException(getErrorMessage(e.getMessage(), null, -1)); } return (character != -1); } // private void shiftToNextRecord(int fieldNum) { // if(metadata.isSpecifiedRecordDelimiter()) { // findFirstRecordDelimiter(); // } else { // findEndOfRecord(fieldNum); /** * Is record delimiter in the input channel? * @return */ private boolean recordDelimiterFound() { if(hasRecordDelimiter) { return delimiterSearcher.isPattern(RECORD_DELIMITER_IDENTIFIER); } else { return false; } } /** * Is default field delimiter in the input channel? * @return */ private boolean defaultFieldDelimiterFound() { if(hasDefaultFieldDelimiter) { return delimiterSearcher.isPattern(DEFAULT_FIELD_DELIMITER_IDENTIFIER); } else { return false; } } /** * Follow field delimiter in the input channel? * @param fieldNum field delimiter identifier * @return */ StringBuffer temp = new StringBuffer(); private boolean followFieldDelimiter(int fieldNum) { int character; temp.setLength(0); try { while ((character = readChar()) != -1) { temp.append((char) character); delimiterSearcher.update((char) character); if(delimiterSearcher.isPattern(fieldNum)) { return true; } if(delimiterSearcher.getMatchLength() == 0) { tempReadBuffer.append(temp); return false; } } } catch (IOException e) { throw new RuntimeException(getErrorMessage(e.getMessage(), null, -1)); } //end of file return false; } // /** // * Follow record delimiter in the input channel? // * @return // */ // private boolean followRecordDelimiter() { // int count = 1; // int character; // try { // while ((character = readChar()) != -1) { // delimiterSearcher.update((char) character); // if(recordDelimiterFound()) { // return (count == delimiterSearcher.getMatchLength()); // count++; // } catch (IOException e) { // throw new RuntimeException(getErrorMessage(e.getMessage(), null, -1)); // //end of file // return false; /** * Specifies whether leading blanks at each field should be skipped * @param skippingLeadingBlanks The skippingLeadingBlanks to set. */ public void setSkipLeadingBlanks(boolean skipLeadingBlanks) { this.skipLeadingBlanks = skipLeadingBlanks; } public String getCharsetName() { return decoder.charset().name(); } public boolean endOfInputChannel() { return reader == null || !reader.isOpen(); } public int getRecordCount() { return recordCounter; } public String getLastRawRecord() { recordBuffer.flip(); return recordBuffer.toString(); } public void setQuotedStrings(boolean quotedStrings) { this.quotedStrings = quotedStrings; } public void setTreatMultipleDelimitersAsOne(boolean treatMultipleDelimitersAsOne) { this.treatMultipleDelimitersAsOne = treatMultipleDelimitersAsOne; } // /** // * Skip first line/record in input channel. // */ // public void skipFirstLine() { // int character; // try { // while ((character = readChar()) != -1) { // delimiterSearcher.update((char) character); // if(delimiterSearcher.isPattern(-2)) { // break; // if(character == -1) { // throw new RuntimeException("Skipping first line: record delimiter not found."); // } catch (IOException e) { // throw new RuntimeException(getErrorMessage(e.getMessage(), null, -1)); /* (non-Javadoc) * @see org.jetel.data.parser.Parser#skip(int) */ public int skip(int count) throws JetelException { int skipped; if(metadata.isSpecifiedRecordDelimiter()) { for(skipped = 0; skipped < count; skipped++) { if(!findFirstRecordDelimiter()) { break; } } } else { for(skipped = 0; skipped < count; skipped++) { if(!findEndOfRecord(0)) { break; } } } return skipped; } public void setExceptionHandler(IParserExceptionHandler handler) { this.exceptionHandler = handler; } public IParserExceptionHandler getExceptionHandler() { return exceptionHandler; } public PolicyType getPolicyType() { if(exceptionHandler != null) { return exceptionHandler.getType(); } return null; } public Boolean getTrim() { return trim; } public void setTrim(Boolean trim) { this.trim = trim; } /* * (non-Javadoc) * @see org.jetel.data.parser.Parser#reset() */ public void reset() { if (releaseInputSource) releaseDataSource(); decoder.reset();// reset CharsetDecoder recordCounter = 0;// reset record counter } }
package org.jetel.graph.runtime; import java.lang.management.ManagementFactory; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.Callable; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import javax.management.InstanceAlreadyExistsException; import javax.management.MBeanRegistrationException; import javax.management.MBeanServer; import javax.management.MalformedObjectNameException; import javax.management.NotCompliantMBeanException; import javax.management.ObjectName; import org.apache.log4j.Logger; import org.apache.log4j.MDC; import org.jetel.exception.ComponentNotReadyException; import org.jetel.graph.ContextProvider; import org.jetel.graph.GraphElement; import org.jetel.graph.IGraphElement; import org.jetel.graph.JobType; import org.jetel.graph.Node; import org.jetel.graph.Phase; import org.jetel.graph.Result; import org.jetel.graph.TransformationGraph; import org.jetel.graph.runtime.jmx.CloverJMX; import org.jetel.graph.runtime.tracker.TokenTracker; import org.jetel.util.ExceptionUtils; import org.jetel.util.primitive.MultiValueMap; /** * Description of the Class * * @author dpavlis * @since July 29, 2002 */ public class WatchDog implements Callable<Result>, CloverPost { /** * This lock object guards currentPhase variable and watchDogStatus. */ private final Lock CURRENT_PHASE_LOCK = new ReentrantLock(); private final Object ABORT_MONITOR = new Object(); private boolean abortFinished = false; public final static String MBEAN_NAME_PREFIX = "CLOVERJMX_"; public final static long WAITTIME_FOR_STOP_SIGNAL = 5000; //miliseconds private static final long ABORT_TIMEOUT = 5000L; private static final long ABORT_WAIT = 2400L; public static final String WATCHDOG_THREAD_NAME_PREFIX = "WatchDog_"; private int[] _MSG_LOCK=new int[0]; private static Logger logger = Logger.getLogger(WatchDog.class); /** * Thread manager is used to run nodes as threads. */ private IThreadManager threadManager; private volatile Result watchDogStatus; private TransformationGraph graph; private Phase currentPhase; private BlockingQueue <Message<?>> inMsgQueue; private MultiValueMap<IGraphElement, Message<?>> outMsgMap; private volatile Throwable causeException; private volatile IGraphElement causeGraphElement; private CloverJMX cloverJMX; // private volatile boolean runIt; private boolean provideJMX = true; private boolean finishJMX = true; //whether the JMX mbean should be unregistered on the graph finish private final GraphRuntimeContext runtimeContext; static private MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); private ObjectName jmxObjectName; private TokenTracker tokenTracker; /** *Constructor for the WatchDog object * * @param graph Description of the Parameter * @param phases Description of the Parameter * @since September 02, 2003 */ public WatchDog(TransformationGraph graph, GraphRuntimeContext runtimeContext) { graph.setWatchDog(this); this.graph = graph; this.runtimeContext = runtimeContext; currentPhase = null; watchDogStatus = Result.N_A; inMsgQueue = new LinkedBlockingQueue<Message<?>>(); outMsgMap = new MultiValueMap<IGraphElement, Message<?>>(Collections.synchronizedMap(new HashMap<IGraphElement, List<Message<?>>>())); //is JMX turned on? provideJMX = runtimeContext.useJMX(); //passes a password from context to the running graph graph.setPassword(runtimeContext.getPassword()); } /** * WatchDog initialization. */ public void init() { //at least simple thread manager will be used if(threadManager == null) { threadManager = new SimpleThreadManager(); } //create token tracker if graph is jobflow type if (graph.getJobType() == JobType.JOBFLOW) { tokenTracker = new TokenTracker(graph); } //start up JMX cloverJMX = new CloverJMX(this); if(provideJMX) { registerTrackingMBean(cloverJMX); } //watchdog is now ready to use watchDogStatus = Result.READY; } private void finishJMX() { if(provideJMX) { try { mbs.unregisterMBean(jmxObjectName); } catch (Exception e) { logger.error("JMX error - ObjectName cannot be unregistered.", e); } } } /** Main processing method for the WatchDog object */ @Override public Result call() { CURRENT_PHASE_LOCK.lock(); String originalThreadName = null; try { //thread context classloader is preset to a reasonable classloader //this is just for sure, threads are recycled and no body can guarantee which context classloader remains preset Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); //we have to register current watchdog's thread to context provider - from now all //ContextProvider.getGraph() invocations return proper transformation graph ContextProvider.registerGraph(graph); MDC.put("runId", runtimeContext.getRunId()); Thread t = Thread.currentThread(); originalThreadName = t.getName(); String newThreadName = WATCHDOG_THREAD_NAME_PREFIX + runtimeContext.getRunId(); if (logger.isTraceEnabled()) logger.trace("rename thread " + originalThreadName + " to " + newThreadName); t.setName(newThreadName); long startTimestamp = System.currentTimeMillis(); //print graph properties graph.getGraphProperties().print(logger, "Graph parameters:"); //print out runtime context logger.debug("Graph runtime context: " + graph.getRuntimeContext().getAllProperties()); //print initial dictionary content graph.getDictionary().printContent(logger, "Initial dictionary content:"); if (runtimeContext.isVerboseMode()) { // this can be called only after graph.init() graph.dumpGraphConfiguration(); } watchDogStatus = Result.RUNNING; //creates tracking logger for cloverJMX mbean TrackingLogger.track(cloverJMX); cloverJMX.graphStarted(); //pre-execute initialization of graph try { graph.preExecute(); } catch (Exception e) { causeException = e; if (e instanceof ComponentNotReadyException) { causeGraphElement = ((ComponentNotReadyException) e).getGraphElement(); } watchDogStatus = Result.ERROR; logger.error("Graph pre-execute initialization failed.", e); } //run all phases if (watchDogStatus == Result.RUNNING) { Phase[] phases = graph.getPhases(); Result phaseResult = Result.N_A; for (int currentPhaseNum = 0; currentPhaseNum < phases.length; currentPhaseNum++) { //if the graph runs in synchronized mode we need to wait for synchronization event to process next phase if (runtimeContext.isSynchronizedRun()) { logger.info("Waiting for phase " + phases[currentPhaseNum] + " approval..."); watchDogStatus = Result.WAITING; CURRENT_PHASE_LOCK.unlock(); synchronized (cloverJMX) { while (cloverJMX.getApprovedPhaseNumber() < phases[currentPhaseNum].getPhaseNum() && watchDogStatus == Result.WAITING) { //graph was maybe aborted try { cloverJMX.wait(); } catch (InterruptedException e) { throw new RuntimeException("WatchDog was interrupted while was waiting for phase synchronization event."); } } } CURRENT_PHASE_LOCK.lock(); //watchdog was aborted while was waiting for next phase approval if (watchDogStatus == Result.ABORTED) { logger.warn("!!! Graph execution aborted !!!"); break; } else { watchDogStatus = Result.RUNNING; } } cloverJMX.phaseStarted(phases[currentPhaseNum]); //execute phase phaseResult = executePhase(phases[currentPhaseNum]); if(phaseResult == Result.ABORTED) { cloverJMX.phaseAborted(); logger.warn("!!! Phase execution aborted !!!"); break; } else if(phaseResult == Result.ERROR) { cloverJMX.phaseError(getErrorMessage()); logger.error("!!! Phase finished with error - stopping graph run !!!"); break; } cloverJMX.phaseFinished(); } //post-execution of graph try { graph.postExecute(); } catch (Exception e) { causeException = e; if (e instanceof ComponentNotReadyException) { causeGraphElement = ((ComponentNotReadyException) e).getGraphElement(); } watchDogStatus = Result.ERROR; logger.error("Graph post-execute method failed.", e); } //aborted graph does not follow last phase status if (watchDogStatus == Result.RUNNING) { watchDogStatus = phaseResult; } } //commit or rollback if (watchDogStatus == Result.FINISHED_OK) { try { graph.commit(); } catch (Exception e) { causeException = e; watchDogStatus = Result.ERROR; logger.fatal("Graph commit failed", e); } } else { try { graph.rollback(); } catch (Exception e) { causeException = e; watchDogStatus = Result.ERROR; logger.fatal("Graph rollback failed", e); } } //print initial dictionary content graph.getDictionary().printContent(logger, "Final dictionary content:"); sendFinalJmxNotification(); logger.info("WatchDog thread finished - total execution time: " + (System.currentTimeMillis() - startTimestamp) / 1000 + " (sec)"); } catch (Throwable t) { causeException = t; causeGraphElement = null; watchDogStatus = Result.ERROR; ExceptionUtils.logException(logger, "Error watchdog execution", t); } finally { if (finishJMX) { finishJMX(); } //we have to unregister current watchdog's thread from context provider ContextProvider.unregister(); CURRENT_PHASE_LOCK.unlock(); if (originalThreadName != null) Thread.currentThread().setName(originalThreadName); MDC.remove("runId"); } return watchDogStatus; } private void sendFinalJmxNotification() { sendFinalJmxNotification0(); //is there anyone who is really interested in to be informed about the graph is really finished? - at least our clover designer runs graphs with this option if (runtimeContext.isWaitForJMXClient()) { //wait for a JMX client (GUI) to download all tracking information long startWaitingTime = System.currentTimeMillis(); synchronized (cloverJMX) { while (WAITTIME_FOR_STOP_SIGNAL > (System.currentTimeMillis() - startWaitingTime) && !cloverJMX.canCloseServer()) { try { cloverJMX.wait(10); sendFinalJmxNotification0(); } catch (InterruptedException e) { throw new RuntimeException("WatchDog was interrupted while was waiting for close signal."); } } if (!cloverJMX.canCloseServer()) { // give client one last chance to react to final notification and to send close signal before cloverJMX is unregistering try { cloverJMX.wait(100); } catch (InterruptedException e) { throw new RuntimeException("WatchDog was interrupted while was waiting for close signal."); } if (!cloverJMX.canCloseServer()) { logger.debug("JMX server close signal timeout; client may have missed final notification"); } } } } //if the graph was aborted, now the aborting thread is waiting for final notification - this is the way how to send him word about the graph finished right now synchronized (ABORT_MONITOR) { abortFinished = true; ABORT_MONITOR.notifyAll(); } } private void sendFinalJmxNotification0() { switch (watchDogStatus) { case FINISHED_OK: cloverJMX.graphFinished(); break; case ABORTED: cloverJMX.graphAborted(); break; case ERROR: cloverJMX.graphError(getErrorMessage()); break; default: break; } } /** * Register given jmx mbean. */ private void registerTrackingMBean(CloverJMX cloverJMX) { String mbeanId = graph.getId(); // Construct the ObjectName for the MBean we will register try { String name = createMBeanName(mbeanId != null ? mbeanId : graph.getName(), this.getGraphRuntimeContext().getRunId()); jmxObjectName = new ObjectName( name ); logger.debug("register MBean with name:"+name); // Register the MBean mbs.registerMBean(cloverJMX, jmxObjectName); } catch (MalformedObjectNameException e) { logger.error(e); } catch (InstanceAlreadyExistsException e) { logger.error(e); } catch (MBeanRegistrationException e) { logger.error(e); } catch (NotCompliantMBeanException e) { logger.error(e); } } /** * Creates identifier for shared JMX mbean. * @param defaultMBeanName * @return */ public static String createMBeanName(String mbeanIdentifier) { return createMBeanName(mbeanIdentifier, 0); } /** * Creates identifier for shared JMX mbean. * @param mbeanIdentifier * @param runId * @return */ public static String createMBeanName(String mbeanIdentifier, long runId) { return "org.jetel.graph.runtime:type=" + MBEAN_NAME_PREFIX + (mbeanIdentifier != null ? mbeanIdentifier : "") + "_" + runId; } /** * Execute transformation - start-up all Nodes & watch them running * * @param phase Description of the Parameter * @param leafNodes Description of the Parameter * @return Description of the Return Value * @since July 29, 2002 */ @edu.umd.cs.findbugs.annotations.SuppressWarnings("UL") private Result watch(Phase phase) throws InterruptedException { Message<?> message; Set<Node> phaseNodes; // let's create a copy of leaf nodes - we will watch them phaseNodes = new HashSet<Node>(phase.getNodes().values()); // is there any node running ? - this test is necessary for phases without nodes - empty phase if (phaseNodes.isEmpty()) { return watchDogStatus != Result.ABORTED ? Result.FINISHED_OK : Result.ABORTED; } // entering the loop awaiting completion of work by all leaf nodes while (true) { // wait on error message queue CURRENT_PHASE_LOCK.unlock(); try { message = inMsgQueue.poll(runtimeContext.getTrackingInterval(), TimeUnit.MILLISECONDS); } finally { CURRENT_PHASE_LOCK.lock(); } if (message != null) { switch(message.getType()){ case ERROR: causeException = ((ErrorMsgBody) message.getBody()).getSourceException(); causeGraphElement = message.getSender(); ExceptionUtils.logException(logger, null, causeException); return Result.ERROR; case MESSAGE: synchronized (_MSG_LOCK) { if (message.getRecipient() != null) { outMsgMap.putValue(message.getRecipient(), message); } } break; case NODE_FINISHED: phaseNodes.remove(message.getSender()); break; default: // do nothing, just wake up } } // is there any node running ? if (phaseNodes.isEmpty()) { return watchDogStatus != Result.ABORTED ? Result.FINISHED_OK : Result.ABORTED; } // gather graph tracking //etl graphs are tracked only in regular intervals, jobflows are tracked more precise, whenever something happens if (message == null || ContextProvider.getJobType() == JobType.JOBFLOW) { cloverJMX.gatherTrackingDetails(); } } } /** * Gets the Status of the WatchDog * * @return Result of WatchDog run-time * @since July 30, 2002 * @see org.jetel.graph.Result */ public Result getStatus() { return watchDogStatus; } /** * aborts execution of current phase * * @since July 29, 2002 */ public void abort() { CURRENT_PHASE_LOCK.lock(); //only running or waiting graph can be aborted if (watchDogStatus != Result.RUNNING && watchDogStatus != Result.WAITING) { //if the graph status is not final, so the graph was aborted if (!watchDogStatus.isStop()) { watchDogStatus = Result.ABORTED; } CURRENT_PHASE_LOCK.unlock(); return; } try { //if the phase is running broadcast all nodes in the phase they should be aborted if (watchDogStatus == Result.RUNNING) { watchDogStatus = Result.ABORTED; // iterate through all the nodes and stop them for (Node node : currentPhase.getNodes().values()) { node.abort(); logger.warn("Interrupted node: " + node.getId()); } //all components seem to be aborted - let's postExecute them try { currentPhase.postExecute(); } catch (Exception e) { logger.warn(e); } } //if the graph is waiting on a phase synchronization point the watchdog is woken up with current status ABORTED if (watchDogStatus == Result.WAITING) { watchDogStatus = Result.ABORTED; synchronized (cloverJMX) { cloverJMX.notifyAll(); } } } finally { synchronized (ABORT_MONITOR) { CURRENT_PHASE_LOCK.unlock(); long startAbort = System.currentTimeMillis(); while (!abortFinished) { long interval = System.currentTimeMillis() - startAbort; if (interval > ABORT_TIMEOUT) { throw new IllegalStateException("Graph aborting error! Timeout "+ABORT_TIMEOUT+"ms exceeded!"); } try { //the aborting thread try to wait for end of graph run ABORT_MONITOR.wait(ABORT_WAIT); } catch (InterruptedException ignore) { }// catch }// while }// synchronized }// finally } /** * Description of the Method * * @param nodesIterator Description of Parameter * @param leafNodesList Description of Parameter * @since July 31, 2002 */ private void startUpNodes(Phase phase) { synchronized(threadManager) { while(threadManager.getFreeThreadsCount() < phase.getNodes().size()) { //it is sufficient, not necessary condition - so we have to time to time wake up and check it again try { threadManager.wait(); //from time to time thread is woken up to check the condition again } catch (InterruptedException e) { throw new RuntimeException("WatchDog was interrupted while was waiting for free workers for nodes in phase " + phase.getPhaseNum()); } } if (phase.getNodes().size() > 0) { //this barrier can be broken only when all components and wathdog is waiting there CyclicBarrier preExecuteBarrier = new CyclicBarrier(phase.getNodes().size() + 1); //this barrier is used for synchronization of all components between pre-execute and execute //it is necessary to finish all pre-execute's before execution CyclicBarrier executeBarrier = new CyclicBarrier(phase.getNodes().size()); for (Node node: phase.getNodes().values()) { node.setPreExecuteBarrier(preExecuteBarrier); node.setExecuteBarrier(executeBarrier); threadManager.executeNode(node); logger.debug(node.getId()+ " ... starting"); } try { //now we will wait for all components are really alive - node.getNodeThread() return non-null value preExecuteBarrier.await(); logger.debug("All components are ready to start."); } catch (InterruptedException e) { throw new RuntimeException("WatchDog was interrupted while was waiting for workers startup in phase " + phase.getPhaseNum()); } catch (BrokenBarrierException e) { throw new RuntimeException("WatchDog or a worker was interrupted while was waiting for nodes tartup in phase " + phase.getPhaseNum()); } } } } /** * Description of the Method * * @param phase Description of the Parameter * @return Description of the Return Value */ private Result executePhase(Phase phase) { currentPhase = phase; //preExecute() invocation try { phase.preExecute(); } catch (ComponentNotReadyException e) { logger.error("Phase pre-execute initialization failed", e); causeException = e; causeGraphElement = e.getGraphElement(); return Result.ERROR; } logger.info("Starting up all nodes in phase [" + phase.getPhaseNum() + "]"); startUpNodes(phase); logger.info("Successfully started all nodes in phase!"); // watch running nodes in phase Result phaseStatus = Result.N_A; try{ phaseStatus = watch(phase); }catch(InterruptedException ex){ phaseStatus = Result.ABORTED; } finally { //now we can notify all waiting phases for free threads synchronized(threadManager) { threadManager.releaseNodeThreads(phase.getNodes().size()); threadManager.notifyAll(); } //is this code really necessary? why? for (Node node : phase.getNodes().values()) { synchronized (node) { //this is the guard of Node.nodeThread variable Thread t = node.getNodeThread(); long runId = this.getGraphRuntimeContext().getRunId(); if (t == null) { continue; } String newThreadName = "exNode_"+runId+"_"+getGraph().getId()+"_"+node.getId(); if (logger.isTraceEnabled()) logger.trace("rename thread "+t.getName()+" to " + newThreadName); t.setName(newThreadName); // explicit interruption of threads of failed graph; (some nodes may be still running) if (!node.getResultCode().isStop()) { if (logger.isTraceEnabled()) logger.trace("try to abort node "+node); node.abort(); } } }// for //postExecute() invocation try { phase.postExecute(); } catch (ComponentNotReadyException e) { logger.error("Phase post-execute finalization failed", e); causeException = e; causeGraphElement = e.getGraphElement(); phaseStatus = Result.ERROR; } } phase.setResult(phaseStatus); return phaseStatus; } @Override public void sendMessage(Message<?> msg) { inMsgQueue.add(msg); } @Override public Message<?>[] receiveMessage(GraphElement recipient, final long wait) { Message<?>[] msg = null; synchronized (_MSG_LOCK) { msg=(Message[])outMsgMap.get(recipient).toArray(new Message<?>[0]); if (msg!=null) { outMsgMap.remove(recipient); } } return msg; } @Override public boolean hasMessage(GraphElement recipient) { synchronized (_MSG_LOCK ){ return outMsgMap.containsKey(recipient); } } /** * Returns exception (reported by Node) which caused * graph to stop processing.<br> * * @return the causeException * @since 7.1.2007 */ public Throwable getCauseException() { return causeException; } /** * Returns ID of Node which caused * graph to stop processing. * * @return the causeNodeID * @since 7.1.2007 */ public IGraphElement getCauseGraphElement() { return causeGraphElement; } public String getErrorMessage() { return ExceptionUtils.getMessage(getCauseException()); } /** * @return the graph * @since 26.2.2007 */ public TransformationGraph getTransformationGraph() { return graph; } public void setUseJMX(boolean useJMX) { this.provideJMX = useJMX; } public GraphRuntimeContext getGraphRuntimeContext() { return runtimeContext; } public CloverJMX getCloverJmx() { return cloverJMX; } public boolean isFinishJMX() { return finishJMX; } public void setFinishJMX(boolean finishJMX) { this.finishJMX = finishJMX; } public IThreadManager getThreadManager() { return threadManager; } public void setThreadManager(IThreadManager threadManager) { this.threadManager = threadManager; } public TransformationGraph getGraph() { return graph; } public IAuthorityProxy getAuthorityProxy() { return getGraphRuntimeContext().getAuthorityProxy(); } public TokenTracker getTokenTracker() { return tokenTracker; } }
package com.linagora.ldap; import java.sql.SQLException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.SizeLimitExceededException; import javax.naming.directory.Attributes; import javax.naming.directory.SearchResult; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jetel.data.DataField; import org.jetel.data.DataRecord; import org.jetel.data.parser.Parser; import org.jetel.exception.BadDataFormatException; import org.jetel.exception.ComponentNotReadyException; import org.jetel.exception.IParserExceptionHandler; import org.jetel.exception.JetelException; import org.jetel.exception.PolicyType; import org.jetel.metadata.DataFieldMetadata; import org.jetel.metadata.DataRecordMetadata; import com.linagora.ldap.Ldap2JetelData.Ldap2JetelString; /** * this class is the interface between data from an LDAP directory * and Clover's data internal representation. * It gives common hight level method to parse an LDAP response * @author Francois Armand * @since september, 2006 */ public class LdapParser implements Parser { /** timeout, in mili second. 0 means wait indefinitely */ public static int TIMEOUT = 0; /** Max number of result, 0 means no limit */ public static int LIMIT = 0; protected IParserExceptionHandler exceptionHandler; /** Number of record already broadcaster */ protected int recordCounter; /** the ldap connection and action manager */ private LdapManager ldapManager; /** Jetel data description : Datarecord and its metadata. */ // private DataRecord outRecord = null; private DataRecordMetadata metadata; /** List of DN matching the search filter */ List dnList = null; Iterator resultDn = null; /** Transformation object between Attributes and DataRecord */ private Ldap2JetelData[] transMap = null; /** Hack to manage multivaluated attributes */ private final String multiSeparator = "|"; /** Useful constant to connect to the LDAP server and perform the search */ private String base; private String filter; private int scope; private String ldapUrl; private String user; private String pwd; private static Log logger = LogFactory.getLog(LdapParser.class); /** * Minimum information needed to create a new LdapParser * @param ldapUrl : LDAP connection URL, for instance: ldap://localhost:381/ * @param base : LDAP base dn, for instance "ou=linagora,ou=com" * @param filter * @param scope one off SearchControls.OBJECT_SCOPE, * SearchControls.ONELEVEL_SCOPE, SearchControls.SUBTREE_SCOPE */ public LdapParser(String ldapUrl, String base, String filter, int scope) { this.base = base; this.filter = filter; this.ldapUrl = ldapUrl; this.scope = scope; } /** * Constructor to create an authentificated connection to server. * @param ldapUrl * @param base * @param filter * @param scope * @param user * @param pwd */ public LdapParser(String ldapUrl, String base, String filter, int scope, String user, String pwd) { this(ldapUrl, base, filter, scope); this.user = user; this.pwd = pwd; } /** * This function try to contact the LDAP server and perform the search query. * ComponentNotReadyException exception are raised for each caught exceptions. */ public void init(DataRecordMetadata metadata) throws ComponentNotReadyException { this.metadata = metadata; /* * create a new LdapManager to do related actions */ if(user != null) { ldapManager = new LdapManager(ldapUrl,user,pwd); } else { ldapManager = new LdapManager(ldapUrl); } try { ldapManager.openContext(); } catch (NamingException ne) { throw new ComponentNotReadyException(ne); } /* * This part has to be improve. We must think about large result set, * and we must find a way to paginate the result, or not load every * DN on memory, or something like that. */ NamingEnumeration ne = null; /* * Search for DN matching filter */ try { ne = ldapManager.search(base,filter,new String[] { "1.1" },scope); } catch (NamingException e) { throw new ComponentNotReadyException(e); } dnList = new ArrayList(); int i = 0; try { while (ne.hasMore()) { i++; String name = ((SearchResult) ne.next()).getName(); dnList.add(name + (base.length() != 0 && name.length() != 0 ? "," : "") + base); } } catch (SizeLimitExceededException e) { if( LIMIT == 0 || i < LIMIT) { if(logger.isInfoEnabled()) {logger.info(" WARNING ! Ldap Search request reach server size limit !"); }; } else { if(logger.isInfoEnabled()) {logger.info(" WARNING ! Ldap Search request reach client size limit !"); }; } } catch (NamingException e1) { throw new ComponentNotReadyException(e1); } finally { try { ne.close(); } catch (NamingException e) { // nothing to do } } resultDn = dnList.iterator(); if (transMap == null) { transMap = new Ldap2JetelData[this.metadata.getNumFields()]; try { /* * We assume that all search result have the same * class hierarchy, so we can take an one of them. */ if (dnList.size() != 0) { initTransMap((String)dnList.get(0)); } } catch (Exception e) { throw new ComponentNotReadyException("Bad metadata name in LdapReader component"); } } } /* (non-Javadoc) * @see org.jetel.data.parser.Parser#setDataSource(java.lang.Object) */ public void setReleaseDataSource(boolean releaseInputSource) { } /* (non-Javadoc) * @see org.jetel.data.parser.Parser#setDataSource(java.lang.Object) */ public void setDataSource(Object inputDataSource) { throw new UnsupportedOperationException(); } public void close() { try { ldapManager.close(); } catch (NamingException e) { //nothing to do ? } } /** * Gets the Next attribute of the LdapParser object * * @return The Next value * @exception JetelException * Description of Exception * @since August 27, 2006 */ public DataRecord getNext() throws JetelException { DataRecord localOutRecord = new DataRecord(metadata); localOutRecord.init(); return getNext(localOutRecord); } /** * Returs next data record parsed from input data source or NULL if no more data * available The specified DataRecord's fields are altered to contain new * values. * *@param record Description of Parameter *@return The Next value *@exception SQLException Description of Exception *@since Angust 27, 2006 */ public DataRecord getNext(DataRecord record) throws JetelException { record = parseNext(record); if(exceptionHandler != null ) { //use handler only if configured while(exceptionHandler.isExceptionThrowed()) { exceptionHandler.handleException(); record = parseNext(record); } } return record; } /** * @param record * @return */ protected DataRecord parseNext(DataRecord record) throws JetelException { /* * This method is intersting. How should I transform an "Attributs" object * to a "DataRecord" one and don't forget to use metadata rules... */ //simplest case... if (resultDn.hasNext() == false) { return null; } Attributes attrs = null; String dn = (String) resultDn.next(); try { attrs = ldapManager.getAttributes(dn); /* * we have to add the dn as a standard attribute */ attrs.put("dn", dn); } catch (NamingException e) { throw new JetelException ( "Error when trying to get datas from Ldap directory entry :" + dn + " "); } /* * Now that the transmap is inited, populated its fields. */ for (int i = 0; i < record.getNumFields(); i++) { DataField df = record.getField(i); try { transMap[i].setField(df,attrs.get(df.getMetadata().getName())); } catch (BadDataFormatException bdfe) { if (exceptionHandler != null) { //use handler only if configured exceptionHandler.populateHandler(getErrorMessage(bdfe .getMessage(), recordCounter, i), record, recordCounter, i, bdfe.getOffendingValue().toString(), bdfe); } else { throw new RuntimeException(getErrorMessage(bdfe.getMessage(), recordCounter, i)); } } catch (Exception ex) { throw new RuntimeException(ex.getClass().getName() + ":" + ex.getMessage()); } } recordCounter++; return record; } protected void initTransMap(String dn) throws BadDataFormatException { /* * TODO : we should have two cases : * - the first one, we can access the schema. In this case, * we can retrieve available attribute from objectclass hierarchy, * and verify that metadata field name match attribute name ; * - the second, we do not have access to the schema. We can not * make any assumption about attribute related to the dn. * We initialize by default transmap to string2jetel. * For now, only the second case is done. */ for (int i = 0; i < metadata.getNumFields(); i++) { DataFieldMetadata dfm = this.metadata.getField(i); if(this.metadata.getField(i).getType() != DataFieldMetadata.STRING_FIELD) { throw new BadDataFormatException("LDAP intialialisation : Field " + dfm.getName() + " has type " + dfm.getType() + " which is not supported." + "Only String type is supported."); } /* * Ok, map the methode to corresponding to the type in * the mapping vector. * Only one type for now. */ transMap[i] = new Ldap2JetelString(multiSeparator); } } /** * Assembles error message when exception occures during parsing * * @param exceptionMessage * message from exception getMessage() call * @param recNo * recordNumber * @param fieldNo * fieldNumber * @return error message * @since September 19, 2002 */ protected String getErrorMessage(String exceptionMessage, int recNo, int fieldNo) { StringBuffer message = new StringBuffer(); message.append(exceptionMessage); message.append(" when parsing record message.append(recordCounter); message.append(" field "); message.append(metadata.getField(fieldNo).getName()); return message.toString(); } public IParserExceptionHandler getExceptionHandler() { return exceptionHandler; } public PolicyType getPolicyType() { if(exceptionHandler != null) { return exceptionHandler.getType(); } return null; } public void setExceptionHandler(IParserExceptionHandler handler) { this.exceptionHandler = handler; } public int skip(int nRec) throws JetelException { throw new UnsupportedOperationException(); } /* * (non-Javadoc) * @see org.jetel.data.parser.Parser#reset() */ public void reset() { resultDn = dnList.iterator(); recordCounter = 0; } }
package com.RyanHodin.RPG; import android.annotation.TargetApi; import android.content.Context; import android.content.SharedPreferences; import android.content.res.Configuration; import android.graphics.Color; import android.os.Build; import android.os.Parcel; import android.os.Parcelable; import android.text.InputType; import android.util.Log; import android.view.Gravity; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnFocusChangeListener; import android.view.animation.AnimationUtils; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.FrameLayout.LayoutParams; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.TextView; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Random; class Cgame implements Serializable, Parcelable { public static final long serialVersionUID=1; public int stage; // Where are we? public int line; // Persistent input public int inputted; // Overwritten per input public boolean doCommitSuicide; // Does exiting the input menu execute user.commitSuicide() or return to runStage()? public static MainActivity t; public Cgame() { stage=0; line=0; inputted=-1; } private Cgame (Parcel in) { stage=in.readInt(); line=in.readInt(); inputted=in.readInt(); } public void saveTo(SharedPreferences.Editor edit) { edit.putInt("gameStage", stage-1); edit.putInt("gameLine", line); edit.putInt("gameInputted", inputted); if (Build.VERSION.SDK_INT>=9) edit.apply(); else edit.commit(); } public void loadFrom(SharedPreferences sp) { stage=sp.getInt("gameStage", stage); line=sp.getInt("gameLine", line); inputted=sp.getInt("gameInputted", inputted); } public void runStage() { t.displayHandler.removeMessages(1); if (Thread.interrupted()) return; t.config.computerPaused=true; doCommitSuicide=false; t.user.dead=false; if (t.config.autosave) { (new Thread(new Runnable() // We don't want to save on the runStage thread, that might cause a noticeable delay. Note that if saving takes too long, we may get a conflict between several saves occurring at once. Consider naming the save thread. { @Override public void run() { t.saveGame(); } })).start(); } switch (stage) { case -1: t.fadeout(); t.runOnUiThread(new Runnable() { @Override public void run() { t.setContentView(R.layout.dead); t.currentView=R.id.deadLayout; t.setUi(); } }); break; case 0: if (t.config.easterEggs && ("King Arthur".equalsIgnoreCase(t.user.name) || "King Arthur of Camelot".equalsIgnoreCase(t.user.name) || "Arthur, King of the Britons".equalsIgnoreCase(t.user.name) || "It is Arthur, King of the Britons".equalsIgnoreCase(t.user.name))) { runArthur((byte)0, null); return; } if (t.config.gender) { t.th=new Thread (new Runnable() { @Override public void run () { t.say("Good.\n\n\tNow, "+t.user.name+", since it\'s too dark to see, and for my accounting purposes..."); } }); t.th.start(); prepContinueButton(); } else { stage=2; runStage(); return; } break; case 1: t.fadeout(); t.runOnUiThread(new Runnable() { @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) @Override public void run() { LinearLayout l=prepInput("What gender are you?"); List<String> genders=new ArrayList<String>(100); genders.add("Male"); genders.add("Female"); if (!t.config.twoGender) { if (t.config.specialGender) { genders.add("Transsexual male"); genders.add("Transsexual female"); genders.add("Metrosexual male"); genders.add("Metrosexual female"); genders.add("Male to Female"); genders.add("Female to Male"); genders.add("Uncertain"); genders.add("Unwilling to say"); genders.add("It\'s complicated"); genders.add("Genderqueer"); genders.add("Dual"); genders.add("Male, but curious as to what being a female is like"); genders.add("Female, but curious as to what being a male is like"); genders.add("Male, but overweight, so have moobs"); genders.add("Female, but have Adam\'s apple"); genders.add("Hermaphrodite with strong male leanings"); genders.add("Hermaphrodite with strong female leanings"); genders.add("Hermaphrodite with no strong gender leanings"); genders.add("Conjoined twin - Male"); genders.add("Conjoined twin - Female"); genders.add("Conjoined twin - Other"); genders.add("Born without genitals - Identify as male"); genders.add("Born without genitals - Identify as female"); genders.add("Born without genitals - Identify otherwise"); genders.add("Born without genitals - and proud of it"); genders.add("Born male, had bad circumcision, raised female"); genders.add("WOMYN, thank you very much!"); genders.add("Angel"); genders.add("Mortal Angel"); genders.add("Sentient Artificial Intelligence - Identify as ungendered"); genders.add("Sentient Artificial Intelligence - Identify as male"); genders.add("Sentient Artificial Intelligence - Identify as female"); genders.add("Sentient Artificial Intelligence - Identify as other"); genders.add("Household pet that walked across the device - Male"); genders.add("Household pet that walked across the device - Female"); genders.add("Household pet that walked across the device - Other"); genders.add("Cross Dresser"); genders.add("In between"); genders.add("Intersex"); genders.add("Pangender"); genders.add("Two spirit"); genders.add("Other"); genders.add("Neutrois"); genders.add("Prefer not to say"); genders.add("None of your business"); if (t.config.easterEggs) { genders.add("Kanye West"); genders.add("Cheese"); genders.add("Raygun"); if (t.config.GoTEggs) { genders.add("The Dothraki do not follow your Genders"); genders.add("Khaleesi"); genders.add("Dragon - Male"); genders.add("Dragon - Female"); genders.add("Dragon - Other"); genders.add("Direwolf"); genders.add("White Walker"); genders.add("Child of the Forest"); } if (t.config.ESEggs) { genders.add("Khajiit"); genders.add("Dovahkiin"); genders.add("Dovah"); genders.add("Draugr"); } if (t.config.schoolEggs) { genders.add("Student"); genders.add("IB Student"); genders.add("Teacher"); genders.add("IB Teacher"); } } } else { genders.add("Multiple"); genders.add("In between"); genders.add("Unsure"); genders.add("None"); genders.add("Prefer not to say"); genders.add("Other"); } } for (int i=0; i<genders.size(); ++i) { Button b=new Button(t); b.setText(genders.get(i)); b.setOnClickListener(new OnClickListener () { @Override public void onClick(View v) { v.setOnClickListener(null); t.user.gender=((TextView)v).getText().toString(); t.th=new Thread (new Runnable () { @Override public void run() { runStage(); } }); t.th.start(); } }); l.addView(b); } genders.clear(); if (t.config.customGender) { Button b=new Button (t); b.setText("Custom"); b.setOnClickListener(new OnClickListener () { @Override public void onClick (View v) { v.setOnClickListener(null); t.config.computerPaused=true; ScrollView sv=new ScrollView (t); int id=Build.VERSION.SDK_INT>=17 ? View.generateViewId() : 5; sv.setId(id); t.currentView=id; LinearLayout.LayoutParams lp=new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); t.setContentView(sv); LinearLayout l=new LinearLayout(t); l.setOrientation(LinearLayout.VERTICAL); sv.addView(l); t.setUi(); lp.topMargin=10; OnFocusChangeListener ofcl=new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus && t.config.fullscreen) { t.setUi(); EditText ev=((EditText)t.findViewById(t.user.parsedGender)); LinearLayout.LayoutParams lp=(LinearLayout.LayoutParams)ev.getLayoutParams(); int result=0; int resourceId = t.getResources().getIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { result = t.getResources().getDimensionPixelSize(resourceId); } lp.topMargin=result+5; } } }; EditText ev=new EditText(t); t.user.parsedGender=999999999; ev.setId(t.user.parsedGender); ev.setOnFocusChangeListener(ofcl); ev.setBackgroundColor(Color.rgb(128,128,128)); ev.setHint("What gender are you?"); ev.setHintTextColor(Color.WHITE); ev.setTextColor(Color.BLACK); ev.setShadowLayer(5.0f,5,5,Color.WHITE); ev.setSingleLine(false); ev.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_FLAG_AUTO_CORRECT|InputType.TYPE_TEXT_FLAG_MULTI_LINE|InputType.TYPE_TEXT_FLAG_CAP_SENTENCES); ev.setImeOptions(EditorInfo.IME_FLAG_NO_ENTER_ACTION); l.addView(ev, lp); if (t.config.addressGender) { ev=new EditText(t); lp=new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); lp.topMargin=20; t.user.weapon.type=7; // Bad form, but we won't have a real parsed weapon for a while... It can be temporary storage until then. ev.setId(t.user.weapon.type); ev.setOnFocusChangeListener(ofcl); ev.setBackgroundColor(Color.rgb(128,128,128)); ev.setHint("What should I address one of your gender as?"); ev.setHintTextColor(Color.WHITE); ev.setTextColor(Color.BLACK); ev.setShadowLayer(5.0f,5,5,Color.WHITE); ev.setSingleLine(false); ev.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_FLAG_AUTO_CORRECT|InputType.TYPE_TEXT_FLAG_MULTI_LINE|InputType.TYPE_TEXT_FLAG_CAP_SENTENCES); ev.setImeOptions(EditorInfo.IME_FLAG_NO_ENTER_ACTION); l.addView(ev, lp); } Button b=new Button(t); b.setText("Submit"); lp=new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); lp.topMargin=250; lp.gravity=Gravity.RIGHT; b.setOnClickListener(new OnClickListener() { @Override public void onClick (View v) { v.setOnClickListener(null); t.th=new Thread (new Runnable () { @Override public void run () { // Close the soft keyboard, now that there's nothing for it to write to. ((InputMethodManager)t.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(t.findViewById(t.user.parsedGender).getWindowToken(), 0); t.user.gender=((TextView)t.findViewById(t.user.parsedGender)).getText().toString().trim(); if (t.config.addressGender) { String str=((TextView)t.findViewById(t.user.weapon.type)).getText().toString().trim(); if (str.startsWith("the ") || str.startsWith("The ")) str=str.substring(4); // Trim off the 'the' to avoid the 'The The' quirk. t.user.genderAddress="The "+str; } runStage(); } }); t.th.start(); } }); l.addView(b, lp); } }); l.addView(b); } } }); break; case 2: t.th=new Thread (new Runnable() { @Override public void run() { if (t.config.gender && t.config.addressGender && t.user.parsedGender!=999999999) t.user.parseGenderAddress(); t.say("I see.\n\n\tWell, "+t.user+", it is time to make a decision.\n\n\tAre you going to try to escape?"); } }); t.th.start(); prepContinueButton(); if (t.config.gender) t.user.parseGender(); break; case 3: t.fadeout(); t.runOnUiThread (new Runnable () { @Override public void run() { LinearLayout l=prepInput(); Button b=new Button (t); b.setText("Escape"); b.setOnClickListener(new OnClickListener () { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread (new Runnable () { @Override public void run () { inputted=0; runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button (t); b.setText("Stay"); b.setOnClickListener(new OnClickListener() { @Override public void onClick (View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread (new Runnable () { @Override public void run () { inputted=1; runStage(); } }); t.th.start(); } }); l.addView(b); } }); break; case 4: if (inputted==0) { if (onMove(99)) return; t.th=new Thread (new Runnable() { @Override public void run() { String creature; boolean plural=false; if (t.gen.nextBoolean()) { if (t.gen.nextBoolean()) creature="troll"; else creature="dinosaur"; } else { if (t.gen.nextBoolean()) { creature="alligator"; plural=true; } else creature="goblin"; } t.say("You start to escape...","But you see a shape.\n\tIt\'s "+(plural ? "an" : "a")+" "+creature+"!\n\n\tYou search for a weapon, but only find a stick."); } }); t.th.start(); prepContinueButton(); } else { if (onMove(50)) return; line=1; if (t.config.triggerEgg(.1)) { t.th=new Thread (new Runnable() { @Override public void run() { t.say("You remain in the cave.","Despite the lack of any way to survive, you stubbornly stay in the cave, starving...\n\tSuddenly, Gandalf the Grey appears.\n\t\t\"Fly, you fool! You will die!!\"\nSince you make no move to escape, Gandalf sighs, and takes you with him."); } }); t.th.start(); prepContinueButton(); } else { t.th=new Thread (new Runnable() { @Override public void run() { t.say("You stay in the cave...","...And starve to death because there\'s no food in the cave."); } }); t.th.start(); t.user.dead=true; prepContinueButton(); } } break; case 5: if (line==0) { t.fadeout(); t.runOnUiThread(new Runnable () { @Override public void run () { doCommitSuicide=true; LinearLayout l=prepInput(); Button b=new Button(t); b.setText("Fight it with a stick"); b.setOnClickListener(new OnClickListener () { @Override public void onClick (View v) { v.setOnClickListener(null); t.th=new Thread (new Runnable () { @Override public void run() { t.user.weapon.name="stick"; t.user.weapon.type=Cweapon.TYPE_BLUNT; inputted=0; runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("Fight it with your fists"); b.setOnClickListener(new OnClickListener () { @Override public void onClick (View v) { v.setOnClickListener(null); t.th=new Thread (new Runnable () { @Override public void run() { t.user.weapon.type=Cweapon.TYPE_HAND_TO_HAND; inputted=0; runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("Run away!!"); b.setOnClickListener(new OnClickListener () { @Override public void onClick (View v) { v.setOnClickListener(null); t.th=new Thread (new Runnable () { @Override public void run() { inputted=1; runStage(); } }); t.th.start(); } }); l.addView(b); } }); } else { t.th=new Thread (new Runnable() { @Override public void run() { t.say("You win!","You have won the game of life."); } }); t.th.start(); doCommitSuicide=true; prepContinueButton(onWin); } break; case 6: if (inputted==1) { if (onMove(78)) return; t.th=new Thread(new Runnable() { @Override public void run() { t.say("Run away!!!", "You try to run away from the creature, but it\'s too fast."); } }); t.th.start(); t.user.dead=true; prepContinueButton(); } else { if (t.user.weapon.type==Cweapon.TYPE_HAND_TO_HAND) { if (t.determineUserDeath(.5)) { t.th=new Thread(new Runnable() { @Override public void run() { t.say("Fight with fists!","You punch it, but it eats you anyway."); } }); t.th.start(); prepContinueButton(); } else { t.th=new Thread(new Runnable() { @Override public void run() { t.say("Fight with fists", "You punch the monster, and barely manage to scare it.\n\tYou take a deep breath, and continue."); } }); t.th.start(); prepContinueButton(); } } else { t.th=new Thread(new Runnable () { @Override public void run () { t.say("You grab the stick, and beat the creature until it leaves."); } }); t.th.start(); prepContinueButton(); } } break; case 7: if (onMove(105)) return; t.th=new Thread (new Runnable () { @Override public void run () { t.say ("You Escape!", "You escape from the cave.\n\n\tIt is a bright and sunny day outside.\n\n\tHowever, there is nothing around you besides sand and dust.\nIt would appear that you are in a desert.\n\n\n\tHowever, a while away, there is a lush valley, full of greenery. You decide to head for it.\n\n\tAlong the way, you find a foreboding cave. A sharp iron sword is sitting by the mouth of the cave, glimmering in the sunlight."); } }); t.th.start(); prepContinueButton(); break; case 8: t.fadeout(); t.runOnUiThread(new Runnable() { @Override public void run() { LinearLayout l=prepInput(); Button b=new Button (t); b.setText("Grab the sword and enter the cave"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { if (t.user.isArthur) { t.user.weapon.name="Excalibur"; // King Arthur gets the greatest of swords t.user.weapon.setCharacteristics(Cweapon.ACCURATE|Cweapon.CLOSE_RANGE|Cweapon.CLOSE_RANGE_ONLY|Cweapon.HIGH_CALIBER|Cweapon.HIGH_POWER_ROUNDS|Cweapon.LEGENDARY|Cweapon.LIGHT|Cweapon.ONE_ROUND_MAGAZINE|Cweapon.QUICK_RELOAD); t.user.weapon.strengthModifier=1+t.gen.nextDouble(); // Excalibur is in epic condition. } else { t.user.weapon.name = "sword"; t.user.weapon.setCharacteristics(Cweapon.ACCURATE | Cweapon.CLOSE_RANGE | Cweapon.CLOSE_RANGE_ONLY | Cweapon.HIGH_CALIBER | Cweapon.ONE_ROUND_MAGAZINE | Cweapon.QUICK_RELOAD); t.user.weapon.strengthModifier=-0.05*t.gen.nextDouble(); // The sword should be in poor condition // This exaggerates the difference between the sword and Excalibur } t.user.weapon.type = Cweapon.TYPE_SHARP; inputted=0; runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button (t); b.setText("Ignore the sword and enter the cave"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { inputted=0; runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button (t); b.setText("Ignore the sword and continue away from the cave"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { inputted=1; runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button (t); b.setText("Grab the sword and continue away from the cave"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { if (t.user.isArthur) { t.user.weapon.name="Excalibur"; // King Arthur gets the greatest of swords t.user.weapon.setCharacteristics(Cweapon.ACCURATE|Cweapon.CLOSE_RANGE|Cweapon.CLOSE_RANGE_ONLY|Cweapon.HIGH_CALIBER|Cweapon.HIGH_POWER_ROUNDS|Cweapon.LEGENDARY|Cweapon.LIGHT|Cweapon.ONE_ROUND_MAGAZINE|Cweapon.QUICK_RELOAD); t.user.weapon.strengthModifier=1+t.gen.nextDouble(); // Excalibur is in epic condition. } else { t.user.weapon.name = "sword"; t.user.weapon.setCharacteristics(Cweapon.ACCURATE | Cweapon.CLOSE_RANGE | Cweapon.CLOSE_RANGE_ONLY | Cweapon.HIGH_CALIBER | Cweapon.ONE_ROUND_MAGAZINE | Cweapon.QUICK_RELOAD); t.user.weapon.strengthModifier=-0.05*t.gen.nextDouble(); // The sword should be in poor condition // This exaggerates the difference between the sword and Excalibur } t.user.weapon.type = Cweapon.TYPE_SHARP; inputted=1; runStage(); } }); t.th.start(); } }); l.addView(b); } }); break; case 9: if (inputted==0) { if (onMove(67)) return; t.user.dead=(t.user.weapon.type<Cweapon.TYPE_SHARP); t.th=new Thread(new Runnable() { @Override public void run() { String title="You enter the cave"; if (t.user.dead) t.say(title,"Ignoring the sword, you enter.\n\tImmediately, the creature from the last cave attacks you. It is incredibly angry, and no "+t.user.weapon+" will scare it off."); else { if (t.user.isArthur) t.say(title,"You take the sword, and examine it.\n\n\tIt seemed to call to you like an old friend, and suddenly you recognize it: It is "+t.user.weapon+"!\n\n\n\tYou take a moment with the blade, twirling it about to remember.\n\n\tAll of a sudden, a shape approaches: You recognize it as the creature from the last cave.\n\tYou bring "+t.user.weapon+" to bear."); else t.say(title, "With the sword in hand, you enter.\n\tImmediately, the creature that fled the last cave attacks you. It is incredibly angry, and a stick will not be enough to make it flee.\n\n\tLuckily, you had the prudence to grab the " + t.user.weapon + ".\n\tYou ready it."); } } }); t.th.start(); prepContinueButton(); } else { stage=25; runStage(); return; } break; case 10: t.fadeout(); t.runOnUiThread(new Runnable() { @Override public void run() { doCommitSuicide=true; LinearLayout l=prepInput(); Button b=new Button(t); b.setText("Fight the monster"); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread (new Runnable() { @Override public void run() { inputted=0; runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("Run away!!"); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick (View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread (new Runnable() { @Override public void run() { inputted=1; runStage(); } }); t.th.start(); } }); l.addView(b); } }); break; case 11: if (onMove(45)) return; t.user.dead=(inputted!=0); t.th=new Thread(new Runnable() { @Override public void run() { if (t.user.dead) t.say("Run away!!!", "You turn to run, but the monster is far too fast."); else t.say("You fight the monster", "The monster lunges at you, but you swiftly dodge it, turn, and behead it.\n\n\n\tCovered in blood, you contemplate whether you should continue."); } }); t.th.start(); prepContinueButton(); break; case 12: t.fadeout(); t.runOnUiThread(new Runnable() { @Override public void run() { LinearLayout l=prepInput(); Button b=new Button (t); b.setText("Continue into the cave"); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick (View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("Escape from the cave"); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick (View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { stage=24; runStage(); } }); t.th.start(); } }); l.addView(b); } }); break; case 13: if (onMove(15+t.gen.nextInt(20))) return; t.th=new Thread (new Runnable() { @Override public void run() { t.say("Forward into Dusk","You continue into the cave.\n\tYou encounter a rather horrifying monster, one that chills you to the bone.\n\n\tIt seems to be extremely afraid of the light.\n\n\n\tUnfortunately, there is no way around it."); } }); t.th.start(); prepContinueButton(); break; case 14: t.fadeout(); t.runOnUiThread(new Runnable() { @Override public void run() { LinearLayout l=prepInput(); Button b=new Button(t); b.setText("Fight the grue"); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("Flee from the grue"); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { stage=24; runStage(); } }); t.th.start(); } }); l.addView(b); } }); break; case 15: if (t.user.weapon.characteristicSet(Cweapon.LEGENDARY)) // Check for Excalibur t.determineUserDeath(1,5); // Slightly reduced odds of death else t.determineUserDeath(1, 3); // Standard, "Traditional" weighting t.th=new Thread(new Runnable() { @Override public void run() { if (t.user.dead) { if (t.config.specMon) { t.user.dead=false; line=1; } t.say("You lunge at the grue", "But the grue is too strong, and you get eaten."); } else t.say("You swing your sword...", "...and get in a lucky shot. The grue\'s head falls to the floor.\n\n\tYou again consider whether you should continue."); } }); t.th.start(); prepContinueButton(); break; case 16: if (line==1) { eatenByGrue(); prepContinueButton(); t.runOnUiThread(new Runnable() { @Override public void run() { ((TextView)t.findViewById(R.id.gameContinueButton)).setTextColor(Color.GREEN); } }); } else { t.fadeout(); t.runOnUiThread(new Runnable() { @Override public void run() { LinearLayout l=prepInput(); Button b=new Button(t); b.setText("Continue into the depths of the cave"); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick (View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("Escape from the monsters yet to be found within the cave"); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { stage=24; runStage(); } }); t.th.start(); } }); l.addView(b); } }); } break; case 17: if (onMove(5+t.gen.nextInt(10))) return; t.th=new Thread(new Runnable() { @Override public void run() { t.say("Into the Darkness of Death", "You continue into the foreboding darkness of the cave, trembling in fear, wondering what the next monster to come far too close to ending your life will be.\n\n\n\n\tYour fears are answered in a horrifying way when you see an enormous, hulking, towering shape in front of you.\n\n\tIt lumbers toward you, the ground quaking as it stomps.\n\n\tYou quickly contemplate taking flight."); } }); t.th.start(); prepContinueButton(); break; case 18: t.fadeout(); t.runOnUiThread(new Runnable() { @Override public void run() { LinearLayout l=prepInput(); Button b=new Button(t); b.setText("Run away before you get killed"); b.setTextColor(Color.rgb(250, 255, 250)); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread (new Runnable() { @Override public void run() { stage=24; runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("Challenge the utter despotic power of the creature before you"); b.setTextColor(Color.rgb(255, 250, 250)); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { runStage(); } }); t.th.start(); } }); l.addView(b); } }); break; case 19: if (t.user.weapon.characteristicSet(Cweapon.LEGENDARY)) // Check for Excalibur t.determineUserDeath(3, 10); // Slightly less than one third else t.determineUserDeath(2, 3); // Two thirds "Traditional" weighting t.th=new Thread(new Runnable() { @Override public void run() { if (t.user.dead) t.say("You fight the monster...", "... But it flattens you."); else t.say("David vs. Goliath", "David killed Goliath, and you killed.... Whatever that was.\n\n\tCollecting yourself as a massive thud rolls through the cave and the monster lies vanquished before you, you again consider whether you should continue further into the depths of the frightening cave."); } }); t.th.start(); prepContinueButton(); break; case 20: t.fadeout(); t.runOnUiThread(new Runnable() { @Override public void run() { doCommitSuicide=t.config.easterEggs; LinearLayout l=prepInput(); Button b=new Button(t); b.setText("Get out of the cave now, before it is too late!"); b.setPadding(5, 5, 5, 5); b.setTextColor(Color.rgb(245, 255, 245)); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { stage=24; runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("Bravely, yet perhaps foolishly, continue onwards towards the horrors you know not of"); b.setTextColor(Color.rgb(245, 235, 235)); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { runStage(); } }); t.th.start(); } }); l.addView(b); } }); break; case 21: if (line==1) { t.fadeout(); t.runOnUiThread(new Runnable() { @Override public void run() { doCommitSuicide=true; LinearLayout l=prepInput(); Button b=new Button(t); b.setText("Ignore the weapon and exit the cave"); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("Grab the superweapon and exit the cave"); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_FUTURE, Cweapon.ACCURATE|Cweapon.AUTOMATIC|Cweapon.CLOSE_RANGE|Cweapon.EXPLOSIVE|Cweapon.HIGH_POWER_ROUNDS|Cweapon.LARGE_MAGAZINE|Cweapon.LEGENDARY|Cweapon.LIGHT|Cweapon.LONG_RANGE|Cweapon.SLOW_RELOAD, "raygun", null)); t.user.weapon.strengthModifier=1; runStage(); } }); t.th.start(); } }); l.addView(b); } }); } else { if (onMove(50)) return; t.th=new Thread (new Runnable() { @Override public void run() { t.say("You come to a dead end in the cave, sighing with relief.\n\n\tOn the ground before you, there is a semi-automatic pistol."); } }); t.th.start(); prepContinueButton(); } break; case 22: if (line==1) { line=0; if (t.user.weapon.type==Cweapon.TYPE_FUTURE) { t.th=new Thread (new Runnable() { @Override public void run() { t.say("The "+t.capitalize(t.user.weapon.name), "You take the "+t.user.weapon+", considering it.\n\n\tSuddenly, a grue appears!\n\n\n\n\n\tWithout thinking, you aim the "+t.user.weapon+" at the grue, and pull the trigger.\n\n\tA bright green bolt shoots out of the superweapon, and where the grue was, there is only ash.\n\n\n\tYou consider the "+t.user.weapon+", thinking you\'ll never need to worry about any monster ever again.\n\n\tGrinning, you set off to leave the cave."); } }); } else { t.th=new Thread(new Runnable() { @Override public void run() { t.user.dead=true; if (t.config.specMon) { t.user.dead=false; line=1; } t.say("You ignore the superweapon, turning to head out of the cave.\n\n\tSuddenly, a grue appears!\n\n\tYou try to bring your sword to bear, but it\'s too slow."); } }); } t.th.start(); prepContinueButton(); } else { t.fadeout(); t.runOnUiThread(new Runnable() { @Override public void run() { LinearLayout l=prepInput(); Button b=new Button(t); b.setText("Grab the pistol and escape the cave"); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick (View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.CLOSE_RANGE|Cweapon.LARGE_MAGAZINE|Cweapon.LIGHT|Cweapon.QUICK_RELOAD, "pistol", null)); runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("Foolishly ignore the pistol and leave the cave"); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick (View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { runStage(); } }); t.th.start(); } }); l.addView(b); } }); } break; case 23: if (line==1) { eatenByGrue(); t.frameTick(); prepContinueButton(); t.runOnUiThread(new Runnable() { @Override public void run() { ((TextView)t.findViewById(R.id.gameContinueButton)).setTextColor(Color.GREEN); } }); break; } ++stage; // Fall through case 24: if (onMove(70)) return; t.th=new Thread(new Runnable() { @Override public void run() { t.say("You escape!", "You leave the cave, and gaze towards the lush valley in the distance."); } }); t.th.start(); prepContinueButton(); break; case 25: if (onMove(90)) return; t.th=new Thread(new Runnable() { @Override public void run() { String address; String pronoun; if (t.gen.nextBoolean()) { address="him"; pronoun="he"; } else { address="her"; pronoun="she"; } t.say("Continuation", "You continue, towards the lush valley.\n\n\tAlong the way, you encounter an archer.\n\tBefore you\'re able to greet "+address+", "+pronoun+" readies "+address+"self to shoot you."); } }); t.th.start(); prepContinueButton(); break; case 26: t.fadeout(); t.runOnUiThread(new Runnable() { @Override public void run() { doCommitSuicide=true; LinearLayout l=prepInput(); Button b=new Button(t); String action; switch(t.user.weapon.type) { case Cweapon.TYPE_HAND_TO_HAND: case Cweapon.TYPE_BLUNT: action="Fight"; break; case Cweapon.TYPE_SHARP: action="Stab"; break; case Cweapon.TYPE_MODERN: case Cweapon.TYPE_FUTURE: action="Shoot"; break; default: action="Kill"; } b.setText(action+" the archer"); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick (View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { inputted=0; runStage(); } }); t.th.start(); } }); l.addView(b); t.user.weapon.addSwapperTo(l); b=new Button(t); b.setText("Run away"); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick (View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { inputted=1; runStage(); } }); t.th.start(); } }); l.addView(b); } }); break; case 27: if (inputted==0) { t.th=new Thread (new Runnable() { @Override public void run() { switch (t.user.weapon.type) { case Cweapon.TYPE_HAND_TO_HAND: t.user.dead=true; t.say("Fistfight!", "You try to get in punching range of the archer, but an arrow appears in your chest before you get close."); break; case Cweapon.TYPE_BLUNT: t.user.dead=true; t.say(t.capitalize(t.user.weapon.name)+"fight", "You run up to the archer, barely managing to get in a swing, when the archer shoots you."); break; case Cweapon.TYPE_SHARP: if (t.user.weapon.characteristicSet(Cweapon.LEGENDARY)) { // Excalibur check t.determineUserDeath(.2); // Excalibur weighting if (t.user.dead) t.say("The Might of "+t.user.weapon, "With "+t.user.weapon+" in hand, you charge the archer.\n\n\tA few arrows fly towards you, and one strikes you in the stomach, stopping you in your tracks.\n\n\t"+t.user.weapon+" falls beside you as your eyes fixate upon it, barely seeing the archer walk up beside you to draw a killing arrow from his quiver.\n\n\n\tAs you watch, "+t.user.weapon+" is surrounded by a pool of growing, shimmering water, forming a mirror.\n\n\tAs the blade is enveloped, it begins to dissolve, becoming one with the water, until it is but a part of the pool.\n\n\tAs the archer shoots an arrow into your head, you watch the pool that was "+t.user.weapon+" dissolve into the soil, lost once more in the oceans of time."); else t.say("The Might of "+t.user.weapon, "With "+t.user.weapon+" in hand, you charge the archer.\n\n\tA few arrows fly towards you, but you dodge one half, and "+(t.gen.nextBoolean() ? "swiftly" : "deftly")+" deflect the other.\n\n\tHaving closed the distance between yourself and the archer, you swing your legendary blade at your enemy.\n\n\n\tThe archer deftly rolls away, but "+t.user.weapon+" knows what to do, adjusting its swing, pulling you along, until you cleave the archer in two."); } else { t.determineUserDeath(.5); // Traditional weighting t.say(t.capitalize(t.user.weapon.name) + " battle!", "You run up to the archer, and lunge!\n\n\t" + (t.user.dead ? "Unfortunately, you miss, and get shot in the " + (t.config.ESEggs && t.config.triggerEgg(.9) ? "knee." : "back.") : "You connect!\n\n\tThe archer falls, dead.\n\n\tThe bow drops to the ground.\n\tYou eye it.")); } break; case Cweapon.TYPE_MODERN: t.determineUserDeath(1, 6); t.say(t.capitalize(t.user.weapon.name)+" vs. bow", "You carefully take aim at the archer, and pull the trigger.\n\n\t"+(t.user.dead ? "Unfortunately, you miss, and get shot before you can aim again." : (t.gen.nextBoolean() ? "A neat hole appears in the archer\'s chest." : "You wing the archer, the bow swinging off it\'s aim, and then you shoot again, scoring a fatal hit.")+"\n\n\tThe bow falls to the ground.\n\tYou eye it, but decide that you prefer your "+t.user.weapon+".")); break; case Cweapon.TYPE_FUTURE: t.say(t.capitalize(t.user.weapon.name)+" Kill", "You calmly aim at the archer, and pull the trigger.\n\n\tWhere the archer was standing, there is only ash."); break; default: t.user.dead=true; t.logError("Unknown weapon code: "+t.user.weapon.type+". Weapon: "+t.user.weapon+"."); t.say("Your weapon is unknowable to the mere humans, so..."); } } }); t.th.start(); if (t.user.weapon.type<Cweapon.TYPE_HAND_TO_HAND || t.user.weapon.type==Cweapon.TYPE_ARCHERY || t.user.weapon.type>Cweapon.TYPE_FUTURE) prepContinueButton(new OnClickListener () { @Override public void onClick (View v) { t.user.weapon.type=Cweapon.TYPE_USED_FOR_CONVENIENCE; t.user.commitSuicide(); } }); else prepContinueButton(); } else { if (onMove(65)) return; t.user.dead=true; t.th=new Thread(new Runnable() { @Override public void run() { t.say("Run away!!!", "You try to run away, but you "+(t.config.easterEggs && t.config.ESEggs ? "take an arrow in the knee." : "get shot before you can get away.")); } }); t.th.start(); prepContinueButton(); } break; case 28: if (t.user.weapon.type==Cweapon.TYPE_MODERN || t.user.weapon.type==Cweapon.TYPE_FUTURE) { ++stage; runStage(); return; } t.fadeout(); t.runOnUiThread(new Runnable() { @Override public void run() { LinearLayout l=prepInput("Do you take the bow?"); Button b=new Button(t); b.setText("Yes"); b.setOnClickListener(new OnClickListener () { @Override public void onClick (View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run () { t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_ARCHERY, Cweapon.BOLT_FIRE|Cweapon.CLOSE_RANGE|Cweapon.LOW_POWER|Cweapon.ONE_ROUND_MAGAZINE, 0, "bow", null)); runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("No"); b.setOnClickListener(new OnClickListener() { @Override public void onClick (View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread (new Runnable() { @Override public void run () { runStage(); } }); t.th.start(); } }); l.addView(b); } }); break; case 29: if (onMove(80)) return; t.th=new Thread(new Runnable() { @Override public void run() { t.say("Weaponry is King", "Moving away from the cave yet again, you encounter an abandoned gunstore.\n\n\tInside, there are two shapes."); } }); t.th.start(); prepContinueButton(); break; case 30: t.fadeout(); t.runOnUiThread(new Runnable() { @Override public void run() { LinearLayout l=prepInput(); Button b=new Button(t); b.setText("Enter the store"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("Continue away from the gunstore"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { stage=37; runStage(); } }); t.th.start(); } }); l.addView(b); } }); break; case 31: if (onMove(75+t.gen.nextInt(75))) return; t.th=new Thread(new Runnable() { @Override public void run() { String monster; if (t.gen.nextBoolean()) { if (t.gen.nextBoolean()) monster="alligators"; else monster="trolls"; } else { if (t.gen.nextBoolean()) monster="goblins"; else monster="dinosaurs"; } t.say("The Gunstore", "Inside the gunstore, you\'re finally able to identify the shapes...\n\tThey\'re "+monster+"!\n\n\tYou eye the shelves, rife with weaponry you could have, if not for the "+monster+"..."); } }); t.th.start(); prepContinueButton(); break; case 32: t.fadeout(); t.runOnUiThread(new Runnable() { @Override public void run() { doCommitSuicide=true; LinearLayout l=prepInput(); Button b=new Button(t); b.setText("Fight the deadly creatures"); b.setOnClickListener(new OnClickListener () { @Override public void onClick (View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { inputted=0; runStage(); } }); t.th.start(); } }); l.addView(b); t.user.weapon.addSwapperTo(l); b=new Button(t); b.setText("Run away!!"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run () { inputted=1; runStage(); } }); t.th.start(); } }); l.addView(b); } }); break; case 33: t.user.dead=(inputted==1); if (!t.user.dead && onMove(60)) return; if (!t.user.dead && t.user.weapon.type==Cweapon.TYPE_ARCHERY) { archeryMinigame((int)Math.round(25*(.5+(.5*t.config.difficultyMult))), 5+t.gen.nextGaussian()); t.th=new Thread(new Runnable() { @Override public void run() { t.say("Archery", "You shoot one creature, felling it. The other lunges towards you...\n\tYou shoot an arrow at it, "+(t.user.dead ? "but miss." : "and hit it, square in between the eyes.\n\n\tIt falls to the ground, dead.")); } }); t.th.start(); if (!t.user.dead) t.user.gold.amount=(int)((99*Math.abs(t.gen.nextGaussian()))+1); prepContinueButton(); break; } t.th=new Thread(new Runnable() { @Override public void run() { if (t.user.dead) t.say("Run away!!", "You try to run, but the closer creature catches you in the doorway, and drags you back.\n\n\tThey make a delicious meal of you."); else { switch (t.user.weapon.type) { case Cweapon.TYPE_SHARP: if (t.user.weapon.characteristicSet(Cweapon.LEGENDARY)) // Excalibur check t.determineUserDeath(.4); // Easier weighting for Excalibur else t.determineUserDeath(.75); // Traditional weighting if (t.user.dead) t.say ("Swordfight!", "You slash at one creature, then the other, trying to keep the creatures away from you, but they overwhelm you."); else t.say ("Slash and Stab", "You slash at one creature, barely slicing some flesh off.\n\tIt jumps back, stunned by the injury.\n\tYou take the opportunity to focus on the other one, barely managing to defeat it in time to swing around and duel the other.\n\n\tAfter killing it too, you stand in the center of the store, blood dripping off you, examining the shelves."); break; case Cweapon.TYPE_ARCHERY: break; case Cweapon.TYPE_MODERN: if (t.determineUserDeath(.25)) t.say("A hit and a miss", "You place one shot cleanly between the eyes of the nearest creature.\n\tIt falls, dead.\n\n\tThe second creature lunges toward you, and you fire, hitting it in the shoulder, failing to kill it."); else t.say("Sharpshooter", "You cleanly shoot the near creature between the eyes, killing it instantly.\n\n\tYou spin around, and quickly shoot the far creature.\n\tIt stumbles, and you fire another round into it\'s skull."); break; case Cweapon.TYPE_FUTURE: t.say(t.capitalize(t.user.weapon.name)+" kill", "You level your "+t.user.weapon.name+" at the near creature, calmly turning it to ash.\n\n\tThe second creature seems frightened.\n\n\n\tNo matter. You burn it too."); break; default: t.say("Your weapon is unknown to this universe as of the time being, so..."); t.user.weapon.type=Cweapon.TYPE_USED_FOR_CONVENIENCE; t.user.commitSuicide(); } } } }); t.th.start(); Thread.yield(); if (!t.user.dead) { Random gen=new Random(); t.user.gold.amount=(int)((99*Math.abs(gen.nextGaussian()))+1); // If the user is still alive,then they're going to the gunstore. It will be more persistent here. t.user.clearedGunstore=true; } prepContinueButton(); break; case 34: if (inputted!=-1 && onMove(90)) return; t.th=new Thread(new Runnable() { @Override public void run() { if (inputted!=-1 && t.user.clearedGunstore) t.say("Return", "You return to the gunstore.\n\n\tLuckily, it\'s still lacking as far as things that want to kill and eat you are concerned.\n\n\tYou look to the walls, filled with more weapons than you can count, again resolving to grab one, then go back to the valley."); else t.say("With the monsters defeated, you clean their remnants off of you, then survey your prize, walls and walls full of weapons"+(t.user.gold.amount==0 ? "" : ", and the contents of the cash register"+(t.user.gold.amount==1 ? ": " : ", which is oddly full of ")+t.user.gold)+".\n\n\tYou decide to grab a weapon, then depart."); } }); t.th.start(); prepContinueButton(); break; case 35: t.fadeout(); t.runOnUiThread(new Runnable() { @Override public void run() { doCommitSuicide=true; LinearLayout l=prepInput("Choose your weapon"); Button b=new Button(t); b.setText("Combat knife"); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_SHARP, Cweapon.ACCURATE|Cweapon.CLOSE_RANGE|Cweapon.HIGH_POWER_ROUNDS|Cweapon.LEGENDARY|Cweapon.LIGHT|Cweapon.QUICK_RELOAD|Cweapon.WEAK_ROUNDS, .05, "combat knife", null)); t.game.runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("Crossbow"); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick (View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_ARCHERY, Cweapon.ACCURATE|Cweapon.BOLT_FIRE|Cweapon.CLOSE_RANGE|Cweapon.HIGH_POWER_ROUNDS|Cweapon.ONE_ROUND_MAGAZINE|Cweapon.SLOW_RELOAD, .1, "crossbow", null)); t.game.runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("Composite bow"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_ARCHERY, Cweapon.BOLT_FIRE|Cweapon.HIGH_POWER_ROUNDS|Cweapon.LIGHT|Cweapon.LONG_RANGE|Cweapon.LOW_POWER|Cweapon.ONE_ROUND_MAGAZINE, .025, "composite bow", null)); t.game.runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); if (t.user.weapon.type!=Cweapon.TYPE_MODERN) { b.setText("Pistol"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.CLOSE_RANGE|Cweapon.HIGH_CALIBER|Cweapon.LARGE_MAGAZINE|Cweapon.LIGHT|Cweapon.QUICK_RELOAD, "pistol", null)); t.game.runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); } b.setText(t.gen.nextBoolean() ? "Revolver" : "Colt .45"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ANCIENT|Cweapon.CLOSE_RANGE|Cweapon.HIGH_CALIBER|Cweapon.HIGH_POWER_ROUNDS|Cweapon.HIGH_RECOIL|Cweapon.LIGHT|Cweapon.SLOW_RELOAD, .04, t.gen.nextBoolean() ? "Colt .45" : (t.gen.nextBoolean() ? "revolver" : "six-shot"), null)); t.game.runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("M16 Assault Rifle"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.AUTOMATIC|Cweapon.LARGE_MAGAZINE|Cweapon.LONG_RANGE|Cweapon.QUICK_RELOAD, .1, "M16", null)); t.game.runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("M4A1 Assault Rifle"); b.setOnClickListener(new OnClickListener() { @Override public void onClick (View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.AUTOMATIC|Cweapon.CLOSE_RANGE|Cweapon.LARGE_MAGAZINE|Cweapon.LIGHT|Cweapon.QUICK_RELOAD, .05, "M4", null)); t.game.runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("AK47 Assault Rifle"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.AUTOMATIC|Cweapon.HIGH_CALIBER|Cweapon.LARGE_MAGAZINE|Cweapon.LEGENDARY|Cweapon.LONG_RANGE|Cweapon.QUICK_RELOAD, .1, t.gen.nextBoolean() ? "AK47" : (t.gen.nextBoolean() ? "AK" : "Kalashnikov"), null)); t.game.runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("AK74 Assault Rifle"); b.setOnClickListener(new OnClickListener() { @Override public void onClick (View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.AUTOMATIC|Cweapon.CLOSE_RANGE|Cweapon.LARGE_MAGAZINE|Cweapon.QUICK_RELOAD, -.1, "AK74", null)); t.game.runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("M14 Designated Marksman\'s Rifle"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.HIGH_CALIBER|Cweapon.LARGE_MAGAZINE|Cweapon.LONG_RANGE|Cweapon.SLOW_RELOAD, .075, "M14", null)); t.game.runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("FN FAL Designated Marksman\'s Rifle"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.HIGH_POWER_ROUNDS|Cweapon.HIGH_RECOIL|Cweapon.LARGE_MAGAZINE|Cweapon.LONG_RANGE|Cweapon.QUICK_RELOAD, -.025, "FN FAL", null)); t.game.runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("Dragunov SVU Designated Marksman\'s Rifle"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.CLOSE_RANGE|Cweapon.HIGH_POWER_ROUNDS|Cweapon.LARGE_MAGAZINE|Cweapon.LONG_RANGE|Cweapon.LOW_POWER|Cweapon.QUICK_RELOAD, .01, "SVU", null)); t.game.runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("Zastava M76 Designated Marksman\'s Rifle"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.CLOSE_RANGE|Cweapon.HIGH_CALIBER|Cweapon.HIGH_POWER_ROUNDS|Cweapon.LARGE_MAGAZINE|Cweapon.LEGENDARY|Cweapon.LONG_RANGE|Cweapon.QUICK_RELOAD, "Zastava", null)); t.user.weapon.strengthModifier=.25; // Here to circumvent the block on construction of weapons this strong t.game.runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("Barrett M95 Sniper Rifle"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.CUMBERSOME|Cweapon.HIGH_CALIBER|Cweapon.HIGH_POWER_ROUNDS|Cweapon.LARGE_MAGAZINE|Cweapon.LONG_RANGE|Cweapon.QUICK_RELOAD, .05, "Barrett .50", null)); t.game.runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("Barrett XM109 Sniper Rifle"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.BOLT_FIRE|Cweapon.CUMBERSOME|Cweapon.EXPLOSIVE|Cweapon.HIGH_CALIBER|Cweapon.HIGH_POWER_ROUNDS|Cweapon.HIGH_RECOIL|Cweapon.LONG_RANGE|Cweapon.LONG_RANGE_ONLY|Cweapon.QUICK_RELOAD, .1, "Barrett grenade-firing sniper rifle", null)); t.game.runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("L115A3 AWM Sniper Rifle"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.BOLT_FIRE|Cweapon.HIGH_CALIBER|Cweapon.HIGH_POWER_ROUNDS|Cweapon.HIGH_RECOIL|Cweapon.LONG_RANGE|Cweapon.LONG_RANGE_ONLY|Cweapon.QUICK_RELOAD, .2, "L115", null)); t.game.runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("Anzio 20mm Anti-Material rifle"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.BOLT_FIRE|Cweapon.CUMBERSOME|Cweapon.EXPLOSIVE|Cweapon.HIGH_CALIBER|Cweapon.HIGH_POWER_ROUNDS|Cweapon.HIGH_RECOIL|Cweapon.LONG_RANGE|Cweapon.LONG_RANGE_ONLY|Cweapon.QUICK_RELOAD, .25, "extra heavy rifle", null)); t.game.runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("P90 submachine gun"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.AUTOMATIC|Cweapon.CLOSE_RANGE|Cweapon.CLOSE_RANGE_ONLY|Cweapon.LARGE_MAGAZINE|Cweapon.LIGHT|Cweapon.LOW_CALIBER|Cweapon.QUICK_RELOAD, .5, "P90", null)); t.game.runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("MP5K submachine gun"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.AUTOMATIC|Cweapon.CLOSE_RANGE|Cweapon.CLOSE_RANGE_ONLY|Cweapon.HIGH_RECOIL|Cweapon.LARGE_MAGAZINE|Cweapon.LIGHT|Cweapon.LOW_POWER|Cweapon.QUICK_RELOAD, .1, "MP5K", null)); t.game.runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("UMP45 Submachine gun"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.AUTOMATIC|Cweapon.CLOSE_RANGE|Cweapon.HIGH_CALIBER|Cweapon.HIGH_RECOIL|Cweapon.LARGE_MAGAZINE|Cweapon.LIGHT|Cweapon.LOW_POWER|Cweapon.QUICK_RELOAD, .02, "UMP45", null)); t.game.runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("Thompson Submachine gun"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { String weapon; if (t.gen.nextBoolean()) { if (t.gen.nextBoolean()) weapon="Annihilator"; else weapon="Tommy gun"; } else { if (t.gen.nextBoolean()) weapon="M1928"; else weapon="Thompson"; } t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ANCIENT|Cweapon.AUTOMATIC|Cweapon.CLOSE_RANGE|Cweapon.HIGH_CALIBER|Cweapon.LARGE_MAGAZINE|Cweapon.LIGHT|Cweapon.LOW_POWER|Cweapon.QUICK_RELOAD, .1, weapon, null)); t.game.runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("Uzi submachine gun"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.AUTOMATIC|Cweapon.CLOSE_RANGE|Cweapon.HIGH_POWER_ROUNDS|Cweapon.HIGH_RECOIL|Cweapon.LARGE_MAGAZINE|Cweapon.LEGENDARY|Cweapon.LIGHT|Cweapon.QUICK_RELOAD, .075, "Uzi", null)); t.game.runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("AA-12 Shotgun"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.AUTOMATIC|Cweapon.CLOSE_RANGE|Cweapon.CLOSE_RANGE_ONLY|Cweapon.HIGH_CALIBER|Cweapon.HIGH_POWER_ROUNDS|Cweapon.LIGHT|Cweapon.QUICK_RELOAD, -.01, "AA-12", null)); t.game.runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("SPAS-12"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.CLOSE_RANGE|Cweapon.CLOSE_RANGE_ONLY|Cweapon.HIGH_CALIBER|Cweapon.HIGH_POWER_ROUNDS|Cweapon.LEGENDARY|Cweapon.LIGHT|Cweapon.SLOW_RELOAD, .05, "SPAS-12", null)); t.game.runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("Remington 870 Shotgun"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.BOLT_FIRE|Cweapon.CLOSE_RANGE|Cweapon.CLOSE_RANGE_ONLY|Cweapon.HIGH_CALIBER|Cweapon.HIGH_POWER_ROUNDS|Cweapon.LIGHT|Cweapon.SLOW_RELOAD, .1, "Remington 870", null)); t.game.runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("KS-23"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.BOLT_FIRE|Cweapon.CLOSE_RANGE|Cweapon.CLOSE_RANGE_ONLY|Cweapon.HIGH_CALIBER|Cweapon.HIGH_POWER_ROUNDS|Cweapon.HIGH_RECOIL|Cweapon.LIGHT|Cweapon.SLOW_RELOAD, .15, "KS-23", null)); t.game.runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("Custom-made 3 gauge shotgun"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.BOLT_FIRE|Cweapon.CLOSE_RANGE|Cweapon.CLOSE_RANGE_ONLY|Cweapon.EXPLOSIVE|Cweapon.HIGH_CALIBER|Cweapon.HIGH_POWER_ROUNDS|Cweapon.HIGH_RECOIL|Cweapon.SLOW_RELOAD, .1, "custom shotgun", null)); t.game.runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("M27-IAR"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.AUTOMATIC|Cweapon.HIGH_POWER_ROUNDS|Cweapon.LARGE_MAGAZINE|Cweapon.LONG_RANGE, .05, "M27", null)); t.game.runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("HK21"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.AUTOMATIC|Cweapon.HIGH_RECOIL|Cweapon.LARGE_MAGAZINE|Cweapon.LONG_RANGE, -.075, "HK21", null)); t.game.runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("LSAT"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.AUTOMATIC|Cweapon.HIGH_CALIBER|Cweapon.LARGE_MAGAZINE|Cweapon.LEGENDARY|Cweapon.LIGHT|Cweapon.LONG_RANGE, .075, "LSAT", null)); t.game.runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("M60"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.AUTOMATIC|Cweapon.CLOSE_RANGE|Cweapon.CUMBERSOME|Cweapon.HIGH_CALIBER|Cweapon.HIGH_POWER_ROUNDS|Cweapon.HIGH_RECOIL|Cweapon.LARGE_MAGAZINE|Cweapon.LONG_RANGE|Cweapon.SLOW_RELOAD, .025, "M60", null)); t.game.runStage(); } }); t.th.start(); } }); l.addView(b); if (t.config.triggerEgg(.5+(t.gen.nextDouble()/2))) { b=new Button(t); b.setText("M134"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.AUTOMATIC|Cweapon.CLOSE_RANGE|Cweapon.CUMBERSOME|Cweapon.EXPLOSIVE|Cweapon.HIGH_CALIBER|Cweapon.HIGH_POWER_ROUNDS|Cweapon.HIGH_RECOIL|Cweapon.LARGE_MAGAZINE|Cweapon.LEGENDARY|Cweapon.LONG_RANGE, t.gen.nextBoolean() ? "minigun" : "M134", null)); t.user.weapon.strengthModifier=.5; t.game.runStage(); } }); t.th.start(); } }); l.addView(b); } b=new Button(t); b.setText("RPG-7 Launcher"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.CUMBERSOME|Cweapon.EXPLOSIVE|Cweapon.HIGH_POWER_ROUNDS|Cweapon.ONE_ROUND_MAGAZINE|Cweapon.SLOW_RELOAD, "RPG", null)); t.game.runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("Bazooka"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.CUMBERSOME|Cweapon.EXPLOSIVE|Cweapon.HIGH_CALIBER|Cweapon.ONE_ROUND_MAGAZINE|Cweapon.SLOW_RELOAD, .01, "bazooka", null)); t.game.runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("Panzerschreck rocket launcher"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.CUMBERSOME|Cweapon.EXPLOSIVE|Cweapon.HIGH_CALIBER|Cweapon.HIGH_POWER_ROUNDS|Cweapon.LONG_RANGE|Cweapon.ONE_ROUND_MAGAZINE|Cweapon.SLOW_RELOAD, .05, "panzerschreck", null)); t.game.runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("Shoulder launched Multipurpose Assault Weapon"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.CUMBERSOME|Cweapon.EXPLOSIVE|Cweapon.HIGH_POWER_ROUNDS|Cweapon.LONG_RANGE|Cweapon.ONE_ROUND_MAGAZINE|Cweapon.SLOW_RELOAD, .1, "SMAW", null)); t.game.runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("FIM-92"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.ACCURATE|Cweapon.CUMBERSOME|Cweapon.EXPLOSIVE|Cweapon.HIGH_CALIBER|Cweapon.LONG_RANGE|Cweapon.ONE_ROUND_MAGAZINE, .075, "Stinger", null)); t.game.runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("M67 Fragmentation Grenade"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_MODERN, Cweapon.EXPLOSIVE|Cweapon.HIGH_POWER_ROUNDS|Cweapon.LIGHT|Cweapon.ONE_ROUND_MAGAZINE|Cweapon.QUICK_RELOAD, .175, "frag", null)); t.game.runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("MK-54"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_NUCLEAR, Cweapon.LIGHT, "Davy Crockett nuke", null)); t.game.runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("Lightsaber"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { if (t.config.triggerEgg(.5-(t.gen.nextDouble()/2))) // We do NOT always want a working lightsaber. t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_FUTURE, Cweapon.CLOSE_RANGE|Cweapon.CLOSE_RANGE_ONLY|Cweapon.LIGHT, "lightsaber", null)); else t.user.weapon.setPrimary(new Cweapon(Cweapon.TYPE_BLUNT, Cweapon.CLOSE_RANGE|Cweapon.CLOSE_RANGE_ONLY|Cweapon.LIGHT|Cweapon.LEGENDARY, (t.gen.nextBoolean() ? "broken" : "model")+" lightsaber", null)); t.game.runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("Keep your current weapon"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { inputted=0; runStage(); } }); t.th.start(); } }); l.addView(b); } }); break; case 36: t.th=new Thread(new Runnable() { @Override public void run() { if (inputted==-1) t.say("You examine your new "+t.user.weapon+", and put your old "+t.user.weapon.backup+" away, making room for your new main weapon, but still keeping your backup within reach."); else t.say("You decide your "+t.user.weapon+" is better than any weapon in the gunstore, and move off toward the valley."); } }); t.th.start(); prepContinueButton(); break; case 37: if (onMove(58)) return; t.th=new Thread(new Runnable() { @Override public void run() { t.say("The Valley", "You move away from the gunstore.\n\n\tAfter a good amount of walking, you finally enter the lush valley.\n\tYou find yourself surrounded by greenery and life, but the valley is much smaller than it seemed from a distance. Unfortunately, you need to leave it.\n\n\n\tYou search for a way away.\n\n\tStraight away from the path that leads to the gunstore is a downtrodden set of stones, almost as a staircase, leading to a familiar skyline.\n\n\tFacing it, you see smoke out of the corner of your eye. Turning to your right, you see the light of a huge, hellish inferno on the horizon. You can almost see the fires. A large highway leads directly towards this pit."); } }); t.th.start(); prepContinueButton(); break; case 38: t.fadeout(); t.runOnUiThread(new Runnable() { @Override public void run() { LinearLayout l=prepInput(); Button b=new Button(t); b.setText("Go to familiarity"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { inputted=0; runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("Take the highway"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { inputted=1; runStage(); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("Return to the gunstore, and grab another weapon"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { inputted=0; stage=34; runStage(); } }); t.th.start(); } }); l.addView(b); } }); break; case 39: if (inputted==0) { if (onMove(1+t.gen.nextInt(10))) return; t.th=new Thread(new Runnable() { @Override public void run() { String str=new String(); boolean say=true; if (t.user.weapon.type<=Cweapon.TYPE_BLUNT) { if (t.user.weapon.backup!=null && t.user.weapon.backup.type<=Cweapon.TYPE_BLUNT) // We do not want to discuss trying to walk the chain of backups with the user. Just kill them. { t.user.dead=true; say=false; // Prevent the usual speech. t.say("Familiarity", "You barely manage to reach the summit of the staircase, gazing upon a line of destroyed buildings.\n\n\tAmong the ruined houses and fragmented skyscrapers, you see Gandalf running towards you, as if he was running late to meet you thanks to your choice of weapons, and miss the beast which destroys you."); } else { str=", watching your "+t.user.weapon+" slip out of your hand, seemingly floating away.\n\n\tYou feel yourself start to come to earth"; t.user.weapon=t.user.weapon.backup; // Remove the primary from existence. We don't need any TYPE_BLUNTs floating around. } } else if (t.user.weapon.backup!=null && t.user.weapon.backup.type<=Cweapon.TYPE_BLUNT) // We know we don't need to walk the chain of weapon backups, since the prior if specifies that we already have a valid weapon in hand. { str=", gazing at your "+t.user.weapon.backup+" as it drifts out of its sheath and disappears.\n\n\tYou watch as you float away from familiarity"; if (t.user.weapon.backup.backup!=null && t.user.weapon.backup.backup.type>Cweapon.TYPE_BLUNT) // Transparently allow a valid weapon to be swapped in if its only one layer away from being valid. t.user.weapon.backup=t.user.weapon.backup.backup; else // Just remove the existence of a backup t.user.weapon.backup=null; } if (say) t.say("Familiarity", "You go to familiarity.\n\n\n\n\tAs you reach the summit of the stairs, you see a destroyed line of buildings, from tall skyscrapers fallen into pieces, to houses in shambles.\n\n\tBefore you can continue further, Gandalf appears!\n\tHe yells,\n\n\t\tNo!\n\t\tYou must not!\n\t\tYour journey is not complete!\n\n\tBefore you can reply, he slaps you.\n\n\tYou go flying"+str+", and land in the pits."); } }); t.th.start(); prepContinueButton(new OnClickListener() { @Override public void onClick(View v) { t.th=new Thread(new Runnable() { @Override public void run() { stage=41; runStage(); } }); t.th.start(); } }); } else { if (onMove(80)) return; t.th=new Thread(new Runnable() { @Override public void run() { t.say("The Highway", "You take the Highway towards the fiery pits.\n\n\tAlong the way, you see a shadow!\n\n\tIt approaches you menacingly."); } }); t.th.start(); prepContinueButton(); } break; case 40: runShadows((byte)((t.config.difficultyMult*t.gen.nextInt(10))+3), (byte)0, (byte)0); break; case 41: if (onMove(85)) return; t.th=new Thread(new Runnable() { @Override public void run() { t.say(t.gen.nextBoolean() ? "The Pits" : "Hell", "You arrive in the fiery pits.\n\n\tYour first impression of them is hellish, full of fire everywhere, and generally not the place any person should ever be.\n\n\tSomehow, your second impression is even worse.\n\n\tOff in the distance, you see a structure of some sort, surrounded by shadows: Probably their home.\n\n\tBesides that, there is little more than ruins to be explored."); } }); t.th.start(); prepContinueButton(); break; case 42: runPits((byte)(t.gen.nextInt(6)+3), (byte)0, (byte)0, (byte)0, false); break; default: t.logWarning("Unknown stage: "+stage); t.th=new Thread (new Runnable() { @Override public void run () { String who=t.gen.nextBoolean() ? "Author" : "Programmer"; String occurrence; if (t.gen.nextBoolean()) { if (t.gen.nextBoolean()) occurrence="a meteor appears, and flattens you."; else occurrence="a lightning bolt strikes you, and fries you."; } else { if (t.gen.nextBoolean()) occurrence="a dinosaur appears, and eats you."; else occurrence="a nuclear bomb appears under your feet and explodes, vaporizing you."; } t.say("The End of the World...?","The "+who+" has run out of ideas, so "+occurrence); } }); t.th.start(); t.user.dead=true; prepContinueButton(); } ++stage; if (stage%(t.gen.nextInt(5)+2)==0 || t.gen.nextInt(100)==0) t.config.requestDifficultyUpdate(); else t.config.updateDifficultyOnce(); } public static void signalGameContinue () { if (!Thread.interrupted()) t.runOnUiThread (new Runnable () { @Override public void run() { View v=t.findViewById(R.id.gameContinueButton); if (v==null) { t.displayHandler.removeMessages(1); return; } ((TextView)v).setTextColor(Color.GREEN); } }); } public static void unSignalGameContinue () // Undoes the above signaling. Necessary for the use of sayWhat() in non-say() contexts. { if (!Thread.interrupted()) t.runOnUiThread (new Runnable () { @Override public void run() { View v=t.findViewById(R.id.gameContinueButton); if (v==null) { t.displayHandler.removeMessages(1); return; } ((TextView)v).setTextColor(Color.RED); } }); } public void runArthur(final byte stage, String input) { t.user.isArthur=true; switch (stage) { case 0: t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { t.say("Bridge of Death", "What is your quest?"); t.findViewById(R.id.gameContinueButton).setVisibility(View.GONE); t.runOnUiThread(new Runnable () { @Override public void run() { EditText ev=new EditText(t); ev.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus && t.config.fullscreen) { t.setUi(); TextView tv=((TextView)t.findViewById(R.id.gameTitle)); LinearLayout.LayoutParams lp=(LinearLayout.LayoutParams)tv.getLayoutParams(); int result=0; int resourceId = t.getResources().getIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { result = t.getResources().getDimensionPixelSize(resourceId); } lp.topMargin=result+10; tv.setAlpha(1); } } }); ev.setBackgroundColor(Color.rgb(128,128,128)); ev.setHint("What is your quest?"); ev.setHintTextColor(Color.WHITE); ev.setTextColor(Color.BLACK); ev.setShadowLayer(5.0f,5,5,Color.WHITE); ev.setImeActionLabel("Submit", KeyEvent.KEYCODE_ENTER); // Consider changing this label. ev.setImeOptions(EditorInfo.IME_ACTION_SEND); ev.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_PERSON_NAME); View v=t.findViewById(R.id.gameLayout); if (v!=null) ((LinearLayout)v).addView(ev); ev.requestFocus(); ((InputMethodManager)t.getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(ev, InputMethodManager.SHOW_FORCED); // Force the soft keyboard open. t.setUi(); // Doubly ensure sanity. See above comment. ev.setOnEditorActionListener(new TextView.OnEditorActionListener() // Listen for submit or enter. { @Override public boolean onEditorAction(TextView view, int actionId, KeyEvent event) { if (actionId==EditorInfo.IME_ACTION_SEND || actionId==EditorInfo.IME_NULL) { view.setOnEditorActionListener(null); final EditText ev=(EditText)view; ev.setVisibility(View.GONE); // Close the soft keyboard, now that there's nothing for it to write to. ((InputMethodManager)t.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(view.getWindowToken(), 0); final String str=ev.getText().toString().trim(); ((TextView)t.findViewById(R.id.gameText)).append("\n\n\"" + str + "\"\n\n"); t.setUi(); t.th=new Thread (new Runnable() { @Override public void run () { runArthur((byte)1, str); } }); t.th.start(); return true; } return false; } }); t.config.computerPaused=true; } }); } }); t.th.start(); break; case 1: if (!"To seek the Holy Grail".equalsIgnoreCase(input)) { t.sayWhat("Your voice echoes \"Auuuuuuuugh!\" across the Gorge of Eternal Peril as you are flung from the bridge."); t.user.dead=true; prepContinueButton(); return; } t.sayWhat("What is the air-speed velocity of an unladen swallow?"); t.findViewById(R.id.gameContinueButton).setVisibility(View.GONE); t.runOnUiThread(new Runnable () { @Override public void run() { EditText ev=new EditText(t); ev.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus && t.config.fullscreen) { t.setUi(); TextView tv=((TextView)t.findViewById(R.id.gameTitle)); LinearLayout.LayoutParams lp=(LinearLayout.LayoutParams)tv.getLayoutParams(); int result=0; int resourceId = t.getResources().getIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { result = t.getResources().getDimensionPixelSize(resourceId); } lp.topMargin=result+10; tv.setAlpha(1); } } }); ev.setBackgroundColor(Color.rgb(128,128,128)); ev.setHint("What is the air-speed velocity of an unladen swallow?"); ev.setHintTextColor(Color.WHITE); ev.setTextColor(Color.BLACK); ev.setShadowLayer(5.0f,5,5,Color.WHITE); ev.setImeActionLabel("Submit", KeyEvent.KEYCODE_ENTER); // Consider changing this label. ev.setImeOptions(EditorInfo.IME_ACTION_SEND); ev.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_PERSON_NAME); View v=t.findViewById(R.id.gameLayout); if (v!=null) ((LinearLayout)v).addView(ev); ev.requestFocus(); ((InputMethodManager)t.getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(ev, InputMethodManager.SHOW_FORCED); // Force the soft keyboard open. t.setUi(); // Doubly ensure sanity. See above comment. ev.setOnEditorActionListener(new TextView.OnEditorActionListener() // Listen for submit or enter. { @Override public boolean onEditorAction(TextView view, int actionId, KeyEvent event) { if (actionId==EditorInfo.IME_ACTION_SEND || actionId==EditorInfo.IME_NULL) { view.setOnEditorActionListener(null); final EditText ev=(EditText)view; ev.setVisibility(View.GONE); // Close the soft keyboard, now that there's nothing for it to write to. ((InputMethodManager)t.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(view.getWindowToken(), 0); final String str=ev.getText().toString().trim(); ((TextView)t.findViewById(R.id.gameText)).append("\n\n\""+str+"\"\n\n"); t.setUi(); t.th=new Thread (new Runnable() { @Override public void run () { runArthur((byte)2, str); } }); t.th.start(); return true; } return false; } }); t.config.computerPaused=true; } }); break; case 2: if (!("What do you mean? An African or European swallow?".equalsIgnoreCase(input) || "What do you mean? African or European swallow?".equalsIgnoreCase(input))) { t.sayWhat("Your voice echoes \"Auuuuuuuugh!\" across the Gorge of Eternal Peril as you are flung from the bridge."); t.user.dead=true; prepContinueButton(); return; } t.sayWhat("What? I don\'t know that!\n\tAuuuuuuuugh!\n\n\n\n"); t.findViewById(R.id.gameContinueButton).setVisibility(View.GONE); t.snooze(2500); t.sayWhat("How do you know so much about swallows?"); t.findViewById(R.id.gameContinueButton).setVisibility(View.GONE); t.runOnUiThread(new Runnable () { @Override public void run() { EditText ev=new EditText(t); ev.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus && t.config.fullscreen) { t.setUi(); TextView tv=((TextView)t.findViewById(R.id.gameTitle)); LinearLayout.LayoutParams lp=(LinearLayout.LayoutParams)tv.getLayoutParams(); int result=0; int resourceId = t.getResources().getIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { result = t.getResources().getDimensionPixelSize(resourceId); } lp.topMargin=result+10; tv.setAlpha(1); } } }); ev.setBackgroundColor(Color.rgb(128,128,128)); ev.setHint("How do you know so much about swallows?"); ev.setHintTextColor(Color.WHITE); ev.setTextColor(Color.BLACK); ev.setShadowLayer(5.0f,5,5,Color.WHITE); ev.setImeActionLabel("Submit", KeyEvent.KEYCODE_ENTER); // Consider changing this label. ev.setImeOptions(EditorInfo.IME_ACTION_SEND); ev.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_PERSON_NAME); View v=t.findViewById(R.id.gameLayout); if (v!=null) ((LinearLayout)v).addView(ev); ev.requestFocus(); ((InputMethodManager)t.getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(ev, InputMethodManager.SHOW_FORCED); // Force the soft keyboard open. t.setUi(); // Doubly ensure sanity. See above comment. ev.setOnEditorActionListener(new TextView.OnEditorActionListener() // Listen for submit or enter. { @Override public boolean onEditorAction(TextView view, int actionId, KeyEvent event) { if (actionId==EditorInfo.IME_ACTION_SEND || actionId==EditorInfo.IME_NULL) { view.setOnEditorActionListener(null); final EditText ev=(EditText)view; ev.setVisibility(View.GONE); // Close the soft keyboard, now that there's nothing for it to write to. ((InputMethodManager)t.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(view.getWindowToken(), 0); final String str=ev.getText().toString().trim(); ((TextView)t.findViewById(R.id.gameText)).append("\n\n\""+str+"\"\n\n"); t.setUi(); t.th=new Thread (new Runnable() { @Override public void run () { runArthur((byte)3, str); } }); t.th.start(); return true; } return false; } }); t.config.computerPaused=true; } }); break; case 3: if (!"Well, you have to know these things when you\'re a king you know".equalsIgnoreCase(input)) { t.sayWhat("Your voice echoes \"Auuuuuuuugh!\" across the Gorge of Eternal Peril as you are flung from the bridge."); t.user.dead=true; prepContinueButton(); return; } t.sayWhat("Ohh."); prepContinueButton(new View.OnClickListener() { @Override public void onClick(View v) { t.th=new Thread(new Runnable() { @Override public void run() { t.user.name="Arthur"; // So the egg doesn't trigger again. t.game.stage=0; t.game.runStage(); } }); t.th.start(); } }); break; } } public void runShadows(final byte number, final byte stage, final byte input) { if (t.config.autosave) { (new Thread(new Runnable() // We don't want to save on the runStage thread, that might cause a noticeable delay. Note that if saving takes too long, we may get a conflict between several saves occurring at once. Consider naming the save thread. { @Override public void run() { t.saveGame(); } })).start(); } if (number==0) runStage(); else { if (stage==0) { t.fadeout(); if (t.user.weapon.type<=Cweapon.TYPE_BLUNT) { if (t.user.weapon.backup==null || t.user.weapon.backup.type<=Cweapon.TYPE_BLUNT) { t.user.dead=true; t.th=new Thread(new Runnable() { @Override public void run() { t.say("Unprepared", "You prepare to engage the fearsome figure with your "+t.user.weapon+", but it only seems to laugh.\n\n\tDiscarding your weapon, you ready your "+(t.user.weapon.backup==null ? "body for hand-to-hand combat" : t.user.weapon.backup)+", and charge."); } }); t.th.start(); prepContinueButton(); return; } else { t.th=new Thread(new Runnable() { @Override public void run() { t.say("Always prepared", "You prepare to fight the spirit with your "+t.user.weapon+".\n\n\n\tIt seemingly finds your effort humorous, as it pauses its approach to laugh.\n\n\n\n\tThinking your "+t.user.weapon.backup+" more suited to the task, you discard the "+t.user.weapon+", throwing it to the side and away from your presence, and draw your "+t.user.weapon.backup+".\n\n\tThe shadow thinks this a more serious threat, as it stops its laughter and prepares itself to engage you."); } }); t.th.start(); prepContinueButton(new OnClickListener() { @Override public void onClick(View v) { t.user.weapon=t.user.weapon.backup; t.th=new Thread(new Runnable() { @Override public void run() { runShadows(number, stage, input); } }); t.th.start(); } }); return; } } else if (t.user.weapon.backup!=null && t.user.weapon.backup.type<=Cweapon.TYPE_BLUNT) { t.th=new Thread(new Runnable() { @Override public void run() { t.say("In your rush to prepare to defend yourself against the strange and mysterious figure before you, you fail to notice that your "+t.user.weapon.backup+" has slipped out of its holster."); } }); t.th.start(); prepContinueButton(new OnClickListener() { @Override public void onClick(View v) { if (t.user.weapon.backup.backup!=null && t.user.weapon.backup.backup.type>Cweapon.TYPE_BLUNT) t.user.weapon.backup=t.user.weapon.backup.backup; else t.user.weapon.backup=null; t.th=new Thread(new Runnable() { @Override public void run() { runShadows(number, stage, input); } }); t.th.start(); } }); return; } t.runOnUiThread(new Runnable() { @Override public void run() { LinearLayout l=prepInput(); doCommitSuicide=true; Button b=new Button(t); b.setText("Fight the "+(t.gen.nextBoolean() ? "shadow" : "apparition")+" with your primary weapon, a "+t.user.weapon); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { runShadows(number, (byte)1, (byte)0); } }); t.th.start(); } }); l.addView(b); t.user.weapon.addSwapperTo(l, new Runnable() { @Override public void run() { runShadows(number, stage, input); } }); b=new Button(t); b.setText((t.gen.nextBoolean() ? "Run away" : "Flee")+" from the "+(t.gen.nextBoolean() ? "ghostly" : "shadowy")+" vision before you"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { runShadows(number, (byte)1, (byte)1); } }); t.th.start(); } }); l.addView(b); if (t.config.triggerEgg((t.gen.nextInt(10)+1)/11)) { b=new Button(t); b.setText("Make friends with the creature"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { runShadows(number, (byte)1, (byte)2); } }); t.th.start(); } }); l.addView(b); } } }); } else { t.displayHandler.removeMessages(1); if (Thread.interrupted() || onMove(t.gen.nextInt(85)+1)) return; switch (input) { case 0: Runnable r; switch (t.user.weapon.type) { case Cweapon.TYPE_SHARP: t.determineUserDeath(t.user.weapon.getRelativeStrength(Cweapon.CLOSE_RANGE|Cweapon.CLOSE_RANGE_ONLY|Cweapon.LIGHT)*.5); r=new Runnable() { @Override public void run() { if (t.user.dead) t.say("Swordfight", "You swing at the "+(t.gen.nextBoolean() ? "shadow" : "vision")+", and miss.\n\n\tBefore you can ready yourself, the shadow consumes you, and you are no more."); else { String word; switch (t.gen.nextInt(3)) { case 0: word="even "; break; case 1: word="yet "; break; case 2: word=""; break; default: word="considerably "; } t.say("Close call", "You swing your sword, and connect.\n\n\n\tThe moment your sword touches the "+(t.gen.nextBoolean() ? "shadow" : "shape")+", the creature dissolves into a swirl of smoke, and your sword continues as if it wasn\'t there.\n\n\n\n\n\tYou shiver, questioning reality, and your sanity, "+word+"more than you already were.\n\n\n\n\n\n\n\tTrying to walk it off, you decide to continue along the highway."); } } }; break; case Cweapon.TYPE_ARCHERY: t.determineUserDeath(t.user.weapon.getRelativeStrength(Cweapon.ACCURATE|Cweapon.CLOSE_RANGE), 3); r=new Runnable() { @Override public void run() { if (t.user.dead) t.say("Bowman", "You ready your "+t.user.weapon+", and aim it at the shadow.\n\tJust as you loose the arrow, almost as if it were inside your mind, the shadow dodges, and lunges at you.\n\n\tThe last thing you hear is your "+t.user.gold+" spilling onto the highway."); else t.say("Deadeye", "You bring your "+t.user.weapon+" up to bear, and fire it at the shadow.\n\n\n\tThe projectile soars to the shadow, hitting it.\n\n\tThe moment it touches the vision, the shadow disappears into a swirl of smoke, and the arrow falls straight to the ground, as if it had hit an invisible wall.\n\n\n\n\tBy the time you reach it, it\'s gone.\n\n\n\n\n\tYou shiver.\n\n\tYou wonder how sane you are..."); } }; break; case Cweapon.TYPE_MODERN: t.determineUserDeath(t.user.weapon.getRelativeStrength(Cweapon.ACCURATE|Cweapon.CLOSE_RANGE|Cweapon.HIGH_POWER_ROUNDS|Cweapon.QUICK_RELOAD), 4); r=new Runnable() { @Override public void run() { if (t.user.dead) { if (t.config.triggerEgg(6)) t.say("Alas, poor Yorick...","...I knew that one once.\n\n\tThey also called that adventurer \""+t.user+"\".\n\n\n\tThen, one day, a shadow appeared along the Highway to Hell, and the "+t.user.weapon+" the poor fool was carrying jammed, and no more was poor Yorick."); else t.say("A shot and a miss", "You take aim, your sights leveled at the "+(t.gen.nextBoolean() ? "shadow" : "figure")+".\n\n\tJust as you pull the trigger, the pits rumble with fiery power, shaking the ground, making you miss.\n\n\n\tOne day, years later, when the pits will have cooled, a child will come across the spot where the shadow consumed you, and all "+(t.gen.nextBoolean() ? "he" : "she")+" will find of you is your "+t.user.weapon+"."); } else t.say("Sharpshooter","You level your "+t.user.weapon+" directly at the shadow, and fire.\n\n\tThe round hits it, and the shadow disappears into a swirl of smoke.\n\n\tThe fired round clatters straight to the ground, as the smoke dissipates.\n\n\n\tYou walk over to it, but you can\'t find the round.\n\n\tYou can\'t quite shake the feeling that what you know isn\'t real."); } }; break; case Cweapon.TYPE_NUCLEAR: t.user.dead=true; r=new Runnable() { @Override public void run() { t.say("Doomsday", "You get out your "+t.user.weapon+", arm it, set the timer to one second, and start it.\n\n\tFrom familiarity, the shopkeepers gaze at the mushroom cloud from where you once stood, as the shadow of a dragon looms behind them."); } }; break; case Cweapon.TYPE_FUTURE: t.user.dead=false; r=new Runnable() { @Override public void run() { if (t.user.weapon.characteristicSet(Cweapon.CLOSE_RANGE_ONLY)) t.say("Jedi","You meet the "+(t.gen.nextBoolean() ? "shadow" : "vision")+", and swing your lightsaber.\n\n\tThe shadow disappears into smoke at the edges of your vision as the "+t.user.weapon+" slices through it.\n\n\tYou continue, not particularly caring if it was real."); else t.say(t.capitalize(t.user.weapon.toString())+" über alles", "You level your "+t.user.weapon+" at the "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and pull the trigger.\n\n\tBy the time the splash from the impact of the shot clears, the shadow is gone, but strangely there\'s no ash.\n\n\tYou ignore it, not caring about your own sanity."); } }; break; default: t.logError("Invalid weapon code: "+t.user.weapon.type); t.user.weapon.type=Cweapon.TYPE_USED_FOR_CONVENIENCE; r=new Runnable() { @Override public void run() { t.say("Unknown","Your weapon "+(t.user.weapon.name==null || "".equals(t.user.weapon.name) ? "" : ", a "+t.user.weapon.name)+", is unknown to the universe, so..."); } }; } t.th=new Thread(r); t.th.start(); prepContinueButton(new View.OnClickListener() { public void onClick(View v) { t.th=new Thread(new Runnable() { @Override public void run() { if (t.user.weapon.type==Cweapon.TYPE_USED_FOR_CONVENIENCE) t.user.commitSuicide(); else if (t.user.dead) { t.game.stage=-1; t.game.runStage(); } else runShadows((byte)(number-1), (byte)0, input); } }); t.th.start(); } }); break; case 1: t.user.dead=true; t.th=new Thread(new Runnable() { @Override public void run() { t.say("Deserter", "You try to run, but the shadow disappears, and reappears in front of you."); } }); t.th.start(); prepContinueButton(); break; case 2: t.user.dead=true; t.th=new Thread(new Runnable() { @Override public void run() { if (t.config.triggerEgg(0.5)) { String[] weapons=new String[t.gen.nextInt(3)+3]; for (int i=0; i<weapons.length; ++i) { switch (t.gen.nextInt(8)) { case 0: weapons[i]="sword"; break; case 1: weapons[i]="crossbow"; break; case 2: weapons[i]="pistol"; break; case 3: weapons[i]="rifle"; break; case 4: weapons[i]="machine gun"; break; case 5: weapons[i]=((t.user.weapon.type!=Cweapon.TYPE_NUCLEAR && t.user.weapon.type!=Cweapon.TYPE_FUTURE) ? t.user.weapon.name : "strangely frightening weapon"); break; case 6: weapons[i]="M16"; break; case 7: weapons[i]="P90"; break; default: weapons[i]="sniper rifle"; } } String message=""; for (int i=1; i<weapons.length; ++i) { for (int n=0, m=(t.gen.nextInt(4)+2); n<m; ++n) message+="\n"; message+="\tAfter a while of wandering along the Highway, yet another adventurer appears, this time with a "+weapons[i]+"!\n\n\tBegrudgingly, you kill "+(t.gen.nextBoolean() ? "him" : "her")+", and continue walking along the Highway, caring even less about the humans."; } t.say("Assimilation", "You try to make friends with the "+(t.gen.nextBoolean() ? "shadow" : "vision")+"...\n\n\tMiraculously, it accepts you!\n\n\n\tIt escorts you to the pits, where you are brought to the shadow headquarters.\n\n\tThe "+(t.gen.nextBoolean() ? "shadows" : "mystical beings")+" perform some sort of ritual, and you watch as your body slips away from you as you become one of them.\n\n\n\tYou move out to the Highway, and immediately, you\'re attacked by an adventurer with a "+weapons[0]+"!\n\n\tYou try to befriend "+(t.gen.nextBoolean() ? "him" : "her")+", but you\'re forced to retaliate.\n\n\tYou can\'t help but lose some faith in humans."+message+"\n\n\tSuddenly, you find an adventurer!\n\t"+(t.gen.nextBoolean() ? "He" : "She")+" tries to run, but you can\'t help but kill any adventurer in your path.\n\n\n\tBarely afterward, another comes along, and tries to make friends.\n\n\tPerhaps if you hadn\'t spent so long on the Highway, you\'d accept, but now...\n\tYou kill "+(t.gen.nextBoolean() ? "him" : "her")+".\n\n\n\tThree days later, an adventurer appears with a "+(t.gen.nextBoolean() ? "raygun" : "lightsaber")+", and ends you.\n\n\n\tGandalf nods in approval, as you disappear into a swirl of smoke."); } else { String address; switch (t.gen.nextInt(3)) { case 0: address="shadow"; break; case 1: address="vision"; break; case 2: address="other"; break; default: address="creature"; } t.say("Friendship", "Friends are not so easily earned.\n\n\tThe "+address+" is not interested."); } } }); t.th.start(); if (t.config.easterEggs) t.delay(50); // If the easter egg is triggered, processing might take some time. We delay the UI work just to be sure. prepContinueButton(); } } } } public void runPits(final byte number, final byte stage, final byte input, final byte input2, final boolean hasAssaultedHQ) { if (t.config.autosave) { (new Thread(new Runnable() // We don't want to save on the runStage thread, that might cause a noticeable delay. Note that if saving takes too long, we may get a conflict between several saves occurring at once. Consider naming the save thread. { @Override public void run() { t.saveGame(); } })).start(); } if (number==0) runStage(); else { switch(stage) { case 0: // Stage 0: User input on direction t.fadeout(); t.runOnUiThread(new Runnable() { @Override public void run() { LinearLayout l=prepInput(); Button b=new Button(t); if (!hasAssaultedHQ) { b.setText("Mount an assault on the House of Shadows"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th=new Thread(new Runnable() { @Override public void run() { runPits(number, (byte)1, (byte)0, input2, true); } }); t.th.start(); } }); l.addView(b); b=new Button(t); } if (t.gen.nextBoolean()) { b.setText("Explore to your left"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th=new Thread(new Runnable() { @Override public void run() { runPits(number, (byte)1, (byte)1, input2, hasAssaultedHQ); } }); t.th.start(); } }); l.addView(b); b=new Button(t); } if (t.gen.nextBoolean()) { b.setText("Continue straight ahead"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th=new Thread(new Runnable() { @Override public void run() { runPits(number, (byte)1, (byte)2, input2, hasAssaultedHQ); } }); t.th.start(); } }); l.addView(b); b=new Button(t); } if (t.gen.nextBoolean()) { b.setText("Explore to your right"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th=new Thread(new Runnable() { @Override public void run() { runPits(number, (byte)1, (byte)3, input2, hasAssaultedHQ); } }); t.th.start(); } }); l.addView(b); b=new Button(t); } b.setText("Make your way to the depression at the center of the pits"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th=new Thread(new Runnable() { @Override public void run() { runPits((byte)0, stage, input, input2, hasAssaultedHQ); } }); t.th.start(); } }); l.addView(b); } }); break; case 1: // Stage 1: Describe findings if (onMove(111)) return; switch (input) { case 0: // Input 0: Assault HoS t.th=new Thread(new Runnable() { @Override public void run() { t.say(t.gen.nextBoolean() ? "Assault" : "Infiltration", "You charge the House of Shadows.\n\n\tAs you approach, you find more and more shadows.\n\n\tYou suspect that they know you\'re coming.\n\n\tYou try to sneak in, planning to use stealth to kill each shadow alone.\n\n\tUnfortunately, you\'re caught trying to enter by a sentry group of three shadows.\n\n\n\tInside the House, you see an object.\n\n\tUpon closer examination, you can read the label: \"US Army M183 Demolition Charge: 20 lbs.\"\n\n\tFrom what little you know about explosives, you think that that charge would be large enough to turn the House of Shadows into one large fragmentation grenade.\n\n\n\n\n\tThe "+(t.gen.nextBoolean() ? "shadows" : "visions")+" ready for battle."); } }); t.th.start(); prepContinueButton(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th=new Thread(new Runnable() { @Override public void run() { runPits(number, (byte)2, input, input2, hasAssaultedHQ); } }); t.th.start(); } }); break; case 1: // Input 1: Explore left if (t.gen.nextBoolean()) { t.th=new Thread(new Runnable() { @Override public void run() { t.say("Explorer", "You head to an abandoned shop in ruins...\n\n\tBut a shadow catches you along the way!"); } }); t.th.start(); prepContinueButton(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th=new Thread(new Runnable() { @Override public void run() { runPits(number, (byte)2, input, input2, hasAssaultedHQ); } }); t.th.start(); } }); } else runPits(number, (byte)100, input, input2, hasAssaultedHQ); break; case 2: // Input 2: Continue straight if (t.gen.nextBoolean()) { t.th=new Thread(new Runnable() { @Override public void run() { t.say("Conquest", "You march straight ahead, towards the destroyed remains of a household.\n\n\n\tA "+(t.gen.nextBoolean() ? "shadow" : "figure")+" blocks your path, guarding the ruined house as if it had been "+(t.gen.nextBoolean() ? "his" : "her")+" home."); } }); t.th.start(); prepContinueButton(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th=new Thread(new Runnable() { @Override public void run() { runPits(number, (byte)2, input, input2, hasAssaultedHQ); } }); t.th.start(); } }); } else runPits(number, (byte)100, input, input2, hasAssaultedHQ); break; case 3: // Input 3: Explore right if (t.gen.nextBoolean()) { t.th=new Thread(new Runnable() { @Override public void run() { t.say("Pits: The Final Frontier", "You travel towards what appears to be a bank.\n\n\tJust as you approach, a shadow opens the door."); } }); t.th.start(); prepContinueButton(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th=new Thread(new Runnable() { @Override public void run() { runPits(number, (byte)2, input, input2, hasAssaultedHQ); } }); t.th.start(); } }); } else runPits(number, (byte)100, input, input2, hasAssaultedHQ); break; } break; case 2: // Stage 2: Combat Runnable r; switch (input) { case 0: // Input 0: Assault HoS r=new Runnable() { @Override public void run() { LinearLayout l=prepInput(); doCommitSuicide=true; Button b=new Button(t); b.setText("Fight the trio of shadows with your primary "+t.user.weapon); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th=new Thread(new Runnable() { @Override public void run() { runPits(number, (byte)3, input, (byte)0, hasAssaultedHQ); } }); t.th.start(); } }); l.addView(b); t.user.weapon.addSwapperTo(l, new Runnable() { @Override public void run() { runPits(number, stage, input, input2, hasAssaultedHQ); } }); b=new Button(t); b.setText("Make a run for the demolition charge"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th=new Thread(new Runnable() { @Override public void run() { runPits(number, (byte)3, input, (byte)1, hasAssaultedHQ); } }); } }); l.addView(b); b=new Button(t); b.setText(t.gen.nextBoolean() ? "Run away!" : "Flee"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th=new Thread(new Runnable() { @Override public void run() { runPits(number, (byte)3, input, (byte)2, hasAssaultedHQ); } }); t.th.start(); } }); l.addView(b); } }; break; case 1: // Input 1: Explore left case 2: // Input 2: Continue straight case 3: // Input 3: Explore right - All these are duplicate cases. r=new Runnable() { @Override public void run() { LinearLayout l=prepInput(); doCommitSuicide=true; Button b=new Button(t); String word; switch (t.gen.nextInt(4)) { case 0: word="shadow"; break; case 1: word="figure"; break; case 2: word="vision"; break; case 3: word="monster"; break; default: word="creature"; } b.setText("Fight the "+word+" with your primary "+t.user.weapon); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th=new Thread(new Runnable() { @Override public void run() { runPits(number, (byte)3, input, (byte)0, hasAssaultedHQ); } }); t.th.start(); } }); l.addView(b); t.user.weapon.addSwapperTo(l, new Runnable() { @Override public void run() { runPits(number, stage, input, input2, hasAssaultedHQ); } }); b=new Button(t); b.setText(t.gen.nextBoolean() ? "Run away" : "Flee"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th=new Thread(new Runnable() { @Override public void run() { runPits(number, (byte)3, input, (byte)1, hasAssaultedHQ); } }); t.th.start(); } }); l.addView(b); } }; break; default: r=new Runnable() { @Override public void run() { LinearLayout l=prepInput("Your situation is unknown"); doCommitSuicide=true; Button b=new Button(t); b.setText("Try this again"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th=new Thread(new Runnable() { @Override public void run() { runPits(number, (byte)0, (byte)0, (byte)0, true); } }); t.th.start(); } }); l.addView(b); b=new Button(t); b.setText("Be done with it"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); t.th=new Thread(new Runnable() { @Override public void run() { t.user.commitSuicide(); } }); t.th.start(); } }); l.addView(b); } }; } t.fadeout(); t.runOnUiThread(r); break; case 3: // Stage 3: Results of combat switch (input) { case 0: switch (input2) { case 0: if (t.user.weapon.type==Cweapon.TYPE_ARCHERY && .5>(t.config.difficultyMult*.75*t.user.weapon.getAbsoluteStrength())) { archeryMinigame((int)Math.ceil(t.gen.nextInt(40)+(t.config.difficultyMult*10)+5), ((20*(1-t.config.difficultyMult))+5)/5); t.th=new Thread(new Runnable() { @Override public void run() { if (t.user.dead) { String title; switch (t.gen.nextInt(3)) { case 0: title="Archer"; break; case 1: title="Bowman"; break; case 2: title="Outnumbered"; break; default: title="Outdone by the dark"; } switch (t.gen.nextInt(3)) { case 0: t.say(title, "You turn to face the "+(t.gen.nextBoolean() ? "figures" : "shadows")+", but you\'re immediately killed by the leading shadow."); break; case 1: t.say(title, "You draw your "+t.user.weapon+", turning against the "+(t.gen.nextBoolean() ? "shadows" : "figures")+", shooting the leading one, and turning it to swirling smoke, but the others reach you before you can ready another shot."); break; case 2: t.say(title, "You quickly turn and fire an arrow at the lead "+(t.gen.nextBoolean() ? "shadow" : "vision")+", turning it into a cloud of smoke. Quickly, you dodge to the side of the remaining two attacks.\n\n\tYou ready and fire a second shot, eliminating another opponent, but the last defeats you."); break; default: Log.wtf("Cgame at House of Shadows", "Invalid return from Random.nextInt()"); t.say(title, "The enemies that stand before you overpower you."); } } else t.say("Veteran", "Despite the odds against you, your archery skills prevail in a tale that will be sung throughout time: You shoot the leading "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and dodge the attack of the next without pausing to watch the smoke swirl away.\n\n\tIn the blink of an eye, the second "+(t.gen.nextBoolean() ? "shadow" : "vision")+" recuperates, but you ready your "+t.user.weapon+" even faster, and shoot it too.\n\n\tThe third is upon you quickly, and you defend yourself by blocking with your "+t.user.weapon+", which gets tossed aside in the process.\n\n\n\tBefore the final "+(t.gen.nextBoolean() ? "shadow" : "creature")+" can "+(t.gen.nextBoolean() ? "attack" : "assault")+" you, you draw "+("crossbow".equalsIgnoreCase(t.user.weapon.name) ? "a bolt" : "an arrow")+" from your stockpile, and stab it.\n\n\tIt vanishes in a swirling cloud of smoke.\n\n\tYou note your spent ammunition has disappeared entirely.\n\n\n\tBrushing this fact aside, you turn your attention to the House of Shadows."); } }); t.th.start(); if (t.user.dead) prepContinueButton(); else prepContinueButton(new OnClickListener() { @Override public void onClick(View v) { t.th=new Thread(new Runnable() { @Override public void run() { runPits(number, (byte)4, input, input2, hasAssaultedHQ); } }); t.th.start(); } }); } else { boolean undead=false; switch (t.user.weapon.type) { case Cweapon.TYPE_SHARP: t.determineUserDeath((t.user.weapon.getUnneededFlags(Cweapon.CLOSE_RANGE_ONLY, 5)+(1-t.user.weapon.getNeededFlags(Cweapon.ACCURATE|Cweapon.CLOSE_RANGE|Cweapon.LIGHT|Cweapon.QUICK_RELOAD, 2)))*.99); r=new Runnable() { @Override public void run() { if (t.user.dead) { switch (t.gen.nextInt(3)) { case 0: t.say("Outnumbered and outdone", "You face the creatures with your "+t.user.weapon+", fending them away, but one gets past you long before you can strike any."); break; case 1: t.say("Death "+(t.gen.nextBoolean() ? "Unbounded" : "knows no bounds"), "You swing your sword at the leading "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and, miraculously, connect.\n\n\tThe lead shadow disappears in a swirl of smoke, and you turn to face the next, but you\'re caught from behind by the last."); break; case 2: t.say("The Darkness of Death", "You move quickly, as quickly as you ever have in your life.\n\n\tYou turn the leading shadow into a swirl of smoke, then the second.\n\nThe third, however, evades your swing, not letting it touch, and ends you."); break; default: Log.wtf("Cgame at House of Shadows", "Invalid result from Random.nextInt()"); t.say("Nonexistence", "You corrupt the state of the Universe and cease to exist."); } } else t.say(t.gen.nextBoolean() ? "Swordsman" : "Sword master", "You swing your sword as fast as humanly possible, turning one, then two, "+(t.gen.nextBoolean() ? "shadows" : "figures")+" into swirling smoke.\n\n\tThe last shadow charges toward you, but your sword nicks it, and it disappears.\n\n\tA booming voice, almost like Gandalf\'s, echoes from the clouds:\n\n\t\tWhy do you still carry that puny "+t.user.weapon+"??\n\t\tFind a new weapon.\n\t\tNow.\n\n\n\n\n\tYou turn your attention away from the voice, and to the House of Shadows."); } }; break; case Cweapon.TYPE_ARCHERY: t.determineUserDeath(.75*t.user.weapon.getAbsoluteStrength()); r=new Runnable() { @Override public void run() { if (t.user.dead) { String title; switch (t.gen.nextInt(4)) { case 0: title="Archer"; break; case 1: title="Bowman"; break; case 2: title="Outnumbered"; break; default: title="Outdone by the dark"; } switch (t.gen.nextInt(3)) { case 0: t.say(title, "You turn to face the shadows, but they easily defeat you before you get off a single shot."); break; case 1: t.say(title, "You spin to face your enemy, and fire a single "+("crossbow".equalsIgnoreCase(t.user.weapon.name) ? "bolt" : "arrow")+" at the leading "+(t.gen.nextBoolean() ? "shadow" : "apparition")+".\n\n\tYour aim "+(t.gen.nextBoolean() ? "is true" : (t.gen.nextBoolean() ? "is that of a master" : "is masterful"))+", turning the leader of the trio into a swirl of smoke.\n\n\tHowever, before you can ready yourself again, the other two eliminate you."); break; case 2: t.say(title, "You load one "+("crossbow".equalsIgnoreCase(t.user.weapon.name) ? "bolt" : "arrow")+", and thoughtlessly fire it at the lead "+(t.gen.nextBoolean() ? "shadow" : "figure")+".\n\n\tYou\'ve practiced your archery considerably, and the shot flies directly into its target.\n\n\tYou ignore the sight as your opponent disappears into a swirling cloud of shadowy smoke, and dodge the advance of your second adversary, which you shoot shortly afterwards.\n\n\n\tAlas, you lost track of the third shadow, which comes from behind you, and kills you."); break; default: Log.wtf("Cgame at the House of Shadows", "Invalid output from Random.nextInt()"); } } else t.say((t.config.GoTEggs && t.config.triggerEgg(.8)) ? "Lightbringer" : "Defeater of Shadows", "You turn, snappily aiming your "+t.user.weapon+" directly at the leading "+(t.gen.nextBoolean() ? "shadow" : "apparition")+", and shooting it.\n\n\tPaying it no attention as it disappears into swirling smoke.\n\n\tInstead, as if by instinct, you roll towards the House of Shadows."+(t.gen.nextBoolean() ? "" : "\n\n\tYou quickly recover from the pain of your miscalculation after you slam into the outer wall.")+"\n\n\tWithout taking the time to stand, you adjust your aim, directly at the second enemy.\n\n\tQuickly, you release your shot, sending "+("crossbow".equalsIgnoreCase(t.user.weapon.name) ? "a bolt" : "an arrow")+" flying into the second shape, then clattering to the ground as your opponent swirls away.\n\n\n\tThe third charges, but you pull one "+("crossbow".equalsIgnoreCase(t.user.weapon.name) ? "bolt" : "arrow")+" from your reserves, and drive it through your final adversary, noting the lack of resistance as it goes through.\n\n\tYou watch the remains of your opponent swirl away, and note your two fired shots have vanished."); } }; break; case Cweapon.TYPE_MODERN: final targetingMinigame.output res=aimMinigame(); undead=(res.type==targetingMinigame.output.BULLSEYE); final String title=res.toString(); r=new Runnable() { @Override public void run() { if (t.user.weapon.characteristicSet(Cweapon.AUTOMATIC)) { t.user.dead=(res.distance/(.8*targetingMinigame.output.MAX_DISTANCE))<((.5*(t.gen.nextDouble()+t.config.difficultyMult))+.5); if (t.user.dead) { switch (res.type) { case targetingMinigame.output.MISSED: t.say(title, "You fire a burst of bullets towards the shadows, but your aim is off, and the "+(t.gen.nextBoolean() ? "shadows" : "figures")+" end you."); break; case targetingMinigame.output.GRAZED: t.say(title, "You turn at the shadows, and fire a burst of automatic fire. One shot hits the nearest "+(t.gen.nextBoolean() ? "shadow" : "vision")+", turning it to a swirl of smoke, but the remaining two intercept you."); break; case targetingMinigame.output.POOR: t.say(title, "You fire at the shadows, grazing one, turning it to swirling smoke, and barely hitting another.\n\n\tThe last consumes you as the second disappears."); break; case targetingMinigame.output.HIT: t.say(title, "You fire at the shadows, hitting one with a solid shot, and "+(t.gen.nextBoolean() ? "turning" : "converting")+" it into a swirling cloud.\n\n\tAnother bullet strikes the second, eliminating it as well, but "+(t.user.weapon.characteristicSet(Cweapon.HIGH_RECOIL) ? "the recoil of your "+t.user.weapon+" throws off your aim." : "the last shadow moves out of your sights too quickly.")); break; case targetingMinigame.output.GOOD: t.say(title, "You hit two shadows with near perfect shots.\n\n\tThe shadows disappear into swirling smoke, as the third approaches you.\n\n\n\n\n\tYou quickly twist, aiming directly at the last shadow.\n\n\n\n\n\n\tYou pull the trigger, just as it reaches you."+(t.config.triggerEgg(.5) ? "\n\n\n\tThe shadow of a dragon looms over the pits, the rush of air stirring everything around, as you both become swirling smoke, and "+t.user.gold+", along with your "+t.user.weapon+", clatter to the ground." : "")); break; case targetingMinigame.output.CRITICAL: t.say(title, "You hit the first two shadows with perfect shots, but find that the third seems to have disappeared.\n\n\tYou twist and turn, searching for it, "+(t.config.triggerEgg(.75) ? "and feel a thud, and a weight.\n\n\tYou fall, watching the shadow run, and attempt to give chase.\n\n\tSoon, it leaves your sight. Contented, you enter the House of Shadows, grabbing the detonator, assuming that the charge is at it was.\n\n\n\n\tYou walk clear of the House, wondering why you feel as if there is a huge weight on your back.\n\n\n\tYou realize that the shadow planted the charge on your back a moment too late, as you trigger the explosive." : "and soon finding it, right behind you.\n\n\tYou dodge its lunge, dropping your "+t.user.weapon+" in your haste to "+(t.gen.nextBoolean() ? "escape" : "survive")+", and, just as you think you\'ve escaped, you trip, rolling down a hill, coming to a stop in a ditch full of a hundred shadows.")); break; case targetingMinigame.output.BULLSEYE: t.user.dead=false; t.say(title+", despite impossibility", "You fire three utterly perfect shots, cleanly converting two shadows into swirling smoke, and then you fire a hail of bullets into the third, ending it as well.\n\n\tDespite the incredibly difficult odds against you, you have prevailed."); break; default: t.say("Gunshot", "You are easily defeated by the shadows."); } } else { switch (res.type) { case targetingMinigame.output.MISSED: t.say(title, "You miss every shot in your magazine, yet manage to kill all three shadows by using your "+t.user.weapon+" as a club.\n\n\n\tFrom the clouds, a booming voice, almost like Gandalf\'s, echoes through the pits:\n\n\t\tGet better aim!!\n\t\tSeriously, go to target practice or something...\n\t\tThat was ridiculous.\n\n\n\n\n\n\tYou shake it off and turn your attention to the House of Shadows."); break; case targetingMinigame.output.GRAZED: t.say(title, "You fire at the enemies, full automatic fire, and yet the shadows keep managing to dodge your fire.\n\n\t"+(t.user.weapon.characteristicSet(Cweapon.HIGH_RECOIL) ? "You suspect that its because your "+t.user.weapon+" has too much recoil.\n\n\t" : "")+"Just as you begin to worry about the need to reload, one bullet grazes the leading shadow.\n\tSomehow, to your surprise, it disappears, turning into swirling smoke.\n\n\n\n\tThe remaining "+(t.gen.nextBoolean() ? "shadows" : "figures")+" mirror your surprise: They pause in shock.\n\n\tYou take advantage of their surprise to fire "+(t.gen.nextBoolean() ? "a trio" : "a hail")+" of "+(t.gen.nextBoolean() ? "rounds" : "bullets")+" at the second "+(t.gen.nextBoolean() ? "figure" : "shadow")+".\n\n\tIt disappears into a swirling cloud of smoke, and you continue firing, now at the last enemy, and barely manage to graze it.\n\n\n\tIgnoring what is now just a cloud of smoke, you turn on the House of Shadows."); break; case targetingMinigame.output.POOR: t.say(title, "You level the sights of your "+t.user.weapon+" directly at the leading "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and fire a "+(t.gen.nextBoolean() ? "hail" : "number")+" of rounds into it.\n\n\n\tIt "+(t.gen.nextBoolean() ? "becomes" : "disappears into")+" a swirling cloud of smoke, as you turn your attention to the second enemy.\n\n\tIt approaches "+(t.gen.nextBoolean() ? "menacingly" : "threateningly")+", but you "+(t.gen.nextBoolean() ? "are able" : "manage")+" to level your sights at it, and you squeeze the trigger, watching the bullets barely hit the "+(t.gen.nextBoolean() ? "shadow" : "figure")+".\n\n\tLuckily, it seems that any hit will "+(t.gen.nextBoolean() ? "dissolve" : "destroy")+" the shadow, and you watch as it disappears into a swirling cloud of smoke.\n\n\n\n\n\tUnfortunately, you seem to have lost track of the third...\n\n\n\n\tYou look left...\n\n\t...and right...\n\n\t...left...\n\n\t...and there it is!\n\n\n\n\tThe last "+(t.gen.nextBoolean() ? "shadow" : "figure")+" "+(t.gen.nextBoolean() ? "shows itself" : "appears")+" immediately just in front of you!\n\n\n\n\n\n\tYou hastily fire your "+t.user.weapon+", and turn it to smoke, barely surviving the encounter.\n\n\tYou shake yourself off, and turn to face the House of Shadows."); break; case targetingMinigame.output.HIT: t.say(title, "You aim your "+t.user.weapon+" directly at the leading enemy, and "+(t.gen.nextBoolean() ? "squeeze" : "pull")+" the trigger.\n\n\tA "+(t.gen.nextBoolean() ? "burst" : "number")+" of rounds fly directly at it, and strike it, turning it into a swirling cloud of smoke.\n\n\tYou quickly turn, and aim at the second "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and manage to send a hail of "+(t.gen.nextBoolean() ? "rounds" : "fire")+" flying directly at it.\n\n\n\tYou pause for a split second to watch as the "+(t.gen.nextBoolean() ? "apparition" : "shadow")+" dissolves into a cloud of smoke.\n\n\tThe final shadow seems to have disappeared.\n\n\t"+(t.gen.nextBoolean() ? "You" : "Your "+t.user.weapon)+" feels light, "+(t.user.weapon.characteristicSet(Cweapon.QUICK_RELOAD) ? "so you quickly switch cartridges." : "but you decide it would take too long to reload it.")+"\n\n\n\n\tYou return your attention to where it probably should be, the rather deadly "+(t.gen.nextBoolean() ? "shadow" : "apparition")+" that could reappear and kill you at any moment.\n\tSuddenly, it reappears: Right in front of you!\n\n\n\n\tYou quickly pull the trigger, firing several shots into the "+(t.gen.nextBoolean() ? "figure" : "shadow")+" before you.\n\n\n\tYou turn to oppose the House of Shadows as it disappears into a swirling cloud of smoke."); break; case targetingMinigame.output.GOOD: t.say(title, "You aim, and fire your "+t.user.weapon+" directly at the "+(t.gen.nextBoolean() ? "nearest" : (t.gen.nextBoolean() ? "closest" : "nearest"))+" "+(t.gen.nextBoolean() ? "shadow" : "figure")+", sending a hail of bullets flying directly at its core.\n\n\n\tThe first round out of your "+(t.gen.nextBoolean() ? "weapon" : t.user.weapon)+" hits it, turning it into a swirling cloud of smoke.\n\n\n\tYou quickly shift your aim, leveling your sights at the next target, and "+(t.gen.nextBoolean() ? "squeeze" : "pull")+" the trigger, scoring a solid hit, and turning the shadow into a swirling cloud of smoke.\n\n\n\tThe third shadow comes around to face you, and dodges your first burst.\n\n\n\tYou quickly adjust your aim, and "+(t.gen.nextBoolean() ? "squeeze" : "pull")+" the trigger, scoring another hit and ending the shadow.\n\n\n\tYou turn to face the House of Shadows as it turns to swirling smoke."); break; case targetingMinigame.output.CRITICAL: t.say(title, "You aim at the leading "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and fire a hail of rounds from your "+t.user.weapon+", scoring an extremely solid shot and dissolving it.\n\n\n\tAs it disappears into smoke, you adjust your aim, aiming for the next "+(t.gen.nextBoolean() ? "shadow" : "apparition")+", and fire a trio of bullets into its core, turning it into a swirling cloud of smoke.\n\n\n\n\tThe last shadow attempts to disappear, to catch you from behind, but you fire, and hit it precisely in its center of mass.\n\n\n\tAs it dissolves into swirling smoke, you turn to face the House of Shadows."); break; case targetingMinigame.output.BULLSEYE: t.say(title, "You level your "+t.user.weapon+" at the "+(t.gen.nextBoolean() ? "leading" : "nearest")+" "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and squeeze the trigger, sending a hail of bullets flying directly towards it, striking it perfectly between the two glowing spots that pass for eyes.\n\n\tAs it disappears into swirling smoke, you let off the trigger, and adjust your aim, ready to eliminate the second one.\n\n\n\n\tJust as it begins to approach you, you fire again, and a trio of bullets score a perfect hit on your target.\n\n\n\tIt disappears into smoke, and you aim directly at the last target.\n\n\tIt attempts to flee, but you don\'t allow it the chance: You "+(t.gen.nextBoolean() ? "squeeze" : "pull")+" the trigger, sending a single round into the "+(t.gen.nextBoolean() ? "shadow" : "figure")+", hitting its forehead dead-center, and converting it into a swirling cloud of smoke.\n\n\n\n\tYou turn to face the House of Shadows."); break; default: t.say("A "+t.user.weapon+" to a shadowfight", "You manage to defeat the shadows."); } } } else { t.user.dead=(res.distance/(.6*targetingMinigame.output.MAX_DISTANCE))<((.5*(t.gen.nextDouble()+t.config.difficultyMult))+.5); if (t.user.dead) { switch (res.type) { case targetingMinigame.output.MISSED: t.say(title, "You aim at the leading "+(t.gen.nextBoolean() ? "figure" : "shadow")+", and fire.\n\n\tYou miss.\n\tBadly.\n\n\t"+(t.config.triggerEgg(.5) ? ("Years from now, after the Fall of the Shadows, and after another explorer, perhaps even one called "+t.user+", has liberated the Great Familiar City, a small "+(t.gen.nextBoolean() ? "boy, and his" : "girl, and her")+" "+(t.gen.nextBoolean() ? "mother" : (t.config.triggerEgg(.2) ? "Big Daddy" : "father"))+" will come across the spot where you faced the shadows, and they will take all they find, your "+t.user.weapon+", home as a souvenir.") : (t.user.weapon.characteristicSet(Cweapon.BOLT_FIRE) ? "Before you can cycle the action, they are upon you." : "They take the chance to consume you."))); break; case targetingMinigame.output.GRAZED: t.say(title, "You level your "+t.user.weapon+" at the lead "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and squeeze the trigger.\n\n\n\tA single round flies into the side of it, and it vanishes from the slightest impact.\n\n\tIt would appear that the slightest impact will eliminate a shadow.\n\n\n\n\tYou level your weapon at the second shadow, but you have just enough time to notice that the third has disappeared from your sight when it appears behind you, and ends you."); break; case targetingMinigame.output.POOR: t.say(title, "You place the sights of your "+t.user.weapon+" at the leading "+(t.gen.nextBoolean() ? "apparition" : "shadow")+", and pull the trigger.\n\n\n\tAlmost as if by instinct, you find that you're adjusting your aim to fire at the second "+(t.gen.nextBoolean() ? "shadow" : "figure")+".\n\n\n\tAlas, your instinct is not as skilled as your hand, and your shot flies wide.\n\n\n\n\tYou try to readjust your aim, but the "+(t.gen.nextBoolean() ? "shadows" : "figures")+" are too fast."); break; case targetingMinigame.output.HIT: t.say(title, "You aim towards the leading shadow, and pull the trigger, sending a single round flying into it.\n\n\tThe shot scores a solid hit, and turns the "+(t.gen.nextBoolean() ? "shadow" : "figure")+" into a swirling cloud of smoke.\n\n\tWithout pausing to watch it, you adjust your aim, leveling your "+t.user.weapon+" at your second opponent.\n\n\tYou fire a shot, and barely nick it, turning it into smoke.\n\n\tThe last "+(t.gen.nextBoolean() ? "shadow" : "apparition")+" seems to have disappeared.\n\n\tYou look left..\n\t..and right..\n\n\n\n\t...left...\n\t...and right...\n\n\n\tCautiously, you turn to face the House of Shadows, only to find it in mid-air, flying directly towards you."); break; case targetingMinigame.output.GOOD: t.say(title, "You direct your "+t.user.weapon+" at the "+(t.gen.nextBoolean() ? "lead" : "first")+" "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and pull the trigger.\n\n\n\tA single round flies towards it, striking it right in the chest.\n\n\n\tAs it disappears into swirling smoke, you twist to aim at the second.\n\n\tJust as it lines up with your sight, you squeeze the trigger, and a "+(t.gen.nextBoolean() ? "single" : "solitary")+" round flies straight and true, "+(t.gen.nextBoolean() ? "hitting" : "striking")+" it right where its heart should be, and turning it to a swirling cloud of smoke.\n\n\n\tYou aim at the third, firing another round, but the "+(t.gen.nextBoolean() ? "shadow" : "apparition")+" manages to "+(t.gen.nextBoolean() ? "dodge" : "evade")+" your shot.\n\n\t"+(t.user.weapon.characteristicSet(Cweapon.ONE_ROUND_MAGAZINE) ? "Before you can switch magazines, " : "Before you can get off another round, ")+"it is upon you."); break; case targetingMinigame.output.CRITICAL: t.say(title, "You aim your "+t.user.weapon+" at the "+(t.gen.nextBoolean() ? "leading" : "primary")+" "+(t.gen.nextBoolean() ? "shadow" : "apparition")+", and fire.\n\n\n\tYour aim was true, and your round flies directly into its head, turning it into swirling smoke.\n\n\n\tThe second shadow "+(t.gen.nextBoolean() ? "tries" : "attempts")+" to "+(t.gen.nextBoolean() ? "dodge" : "evade")+" your shot, but you are too skilled a "+(t.gen.nextBoolean() ? "gunslinger" : "sharpshooter")+", and it vanishes into swirling smoke.\n\n\n\tYou turn yor attention to the third.\n\n\n\n\n\tIt seems to have disappeared.\n\n\tYou look left...\n\t...and right...\n\n\n\n\t...left...\n\t...and right...\n\n\n\n\n\t...Suddenly, its in front of you!\n\n\n\n\t"+(t.user.weapon.characteristicSet(Cweapon.CLOSE_RANGE) ? "You jump away, bringing your "+t.user.weapon+" to bear.\n\n\n\n\tYou manage to get off a shot just as it is upon you, turning the "+(t.gen.nextBoolean() ? "shadow" : "apparition")+" into swirling smoke, just as your life is prematurely ended by it.\n\n\n\n\t" : "You try to get off a shot with your "+t.user.weapon+", but you find that it is too cumbersome to be used effectively at close range, and the shadow consumes you.\n\n\t")+t.capitalize(t.user.gold.toString())+" and your "+t.user.weapon+" clatter to the ground."+(t.config.triggerEgg(.4) ? "\n\n\n\tSomeday, years after the Great Shadow War, and after the Great Familiar City has been conquered by the Army of the Second Coming, a Little Sister of the Rapture, along with her Big Daddy, will come across the remnants of the Pits, and all they will find of you is "+t.user.gold+" and your "+t.user.weapon+"." : "Somewhere in the distance, another adventurer approaches the Pits.")); break; case targetingMinigame.output.BULLSEYE: t.user.dead=false; t.say(title+" against the odds", "You level your "+t.user.weapon+" at the shadows.\n\n\n\n\tDespite the impossibility of the odds, you ready yourself to fight.\n\n\n\tIn quick succession, you fire a round at each shadow, adjusting your aim without pausing to see if your aim is true, hitting each shadow right where the bright spots that pass for their eyes are.\n\n\n\n\tDespite the impossibility of how outmatched you are by the shadows, you have emerged victorious."); break; default: t.say("Absorbed", "Your aim is out of this world!\n\n\n\tNo, seriously, that shot was... I don't even know.\n\n\n\tLet\'s just say this..."); } } else { switch (res.type) { case targetingMinigame.output.MISSED: t.say(title, "You fire one round at the "+(t.gen.nextBoolean() ? "nearest" : "leading")+" "+(t.gen.nextBoolean() ? "shadow" : "figure")+".\n\n\n\n\tYou miss."+(t.user.weapon.characteristicSet(Cweapon.ONE_ROUND_MAGAZINE) ? "You opt to forgo loading another shot, instead using your "+t.user.weapon+" as if it were a club." : "You aim again, and once more, you miss.\n\n\n\tThis process repeats itself over and over, until the "+(t.gen.nextBoolean() ? "shadows" : "apparitions")+" cease to worry about your shots, and instead process to laugh at you and your "+t.user.weapon+".\n\n\tAt that point, you decide it is better used as a club.")+"\n\n\n\tYou rush the shadows, striking one, and then proceeding to fight the others.\n\n\n\tMiraculously, it works.\n\n\n\tAs the "+(t.gen.nextBoolean() ? "last" : "final")+" "+(t.gen.nextBoolean() ? "shadow" : "figure")+" turns into swirling smoke, a voice, a great and majestic voice, echoes through the Pits:\n\n\n\n\t\tLearn to aim!!\n\t\tThat was awful!\n\t\tGo to the shooting range or something.\n\t\tNow!!\n\n\tIgnoring the voice, shaking off the fright, you turn to face the House of Shadows."); break; case targetingMinigame.output.GRAZED: t.say(title, "You level your "+t.user.weapon+" at the nearest "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and squeeze the trigger.\n\n\tThe round flies straight and true, flying towards its target.\n\tThe "+(t.gen.nextBoolean() ? "shadow" : "apparition")+", as if it had sensed that you were shooting at it, "+(t.gen.nextBoolean() ? "dodging" : "evading")+" the shot.\n\n\tUnfortunately, at least for it, the round barely grazes it.\n\n\n\n\tApparently, even such a small impact is plenty to end it, turning it into a swirling cloud of smoke.\n\n\n\tThe second pauses, if only for a split second, and you take the opportunity to aim at the second one.\n\n\tYour shot is imperfect, and the "+(t.gen.nextBoolean() ? "shadow" : "apparition")+" manages to "+(t.gen.nextBoolean() ? "evade" : "dodge")+" it.\n\n\n\tSwearing quietly, you "+(t.user.weapon.characteristicSet(Cweapon.BOLT_FIRE) ? "cycle the bolt on your "+t.user.weapon : "adjust your aim")+", firing again just in time to hit the second before it gets close.\n\n\n\n\tWithout pausing to watch it disappear into a cloud of smoke, you roll to the side, evading the lunge of the last "+(t.gen.nextBoolean() ? "shadow" : "figure")+".\n\n\tYou manage to bring your "+t.user.weapon+" to bear, and fire a single shot, managing to end it.\n\n\n\tShaking off your close encounter, you turn to face the House of Shadows."); break; case targetingMinigame.output.POOR: t.say(title, "You aim your "+t.user.weapon+" directly at the leading "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and fire.\n\n\n\tThe round flies at its target, hitting it off center, and turning it into a swirling cloud of smoke, as you adjust your aim to hit the second enemy.\n\n\n\tThe second "+(t.gen.nextBoolean() ? "figure" : "shadow")+" faces you as you "+(t.user.weapon.characteristicSet(Cweapon.BOLT_FIRE) ? "cycle the bolt on your"+t.user.weapon : "steady your aim")+", approaching as you do.\n\n\t"+(t.gen.nextBoolean() ? "Luckily" : "Fortunately")+", you\'re able to get off the shot before it gets close.\n\n\tThe round hits the "+(t.gen.nextBoolean() ? "shadow" : "apparition")+", barely, turning it into a swirling cloud of smoke.\n\n\tThe final shadow turns to flee, as you level your "+t.user.weapon+" directly at it.\n\n\n\tYou fire before it gets out of range or into cover, and the final shadow disappears into swirling smoke.\n\n\n\n\n\tSatisfied with your victory, you turn to face the House of Shadows."); break; case targetingMinigame.output.HIT: t.say(title, "You ready yourself, aiming directly at the closest "+(t.gen.nextBoolean() ? "shadow" : "apparition")+".\n\n\n\tYou quickly fire a shot, fully aware of the threat of the two remaining shadows, and watch only for a moment as the round flies through the air, and hits its mark.\n\n\n\tThe "+(t.gen.nextBoolean() ? "shadow" : "figure")+" turns into a swirling cloud of smoke, and you swing your "+t.user.weapon+" to fire at its lieutenant.\n\n\n\tYour enemy advances towards you, and you calmly "+(t.gen.nextBoolean() ? "squeeze" : "pull")+" the trigger.\n\n\n\tYour aim was near-perfect, but the "+(t.gen.nextBoolean() ? "figure" : "shadow")+" sees it coming, and moves to "+(t.gen.nextBoolean() ? "evade" : "dodge")+" it.\n\n\tThe shadow is not quite quick enough, and the round strikes it, turning it to smoke.\n\n\n\tThe final shadow seems to have disappeared, but you see a hint of motion in the corner of your eye, and, almost as if by instinct, turn to face it.\n\n\n\n\n\n\tThe shadow is charging at you, doing its best to end you and defend the House of Shadows, but you are too quick for it, deftly pulling the trigger, and turning the shadow into a cloud of smoke.\n\n\n\tAfter contently watching it swirl away, you turn to face the House of Shadows."); break; case targetingMinigame.output.GOOD: t.say(title, "You quickly survey the field before you, and the three shadows that are before you.\n\n\n\tYou adjust your aim, leveling your "+t.user.weapon+" at the "+(t.gen.nextBoolean() ? "nearest" : "leading")+" "+(t.gen.nextBoolean() ? "apparition" : "shadow")+", prepared to fire.\n\n\n\tAs the "+(t.gen.nextBoolean() ? "figures" : "shadows")+" begin to approach you, you grin ever-so-slightly, and "+(t.gen.nextBoolean() ? "squeeze" : "pull")+" the trigger.\n\n\n\tThe round glides smoothly towards its target, impacting it, and converting it into a swirling cloud of smoke.\n\n\n\tYou turn slightly, ready to fire at the next enemy, and "+(t.gen.nextBoolean() ? "adjust" : "calibrate")+" your aim.\n\n\n\n\tWhen your sights are in place, you fire, and turn the second "+(t.gen.nextBoolean() ? "enemy" : "apparition")+" into swirling smoke.\n\n\n\n\tYou frown slightly.\n\n\tYou could have sworn there where three, yet an empty battlefield and two kills seems to suggest otherwise.\n\n\n\tYou cautiously survey the area, then slowly start to move towards the House of Shadows.\n\n\n\tSuddenly, you see a dark smudge on the edge of your vision, and you turn to grab a better look.\n\n\n\tThe "+(t.gen.nextBoolean() ? "shadow" : "apparition")+", seeing that you found it, charges, as if it was hoping to eliminate you before you can do the same to it, but you fire, and it vanishes, replaced only by smoke."); break; case targetingMinigame.output.CRITICAL: t.say(title, "You stare down the three approaching "+(t.gen.nextBoolean() ? "shadows" : "figures")+", sizing up your opposition.\n\n\n\tThe moment they move to attack, you start to fire, cleanly eliminating your leading "+(t.gen.nextBoolean() ? "target" : "enemy")+", and adjust your aim, targeting the second.\n\n\tIt makes an attempt to flee, but you fire, hitting it in what passes as its head.\n\n\n\tThe last shadow attempts to dodge your line of sight, but you follow it, and eliminate it too.\n\n\n\n\n\tYou pause for only a second to watch the trio disappear into swirling smoke as it diffuses, then turn towards the House of Shadows."); break; case targetingMinigame.output.BULLSEYE: t.say(title, "You effortlessly fire a perfect shot at the "+(t.gen.nextBoolean() ? "nearest" : "leading")+"shadow, a single blast from your"+t.user.weapon+" turning it to smoke.\n\n\tThe remaining shadows hesitate, and thus, you get in a shot at the second "+(t.gen.nextBoolean() ? "figure" : "shadow")+", turning it as well into a swirling cloud of smoke.\n\n\n\tThe last one attempts to flee, but you allow it no such luxury.\n\n\n\n\tWith all three shadows dispatched, you turn to face the House of Shadows."); break; default: t.say("The brightness of a "+t.user.weapon, "In a long and drawn-out engagement, you and your "+t.user.weapon+" outshine the darkness of the shadows.\n\n\n\tFeeling invincible, you turn to face the House of Shadows."); } } } } }; break; case Cweapon.TYPE_NUCLEAR: t.user.dead=true; r=new Runnable() { @Override public void run() { t.say("A"+(t.gen.nextBoolean() ? " second" : "nother")+" sun", "You hit the detonator on your "+t.user.weapon+".\n\n\n\tA second fireball appears on the horizon, as the people stand in a familiar landscape, and watch you disappear.\n\n\n\tBehind them, the deadly, sickly glow illuminates a terrifying figure."); } }; break; case Cweapon.TYPE_FUTURE: r=new Runnable() { @Override public void run() { if (t.user.weapon.characteristicSet(Cweapon.CLOSE_RANGE_ONLY)) // CLOSE_RANGE_ONLY is the identifying flag for future weapons. If it's set, we're dealing with a lightsaber. Else, we (probably) have a raygun. These two get different dialogue. t.say("Sword of light", "You charge the "+(t.gen.nextBoolean() ? "figures" : "shadows")+", holding your "+t.user.weapon+" up on high.\n\n\n\tThe leading shadow, seemingly feeling courageous, steps toward you, but you counter its approach, dissolving it.\n\n\n\tThe other two "+(t.gen.nextBoolean() ? "shadows" : "apparitions")+" step away, deterred slightly by your charge, but not far enough.\n\n\n\n\n\tA lunge and a quick extension of the arm is enough to turn the shadow to ash almost akin to a hallucination.\n\n\tThe third shadow begins full flight, perhaps attempting to survive, perhaps attempting to draw you away from the House of Shadows.\n\tTo you, it doesn't matter: You chase it down, and eliminate it.\n\n\n\n\tHaving won a simple victory, you grin, and move towards the House of Shadows."); else t.say("The "+t.capitalize(t.user.weapon.name), "You aim your "+t.user.weapon+" directly at the leading "+t.user.weapon+", and pull the trigger.\n\n\n\tThe bolt of brilliant energy glides to its target, and hits it squarely.\n\n\n\tIt disappears into a mere wisp of smoke, leaving not a mere grain of ash.\n\n\n\n\tThe second and third shadows each seem afraid of you, and your "+t.user.weapon+", but you pay them no attention.\n\n\tYou place your sights in between the bright spots on the second "+(t.gen.nextBoolean() ? "apparition" : "figure")+", and pull the trigger.\n\n\n\tIt attempts to maneuver out of the way, but the bolt strikes it nonetheless, and it disappears as if it were never there.\n\n\n\tThe third turns to "+(t.gen.nextBoolean() ? "escape" : "run away")+", but your bolt outruns it by a factor of several million, and disintegrates it.\n\n\n\n\n\t"+(t.gen.nextBoolean() ? "Victorious" : "Feeling invincible")+", you turn towards the House of Shadows."); } }; break; default: t.user.dead=true; r=new Runnable() { @Override public void run() { t.say("Unknowable", "You suddenly find yourself unable to "+(t.gen.nextBoolean() ? "use" : (t.gen.nextBoolean() ? "grip" : "hold"))+" your "+t.user.weapon+"."); } }; } t.th=new Thread(r); t.th.start(); t.snooze(25); // We need a bit longer to insure processing finishes. if (t.user.dead && !undead) prepContinueButton(); else prepContinueButton(new OnClickListener() { @Override public void onClick(View v) { t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { runPits(number, (byte)4, input, input2, hasAssaultedHQ); } }); t.th.start(); } }); } break; case 1: t.th.interrupt(); Runnable r1; if (t.config.triggerEgg(.05)) { t.user.dead=false; r1=new Runnable() { @Override public void run() { t.say("Impossible", "You face the "+(t.gen.nextBoolean() ? "shadows" : "figures")+" for only a split second before turning, and sprinting for the House of Shadows.\n\n\tYou "+(t.gen.nextBoolean() ? "grab" : "snatch")+" the detonator from its resting place, glancing only for an instant at the cratering charge it controls.\n\n\n\n\tClosely followed by the shadows, you grimace, hoping your distance from the charge is sufficient.\n\n\n\n\n\n\tYou hit the detonator, and the charge goes off, destroying the House and the shadows with it.\n\n\tThe three shadows that had assaulted you are not alone in disappearing, as an invisible wave passes over the pits, turning each shadow it finds into swirling smoke.\n\n\tUnfortunately, you were not quite far enough from the charge, and it throws you up and away, towards the center of the Pits.\n\n\n\n\n\n\n\tIn the mere seconds of flight you get, you resign yourself to your fate of dying, and of never finding out what exists beyond the image of the familiar landscape.\n\n\tAs soon as you do, as if it had been waiting, a strange force slows you and gently redirects your path.\n\n\tYou land, safe but not intact, in the center of "+(t.gen.nextBoolean() ? "Hell." : "the Pits.")); } }; } else { t.user.dead=true; r1=new Runnable() { @Override public void run() { t.say("Foolhardy", "You quickly turn and sprint towards the House of Shadows.\n\n\n\tUnfortunately, the "+(t.gen.nextBoolean() ? "apparitions" : "shadows")+" sense your advance, and absorb you."); } }; } t.th.interrupt(); t.th=new Thread(r1); t.th.start(); if (t.user.dead) prepContinueButton(); else { prepContinueButton(new View.OnClickListener() { @Override public void onClick(View v) { t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { runPits((byte)0, stage, input, input2, true); } }); t.th.start(); } }); } break; case 2: t.user.dead=true; t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { t.say("Outdone", "You attempt to flee from the shadows. They give chase, herding you using their superior numbers.\n\n\tJust when you think you\'ve lost them, you trip on a well, or poorly, placed rock, and tumble down a hill.\n\n\n\n\tWhen you stop, you look at a black sky, only to realize that you\'re staring at a shadow."); } }); t.th.start(); prepContinueButton(); break; default: dataError(); } break; case 1: switch (input2) { case 0: if (t.user.weapon.type==Cweapon.TYPE_ARCHERY && .65>(t.config.difficultyMult*.75*t.user.weapon.getAbsoluteStrength())) { archeryMinigame((int)Math.ceil(t.gen.nextInt(40)+(t.config.difficultyMult*10)+5), ((20*(1-t.config.difficultyMult))+5)/5); t.th=new Thread(new Runnable() { @Override public void run() { if (t.user.dead) { String title; switch (t.gen.nextInt(3)) { case 0: title="Archer"; break; case 1: title="Bowman"; break; case 2: title="Shoplifter"; break; default: title="Outdone by the dark"; } if (t.user.weapon.characteristicSet(Cweapon.SLOW_RELOAD)) // Crossbow t.say(title, "You "+(t.gen.nextBoolean() ? "bring" : "swing")+" your "+t.user.weapon+" to bear, and fire it at your target.\n\n\tThe bolt flies straight and true, towards a point just slightly away from the "+(t.gen.nextBoolean() ? "shadow" : "being")+".\n\n\tYou quickly "+(t.gen.nextBoolean() ? "grab" : "snatch")+" another bolt, trying your best to load your weapon.\n\n\tJust when you\'re ready, you look up to find a pair of glowing eyes staring into your soul."); else t.say(title, "You immediately draw an arrow, bringing it to bear against your foe.\n\n\tUnfortunately, you miss.\n\tYou quickly "+(t.gen.nextBoolean() ? "draw" : "grab")+" another "+(t.gen.nextBoolean() ? "arrow" : "shot")+", and barely manage to draw your "+t.user.weapon+" before the "+(t.gen.nextBoolean() ? "shadow " : "figure ")+(t.gen.nextBoolean() ? "absorbs" : "ends")+" you."); } else t.say(t.gen.nextBoolean() ? "Shopkeeper" : "Veteran", "Your "+(t.gen.nextBoolean() ? "enemy" : "foe")+" charges at you, swaying to "+(t.gen.nextBoolean() ? "evade" : "avoid")+" your line of fire.\n\n\tUnfortunately, for it, you manage to follow its movements, and thusly "+(t.gen.nextBoolean() ? "end" : "kill")+" it, turning it into swirling smoke. You turn your gaze towards the now-cleared shop."); } }); t.th.start(); if (t.user.dead) prepContinueButton(); else prepContinueButton(new OnClickListener() { @Override public void onClick(View v) { t.th=new Thread(new Runnable() { @Override public void run() { runPits(number, (byte)4, input, input2, hasAssaultedHQ); } }); t.th.start(); } }); } else { boolean undead=false; switch (t.user.weapon.type) { case Cweapon.TYPE_SHARP: t.determineUserDeath((1-t.user.weapon.getNeededFlags(Cweapon.CLOSE_RANGE|Cweapon.LIGHT, 2))*.99); r=new Runnable() { @Override public void run() { if (t.user.dead) { if (t.gen.nextBoolean()) t.say("You swing your "+(t.gen.nextBoolean() ? "blade" : t.user.weapon)+", catching the "+(t.gen.nextBoolean() ? "shadow" : "figure")+" off guard."+t.multiplyString('\n', t.gen.nextInt(5)+2)+"\tUnfortunately, it manages to dance its way out of the way, and it ends you."); else t.say(t.gen.nextBoolean() ? "Newcomer" : "Novice", "You bring your "+t.user.weapon+" to bear, fumbling only slightly, then beginning to "+(t.gen.nextBoolean() ? "slash" : "stab")+" at the "+(t.gen.nextBoolean() ? "shadow" : "figure")+", but it evades you at every thrust."+t.multiplyString('\n', t.gen.nextInt(4)+2)+"\tFinally, after a number of mistakes, it outmaneuvers you."+t.multiplyString('\n', t.gen.nextInt(5)+2)+"\tThe last thought in your head before your "+(t.gen.nextBoolean() ? "time" : "existence")+" is ended, "+((t.config.litEggs && t.config.triggerEgg(.8)) ? ("if you had been allowed to give an utterance to the thoughts that were inspiring you, and they were prophetic, they would have been these:"+t.multiplyString('\n', 2+t.gen.nextInt(3))+"\t\t\"I see a great evil fall across a skyline, a city I thought I used to know.\n\t\t\"I see a man, old, bearded, watching in disappointment as the blots form on my name. I see him, foremost of judges and honored men, bringing another, all too much like me, to this place - Then fair to look upon, without a trace of this day\'s disfigurement - and I hear him tell my replacement my story, with a disappointed and somber voice.\n\t\t\"It is a far, far, sorrier thing that I do, than I have ever done; it is a far, far more dismaying rest that I go to than I have ever known.\""+t.multiplyString('\n', t.gen.nextInt(4)+2)+"\tUnfortunately for your memory, you failed to realize that this was not, in fact, \"A Tale of Two Shadows\".") /* Note that adding some gender-specific pronouns to that might not be the worst idea. */ : "is one of sadness: Sadness that you were never able to properly use your "+t.user.weapon+" well enough to defeat the Shadow in the Pits.")); } else t.say(t.gen.nextBoolean() ? "Swordsman" : "Sword master", "You swing your sword as fast as humanly possible, turning one, then two, "+(t.gen.nextBoolean() ? "shadows" : "figures")+" into swirling smoke.\n\n\tThe last shadow charges toward you, but your sword nicks it, and it disappears.\n\n\tA booming voice, almost like Gandalf\'s, echoes from the clouds:\n\n\t\tWhy do you still carry that puny "+t.user.weapon+"??\n\t\tFind a new weapon.\n\t\tNow.\n\n\n\n\n\tYou turn your attention away from the voice, and to the House of Shadows."); } }; break; case Cweapon.TYPE_ARCHERY: t.determineUserDeath(.75*t.user.weapon.getAbsoluteStrength()); r=new Runnable() { @Override public void run() { if (t.user.dead) { String title; switch (t.gen.nextInt(4)) { case 0: title="Archer"; break; case 1: title="Bowman"; break; case 2: title="Outnumbered"; break; default: title="Outdone by the dark"; } switch (t.gen.nextInt(3)) { case 0: t.say(title, "You turn to face the shadows, but they easily defeat you before you get off a single shot."); break; case 1: t.say(title, "You spin to face your enemy, and fire a single "+("crossbow".equalsIgnoreCase(t.user.weapon.name) ? "bolt" : "arrow")+" at the leading "+(t.gen.nextBoolean() ? "shadow" : "apparition")+".\n\n\tYour aim "+(t.gen.nextBoolean() ? "is true" : (t.gen.nextBoolean() ? "is that of a master" : "is masterful"))+", turning the leader of the trio into a swirl of smoke.\n\n\tHowever, before you can ready yourself again, the other two eliminate you."); break; case 2: t.say(title, "You load one "+("crossbow".equalsIgnoreCase(t.user.weapon.name) ? "bolt" : "arrow")+", and thoughtlessly fire it at the lead "+(t.gen.nextBoolean() ? "shadow" : "figure")+".\n\n\tYou\'ve practiced your archery considerably, and the shot flies directly into its target.\n\n\tYou ignore the sight as your opponent disappears into a swirling cloud of shadowy smoke, and dodge the advance of your second adversary, which you shoot shortly afterwards.\n\n\n\tAlas, you lost track of the third shadow, which comes from behind you, and kills you."); break; default: Log.wtf("Cgame at the House of Shadows", "Invalid output from Random.nextInt()"); } } else t.say((t.config.GoTEggs && t.config.triggerEgg(.8)) ? "Lightbringer" : "Defeater of Shadows", "You turn, snappily aiming your "+t.user.weapon+" directly at the leading "+(t.gen.nextBoolean() ? "shadow" : "apparition")+", and shooting it.\n\n\tPaying it no attention as it disappears into swirling smoke.\n\n\tInstead, as if by instinct, you roll towards the House of Shadows."+(t.gen.nextBoolean() ? "" : "\n\n\tYou quickly recover from the pain of your miscalculation after you slam into the outer wall.")+"\n\n\tWithout taking the time to stand, you adjust your aim, directly at the second enemy.\n\n\tQuickly, you release your shot, sending "+("crossbow".equalsIgnoreCase(t.user.weapon.name) ? "a bolt" : "an arrow")+" flying into the second shape, then clattering to the ground as your opponent swirls away.\n\n\n\tThe third charges, but you pull one "+("crossbow".equalsIgnoreCase(t.user.weapon.name) ? "bolt" : "arrow")+" from your reserves, and drive it through your final adversary, noting the lack of resistance as it goes through.\n\n\tYou watch the remains of your opponent swirl away, and note your two fired shots have vanished."); } }; break; case Cweapon.TYPE_MODERN: final targetingMinigame.output res=aimMinigame(); undead=(res.type==targetingMinigame.output.BULLSEYE); final String title=res.toString(); r=new Runnable() { @Override public void run() { if (t.user.weapon.characteristicSet(Cweapon.AUTOMATIC)) { t.user.dead=(res.distance/(.8*targetingMinigame.output.MAX_DISTANCE))<((.5*(t.gen.nextDouble()+t.config.difficultyMult))+.5); if (t.user.dead) { switch (res.type) { case targetingMinigame.output.MISSED: t.say(title, "You fire a burst of bullets towards the shadows, but your aim is off, and the "+(t.gen.nextBoolean() ? "shadows" : "figures")+" end you."); break; case targetingMinigame.output.GRAZED: t.say(title, "You turn at the shadows, and fire a burst of automatic fire. One shot hits the nearest "+(t.gen.nextBoolean() ? "shadow" : "vision")+", turning it to a swirl of smoke, but the remaining two intercept you."); break; case targetingMinigame.output.POOR: t.say(title, "You fire at the shadows, grazing one, turning it to swirling smoke, and barely hitting another.\n\n\tThe last consumes you as the second disappears."); break; case targetingMinigame.output.HIT: t.say(title, "You fire at the shadows, hitting one with a solid shot, and "+(t.gen.nextBoolean() ? "turning" : "converting")+" it into a swirling cloud.\n\n\tAnother bullet strikes the second, eliminating it as well, but "+(t.user.weapon.characteristicSet(Cweapon.HIGH_RECOIL) ? "the recoil of your "+t.user.weapon+" throws off your aim." : "the last shadow moves out of your sights too quickly.")); break; case targetingMinigame.output.GOOD: t.say(title, "You hit two shadows with near perfect shots.\n\n\tThe shadows disappear into swirling smoke, as the third approaches you.\n\n\n\n\n\tYou quickly twist, aiming directly at the last shadow.\n\n\n\n\n\n\tYou pull the trigger, just as it reaches you."+(t.config.triggerEgg(.5) ? "\n\n\n\tThe shadow of a dragon looms over the pits, the rush of air stirring everything around, as you both become swirling smoke, and "+t.user.gold+", along with your "+t.user.weapon+", clatter to the ground." : "")); break; case targetingMinigame.output.CRITICAL: t.say(title, "You hit the first two shadows with perfect shots, but find that the third seems to have disappeared.\n\n\tYou twist and turn, searching for it, "+(t.config.triggerEgg(.75) ? "and feel a thud, and a weight.\n\n\tYou fall, watching the shadow run, and attempt to give chase.\n\n\tSoon, it leaves your sight. Contented, you enter the House of Shadows, grabbing the detonator, assuming that the charge is at it was.\n\n\n\n\tYou walk clear of the House, wondering why you feel as if there is a huge weight on your back.\n\n\n\tYou realize that the shadow planted the charge on your back a moment too late, as you trigger the explosive." : "and soon finding it, right behind you.\n\n\tYou dodge its lunge, dropping your "+t.user.weapon+" in your haste to "+(t.gen.nextBoolean() ? "escape" : "survive")+", and, just as you think you\'ve escaped, you trip, rolling down a hill, coming to a stop in a ditch full of a hundred shadows.")); break; case targetingMinigame.output.BULLSEYE: t.user.dead=false; t.say(title+", despite impossibility", "You fire three utterly perfect shots, cleanly converting two shadows into swirling smoke, and then you fire a hail of bullets into the third, ending it as well.\n\n\tDespite the incredibly difficult odds against you, you have prevailed."); break; default: t.say("Gunshot", "You are easily defeated by the shadows."); } } else { switch (res.type) { case targetingMinigame.output.MISSED: t.say(title, "You miss every shot in your magazine, yet manage to kill all three shadows by using your "+t.user.weapon+" as a club.\n\n\n\tFrom the clouds, a booming voice, almost like Gandalf\'s, echoes through the pits:\n\n\t\tGet better aim!!\n\t\tSeriously, go to target practice or something...\n\t\tThat was ridiculous.\n\n\n\n\n\n\tYou shake it off and turn your attention to the House of Shadows."); break; case targetingMinigame.output.GRAZED: t.say(title, "You fire at the enemies, full automatic fire, and yet the shadows keep managing to dodge your fire.\n\n\t"+(t.user.weapon.characteristicSet(Cweapon.HIGH_RECOIL) ? "You suspect that its because your "+t.user.weapon+" has too much recoil.\n\n\t" : "")+"Just as you begin to worry about the need to reload, one bullet grazes the leading shadow.\n\tSomehow, to your surprise, it disappears, turning into swirling smoke.\n\n\n\n\tThe remaining "+(t.gen.nextBoolean() ? "shadows" : "figures")+" mirror your surprise: They pause in shock.\n\n\tYou take advantage of their surprise to fire "+(t.gen.nextBoolean() ? "a trio" : "a hail")+" of "+(t.gen.nextBoolean() ? "rounds" : "bullets")+" at the second "+(t.gen.nextBoolean() ? "figure" : "shadow")+".\n\n\tIt disappears into a swirling cloud of smoke, and you continue firing, now at the last enemy, and barely manage to graze it.\n\n\n\tIgnoring what is now just a cloud of smoke, you turn on the House of Shadows."); break; case targetingMinigame.output.POOR: t.say(title, "You level the sights of your "+t.user.weapon+" directly at the leading "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and fire a "+(t.gen.nextBoolean() ? "hail" : "number")+" of rounds into it.\n\n\n\tIt "+(t.gen.nextBoolean() ? "becomes" : "disappears into")+" a swirling cloud of smoke, as you turn your attention to the second enemy.\n\n\tIt approaches "+(t.gen.nextBoolean() ? "menacingly" : "threateningly")+", but you "+(t.gen.nextBoolean() ? "are able" : "manage")+" to level your sights at it, and you squeeze the trigger, watching the bullets barely hit the "+(t.gen.nextBoolean() ? "shadow" : "figure")+".\n\n\tLuckily, it seems that any hit will "+(t.gen.nextBoolean() ? "dissolve" : "destroy")+" the shadow, and you watch as it disappears into a swirling cloud of smoke.\n\n\n\n\n\tUnfortunately, you seem to have lost track of the third...\n\n\n\n\tYou look left...\n\n\t...and right...\n\n\t...left...\n\n\t...and there it is!\n\n\n\n\tThe last "+(t.gen.nextBoolean() ? "shadow" : "figure")+" "+(t.gen.nextBoolean() ? "shows itself" : "appears")+" immediately just in front of you!\n\n\n\n\n\n\tYou hastily fire your "+t.user.weapon+", and turn it to smoke, barely surviving the encounter.\n\n\tYou shake yourself off, and turn to face the House of Shadows."); break; case targetingMinigame.output.HIT: t.say(title, "You aim your "+t.user.weapon+" directly at the leading enemy, and "+(t.gen.nextBoolean() ? "squeeze" : "pull")+" the trigger.\n\n\tA "+(t.gen.nextBoolean() ? "burst" : "number")+" of rounds fly directly at it, and strike it, turning it into a swirling cloud of smoke.\n\n\tYou quickly turn, and aim at the second "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and manage to send a hail of "+(t.gen.nextBoolean() ? "rounds" : "fire")+" flying directly at it.\n\n\n\tYou pause for a split second to watch as the "+(t.gen.nextBoolean() ? "apparition" : "shadow")+" dissolves into a cloud of smoke.\n\n\tThe final shadow seems to have disappeared.\n\n\t"+(t.gen.nextBoolean() ? "You" : "Your "+t.user.weapon)+" feels light, "+(t.user.weapon.characteristicSet(Cweapon.QUICK_RELOAD) ? "so you quickly switch cartridges." : "but you decide it would take too long to reload it.")+"\n\n\n\n\tYou return your attention to where it probably should be, the rather deadly "+(t.gen.nextBoolean() ? "shadow" : "apparition")+" that could reappear and kill you at any moment.\n\tSuddenly, it reappears: Right in front of you!\n\n\n\n\tYou quickly pull the trigger, firing several shots into the "+(t.gen.nextBoolean() ? "figure" : "shadow")+" before you.\n\n\n\tYou turn to oppose the House of Shadows as it disappears into a swirling cloud of smoke."); break; case targetingMinigame.output.GOOD: t.say(title, "You aim, and fire your "+t.user.weapon+" directly at the "+(t.gen.nextBoolean() ? "nearest" : (t.gen.nextBoolean() ? "closest" : "nearest"))+" "+(t.gen.nextBoolean() ? "shadow" : "figure")+", sending a hail of bullets flying directly at its core.\n\n\n\tThe first round out of your "+(t.gen.nextBoolean() ? "weapon" : t.user.weapon)+" hits it, turning it into a swirling cloud of smoke.\n\n\n\tYou quickly shift your aim, leveling your sights at the next target, and "+(t.gen.nextBoolean() ? "squeeze" : "pull")+" the trigger, scoring a solid hit, and turning the shadow into a swirling cloud of smoke.\n\n\n\tThe third shadow comes around to face you, and dodges your first burst.\n\n\n\tYou quickly adjust your aim, and "+(t.gen.nextBoolean() ? "squeeze" : "pull")+" the trigger, scoring another hit and ending the shadow.\n\n\n\tYou turn to face the House of Shadows as it turns to swirling smoke."); break; case targetingMinigame.output.CRITICAL: t.say(title, "You aim at the leading "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and fire a hail of rounds from your "+t.user.weapon+", scoring an extremely solid shot and dissolving it.\n\n\n\tAs it disappears into smoke, you adjust your aim, aiming for the next "+(t.gen.nextBoolean() ? "shadow" : "apparition")+", and fire a trio of bullets into its core, turning it into a swirling cloud of smoke.\n\n\n\n\tThe last shadow attempts to disappear, to catch you from behind, but you fire, and hit it precisely in its center of mass.\n\n\n\tAs it dissolves into swirling smoke, you turn to face the House of Shadows."); break; case targetingMinigame.output.BULLSEYE: t.say(title, "You level your "+t.user.weapon+" at the "+(t.gen.nextBoolean() ? "leading" : "nearest")+" "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and squeeze the trigger, sending a hail of bullets flying directly towards it, striking it perfectly between the two glowing spots that pass for eyes.\n\n\tAs it disappears into swirling smoke, you let off the trigger, and adjust your aim, ready to eliminate the second one.\n\n\n\n\tJust as it begins to approach you, you fire again, and a trio of bullets score a perfect hit on your target.\n\n\n\tIt disappears into smoke, and you aim directly at the last target.\n\n\tIt attempts to flee, but you don\'t allow it the chance: You "+(t.gen.nextBoolean() ? "squeeze" : "pull")+" the trigger, sending a single round into the "+(t.gen.nextBoolean() ? "shadow" : "figure")+", hitting its forehead dead-center, and converting it into a swirling cloud of smoke.\n\n\n\n\tYou turn to face the House of Shadows."); break; default: t.say("A "+t.user.weapon+" to a shadowfight", "You manage to defeat the shadows."); } } } else { t.user.dead=(res.distance/(.6*targetingMinigame.output.MAX_DISTANCE))<((.5*(t.gen.nextDouble()+t.config.difficultyMult))+.5); if (t.user.dead) { switch (res.type) { case targetingMinigame.output.MISSED: t.say(title, "You aim at the leading "+(t.gen.nextBoolean() ? "figure" : "shadow")+", and fire.\n\n\tYou miss.\n\tBadly.\n\n\t"+(t.config.triggerEgg(.5) ? ("Years from now, after the Fall of the Shadows, and after another explorer, perhaps even one called "+t.user+", has liberated the Great Familiar City, a small "+(t.gen.nextBoolean() ? "boy, and his" : "girl, and her")+" "+(t.gen.nextBoolean() ? "mother" : (t.config.triggerEgg(.2) ? "Big Daddy" : "father"))+" will come across the spot where you faced the shadows, and they will take all they find, your "+t.user.weapon+", home as a souvenir.") : (t.user.weapon.characteristicSet(Cweapon.BOLT_FIRE) ? "Before you can cycle the action, they are upon you." : "They take the chance to consume you."))); break; case targetingMinigame.output.GRAZED: t.say(title, "You level your "+t.user.weapon+" at the lead "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and squeeze the trigger.\n\n\n\tA single round flies into the side of it, and it vanishes from the slightest impact.\n\n\tIt would appear that the slightest impact will eliminate a shadow.\n\n\n\n\tYou level your weapon at the second shadow, but you have just enough time to notice that the third has disappeared from your sight when it appears behind you, and ends you."); break; case targetingMinigame.output.POOR: t.say(title, "You place the sights of your "+t.user.weapon+" at the leading "+(t.gen.nextBoolean() ? "apparition" : "shadow")+", and pull the trigger.\n\n\n\tAlmost as if by instinct, you find that you're adjusting your aim to fire at the second "+(t.gen.nextBoolean() ? "shadow" : "figure")+".\n\n\n\tAlas, your instinct is not as skilled as your hand, and your shot flies wide.\n\n\n\n\tYou try to readjust your aim, but the "+(t.gen.nextBoolean() ? "shadows" : "figures")+" are too fast."); break; case targetingMinigame.output.HIT: t.say(title, "You aim towards the leading shadow, and pull the trigger, sending a single round flying into it.\n\n\tThe shot scores a solid hit, and turns the "+(t.gen.nextBoolean() ? "shadow" : "figure")+" into a swirling cloud of smoke.\n\n\tWithout pausing to watch it, you adjust your aim, leveling your "+t.user.weapon+" at your second opponent.\n\n\tYou fire a shot, and barely nick it, turning it into smoke.\n\n\tThe last "+(t.gen.nextBoolean() ? "shadow" : "apparition")+" seems to have disappeared.\n\n\tYou look left..\n\t..and right..\n\n\n\n\t...left...\n\t...and right...\n\n\n\tCautiously, you turn to face the House of Shadows, only to find it in mid-air, flying directly towards you."); break; case targetingMinigame.output.GOOD: t.say(title, "You direct your "+t.user.weapon+" at the "+(t.gen.nextBoolean() ? "lead" : "first")+" "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and pull the trigger.\n\n\n\tA single round flies towards it, striking it right in the chest.\n\n\n\tAs it disappears into swirling smoke, you twist to aim at the second.\n\n\tJust as it lines up with your sight, you squeeze the trigger, and a "+(t.gen.nextBoolean() ? "single" : "solitary")+" round flies straight and true, "+(t.gen.nextBoolean() ? "hitting" : "striking")+" it right where its heart should be, and turning it to a swirling cloud of smoke.\n\n\n\tYou aim at the third, firing another round, but the "+(t.gen.nextBoolean() ? "shadow" : "apparition")+" manages to "+(t.gen.nextBoolean() ? "dodge" : "evade")+" your shot.\n\n\t"+(t.user.weapon.characteristicSet(Cweapon.ONE_ROUND_MAGAZINE) ? "Before you can switch magazines, " : "Before you can get off another round, ")+"it is upon you."); break; case targetingMinigame.output.CRITICAL: t.say(title, "You aim your "+t.user.weapon+" at the "+(t.gen.nextBoolean() ? "leading" : "primary")+" "+(t.gen.nextBoolean() ? "shadow" : "apparition")+", and fire.\n\n\n\tYour aim was true, and your round flies directly into its head, turning it into swirling smoke.\n\n\n\tThe second shadow "+(t.gen.nextBoolean() ? "tries" : "attempts")+" to "+(t.gen.nextBoolean() ? "dodge" : "evade")+" your shot, but you are too skilled a "+(t.gen.nextBoolean() ? "gunslinger" : "sharpshooter")+", and it vanishes into swirling smoke.\n\n\n\tYou turn yor attention to the third.\n\n\n\n\n\tIt seems to have disappeared.\n\n\tYou look left...\n\t...and right...\n\n\n\n\t...left...\n\t...and right...\n\n\n\n\n\t...Suddenly, its in front of you!\n\n\n\n\t"+(t.user.weapon.characteristicSet(Cweapon.CLOSE_RANGE) ? "You jump away, bringing your "+t.user.weapon+" to bear.\n\n\n\n\tYou manage to get off a shot just as it is upon you, turning the "+(t.gen.nextBoolean() ? "shadow" : "apparition")+" into swirling smoke, just as your life is prematurely ended by it.\n\n\n\n\t" : "You try to get off a shot with your "+t.user.weapon+", but you find that it is too cumbersome to be used effectively at close range, and the shadow consumes you.\n\n\t")+t.capitalize(t.user.gold.toString())+" and your "+t.user.weapon+" clatter to the ground."+(t.config.triggerEgg(.4) ? "\n\n\n\tSomeday, years after the Great Shadow War, and after the Great Familiar City has been conquered by the Army of the Second Coming, a Little Sister of the Rapture, along with her Big Daddy, will come across the remnants of the Pits, and all they will find of you is "+t.user.gold+" and your "+t.user.weapon+"." : "Somewhere in the distance, another adventurer approaches the Pits.")); break; case targetingMinigame.output.BULLSEYE: t.user.dead=false; t.say(title+" against the odds", "You level your "+t.user.weapon+" at the shadows.\n\n\n\n\tDespite the impossibility of the odds, you ready yourself to fight.\n\n\n\tIn quick succession, you fire a round at each shadow, adjusting your aim without pausing to see if your aim is true, hitting each shadow right where the bright spots that pass for their eyes are.\n\n\n\n\tDespite the impossibility of how outmatched you are by the shadows, you have emerged victorious."); break; default: t.say("Absorbed", "Your aim is out of this world!\n\n\n\tNo, seriously, that shot was... I don't even know.\n\n\n\tLet\'s just say this..."); } } else { switch (res.type) { case targetingMinigame.output.MISSED: t.say(title, "You fire one round at the "+(t.gen.nextBoolean() ? "nearest" : "leading")+" "+(t.gen.nextBoolean() ? "shadow" : "figure")+".\n\n\n\n\tYou miss."+(t.user.weapon.characteristicSet(Cweapon.ONE_ROUND_MAGAZINE) ? "You opt to forgo loading another shot, instead using your "+t.user.weapon+" as if it were a club." : "You aim again, and once more, you miss.\n\n\n\tThis process repeats itself over and over, until the "+(t.gen.nextBoolean() ? "shadows" : "apparitions")+" cease to worry about your shots, and instead process to laugh at you and your "+t.user.weapon+".\n\n\tAt that point, you decide it is better used as a club.")+"\n\n\n\tYou rush the shadows, striking one, and then proceeding to fight the others.\n\n\n\tMiraculously, it works.\n\n\n\tAs the "+(t.gen.nextBoolean() ? "last" : "final")+" "+(t.gen.nextBoolean() ? "shadow" : "figure")+" turns into swirling smoke, a voice, a great and majestic voice, echoes through the Pits:\n\n\n\n\t\tLearn to aim!!\n\t\tThat was awful!\n\t\tGo to the shooting range or something.\n\t\tNow!!\n\n\tIgnoring the voice, shaking off the fright, you turn to face the House of Shadows."); break; case targetingMinigame.output.GRAZED: t.say(title, "You level your "+t.user.weapon+" at the nearest "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and squeeze the trigger.\n\n\tThe round flies straight and true, flying towards its target.\n\tThe "+(t.gen.nextBoolean() ? "shadow" : "apparition")+", as if it had sensed that you were shooting at it, "+(t.gen.nextBoolean() ? "dodging" : "evading")+" the shot.\n\n\tUnfortunately, at least for it, the round barely grazes it.\n\n\n\n\tApparently, even such a small impact is plenty to end it, turning it into a swirling cloud of smoke.\n\n\n\tThe second pauses, if only for a split second, and you take the opportunity to aim at the second one.\n\n\tYour shot is imperfect, and the "+(t.gen.nextBoolean() ? "shadow" : "apparition")+" manages to "+(t.gen.nextBoolean() ? "evade" : "dodge")+" it.\n\n\n\tSwearing quietly, you "+(t.user.weapon.characteristicSet(Cweapon.BOLT_FIRE) ? "cycle the bolt on your "+t.user.weapon : "adjust your aim")+", firing again just in time to hit the second before it gets close.\n\n\n\n\tWithout pausing to watch it disappear into a cloud of smoke, you roll to the side, evading the lunge of the last "+(t.gen.nextBoolean() ? "shadow" : "figure")+".\n\n\tYou manage to bring your "+t.user.weapon+" to bear, and fire a single shot, managing to end it.\n\n\n\tShaking off your close encounter, you turn to face the House of Shadows."); break; case targetingMinigame.output.POOR: t.say(title, "You aim your "+t.user.weapon+" directly at the leading "+(t.gen.nextBoolean() ? "shadow" : "figure")+", and fire.\n\n\n\tThe round flies at its target, hitting it off center, and turning it into a swirling cloud of smoke, as you adjust your aim to hit the second enemy.\n\n\n\tThe second "+(t.gen.nextBoolean() ? "figure" : "shadow")+" faces you as you "+(t.user.weapon.characteristicSet(Cweapon.BOLT_FIRE) ? "cycle the bolt on your"+t.user.weapon : "steady your aim")+", approaching as you do.\n\n\t"+(t.gen.nextBoolean() ? "Luckily" : "Fortunately")+", you\'re able to get off the shot before it gets close.\n\n\tThe round hits the "+(t.gen.nextBoolean() ? "shadow" : "apparition")+", barely, turning it into a swirling cloud of smoke.\n\n\tThe final shadow turns to flee, as you level your "+t.user.weapon+" directly at it.\n\n\n\tYou fire before it gets out of range or into cover, and the final shadow disappears into swirling smoke.\n\n\n\n\n\tSatisfied with your victory, you turn to face the House of Shadows."); break; case targetingMinigame.output.HIT: t.say(title, "You ready yourself, aiming directly at the closest "+(t.gen.nextBoolean() ? "shadow" : "apparition")+".\n\n\n\tYou quickly fire a shot, fully aware of the threat of the two remaining shadows, and watch only for a moment as the round flies through the air, and hits its mark.\n\n\n\tThe "+(t.gen.nextBoolean() ? "shadow" : "figure")+" turns into a swirling cloud of smoke, and you swing your "+t.user.weapon+" to fire at its lieutenant.\n\n\n\tYour enemy advances towards you, and you calmly "+(t.gen.nextBoolean() ? "squeeze" : "pull")+" the trigger.\n\n\n\tYour aim was near-perfect, but the "+(t.gen.nextBoolean() ? "figure" : "shadow")+" sees it coming, and moves to "+(t.gen.nextBoolean() ? "evade" : "dodge")+" it.\n\n\tThe shadow is not quite quick enough, and the round strikes it, turning it to smoke.\n\n\n\tThe final shadow seems to have disappeared, but you see a hint of motion in the corner of your eye, and, almost as if by instinct, turn to face it.\n\n\n\n\n\n\tThe shadow is charging at you, doing its best to end you and defend the House of Shadows, but you are too quick for it, deftly pulling the trigger, and turning the shadow into a cloud of smoke.\n\n\n\tAfter contently watching it swirl away, you turn to face the House of Shadows."); break; case targetingMinigame.output.GOOD: t.say(title, "You quickly survey the field before you, and the three shadows that are before you.\n\n\n\tYou adjust your aim, leveling your "+t.user.weapon+" at the "+(t.gen.nextBoolean() ? "nearest" : "leading")+" "+(t.gen.nextBoolean() ? "apparition" : "shadow")+", prepared to fire.\n\n\n\tAs the "+(t.gen.nextBoolean() ? "figures" : "shadows")+" begin to approach you, you grin ever-so-slightly, and "+(t.gen.nextBoolean() ? "squeeze" : "pull")+" the trigger.\n\n\n\tThe round glides smoothly towards its target, impacting it, and converting it into a swirling cloud of smoke.\n\n\n\tYou turn slightly, ready to fire at the next enemy, and "+(t.gen.nextBoolean() ? "adjust" : "calibrate")+" your aim.\n\n\n\n\tWhen your sights are in place, you fire, and turn the second "+(t.gen.nextBoolean() ? "enemy" : "apparition")+" into swirling smoke.\n\n\n\n\tYou frown slightly.\n\n\tYou could have sworn there where three, yet an empty battlefield and two kills seems to suggest otherwise.\n\n\n\tYou cautiously survey the area, then slowly start to move towards the House of Shadows.\n\n\n\tSuddenly, you see a dark smudge on the edge of your vision, and you turn to grab a better look.\n\n\n\tThe "+(t.gen.nextBoolean() ? "shadow" : "apparition")+", seeing that you found it, charges, as if it was hoping to eliminate you before you can do the same to it, but you fire, and it vanishes, replaced only by smoke."); break; case targetingMinigame.output.CRITICAL: t.say(title, "You stare down the three approaching "+(t.gen.nextBoolean() ? "shadows" : "figures")+", sizing up your opposition.\n\n\n\tThe moment they move to attack, you start to fire, cleanly eliminating your leading "+(t.gen.nextBoolean() ? "target" : "enemy")+", and adjust your aim, targeting the second.\n\n\tIt makes an attempt to flee, but you fire, hitting it in what passes as its head.\n\n\n\tThe last shadow attempts to dodge your line of sight, but you follow it, and eliminate it too.\n\n\n\n\n\tYou pause for only a second to watch the trio disappear into swirling smoke as it diffuses, then turn towards the House of Shadows."); break; case targetingMinigame.output.BULLSEYE: t.say(title, "You effortlessly fire a perfect shot at the "+(t.gen.nextBoolean() ? "nearest" : "leading")+"shadow, a single blast from your"+t.user.weapon+" turning it to smoke.\n\n\tThe remaining shadows hesitate, and thus, you get in a shot at the second "+(t.gen.nextBoolean() ? "figure" : "shadow")+", turning it as well into a swirling cloud of smoke.\n\n\n\tThe last one attempts to flee, but you allow it no such luxury.\n\n\n\n\tWith all three shadows dispatched, you turn to face the House of Shadows."); break; default: t.say("The brightness of a "+t.user.weapon, "In a long and drawn-out engagement, you and your "+t.user.weapon+" outshine the darkness of the shadows.\n\n\n\tFeeling invincible, you turn to face the House of Shadows."); } } } } }; break; case Cweapon.TYPE_NUCLEAR: t.user.dead=true; r=new Runnable() { @Override public void run() { t.say("A"+(t.gen.nextBoolean() ? " second" : "nother")+" sun", "You hit the detonator on your "+t.user.weapon+".\n\n\n\tA second fireball appears on the horizon, as the people stand in a familiar landscape, and watch you disappear.\n\n\n\tBehind them, the deadly, sickly glow illuminates a terrifying figure."); } }; break; case Cweapon.TYPE_FUTURE: r=new Runnable() { @Override public void run() { if (t.user.weapon.characteristicSet(Cweapon.CLOSE_RANGE_ONLY)) // CLOSE_RANGE_ONLY is the identifying flag for future weapons. If it's set, we're dealing with a lightsaber. Else, we (probably) have a raygun. These two get different dialogue. t.say("Sword of light", "You charge the "+(t.gen.nextBoolean() ? "figures" : "shadows")+", holding your "+t.user.weapon+" up on high.\n\n\n\tThe leading shadow, seemingly feeling courageous, steps toward you, but you counter its approach, dissolving it.\n\n\n\tThe other two "+(t.gen.nextBoolean() ? "shadows" : "apparitions")+" step away, deterred slightly by your charge, but not far enough.\n\n\n\n\n\tA lunge and a quick extension of the arm is enough to turn the shadow to ash almost akin to a hallucination.\n\n\tThe third shadow begins full flight, perhaps attempting to survive, perhaps attempting to draw you away from the House of Shadows.\n\tTo you, it doesn't matter: You chase it down, and eliminate it.\n\n\n\n\tHaving won a simple victory, you grin, and move towards the House of Shadows."); else t.say("The "+t.capitalize(t.user.weapon.name), "You aim your "+t.user.weapon+" directly at the leading "+t.user.weapon+", and pull the trigger.\n\n\n\tThe bolt of brilliant energy glides to its target, and hits it squarely.\n\n\n\tIt disappears into a mere wisp of smoke, leaving not a mere grain of ash.\n\n\n\n\tThe second and third shadows each seem afraid of you, and your "+t.user.weapon+", but you pay them no attention.\n\n\tYou place your sights in between the bright spots on the second "+(t.gen.nextBoolean() ? "apparition" : "figure")+", and pull the trigger.\n\n\n\tIt attempts to maneuver out of the way, but the bolt strikes it nonetheless, and it disappears as if it were never there.\n\n\n\tThe third turns to "+(t.gen.nextBoolean() ? "escape" : "run away")+", but your bolt outruns it by a factor of several million, and disintegrates it.\n\n\n\n\n\t"+(t.gen.nextBoolean() ? "Victorious" : "Feeling invincible")+", you turn towards the House of Shadows."); } }; break; default: t.user.dead=true; r=new Runnable() { @Override public void run() { t.say("Unknowable", "You suddenly find yourself unable to "+(t.gen.nextBoolean() ? "use" : (t.gen.nextBoolean() ? "grip" : "hold"))+" your "+t.user.weapon+"."); } }; } t.th=new Thread(r); t.th.start(); t.snooze(25); // We need a bit longer to insure processing finishes. if (t.user.dead && !undead) prepContinueButton(); else prepContinueButton(new OnClickListener() { @Override public void onClick(View v) { t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { runPits(number, (byte)4, input, input2, hasAssaultedHQ); } }); t.th.start(); } }); } break; case 1: t.th.interrupt(); Runnable r1; if (t.config.triggerEgg(.05)) { t.user.dead=false; r1=new Runnable() { @Override public void run() { t.say("Impossible", "You face the "+(t.gen.nextBoolean() ? "shadows" : "figures")+" for only a split second before turning, and sprinting for the House of Shadows.\n\n\tYou "+(t.gen.nextBoolean() ? "grab" : "snatch")+" the detonator from its resting place, glancing only for an instant at the cratering charge it controls.\n\n\n\n\tClosely followed by the shadows, you grimace, hoping your distance from the charge is sufficient.\n\n\n\n\n\n\tYou hit the detonator, and the charge goes off, destroying the House and the shadows with it.\n\n\tThe three shadows that had assaulted you are not alone in disappearing, as an invisible wave passes over the pits, turning each shadow it finds into swirling smoke.\n\n\tUnfortunately, you were not quite far enough from the charge, and it throws you up and away, towards the center of the Pits.\n\n\n\n\n\n\n\tIn the mere seconds of flight you get, you resign yourself to your fate of dying, and of never finding out what exists beyond the image of the familiar landscape.\n\n\tAs soon as you do, as if it had been waiting, a strange force slows you and gently redirects your path.\n\n\tYou land, safe but not intact, in the center of "+(t.gen.nextBoolean() ? "Hell." : "the Pits.")); } }; } else { t.user.dead=true; r1=new Runnable() { @Override public void run() { t.say("Foolhardy", "You quickly turn and sprint towards the House of Shadows.\n\n\n\tUnfortunately, the "+(t.gen.nextBoolean() ? "apparitions" : "shadows")+" sense your advance, and absorb you."); } }; } t.th.interrupt(); t.th=new Thread(r1); t.th.start(); if (t.user.dead) prepContinueButton(); else { prepContinueButton(new View.OnClickListener() { @Override public void onClick(View v) { t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { runPits((byte)0, stage, input, input2, true); } }); t.th.start(); } }); } break; case 2: t.user.dead=true; t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { t.say("Outdone", "You attempt to flee from the shadows. They give chase, herding you using their superior numbers.\n\n\tJust when you think you\'ve lost them, you trip on a well, or poorly, placed rock, and tumble down a hill.\n\n\n\n\tWhen you stop, you look at a black sky, only to realize that you\'re staring at a shadow."); } }); t.th.start(); prepContinueButton(); break; default: dataError(); } break; } break; } } } public void inputClear() { if (doCommitSuicide) t.user.commitSuicide(); else { stage-=2; runStage(); } } public void dataError() // Called when a switch goes to a default case, when this is nonsensical of course. { t.user.dead=true; t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { t.say(t.gen.nextBoolean() ? "Unknowable" : "Legend", "A vortex of Infinite Improbability opens, and consumes you.\n\n\n\n\n\n"); t.snooze(750+t.gen.nextInt(500)); Cgame.unSignalGameContinue(); t.snooze(2500); t.sayWhat("That means you have a bug.\n\n"); Cgame.unSignalGameContinue(); t.snooze(1500); t.sayWhat("Specifically, the game engine managed to set your state to one that makes negative amounts of sense.\n\n"); Cgame.unSignalGameContinue(); t.snooze(500); t.sayWhat("Look buddy, you got a kill-bug.\n\tJust play it again, hopefully the bug won\'t rear its ugly head."); } }); } public void prepContinueButton() { t.snooze(AnimationUtils.loadAnimation(t, R.anim.fadeout).getDuration()); while(t.waiting) t.frameTick(); t.delay(t.gen.nextInt(250)+250); t.runOnUiThread(new Runnable () { @Override public void run() { View v=t.findViewById(R.id.gameContinueButton); if (v!=null) { Button b=(Button)v; b.setOnClickListener(new View.OnClickListener() { @Override public void onClick (View v) { v.setOnClickListener(null); inputted=-1; t.th.interrupt(); t.displayHandler.removeMessages(1); t.th=new Thread (new Runnable () { @Override public void run () { t.displayHandler.removeMessages(1); if (t.user.dead) { stage=-1; t.config.computerPaused=true; } else t.config.computerPaused=false; runStage(); } }); t.th.start(); } }); b.setVisibility(View.VISIBLE); } else t.logError("prepContinueButton() called, but could not find button."); } }); } public void prepContinueButton(final View.OnClickListener onClick) { t.snooze(AnimationUtils.loadAnimation(t, R.anim.fadeout).getDuration()); while(t.waiting) t.frameTick(); t.delay(t.gen.nextInt(250)+250); t.runOnUiThread(new Runnable () { @Override public void run() { View v=t.findViewById(R.id.gameContinueButton); if (v!=null) { Button b=(Button)v; b.setOnClickListener(new View.OnClickListener() { @Override public void onClick (View v) { v.setOnClickListener(null); inputted=-1; t.th.interrupt(); t.displayHandler.removeMessages(1); onClick.onClick(v); } }); b.setVisibility(View.VISIBLE); } else t.logError("prepContinueButton() called, but could not find button."); } }); } private static LinearLayout prepInput() { t.setContentView(R.layout.input); t.currentView=R.id.inputLayout; t.setUi(); return (LinearLayout)t.findViewById(R.id.inputButtonBar); } private static LinearLayout prepInput(String inputTitle) { t.setContentView(R.layout.input); t.currentView=R.id.inputLayout; ((TextView)t.findViewById(R.id.inputTitle)).setText(inputTitle); t.setUi(); return (LinearLayout)t.findViewById(R.id.inputButtonBar); } private static void eatenByGrue() { t.user.dead=true; t.config.computerPaused=true; t.fadeout(); t.runOnUiThread(new Runnable() { @Override public void run() { t.setContentView(R.layout.grue); t.currentView=R.id.grueLayout; t.setUi(); if (t.config.triggerEgg(1, 3)) ((TextView)t.findViewById(R.id.grueContent)).setTextColor(Color.rgb(255, t.gen.nextInt(256), t.gen.nextInt(256))); } }); } public boolean onMove(double IBOdds) { t.user.gold.accrueInterest(); if (t.config.schoolEggs && t.config.triggerEgg(IBOdds)) { t.user.dead=!t.config.triggerEgg(99); t.th=new Thread(new Runnable() { @Override public void run() { if (t.user.dead) { String message="You black out, and wake up in an IB HL English classroom.\n\n\tAs you look around in confusion, the teacher says,\n\n\t\tEssay test today!\n\t\tHere\'s the book!\n\n\tAs the students prepare themselves for an essay test, and the teacher passes out their books, you decide you have no choice.\n\n\tYou close your eyes..."; if (t.user.weapon.type==Cweapon.TYPE_FUTURE) { if (t.user.weapon.characteristicSet(Cweapon.CLOSE_RANGE_ONLY)) // This is the identifying trait of the lightsaber. message+="\n\n\n\n\n\n\t...And draw your "+t.user.weapon+"!\n\n\tYou charge at the teacher, intending to fight your way out.\n\n\tAll of a sudden, a student blocks your path, hitting you, saying something about the teacher not yet having handed out the homework.\n\n\tAs you try to stop, your lightsaber slices cleanly through a girl next to you.\n\n\tShe collapses, dead.\n\n\tBefore you can react, "; else message+="\n\n\n\n\n\t...And draw your "+t.user.weapon+"!\n\n\tYou aim at the teacher, and tense.\n\n\n\tJust as you\'re ready to fire, a student hits you, yelling something about the homework needing explanation.\n\n\t"+(t.gen.nextBoolean() ? "She" : "He")+" throws off your balance, and your aim as well.\n\n\n\tYour shot strikes another student, turning "+(t.gen.nextBoolean() ? "him" : "her")+" into ash.\n\n\tSuddenly, "; message+="Gandalf appears.\n\n\tHe yells,\n\n\t\tHow dare you do this!\n\t\tYou are unworthy!!!\n\n\tWith that..."; } t.say("Baccalaureate", message); } else { String[] topics={ "differentiation", "integration", "the Fundamental Theorem of Calculus", "how to find volume via integrals", "Riemann sums", "limits", "relative rates", "Taylor polynomials", "series", "vectors", "proof by induction", "differential equations", "optimization" }; t.say("The Diploma", "You black out, and awake in an IB HL Math classroom.\n\n\tAs you look around in confusion, the teacher begins to teach "+topics[t.gen.nextInt(topics.length)]+".\n\n\tYou feel...\n\tMotivated, strangely enough.\n\n\n\n\tThrough hard work, perseverance, and worship of Lord 2-19, you get the IB diploma."); } } }); t.th.start(); prepContinueButton(t.user.dead ? new OnClickListener() { @Override public void onClick(View v) { t.th.interrupt(); t.th=new Thread(new Runnable() { @Override public void run() { if (t.user.weapon.type==Cweapon.TYPE_FUTURE) { t.user.weapon.type=Cweapon.TYPE_USED_FOR_CONVENIENCE; t.user.commitSuicide(); } else if (t.config.triggerEgg(.2)) t.user.commitSuicide(); else { stage=-1; runStage(); } } }); t.th.start(); } } : onWin); return true; } return false; } public boolean onMove (double IBNumerator, double IBDenominator) { return onMove(IBNumerator/IBDenominator); } public boolean onMove (int oneIn) { return onMove(1, oneIn); } public OnClickListener onWin=new OnClickListener() { @Override public void onClick(View v) { t.th.interrupt(); t.setContentView(R.layout.quit); t.currentView=R.id.quitLayout; t.setUi(); ((TextView)t.findViewById(R.id.quitTitle)).setText("You win!!"); ((Button)t.findViewById(R.id.quitContinueButton)).setText("Play again"); } }; private boolean archeryMinigame (final int threshold, final double time) // Reimplement this like KEYSEC. { final keypressMinigame game=new keypressMinigame((threshold/time)*.25); t.fadeout(); t.runOnUiThread(new Runnable() { @Override public void run() { t.setContentView(R.layout.archery); t.currentView=R.id.archeryLayout; t.setUi(); game.button=t.findViewById(R.id.archeryBullseye); ((TextView)t.findViewById(R.id.archeryThreshold)).setText(Integer.toString(threshold)); ((TextView)t.findViewById(R.id.archeryCurrent)).setText("0"); ((TextView)t.findViewById(R.id.archeryTiming)).setText(Long.toString((long)game.timeRemaining)); } }); if (t.snooze((long)((1000*game.timeRemaining)-((long)(1000*game.timeRemaining))))) return true; while (game.timeRemaining>=1) { if (t.snooze(1000)) return true; --game.timeRemaining; t.runOnUiThread(new Runnable() { @Override public void run() { ((TextView)t.findViewById(R.id.archeryTiming)).setText(Long.toString((long)game.timeRemaining)); } }); } game.timeRemaining=time; t.runOnUiThread(new Runnable() { @Override public void run() { Configuration c=t.getResources().getConfiguration(); boolean landscape=(c.orientation==Configuration.ORIENTATION_LANDSCAPE); // If we're in landscape mode, we need all the space we can get. t.findViewById(R.id.archeryWait).setVisibility(landscape || t.gen.nextBoolean() ? View.GONE : View.INVISIBLE); ((TextView)t.findViewById(R.id.archeryTimingLabel)).setText("Time ends in:"); ((TextView)t.findViewById(R.id.archeryTiming)).setText(Long.toString((long)game.timeRemaining)); game.button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { game.deltaX+=Math.copySign(Math.max(Math.abs(t.gen.nextGaussian()), t.gen.nextDouble()), game.deltaX); game.deltaY+=Math.copySign(Math.max(Math.abs(t.gen.nextGaussian()), t.gen.nextDouble()), game.deltaY); ++game.presses; ((TextView)t.findViewById(R.id.archeryCurrent)).setText(Integer.toString(game.presses)); } }); } }); Thread ticker=new Thread(new Runnable() { @Override public void run() { LinearLayout.LayoutParams lp=(LinearLayout.LayoutParams)game.button.getLayoutParams(); Runnable r=new Runnable() { @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) @Override public void run() { if (!(Build.VERSION.SDK_INT>=18 && game.button.isInLayout())) game.button.requestLayout(); } }; while (!game.done) { double factor=60.0/MainActivity.TARGET_FPS; int dX=(int)Math.round(game.deltaX*factor); int dY=(int)Math.round(game.deltaY*factor); if ((lp.leftMargin+dX)<0 || (lp.leftMargin+dX)>(t.findViewById(R.id.archeryBullseyeLayout).getWidth()-game.button.getWidth())) { game.deltaX*=-1; dX*=-1; } if ((lp.topMargin+dY)<0 || (lp.topMargin+dY)>(t.findViewById(R.id.archeryBullseyeLayout).getHeight()-game.button.getHeight())) { game.deltaY*=-1; dY*=-1; } lp.topMargin+=dY; lp.leftMargin+=dX; t.runOnUiThread(r); if (t.frameTick()) return; } } }); ticker.start(); t.snooze((long)(1000*(game.timeRemaining-Math.floor(game.timeRemaining)))); game.timeRemaining=Math.floor(game.timeRemaining); while (game.timeRemaining>=1) { t.snooze(1000); --game.timeRemaining; t.runOnUiThread(new Runnable() { @Override public void run() { ((TextView)t.findViewById(R.id.archeryTiming)).setText(Long.toString((long)game.timeRemaining)); } }); } game.done=true; t.user.dead=(game.presses<threshold); return t.user.dead; } public targetingMinigame.output aimMinigame() { final targetingMinigame game=new targetingMinigame(); t.fadeout(); t.runOnUiThread(new Runnable() { @Override public void run() { t.setContentView(R.layout.aimer); t.currentView=R.id.aimerLayout; game.crosshairs=t.findViewById(R.id.aimerCrosshairs); game.layout=t.findViewById(R.id.aimerBullseyeLayout); game.bullseye=t.findViewById(R.id.aimerBullseye); game.crosshairCoord=(RelativeLayout.LayoutParams)game.crosshairs.getLayoutParams(); ((TextView)t.findViewById(R.id.aimerTiming)).setText(Long.toString((long)Math.floor(game.timeRemaining))); Configuration c=t.getResources().getConfiguration(); if (c.orientation==Configuration.ORIENTATION_LANDSCAPE) game.layout.getLayoutParams().width=game.layout.getHeight(); } }); if (t.snooze((long)((1000*game.timeRemaining)-((long)(1000*game.timeRemaining))))) return new targetingMinigame.output(); game.timeRemaining=Math.floor(game.timeRemaining); while (game.timeRemaining>=1) { if (t.snooze(1000)) return new targetingMinigame.output(); --game.timeRemaining; t.runOnUiThread(new Runnable() { @Override public void run() { ((TextView)t.findViewById(R.id.aimerTiming)).setText(Long.toString((long)game.timeRemaining)); } }); } game.timeRemaining=t.gen.nextGaussian()+(t.config.difficultyMult*8)+5; t.runOnUiThread(new Runnable() { @Override public void run() { game.crosshairs.setVisibility(View.VISIBLE); ((TextView)t.findViewById(R.id.aimerTimingTitle)).setText("Time remaining:"); ((TextView)t.findViewById(R.id.aimerTiming)).setText(Long.toString((long)Math.floor(game.timeRemaining))); game.crosshairCoord.leftMargin=t.gen.nextInt(game.layout.getWidth()-game.crosshairs.getWidth()); game.crosshairCoord.topMargin=t.gen.nextInt(game.layout.getHeight()-game.crosshairs.getHeight()); t.findViewById(R.id.aimerUpArrow).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { double delta=Math.abs(t.gen.nextGaussian()+((t.gen.nextDouble()+game.deltaY))); if (game.crosshairCoord.topMargin<=delta) game.crosshairCoord.topMargin=0; else game.crosshairCoord.topMargin-=delta; } }); t.findViewById(R.id.aimerRightArrow).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { double delta=Math.abs(t.gen.nextGaussian()+((t.gen.nextDouble()+game.deltaX))); if (game.crosshairCoord.topMargin+delta+game.crosshairs.getHeight()>=game.layout.getHeight()) game.crosshairCoord.topMargin=game.layout.getHeight()-game.crosshairs.getHeight(); else game.crosshairCoord.leftMargin+=delta; } }); t.findViewById(R.id.aimerDownArrow).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { double delta=Math.abs(t.gen.nextGaussian()+((t.gen.nextDouble()+game.deltaY))); if (game.crosshairCoord.topMargin+delta+game.crosshairs.getHeight()>=game.layout.getHeight()) game.crosshairCoord.topMargin=game.layout.getHeight()-game.crosshairs.getHeight(); else game.crosshairCoord.topMargin+=delta; } }); t.findViewById(R.id.aimerLeftArrow).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { double delta=Math.abs(t.gen.nextGaussian()+((t.gen.nextDouble()+game.deltaX))); if (game.crosshairCoord.topMargin<=delta) game.crosshairCoord.topMargin=0; else game.crosshairCoord.leftMargin-=delta; } }); } }); game.startSway(); t.snooze((long)(1000*(game.timeRemaining-Math.floor(game.timeRemaining)))); game.timeRemaining=Math.floor(game.timeRemaining); while (game.timeRemaining>=1) { t.snooze(1000); --game.timeRemaining; t.runOnUiThread(new Runnable() { @Override public void run() { ((TextView)t.findViewById(R.id.aimerTiming)).setText(Long.toString((long)game.timeRemaining)); } }); } game.swayer.interrupt(); game.swayer=null; return game.result(); } @Override public int describeContents () { return 4; } @Override public void writeToParcel (Parcel out, int n) { out.writeInt(--stage); out.writeInt(line); out.writeInt(inputted); } public static final Parcelable.Creator<Cgame> CREATOR=new Parcelable.Creator<Cgame> () { @Override public Cgame createFromParcel (Parcel in) { return new Cgame(in); } @Override public Cgame[] newArray (int n) { return new Cgame[n]; } }; // Data-Only classes: NOT CONSERVED through onRestoreInstanceState() private static class keypressMinigame { public int presses; public double deltaX; public double deltaY; public double timeRemaining; public boolean done; public View button; public keypressMinigame() { presses=0; deltaX=t.gen.nextGaussian(); deltaY=t.gen.nextGaussian(); timeRemaining=t.gen.nextInt(3)+3+t.gen.nextGaussian(); done=false; } public keypressMinigame(double speedMult) { presses=0; deltaX=speedMult*t.gen.nextGaussian(); deltaY=speedMult*t.gen.nextGaussian(); timeRemaining=t.gen.nextInt(3)+3+t.gen.nextGaussian(); done=false; } } private static class targetingMinigame { public static class output // The type for returned data. { public double distance; // Distance from a true bullseye public int type; // The classification of this shot public output() { distance=-1; type=-1; MAX_DISTANCE=-1; } public static final int MISSED=6; public static final int GRAZED=5; public static final int POOR=4; public static final int HIT=3; public static final int GOOD=2; public static final int CRITICAL=1; public static final int BULLSEYE=0; public static double MAX_DISTANCE; public static String toString (int n) { switch (n) { case MISSED: return t.gen.nextBoolean() ? "Miss" : "Fail"; case GRAZED: return "Close"+(t.gen.nextBoolean() ? (" only counts in "+(t.config.triggerEgg(1, 3) ? "handshoes and horse grenades" : "horseshoes and hand grenades")) : ", but no cigar"); case POOR: return t.gen.nextBoolean() ? "Needs practice" : "Just barely"; case HIT: return "Solid "+(t.gen.nextBoolean() ? "shot" : "hit"); case GOOD: return "Good "+(t.gen.nextBoolean() ? "shot" : "hit"); case CRITICAL: String[] roots={ "Critical", "Excellent", "Great", "Incredible", "Sharpshooter\'s", "Master\'s", "Masterful" }; String[] suffixes={ "hit", "shot", "impact" }; return roots[t.gen.nextInt(roots.length)]+" "+suffixes[t.gen.nextInt(suffixes.length)]; case BULLSEYE: return t.gen.nextBoolean() ? "Bullseye" : "Perfect "+(t.gen.nextBoolean() ? "shot" : "aim"); default: return "Gunshot"; } } public static String toString(output o) { return o.toString(); } @Override public String toString() { return toString(type); } } public View crosshairs; public View bullseye; public View layout; RelativeLayout.LayoutParams crosshairCoord; public double weaponSwayMultiplier; public int weaponSwayMaximum; public double timeRemaining; public double deltaX; public double deltaY; public Thread swayer; public targetingMinigame() { weaponSwayMultiplier=.75+(.25*t.gen.nextGaussian()); weaponSwayMaximum=3+t.gen.nextInt(4); timeRemaining=t.gen.nextInt(3)+3+t.gen.nextGaussian(); deltaX=2*(t.gen.nextDouble()+t.gen.nextInt(21)+10); deltaY=2*(t.gen.nextDouble()+t.gen.nextInt(21)+10); } public void startSway() { if (swayer!=null) swayer.interrupt(); swayer=new Thread(new Runnable() // Improvement target { @Override public void run() { final Runnable r=new Runnable() { @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) @Override public void run() { if (!(Build.VERSION.SDK_INT>=18 && layout.isInLayout())) layout.requestLayout(); } }; double angle=t.gen.nextDouble()*2*Math.PI; while (!Thread.interrupted()) { double velocity=weaponSwayMultiplier*weaponSwayMaximum*Math.max(.25, t.gen.nextDouble())*(MainActivity.TARGET_FPS/60.0); if (0==t.gen.nextInt((int)(MainActivity.TARGET_FPS+1))) { angle+=Math.max(Math.PI/6, t.gen.nextDouble()*Math.PI)*(t.gen.nextBoolean() ? -1 : 1); velocity*=.5; } crosshairCoord.leftMargin=(int)Math.round(Math.max(0, Math.min(layout.getWidth()-crosshairs.getWidth(), crosshairCoord.leftMargin+(Math.cos(angle)*velocity)))); crosshairCoord.topMargin=(int)Math.round(Math.max(0, Math.min(layout.getHeight()-crosshairs.getHeight(), crosshairCoord.topMargin-(Math.sin(angle)*velocity)))); t.runOnUiThread(r); t.frameTick(1); } } }); swayer.start(); } public output result() { output out=new output(); RelativeLayout.LayoutParams bulls=(RelativeLayout.LayoutParams)bullseye.getLayoutParams(); RelativeLayout.LayoutParams cross=(RelativeLayout.LayoutParams)crosshairs.getLayoutParams(); double tmp=(bulls.leftMargin+(bullseye.getWidth()*.5))-(cross.leftMargin+(crosshairs.getWidth()*.5)); double num=(bulls.topMargin+(bullseye.getHeight()*.5))-(cross.topMargin+(crosshairs.getHeight()*.5)); out.distance=Math.sqrt((tmp*tmp)+(num*num)); output.MAX_DISTANCE=.5*bullseye.getWidth(); // out.type=(int)Math.ceil(out.distance/bullseye.getWidth()/12); // Mathematical way. Found to be buggy and disabled: If fixed, this will be more efficient. double diff=bullseye.getWidth()/10; if (out.distance==0) out.type=output.BULLSEYE; else if (out.distance<diff) out.type=output.CRITICAL; else if (out.distance<(2*diff)) out.type=output.GOOD; else if (out.distance<(3*diff)) out.type=output.HIT; else if (out.distance<(4*diff)) out.type=output.POOR; else if (out.distance<(5*diff)) out.type=output.GRAZED; else out.type=output.MISSED; return out; } } }
package minijava.visitor; import minijava.ast.AST; import minijava.ast.And; import minijava.ast.ArrayAssign; import minijava.ast.ArrayLength; import minijava.ast.ArrayLookup; import minijava.ast.Assign; import minijava.ast.Block; import minijava.ast.BooleanLiteral; import minijava.ast.BooleanType; import minijava.ast.Call; import minijava.ast.ClassDecl; import minijava.ast.Expression; import minijava.ast.IdentifierExp; import minijava.ast.If; import minijava.ast.IntArrayType; import minijava.ast.IntegerLiteral; import minijava.ast.IntegerType; import minijava.ast.LessThan; import minijava.ast.MainClass; import minijava.ast.MethodDecl; import minijava.ast.Minus; import minijava.ast.NewArray; import minijava.ast.NewObject; import minijava.ast.NodeList; import minijava.ast.Not; import minijava.ast.ObjectType; import minijava.ast.Plus; import minijava.ast.Print; import minijava.ast.Program; import minijava.ast.This; import minijava.ast.Times; import minijava.ast.Type; import minijava.ast.VarDecl; import minijava.ast.While; import minijava.typechecker.ErrorReport; import minijava.typechecker.implementation.ClassEntry; import minijava.typechecker.implementation.MethodEntry; import minijava.util.ImpTable; public class TypeCheckerVisitor extends ReflectionVisitor { ImpTable<ClassEntry> classTable; ErrorReport reporter; public TypeCheckerVisitor(ImpTable<ClassEntry> classTable, ErrorReport reporter) { this.classTable = classTable; this.reporter = reporter; } public <T extends AST> void visit(NodeList<T> nodeList) { for (int i = 0; i < nodeList.size(); i++) { visit(nodeList.elementAt(i)); } } public <T extends AST> void visit(NodeList<T> nodeList, ClassEntry entry) { for (int i = 0; i < nodeList.size(); i++) { visit(nodeList.elementAt(i), entry); } } public <T extends AST> void visit(NodeList<T> nodeList, MethodEntry entry) { for (int i = 0; i < nodeList.size(); i++) { visit(nodeList.elementAt(i), entry); } } public void visit(Program n) { visit(n.mainClass); visit(n.classes); } public void visit(MainClass n) { ClassEntry classEntry = classTable.lookup(n.className); if(classEntry == null) reporter.undefinedId(n.className); MethodEntry mainMethod = classEntry.lookupMethod("main"); visit(n.statement,mainMethod); } public void visit(ClassDecl n) { ClassEntry classEntry = classTable.lookup(n.name); if(classEntry == null) reporter.undefinedId(n.name); visit(n.vars, classEntry); visit(n.methods, classEntry); } public void visit(MethodDecl n, ClassEntry entry) { MethodEntry method = entry.getMethods().lookup(n.name); visit(n.vars, method); visit(n.statements, method); //must check return type after local vars to pass unit tests. visit(method.getReturnType()); Type returnedType = (Type) visit(n.returnExp, method); if (returnedType!=null) { // check here if the return type even exists visit(returnedType); if (! returnedType.equals(method.getReturnType())) { reporter.typeError(n.returnExp, method.getReturnType(), returnedType); } } else { reporter.typeError(n.returnExp, method.getReturnType(), returnedType); } for(Type t:method.getParamTypes()) visit(t); } public void visit(VarDecl var) { visit(var.type); } public Type visit(IdentifierExp idExp, MethodEntry method) { Type type = method.lookupVariable(idExp.name); if (type == null) { reporter.undefinedId(idExp.name); } return type; } public Type visit(IntegerLiteral exp, MethodEntry method) { return IntegerType.instance; } public Type visit(BooleanLiteral exp, MethodEntry method) { return BooleanType.instance; } public Type visit(Call exp, MethodEntry method) { //also need to check the params are the right types Type reciever = (Type) visit(exp.receiver,method);//this should resolve to an id (do we allow static methods?) if (reciever == null || reciever.getClass()!=ObjectType.class) { reporter.typeErrorExpectObjectType(exp, reciever); }else{ //check that this object actually has a corresponding method String className = ((ObjectType)reciever).name; ClassEntry classEntry = classTable.lookup(className); if(classEntry == null) reporter.undefinedId(className); else{ MethodEntry recMethod = classEntry.lookupMethod(exp.name); if(recMethod==null) reporter.undefinedId(exp.name); else{ NodeList<Expression> args = exp.rands; for(int i = 0;i<Math.min(args.size(), method.getParamTypes().size());i++) { Type expectedType = recMethod.getParamTypes().get(i); Expression e = args.elementAt(i); Type argType = (Type) visit(e,method); visit(argType); if(argType==null || ! argType.equals(expectedType)) { reporter.typeError(e, expectedType, argType); } } if(args.size()!=recMethod.getParamTypes().size()) reporter.wrongNumberOfArguments(exp, method.getParamTypes().size()); return recMethod.getReturnType(); } } } return null; } public void visit(If exp, MethodEntry method) { Type actualType = (Type) visit(exp.tst, method); if (actualType == null || !actualType.equals(BooleanType.instance)) { reporter.typeError(exp.tst, BooleanType.instance, actualType); } visit(exp.els, method); visit(exp.thn, method); } public void visit(While exp, MethodEntry method) { Type actualType = (Type) visit(exp.tst, method); if (actualType == null || !actualType.equals(BooleanType.instance)) { reporter.typeError(exp.tst, BooleanType.instance, actualType); } visit(exp.body, method); } public void visit(Block exp, MethodEntry method) { visit(exp.statements, method); } public Type visit(ArrayLength exp, MethodEntry method) { //array lengths are always integers. //So what we actually have to do here is check that the array expression contains an array Type type = (Type) visit(exp.array,method); if (type==null || ! type.equals(IntArrayType.instance)) { reporter.typeError(exp.array, IntArrayType.instance, type); } return IntegerType.instance; } public Type visit(Minus exp, MethodEntry method) { checkMathBinop(exp.e1,exp.e2,method); return IntegerType.instance; } public Type visit(Plus exp, MethodEntry method) { checkMathBinop(exp.e1,exp.e2,method); return IntegerType.instance; } public Type visit(Times exp, MethodEntry method) { checkMathBinop(exp.e1,exp.e2,method); return IntegerType.instance; } public Type visit(LessThan exp, MethodEntry method) { checkMathBinop(exp.e1,exp.e2,method); return BooleanType.instance; } public Type visit(And exp, MethodEntry method) { checkBooleanBinop(exp.e1,exp.e2,method); return BooleanType.instance; } public Type visit(Not exp, MethodEntry method) { Type type = (Type) visit(exp.e,method); if(type==null|| ! type.equals(BooleanType.instance)) { reporter.typeError(exp.e, BooleanType.instance, type); } return BooleanType.instance; } private void checkMathBinop(Expression left, Expression right, MethodEntry method) { Type typeLeft = (Type) visit(left,method); Type typeRight = (Type) visit(right,method); if(typeLeft==null|| ! typeLeft.equals(IntegerType.instance)) { reporter.typeError(left, IntegerType.instance, typeLeft); }else if(typeRight==null|| ! typeRight.equals(IntegerType.instance)) { reporter.typeError(right, IntegerType.instance, typeRight); } } private void checkBooleanBinop(Expression left, Expression right, MethodEntry method) { Type typeLeft = (Type) visit(left,method); Type typeRight = (Type) visit(right,method); if(typeLeft==null|| ! typeLeft.equals(BooleanType.instance)) { reporter.typeError(left, BooleanType.instance, typeLeft); }else if(typeRight==null|| ! typeRight.equals(BooleanType.instance)) { reporter.typeError(right, BooleanType.instance, typeRight); } } public Type visit(NewArray exp, MethodEntry method) { Type type = (Type) visit(exp.size,method); if(type==null|| ! type.equals(IntegerType.instance)) { reporter.typeError(exp.size, IntegerType.instance, type); } return IntArrayType.instance; } public Type visit(NewObject exp, MethodEntry method) { ClassEntry classEntry = classTable.lookup(exp.typeName); if(classEntry == null) { reporter.undefinedId(exp.typeName); } return new ObjectType(exp.typeName); } /** * This visitor is for instance field declarations * @param exp * @param method * @return */ public Type visit(VarDecl exp, ClassEntry method) { visit(exp.type); return exp.type; } public Type visit(VarDecl exp, MethodEntry method) { visit(exp.type); return exp.type; } public Type visit(ArrayAssign exp, MethodEntry method) { Type arrayType = method.lookupVariable(exp.name); if(arrayType==null) { reporter.undefinedId(exp.name); }else if (! arrayType.equals(IntArrayType.instance)) { //create an expression to pass to the error report. reporter.typeError(new IdentifierExp(exp.name), IntArrayType.instance, arrayType); } Type type = (Type) visit(exp.index,method); if(type==null|| ! type.equals(IntegerType.instance)) { reporter.typeError(exp.index, IntegerType.instance, type); } Type valType = (Type) visit(exp.value,method); if(valType==null|| ! valType.equals(IntegerType.instance)) { reporter.typeError(exp.value, IntegerType.instance, valType); } return IntegerType.instance; } public Type visit(ArrayLookup exp, MethodEntry method) { Type arrayType = (Type) visit(exp.array,method); if(arrayType==null|| ! arrayType.equals(IntArrayType.instance)) { reporter.typeError(exp.index, IntegerType.instance, arrayType); } Type type = (Type) visit(exp.index,method); if(type==null|| ! type.equals(IntegerType.instance)) { reporter.typeError(exp.index, IntegerType.instance, type); } return IntegerType.instance; } public void visit(Assign assign, MethodEntry method) { Type expectedType = method.lookupVariable(assign.name); Type actualType = (Type) visit(assign.value, method); if (expectedType == null) { reporter.undefinedId(assign.name); }else{ if(actualType==null) { reporter.typeError(assign.value, expectedType, actualType);//null is not correctly caught by the .equals method visit(assign.value, method); } else if (! expectedType.equals(actualType)) { reporter.typeError(assign.value, expectedType, actualType); } } //return expectedType; //Do assignments return values in minijava? } public void visit(Print exp, MethodEntry method) { //apparently, print is only allowed to print integer variables, not booleans Type type = (Type) visit(exp.exp,method); if(type == null || ! type.equals(IntegerType.instance)) reporter.typeError(exp.exp, IntegerType.instance, type); } public void visit(ObjectType type) { if (classTable.lookup(type.name) == null) { reporter.undefinedId(type.name); } } public void visit(IntegerType type) { } public void visit(BooleanType type) { } public void visit(IntArrayType type) { } public Type visit(This t, MethodEntry method) { return new ObjectType(method.getParent().getClassName()); } public Type visit(IntegerLiteral lit) { return new IntegerType(); } public Type visit(BooleanLiteral lit) { return new BooleanType(); } }
package com.tpb.hn.test; import android.content.Context; import android.os.Build; import android.os.Bundle; import android.support.annotation.Nullable; import android.text.Html; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.SeekBar; import android.widget.TextView; import com.tpb.hn.R; import com.tpb.hn.item.FragmentPagerAdapter; import com.tpb.hn.item.ItemViewActivity; import com.tpb.hn.item.views.spritzer.SpritzerTextView; import com.tpb.hn.storage.SharedPrefsController; import org.json.JSONException; import org.json.JSONObject; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.OnLongClick; import butterknife.OnTouch; import butterknife.Unbinder; public class Skimmer extends ContentFragment implements ItemLoader, Loader.TextLoader, FragmentPagerAdapter.FragmentCycleListener { private static final String TAG = Skimmer.class.getSimpleName(); private Unbinder unbinder; private ItemViewActivity mParent; @BindView(R.id.skimmer_text_view) SpritzerTextView mTextView; @BindView(R.id.skimmer_progress) SeekBar mSkimmerProgress; @BindView(R.id.skimmer_restart_button) Button mRestartButton; @BindView(R.id.skimmer_error_textview) TextView mErrorView; private Item mItem; private boolean mIsWaitingForAttach = false; private String mArticle; @Override View createView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { final View inflated = inflater.inflate(R.layout.fragment_skimmer, container, false); unbinder = ButterKnife.bind(this, inflated); mTextView.attachSeekBar(mSkimmerProgress); if(mContentReady) { setupSkimmer(); } else if(savedInstanceState != null) { if(savedInstanceState.getString("mArticle") != null) { mArticle = savedInstanceState.getString("mArticle"); setupSkimmer(); } } return inflated; } @OnLongClick(R.id.skimmer_touch_area) boolean onLongClick() { mTextView.play(); return false; } @OnTouch(R.id.skimmer_touch_area) boolean onTouch(MotionEvent motionEvent) { if(motionEvent.getAction() == MotionEvent.ACTION_UP) { mTextView.pause(); } return false; } @OnClick(R.id.skimmer_restart_button) void onRestartClick() { mTextView.setSpritzText(mArticle); mTextView.getSpritzer().start(); if(Build.VERSION.SDK_INT >= 24) { mSkimmerProgress.setProgress(0, true); } else { mSkimmerProgress.setProgress(0); } /* In order to skip one word, we have to wait for one minute / words per minute */ mTextView.postDelayed(new Runnable() { @Override public void run() { mTextView.getSpritzer().pause(); } }, 60000 / mTextView.getSpritzer().getWpm()); } @OnClick(R.id.skimmer_text_view) void onSpritzerClick() { mTextView.showTextDialog(); } @OnLongClick(R.id.skimmer_text_view) boolean onSpritzerLongClick() { mTextView.showWPMDialog(); return true; } private void displayErrorMessage() { mTextView.setVisibility(View.INVISIBLE); mSkimmerProgress.setVisibility(View.INVISIBLE); mRestartButton.setVisibility(View.INVISIBLE); mErrorView.setVisibility(View.VISIBLE); mErrorView.setText(R.string.error_parsing_readable_text); } private void setupSkimmer() { mTextView.setVisibility(View.VISIBLE); mSkimmerProgress.setVisibility(View.VISIBLE); mTextView.setWpm(SharedPrefsController.getInstance(getContext()).getSkimmerWPM()); mTextView.setSpritzText(mArticle); mTextView.pause(); } @Override void attach(Context context) { if(mIsWaitingForAttach) { Loader.getInstance(getContext()).loadArticle(mItem.getUrl(), true, this); } } @Override void bindData() { mArticle = Html.fromHtml(mArticle). toString(). replace("\n", " "); setupSkimmer(); } @Override public void onDestroyView() { super.onDestroyView(); unbinder.unbind(); } @Override public void onPauseFragment() { mTextView.pause(); } @Override public void onResumeFragment() { } @Override public boolean onBackPressed() { return true; } @Override public void loadItem(Item item) { mItem = item; if(item.getUrl() != null) { if(mContextReady) { Loader.getInstance(getContext()).loadArticle(item.getUrl(), true, this); } else { mIsWaitingForAttach = true; } } else { mArticle = item.getText() == null ? "" : Html.fromHtml(item.getText()).toString(); mContentReady = true; if(mViewsReady) bindData(); } } @Override public void textLoaded(JSONObject result) { try { mArticle = result.getString("content"); } catch(JSONException jse) { Log.e(TAG, "textLoaded: ", jse); displayErrorMessage(); } } @Override public void textError(String url, int code) { } }
package ph.pakete.model; import com.google.gson.annotations.SerializedName; import java.util.Date; import io.realm.RealmList; import io.realm.RealmObject; import io.realm.annotations.Ignore; import io.realm.annotations.PrimaryKey; public class Package extends RealmObject { @PrimaryKey @SerializedName("tracking_number") private String trackingNumber; private String name; @SerializedName("track_history") private RealmList<PackageTrackHistory> trackHistory = new RealmList<>(); private Courier courier; private Boolean completed = false; private Boolean archived = false; private Date createdAt = new Date(); @Ignore private Boolean updating = false; public String getTrackingNumber() { return trackingNumber; } public void setTrackingNumber(String trackingNumber) { this.trackingNumber = trackingNumber; } public String getName() { return name; } public void setName(String name) { this.name = name; } public RealmList<PackageTrackHistory> getTrackHistory() { return trackHistory; } public Courier getCourier() { return courier; } public void setCourier(Courier courier) { this.courier = courier; } public Boolean getCompleted() { return completed; } public void setCompleted(Boolean completed) { this.completed = completed; } public Boolean getArchived() { return archived; } public void setArchived(Boolean archived) { this.archived = archived; } public Boolean getUpdating() { return updating; } public void setUpdating(Boolean updating) { this.updating = updating; } public PackageTrackHistory latestTrackHistory() { if (getTrackHistory().size() > 0) { return getTrackHistory().first(); } else { return null; } } }
package com.dglogik.common; import android.app.Application; import android.support.multidex.MultiDex; import org.acra.ACRA; import org.acra.ReportingInteractionMode; import org.acra.annotation.ReportsCrashes; @ReportsCrashes( formKey = "", mode = ReportingInteractionMode.DIALOG, mailTo = "k.endfinger@dglogik.com" ) public class DGApplication extends Application { @Override public void onCreate() { super.onCreate(); // The following line triggers the initialization of ACRA ACRA.init(this); } @Override protected void attachBaseContext(Context base) { super.attachBaseContext(base); MultiDex.install(this); } }
package za.jay.blocks; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.RectF; import android.view.View; /** * A BlockView is a very simple View with a color value. That color is drawn as a rectangle centered * in the view that is either a 1/4 of the size of the View (in "unselected" mode) or fits the * entire view (in "selected" mode). */ public class BlockView extends View { public static enum PathDirection { LEFT, RIGHT, UP, DOWN } private Paint mPaint; private RectF mInnerRect; private Rect mSrcPathRect; private Rect mDestPathRect; private boolean mSelected; public BlockView(Context context) { super(context); init(); } private void init() { mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mPaint.setStyle(Paint.Style.FILL); mInnerRect = new RectF(); mSrcPathRect = new Rect(); mDestPathRect = new Rect(); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); resizeInnerRect(w, h); } private void resizeInnerRect(int w, int h) { int centerX = (int) (w / 2.0f); int centerY = (int) (h / 2.0f); int fifthW = Math.round(w / 5.0f); int fifthH = Math.round(h / 5.0f); mInnerRect.set(centerX - fifthW, centerY - fifthH, centerX + fifthW, centerY + fifthH); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawOval(mInnerRect, mPaint); if (mSelected) { canvas.drawRect(mSrcPathRect, mPaint); canvas.drawRect(mDestPathRect, mPaint); } } public void setColor(int color) { mPaint.setColor(color); postInvalidate(); } public int getColor() { return mPaint.getColor(); } /** Select the dot with a source incoming path (may be null) */ public void select(PathDirection src) { if (!mSelected) { shapePathRectangle(src, mSrcPathRect); mSelected = true; postInvalidate(); } else if (mSrcPathRect.isEmpty()) { shapePathRectangle(src, mSrcPathRect); postInvalidate(); } } /** Deselect the dot, removing any paths */ public void deselect() { if (mSelected) { mSrcPathRect.setEmpty(); mDestPathRect.setEmpty(); mSelected = false; postInvalidate(); } } /** Add a link to the next selected dot */ public void connectNext(PathDirection dest) { if (mSelected) { shapePathRectangle(dest, mDestPathRect); postInvalidate(); } } /** Remove the link to the next dot */ public void disconnectNext() { if (mSelected) { mDestPathRect.setEmpty(); postInvalidate(); } } /** Adjust 'rect' so that it is the path going in direction 'dir' */ private void shapePathRectangle(PathDirection dir, Rect rect) { if (dir == null) { return; } int width = getMeasuredWidth(); int height = getMeasuredHeight(); int centerX = (int) (width / 2.0f); int centerY = (int) (height / 2.0f); int halfPathWidth; switch (dir) { case LEFT: halfPathWidth = (int) (height / 20.0f); rect.set(0, centerY - halfPathWidth, centerX, centerY + halfPathWidth); break; case RIGHT: halfPathWidth = (int) (height / 20.0f); rect.set(centerX, centerY - halfPathWidth, width, centerY + halfPathWidth); break; case UP: halfPathWidth = (int) (width / 20.0f); rect.set(centerX - halfPathWidth, 0, centerX + halfPathWidth, centerY); break; case DOWN: halfPathWidth = (int) (width / 20.0f); rect.set(centerX - halfPathWidth, centerY, centerX + halfPathWidth, height); break; } } public boolean isSelected() { return mSelected; } }
import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.List; import java.util.Collection; import org.hamcrest.Matcher; import org.hamcrest.collection.IsIterableContainingInOrder; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertEquals; public class SchoolTest { private School school; @Before public void setUp() { school = new School(); } @Test public void startsWithNoStudents() { assertThat(school.numberOfStudents(), is(0)); } @Ignore("Remove to run test") @Test public void addsStudents() { school.add("Aimee", 2); assertThat(school.grade(2), hasItem("Aimee")); } @Ignore("Remove to run test") @Test public void addsMoreStudentsInSameGrade() { final int grade = 2; school.add("James", grade); school.add("Blair", grade); school.add("Paul", grade); assertThat(school.grade(grade).size(), is(3)); assertThat(school.grade(grade), allOf(hasItem("James"), hasItem("Blair"), hasItem("Paul"))); } @Ignore("Remove to run test") @Test public void addsStudentsInMultipleGrades() { school.add("Chelsea", 3); school.add("Logan", 7); assertThat(school.numberOfStudents(), is(2)); assertThat(school.grade(3).size(), is(1)); assertThat(school.grade(3), hasItem("Chelsea")); assertThat(school.grade(7).size(), is(1)); assertThat(school.grade(7), hasItem("Logan")); } @Ignore("Remove to run test") @Test public void getsStudentsInEmptyGrade() { assertTrue(school.grade(1).isEmpty()); } @Ignore("Remove to run test") @Test public void sortsSchool() { school.add("Kyle", 4); school.add("Zed", 4); school.add("Adam", 4); school.add("Jennifer", 4); school.add("Kareem", 6); school.add("Christopher", 4); school.add("Kylie", 3); Map<Integer, Matcher> sortedStudents = new HashMap<Integer, Matcher>(); sortedStudents.put(6, IsIterableContainingInOrder .contains("Kareem")); sortedStudents.put(4, IsIterableContainingInOrder .contains("Adam", "Christopher", "Jennifer", "Kyle", "Zed")); sortedStudents.put(3, IsIterableContainingInOrder .contains("Kylie")); Map schoolStudents = school.studentsByGradeAlphabetical(); for (Map.Entry<?, Matcher> entry : sortedStudents.entrySet()) { assertThat((Collection) schoolStudents.get(entry.getKey()), entry.getValue()); } } @Ignore("Remove to run test") @Test public void modifyingFetchedGradeShouldNotModifyInternalDatabase() { String shouldNotBeAdded = "Should not be added to school"; int grade = 1; Collection students = school.grade(grade); try { students.add(shouldNotBeAdded); } catch (Exception exception) { // Also valid that the add operation throws an exception // Such as UnsupportedOperationException when an umodifiable collection type is used } assertThat(school.grade(grade), not(hasItem(shouldNotBeAdded))); } @Ignore("Remove to run test") @Test public void modifyingSortedStudentsShouldNotModifyInternalDatabase() { int grade = 2; String studentWhichShouldNotBeAdded = "Should not be added"; List<String> listWhichShouldNotBeAdded = new ArrayList<>(); listWhichShouldNotBeAdded.add(studentWhichShouldNotBeAdded); Map sortedStudents = school.studentsByGradeAlphabetical(); try { sortedStudents.put(grade, listWhichShouldNotBeAdded); } catch (Exception exception) { // Also valid that the put operation throws an exception // Such as UnsupportedOperationException when an unmodifiableMap is used } assertThat(school.studentsByGradeAlphabetical().get(grade), not(hasItem(studentWhichShouldNotBeAdded))); } }
package org.commcare.tasks; import android.content.Context; import org.commcare.CommCareApplication; import org.commcare.core.interfaces.HttpResponseProcessor; import org.commcare.core.interfaces.ResponseStreamAccessor; import org.commcare.core.network.ModernHttpRequester; import org.commcare.modern.util.Pair; import org.commcare.network.AndroidModernHttpRequester; import org.commcare.tasks.templates.CommCareTask; import org.commcare.utils.AndroidCacheDirSetup; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.HashMap; /** * Makes get/post request and delegates http response to receiver on completion * * @author Phillip Mates (pmates@dimagi.com) */ public class SimpleHttpTask extends CommCareTask<Void, Void, Void, HttpResponseProcessor> implements HttpResponseProcessor, ResponseStreamAccessor { public static final int SIMPLE_HTTP_TASK_ID = 11; private final ModernHttpRequester requestor; private int responseCode; private InputStream responseDataStream; private IOException ioException; public SimpleHttpTask(Context context, URL url, HashMap<String, String> params, boolean isPostRequest, Pair<String, String> usernameAndPasswordToAuthWith) { taskId = SIMPLE_HTTP_TASK_ID; if (usernameAndPasswordToAuthWith != null) { // Means the the user for which we are submitting this request is not yet logged in requestor = new AndroidModernHttpRequester(new AndroidCacheDirSetup(context), url, params, usernameAndPasswordToAuthWith, isPostRequest); } else { // Means the the user for which we are submitting this request is already logged in requestor = CommCareApplication.instance().buildHttpRequesterForLoggedInUser(context, url, params, true, isPostRequest); } requestor.setResponseProcessor(this); } public void setResponseProcessor(HttpResponseProcessor responseProcessor) { requestor.setResponseProcessor(responseProcessor); } @Override protected Void doTaskBackground(Void... params) { requestor.request(); return null; } @Override protected void deliverResult(HttpResponseProcessor httpResponseProcessor, Void result) { if (ioException != null) { httpResponseProcessor.handleIOException(ioException); } else { // route to appropriate callback based on http response code ModernHttpRequester.processResponse( httpResponseProcessor, responseCode, this); } } @Override protected void deliverUpdate(HttpResponseProcessor httpResponseProcessor, Void... update) { } @Override protected void deliverError(HttpResponseProcessor httpResponseProcessor, Exception e) { } @Override public void processSuccess(int responseCode, InputStream responseData) { this.responseCode = responseCode; responseDataStream = responseData; } @Override public void processRedirection(int responseCode) { this.responseCode = responseCode; } @Override public void processClientError(int responseCode) { this.responseCode = responseCode; } @Override public void processServerError(int responseCode) { this.responseCode = responseCode; } @Override public void processOther(int responseCode) { this.responseCode = responseCode; } @Override public void handleIOException(IOException exception) { this.ioException = exception; } @Override public InputStream getResponseStream() throws IOException { return responseDataStream; } }
package com.matthewtamlin.spyglass.library.call_handler_annotations; import com.matthewtamlin.java_utilities.testing.Tested; import com.matthewtamlin.spyglass.library.call_handler_adapters.SpecificFlagHandlerAdapter; import com.matthewtamlin.spyglass.library.meta_annotations.CallHandler; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Declares a method capable of handling specific flag attributes. The method will only * be invoked if the Spyglass framework finds at least one of the specified flags mapped to the * specified attribute. This annotation should only be applied to methods which satisfy all of the * following criteria: * <ul> * <li>The method has no other handler annotations.</li> * <li>The method has no default annotation.</li> * <li>Every parameter has a use annotation.</li> * </ul> * Is it valid for a method with this annotation to have no parameters. */ @Tested(testMethod = "automated") @CallHandler(adapterClass = SpecificFlagHandlerAdapter.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface SpecificFlagHandler { /** * @return the resource ID of the handled attribute */ int attributeId(); /** * @return the specific flags handled by the method */ int handledFlags(); }
package com.matthewtamlin.spyglass.library.default_annotations; import com.matthewtamlin.java_utilities.testing.Tested; import com.matthewtamlin.spyglass.library.default_adapters.DefaultToBooleanResourceAdapter; import com.matthewtamlin.spyglass.library.meta_annotations.Default; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Defines a default for the annotated method, so that the Spyglass framework can invoke the * method if its handler annotation is not satisfied. This annotation should only be applied to * methods which satisfy all of the following criteria: * <ul> * <li>The method has a handler annotation.</li> * <li>The method has no other default annotations.</li> * <li>The method has at least one boolean parameter.</li> * <li>Except for one boolean parameter, every parameter has a use annotation.</li> * </ul> */ @Tested(testMethod = "automated") @Default(adapterClass = DefaultToBooleanResourceAdapter.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface DefaultToBooleanResource { /** * @return the resource ID of the default value, must resolve to a boolean resource */ int value(); }
package org.opencps.usermgt.scheduler; import org.opencps.usermgt.scheduler.utils.SchedulerUtilProcessing; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.component.annotations.Modified; import org.osgi.service.component.annotations.Reference; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.messaging.BaseSchedulerEntryMessageListener; import com.liferay.portal.kernel.messaging.DestinationNames; import com.liferay.portal.kernel.messaging.Message; import com.liferay.portal.kernel.module.framework.ModuleServiceLifecycle; import com.liferay.portal.kernel.scheduler.SchedulerEngineHelper; import com.liferay.portal.kernel.scheduler.TimeUnit; import com.liferay.portal.kernel.scheduler.TriggerFactory; import com.liferay.portal.kernel.scheduler.TriggerFactoryUtil; @Component(immediate = true, service = OneMinute.class) public class OneMinute extends BaseSchedulerEntryMessageListener { @Override protected void doReceive(Message message) { try { doProcessNotification(message); String[] notificationTypeList = { "USER-01", "USER-02", "USER-03", "USER-04" }; SchedulerUtilProcessing.notificationByType(notificationTypeList); } catch (Exception e) { // TODO: handle exception } } private void doProcessNotification(Message message) { // TODO Auto-generated method stub //_log.info("doProcessNotification: "); } @Activate @Modified protected void activate() { schedulerEntryImpl.setTrigger( TriggerFactoryUtil.createTrigger(getEventListenerClass(), getEventListenerClass(), 1, TimeUnit.MINUTE)); _schedulerEngineHelper.register(this, schedulerEntryImpl, DestinationNames.SCHEDULER_DISPATCH); } @Deactivate protected void deactivate() { _schedulerEngineHelper.unregister(this); } @Reference(target = ModuleServiceLifecycle.PORTAL_INITIALIZED, unbind = "-") protected void setModuleServiceLifecycle(ModuleServiceLifecycle moduleServiceLifecycle) { } @Reference(unbind = "-") protected void setSchedulerEngineHelper(SchedulerEngineHelper schedulerEngineHelper) { _schedulerEngineHelper = schedulerEngineHelper; } @Reference(unbind = "-") protected void setTriggerFactory(TriggerFactory triggerFactory) { } private SchedulerEngineHelper _schedulerEngineHelper; private Log _log = LogFactoryUtil.getLog(OneMinute.class); }
/* @java.file.header */ package org.gridgain.grid.kernal.processors.hadoop.jobtracker; import org.gridgain.grid.*; import org.gridgain.grid.cache.*; import org.gridgain.grid.cache.query.*; import org.gridgain.grid.hadoop.*; import org.gridgain.grid.kernal.processors.hadoop.*; import org.gridgain.grid.kernal.processors.hadoop.taskexecutor.*; import org.gridgain.grid.lang.*; import org.gridgain.grid.util.future.*; import org.gridgain.grid.util.typedef.*; import org.jdk8.backport.*; import org.jetbrains.annotations.*; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.*; import static org.gridgain.grid.hadoop.GridHadoopTaskType.COMBINE; import static org.gridgain.grid.kernal.processors.hadoop.jobtracker.GridHadoopJobPhase.*; /** * Hadoop job tracker. */ public class GridHadoopJobTracker extends GridHadoopComponent { /** System cache. */ private GridCacheProjection<GridHadoopJobId, GridHadoopJobMetadata> jobMetaPrj; /** Map-reduce execution planner. */ private GridHadoopMapReducePlanner mrPlanner; /** Locally active jobs. */ private ConcurrentMap<GridHadoopJobId, JobLocalState> activeJobs = new ConcurrentHashMap8<>(); /** Locally requested finish futures. */ private ConcurrentMap<GridHadoopJobId, GridFutureAdapter<GridHadoopJobId>> activeFinishFuts = new ConcurrentHashMap8<>(); /** {@inheritDoc} */ @Override public void onKernalStart() throws GridException { super.onKernalStart(); GridCache<Object, Object> sysCache = ctx.kernalContext().cache().cache(ctx.systemCacheName()); mrPlanner = ctx.planner(); jobMetaPrj = sysCache.projection(GridHadoopJobId.class, GridHadoopJobMetadata.class); GridCacheContinuousQuery<GridHadoopJobId, GridHadoopJobMetadata> qry = jobMetaPrj.queries() .createContinuousQuery(); qry.callback(new GridBiPredicate<UUID, Collection<Map.Entry<GridHadoopJobId, GridHadoopJobMetadata>>>() { @Override public boolean apply(UUID nodeId, Collection<Map.Entry<GridHadoopJobId, GridHadoopJobMetadata>> evts) { processJobMetadata(nodeId, evts); return true; } }); qry.execute(); } /** * Submits execution of Hadoop job to grid. * * @param jobId Job ID. * @param info Job info. * @return Job completion future. */ public GridFuture<GridHadoopJobId> submit(GridHadoopJobId jobId, GridHadoopJobInfo info) { try { GridHadoopJob job = ctx.jobFactory().createJob(jobId, info); Collection<GridHadoopFileBlock> blocks = job.input(); GridHadoopMapReducePlan mrPlan = mrPlanner.preparePlan(blocks, ctx.nodes(), job, null); GridHadoopJobMetadata meta = new GridHadoopJobMetadata(jobId, info); meta.mapReducePlan(mrPlan); meta.pendingBlocks(allBlocks(mrPlan)); meta.pendingReducers(allReducers(job)); GridFutureAdapter<GridHadoopJobId> completeFut = new GridFutureAdapter<>(); GridFutureAdapter<GridHadoopJobId> old = activeFinishFuts.put(jobId, completeFut); assert old == null : "Duplicate completion future [jobId=" + jobId + ", old=" + old + ']'; if (log.isDebugEnabled()) log.debug("Submitting job metadata [jobId=" + jobId + ", meta=" + meta + ']'); jobMetaPrj.put(jobId, meta); return completeFut; } catch (GridException e) { return new GridFinishedFutureEx<>(e); } } /** * Gets hadoop job status for given job ID. * * @param jobId Job ID to get status for. * @return Job status for given job ID or {@code null} if job was not found. */ @Nullable public GridHadoopJobStatus status(GridHadoopJobId jobId) throws GridException { GridHadoopJobMetadata meta = jobMetaPrj.get(jobId); if (meta == null) return null; if (log.isDebugEnabled()) log.debug("Got job metadata for status check [locNodeId=" + ctx.localNodeId() + ", meta=" + meta + ']'); GridHadoopJobInfo info = meta.jobInfo(); if (meta.phase() == PHASE_COMPLETE) { if (log.isDebugEnabled()) log.debug("Job is complete, returning finished future: " + jobId); return new GridHadoopJobStatus(new GridFinishedFutureEx<>(jobId), info); } GridFutureAdapter<GridHadoopJobId> fut = F.addIfAbsent(activeFinishFuts, jobId, new GridFutureAdapter<GridHadoopJobId>()); // Get meta from cache one more time to close the window. meta = jobMetaPrj.get(jobId); if (log.isDebugEnabled()) log.debug("Re-checking job metadata [locNodeId=" + ctx.localNodeId() + ", meta=" + meta + ']'); if (meta == null || meta.phase() == PHASE_COMPLETE) { // TODO exception. fut.onDone(jobId); activeFinishFuts.remove(jobId , fut); } return new GridHadoopJobStatus(fut, info); } /** * Gets job info for running Hadoop map-reduce task by job ID. * * @param jobId Job ID to get job info for. * @return Job info or {@code null} if no information found for this job ID. * @throws GridException If cache lookup for this job ID failed. */ @Nullable public GridHadoopJobInfo jobInfo(GridHadoopJobId jobId) throws GridException { JobLocalState state = activeJobs.get(jobId); if (state != null) return state.job.info(); GridHadoopJobMetadata meta = jobMetaPrj.get(jobId); if (meta != null) return meta.jobInfo(); return null; } /** * Callback from task executor invoked when a task has been finished. * * @param taskInfo Task info. * @param status Task status. */ public void onTaskFinished(GridHadoopTaskInfo taskInfo, GridHadoopTaskStatus status) { if (log.isDebugEnabled()) log.debug("Received task finished callback [taskInfo=" + taskInfo + ", status=" + status + ']'); JobLocalState state = activeJobs.get(taskInfo.jobId()); assert state != null; switch (taskInfo.type()) { case MAP: { state.onMapFinished(taskInfo, status); break; } case REDUCE: { state.onReduceFinished(taskInfo, status); break; } case COMBINE: { state.onCombineFinished(taskInfo, status); break; } } } /** * @param blocks Blocks to init nodes for. */ private void initBlockNodes(Collection<GridHadoopFileBlock> blocks) { } /** * Gets all file blocks for given hadoop map-reduce plan. * * @param plan Map-reduce plan. * @return Collection of all file blocks that should be processed. */ private Collection<GridHadoopFileBlock> allBlocks(GridHadoopMapReducePlan plan) { Collection<GridHadoopFileBlock> res = new HashSet<>(); for (UUID nodeId : plan.mapperNodeIds()) res.addAll(plan.mappers(nodeId)); return res; } /** * Gets all reducers for this job. * * @param job Job to get reducers for. * @return Collection of reducers. */ private Collection<Integer> allReducers(GridHadoopJob job) { Collection<Integer> res = new HashSet<>(); for (int i = 0; i < job.reducers(); i++) res.add(i); return res; } /** * @param origNodeId Originating node ID. * @param updated Updated cache entries. */ private void processJobMetadata(UUID origNodeId, Iterable<Map.Entry<GridHadoopJobId, GridHadoopJobMetadata>> updated) { UUID locNodeId = ctx.localNodeId(); for (Map.Entry<GridHadoopJobId, GridHadoopJobMetadata> entry : updated) { GridHadoopJobId jobId = entry.getKey(); GridHadoopJobMetadata meta = entry.getValue(); if (log.isDebugEnabled()) log.debug("Processing job metadata update callback [locNodeId=" + locNodeId + ", meta=" + meta + ']'); JobLocalState state = activeJobs.get(jobId); GridHadoopJob job = ctx.jobFactory().createJob(jobId, meta.jobInfo()); switch (meta.phase()) { case PHASE_MAP: { // Check if we should initiate new task on local node. Collection<GridHadoopFileBlock> mappers = meta.mapReducePlan().mappers(locNodeId); if (mappers != null) { if (state == null) state = initState(meta); Collection<GridHadoopTask> tasks = null; for (GridHadoopFileBlock block : mappers) { int attempt = meta.attempt(block); if (state.addMapper(attempt, block)) { if (log.isDebugEnabled()) log.debug("Submitting MAP task for execution [locNodeId=" + locNodeId + ", block=" + block + ']'); // TODO task number - how do we count it? GridHadoopTaskInfo taskInfo = new GridHadoopTaskInfo(locNodeId, GridHadoopTaskType.MAP, jobId, 0, attempt, block); GridHadoopTask task = job.createTask(taskInfo); assert task != null : "Job created null task: " + job; if (tasks == null) tasks = new ArrayList<>(); tasks.add(task); } } if (tasks != null) ctx.taskExecutor().run(tasks); } break; } case PHASE_REDUCE: { if (meta.pendingReducers().isEmpty() && ctx.jobUpdateLeader()) { if (log.isDebugEnabled()) log.debug("Moving job to COMPLETE state [locNodeId=" + locNodeId + ", meta=" + meta + ']'); GridCacheEntry<GridHadoopJobId, GridHadoopJobMetadata> jobEntry = jobMetaPrj.entry(jobId); jobEntry.timeToLive(10_000); // TODO configuration? jobEntry.transformAsync(new UpdatePhaseClosure(PHASE_COMPLETE)); return; } int[] reducers = meta.mapReducePlan().reducers(locNodeId); if (reducers != null) { if (state == null) state = initState(meta); Collection<GridHadoopTask> tasks = null; for (int rdc : reducers) { int attempt = meta.attempt(rdc); if (state.addReducer(attempt, rdc)) { if (log.isDebugEnabled()) log.debug("Submitting REDUCE task for execution [locNodeId=" + locNodeId + ", rdc=" + rdc + ']'); GridHadoopTaskInfo taskInfo = new GridHadoopTaskInfo(locNodeId, GridHadoopTaskType.REDUCE, jobId, rdc, attempt, null); GridHadoopTask task = job.createTask(taskInfo); assert task != null : "Job created null task: " + job; if (tasks == null) tasks = new ArrayList<>(); tasks.add(task); } } if (tasks != null) ctx.taskExecutor().run(tasks); } break; } case PHASE_COMPLETE: { if (state != null) { state = activeJobs.remove(jobId); assert state != null; } GridFutureAdapter<GridHadoopJobId> finishFut = activeFinishFuts.remove(jobId); if (finishFut != null) { if (log.isDebugEnabled()) log.debug("Completing job future [locNodeId=" + locNodeId + ", meta=" + meta + ']'); finishFut.onDone(jobId); // TODO exception. } break; } default: assert false; } } } /** * Initializes local state for given job metadata. * * @param meta Job metadata. * @return Local state. */ private JobLocalState initState(GridHadoopJobMetadata meta) { GridHadoopJobId jobId = meta.jobId(); GridHadoopJob job = ctx.jobFactory().createJob(jobId, meta.jobInfo()); JobLocalState state = new JobLocalState(job); return F.addIfAbsent(activeJobs, jobId, state); } private class JobLocalState { /** Job info. */ private GridHadoopJob job; /** Attempts. */ private Map<Integer, AttemptGroup> attempts = new HashMap<>(); /** * @param job Job. */ private JobLocalState(GridHadoopJob job) { this.job = job; } /** * @param attempt Attempt number. * @param mapBlock Map block to add. * @return {@code True} if mapper was added. */ private boolean addMapper(int attempt, GridHadoopFileBlock mapBlock) { AttemptGroup grp = attempts.get(attempt); if (grp == null) attempts.put(attempt, grp = new AttemptGroup()); return grp.addMapper(mapBlock); } /** * @param attempt Attempt number. * @param rdc Reducer number to add. * @return {@code True} if reducer was added. */ private boolean addReducer(int attempt, int rdc) { AttemptGroup grp = attempts.get(attempt); if (grp == null) attempts.put(attempt, grp = new AttemptGroup()); return grp.addReducer(rdc); } /** * @param taskInfo Task info. * @param status Task status. */ private void onMapFinished(GridHadoopTaskInfo taskInfo, GridHadoopTaskStatus status) { GridHadoopJobId jobId = taskInfo.jobId(); AttemptGroup group = attempts.get(taskInfo.attempt()); assert group != null; boolean combine = group.onMapFinished(); if (job.hasCombiner()) { // Create combiner. if (combine) { GridHadoopTaskInfo info = new GridHadoopTaskInfo(ctx.localNodeId(), COMBINE, jobId, 0, taskInfo.attempt(), null); GridHadoopTask task = job.createTask(info); ctx.taskExecutor().run(Collections.singletonList(task)); } } else { jobMetaPrj.transformAsync(jobId, new RemoveMappersClosure(taskInfo.fileBlock())); } } /** * @param taskInfo Task info. * @param status Task status. */ private void onReduceFinished(GridHadoopTaskInfo taskInfo, GridHadoopTaskStatus status) { jobMetaPrj.transformAsync(taskInfo.jobId(), new RemoveReducerClosure(taskInfo.taskNumber())); } /** * @param taskInfo Task info. * @param status Task status. */ private void onCombineFinished(GridHadoopTaskInfo taskInfo, GridHadoopTaskStatus status) { AttemptGroup group = attempts.get(taskInfo.attempt()); assert group != null; GridHadoopJobId jobId = taskInfo.jobId(); assert job.hasCombiner(); jobMetaPrj.transformAsync(jobId, new RemoveMappersClosure(group.mappers())); } } /** * Job tracker's local job state. */ private static class AttemptGroup { /** Mappers. */ private Collection<GridHadoopFileBlock> currentMappers = new HashSet<>(); /** Number of completed mappers. */ private AtomicInteger completedMappersCnt = new AtomicInteger(); /** Reducers. */ private Collection<Integer> currentReducers = new HashSet<>(); /** * Adds mapper for local job state if this mapper has not been added yet. * * @param block Block to add. * @return {@code True} if mapper was not added to this local node yet. */ public boolean addMapper(GridHadoopFileBlock block) { return currentMappers.add(block); } /** * Adds reducer for local job state if this reducer has not been added yet. * * @param rdcIdx Reducer index. * @return {@code True} if reducer was not added to this local node yet. */ public boolean addReducer(int rdcIdx) { return currentReducers.add(rdcIdx); } /** * Gets this group's mappers. * * @return Collection of group mappers. */ public Collection<GridHadoopFileBlock> mappers() { return currentMappers; } /** * @return {@code True} if last mapper has been completed. */ public boolean onMapFinished() { return completedMappersCnt.incrementAndGet() == currentMappers.size(); } } /** * Update job phase transform closure. */ private static class UpdatePhaseClosure implements GridClosure<GridHadoopJobMetadata, GridHadoopJobMetadata> { /** Phase to update. */ private GridHadoopJobPhase phase; /** * @param phase Phase to update. */ private UpdatePhaseClosure(GridHadoopJobPhase phase) { this.phase = phase; } /** {@inheritDoc} */ @Override public GridHadoopJobMetadata apply(GridHadoopJobMetadata meta) { GridHadoopJobMetadata cp = new GridHadoopJobMetadata(meta); cp.phase(phase); return cp; } } /** * Remove mapper transform closure. */ private static class RemoveMappersClosure implements GridClosure<GridHadoopJobMetadata, GridHadoopJobMetadata> { /** Mapper block to remove. */ private Collection<GridHadoopFileBlock> blocks; /** * @param block Mapper block to remove. */ private RemoveMappersClosure(GridHadoopFileBlock block) { blocks = Collections.singletonList(block); } /** * @param blocks Mapper blocks to remove. */ private RemoveMappersClosure(Collection<GridHadoopFileBlock> blocks) { this.blocks = blocks; } /** {@inheritDoc} */ @Override public GridHadoopJobMetadata apply(GridHadoopJobMetadata meta) { GridHadoopJobMetadata cp = new GridHadoopJobMetadata(meta); Collection<GridHadoopFileBlock> blocksCp = new HashSet<>(cp.pendingBlocks()); blocksCp.removeAll(blocks); cp.pendingBlocks(blocksCp); if (blocksCp.isEmpty()) cp.phase(PHASE_REDUCE); return cp; } } /** * Remove reducer transform closure. */ private static class RemoveReducerClosure implements GridClosure<GridHadoopJobMetadata, GridHadoopJobMetadata> { /** Mapper block to remove. */ private int rdc; /** * @param rdc Reducer to remove. */ private RemoveReducerClosure(int rdc) { this.rdc = rdc; } /** {@inheritDoc} */ @Override public GridHadoopJobMetadata apply(GridHadoopJobMetadata meta) { GridHadoopJobMetadata cp = new GridHadoopJobMetadata(meta); Collection<Integer> rdcCp = new HashSet<>(cp.pendingReducers()); rdcCp.remove(rdc); cp.pendingReducers(rdcCp); return cp; } } }
package com.opengamma.strata.product.swap.type; import static com.opengamma.strata.basics.currency.Currency.CHF; import static com.opengamma.strata.basics.currency.Currency.EUR; import static com.opengamma.strata.basics.currency.Currency.GBP; import static com.opengamma.strata.basics.currency.Currency.JPY; import static com.opengamma.strata.basics.currency.Currency.USD; import static com.opengamma.strata.basics.date.BusinessDayConventions.MODIFIED_FOLLOWING; import static com.opengamma.strata.basics.date.DayCounts.ACT_360; import static com.opengamma.strata.basics.date.DayCounts.ACT_365F; import static com.opengamma.strata.basics.date.DayCounts.THIRTY_U_360; import static com.opengamma.strata.basics.date.HolidayCalendarIds.CHZU; import static com.opengamma.strata.basics.date.HolidayCalendarIds.EUTA; import static com.opengamma.strata.basics.date.HolidayCalendarIds.GBLO; import static com.opengamma.strata.basics.date.HolidayCalendarIds.JPTO; import static com.opengamma.strata.basics.date.HolidayCalendarIds.USNY; import static com.opengamma.strata.basics.schedule.Frequency.P12M; import static com.opengamma.strata.basics.schedule.Frequency.P6M; import com.opengamma.strata.basics.date.BusinessDayAdjustment; import com.opengamma.strata.basics.date.HolidayCalendarId; import com.opengamma.strata.basics.index.IborIndices; final class StandardFixedIborSwapConventions { // GBLO+USNY calendar private static final HolidayCalendarId GBLO_USNY = GBLO.combinedWith(USNY); // GBLO+CHZU calendar private static final HolidayCalendarId GBLO_CHZU = GBLO.combinedWith(CHZU); // GBLO+JPTO calendar private static final HolidayCalendarId GBLO_JPTO = GBLO.combinedWith(JPTO); /** * USD(NY) vanilla fixed vs LIBOR 3M swap. * The fixed leg pays every 6 months with day count '30U/360'. */ public static final FixedIborSwapConvention USD_FIXED_6M_LIBOR_3M = ImmutableFixedIborSwapConvention.of( "USD-FIXED-6M-LIBOR-3M", FixedRateSwapLegConvention.of(USD, THIRTY_U_360, P6M, BusinessDayAdjustment.of(MODIFIED_FOLLOWING, GBLO_USNY)), IborRateSwapLegConvention.of(IborIndices.USD_LIBOR_3M)); /** * USD(London) vanilla fixed vs LIBOR 3M swap. * The fixed leg pays yearly with day count 'Act/360'. */ public static final FixedIborSwapConvention USD_FIXED_1Y_LIBOR_3M = ImmutableFixedIborSwapConvention.of( "USD-FIXED-1Y-LIBOR-3M", FixedRateSwapLegConvention.of(USD, ACT_360, P12M, BusinessDayAdjustment.of(MODIFIED_FOLLOWING, GBLO_USNY)), IborRateSwapLegConvention.of(IborIndices.USD_LIBOR_3M)); /** * EUR(1Y) vanilla fixed vs Euribor 3M swap. * The fixed leg pays yearly with day count '30U/360'. */ public static final FixedIborSwapConvention EUR_FIXED_1Y_EURIBOR_3M = ImmutableFixedIborSwapConvention.of( "EUR-FIXED-1Y-EURIBOR-3M", FixedRateSwapLegConvention.of(EUR, THIRTY_U_360, P12M, BusinessDayAdjustment.of(MODIFIED_FOLLOWING, EUTA)), IborRateSwapLegConvention.of(IborIndices.EUR_EURIBOR_3M)); /** * EUR(>1Y) vanilla fixed vs Euribor 6M swap. * The fixed leg pays yearly with day count '30U/360'. */ public static final FixedIborSwapConvention EUR_FIXED_1Y_EURIBOR_6M = ImmutableFixedIborSwapConvention.of( "EUR-FIXED-1Y-EURIBOR-6M", FixedRateSwapLegConvention.of(EUR, THIRTY_U_360, P12M, BusinessDayAdjustment.of(MODIFIED_FOLLOWING, EUTA)), IborRateSwapLegConvention.of(IborIndices.EUR_EURIBOR_6M)); /** * GBP(1Y) vanilla fixed vs LIBOR 3M swap. * The fixed leg pays yearly with day count 'Act/365F'. */ public static final FixedIborSwapConvention GBP_FIXED_1Y_LIBOR_3M = ImmutableFixedIborSwapConvention.of( "GBP-FIXED-1Y-LIBOR-3M", FixedRateSwapLegConvention.of(GBP, ACT_365F, P12M, BusinessDayAdjustment.of(MODIFIED_FOLLOWING, GBLO)), IborRateSwapLegConvention.of(IborIndices.GBP_LIBOR_3M)); /** * GBP(>1Y) vanilla fixed vs LIBOR 6M swap. * The fixed leg pays every 6 months with day count 'Act/365F'. */ public static final FixedIborSwapConvention GBP_FIXED_6M_LIBOR_6M = ImmutableFixedIborSwapConvention.of( "GBP-FIXED-6M-LIBOR-6M", FixedRateSwapLegConvention.of(GBP, ACT_365F, P6M, BusinessDayAdjustment.of(MODIFIED_FOLLOWING, GBLO)), IborRateSwapLegConvention.of(IborIndices.GBP_LIBOR_6M)); /** * CHF(1Y) vanilla fixed vs LIBOR 3M swap. * The fixed leg pays yearly with day count '30U/360'. */ public static final FixedIborSwapConvention CHF_FIXED_1Y_LIBOR_3M = ImmutableFixedIborSwapConvention.of( "CHF-FIXED-1Y-LIBOR-3M", FixedRateSwapLegConvention.of(CHF, THIRTY_U_360, P12M, BusinessDayAdjustment.of(MODIFIED_FOLLOWING, GBLO_CHZU)), IborRateSwapLegConvention.of(IborIndices.CHF_LIBOR_3M)); /** * CHF(>1Y) vanilla fixed vs LIBOR 6M swap. * The fixed leg pays yearly with day count '30U/360'. */ public static final FixedIborSwapConvention CHF_FIXED_1Y_LIBOR_6M = ImmutableFixedIborSwapConvention.of( "CHF-FIXED-1Y-LIBOR-6M", FixedRateSwapLegConvention.of(CHF, THIRTY_U_360, P12M, BusinessDayAdjustment.of(MODIFIED_FOLLOWING, GBLO_CHZU)), IborRateSwapLegConvention.of(IborIndices.CHF_LIBOR_6M)); /** * JPY(Tibor) vanilla fixed vs Tibor 3M swap. * The fixed leg pays every 6 months with day count 'Act/365F'. */ public static final FixedIborSwapConvention JPY_FIXED_6M_TIBORJ_3M = ImmutableFixedIborSwapConvention.of( "JPY-FIXED-6M-TIBOR-JAPAN-3M", FixedRateSwapLegConvention.of(JPY, ACT_365F, P6M, BusinessDayAdjustment.of(MODIFIED_FOLLOWING, JPTO)), IborRateSwapLegConvention.of(IborIndices.JPY_TIBOR_JAPAN_3M)); /** * JPY(LIBOR) vanilla fixed vs LIBOR 6M swap. * The fixed leg pays every 6 months with day count 'Act/365F'. */ public static final FixedIborSwapConvention JPY_FIXED_6M_LIBOR_6M = ImmutableFixedIborSwapConvention.of( "JPY-FIXED-6M-LIBOR-6M", FixedRateSwapLegConvention.of(JPY, ACT_365F, P6M, BusinessDayAdjustment.of(MODIFIED_FOLLOWING, GBLO_JPTO)), IborRateSwapLegConvention.of(IborIndices.JPY_LIBOR_6M)); /** * Restricted constructor. */ private StandardFixedIborSwapConventions() { } }
package org.bouncycastle.tls; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.math.BigInteger; import java.util.Enumeration; import java.util.Hashtable; import java.util.Vector; import org.bouncycastle.asn1.ASN1Encoding; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.bsi.BSIObjectIdentifiers; import org.bouncycastle.asn1.eac.EACObjectIdentifiers; import org.bouncycastle.asn1.edec.EdECObjectIdentifiers; import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; import org.bouncycastle.asn1.oiw.OIWObjectIdentifiers; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.x509.X509ObjectIdentifiers; import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; import org.bouncycastle.tls.crypto.TlsAgreement; import org.bouncycastle.tls.crypto.TlsCertificate; import org.bouncycastle.tls.crypto.TlsCipher; import org.bouncycastle.tls.crypto.TlsCrypto; import org.bouncycastle.tls.crypto.TlsCryptoParameters; import org.bouncycastle.tls.crypto.TlsDHConfig; import org.bouncycastle.tls.crypto.TlsECConfig; import org.bouncycastle.tls.crypto.TlsHash; import org.bouncycastle.tls.crypto.TlsSecret; import org.bouncycastle.tls.crypto.TlsStreamSigner; import org.bouncycastle.tls.crypto.TlsStreamVerifier; import org.bouncycastle.tls.crypto.TlsVerifier; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Integers; import org.bouncycastle.util.Shorts; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.io.Streams; /** * Some helper functions for the TLS API. */ public class TlsUtils { private static byte[] DOWNGRADE_TLS11 = Hex.decode("444F574E47524400"); private static byte[] DOWNGRADE_TLS12 = Hex.decode("444F574E47524401"); // Map OID strings to HashAlgorithm values private static final Hashtable CERT_SIG_ALG_OIDS = createCertSigAlgOIDs(); private static void addCertSigAlgOID(Hashtable h, ASN1ObjectIdentifier oid, short hashAlgorithm, short signatureAlgorithm) { h.put(oid.getId(), SignatureAndHashAlgorithm.getInstance(hashAlgorithm, signatureAlgorithm)); } private static Hashtable createCertSigAlgOIDs() { Hashtable h = new Hashtable(); addCertSigAlgOID(h, NISTObjectIdentifiers.dsa_with_sha224, HashAlgorithm.sha224, SignatureAlgorithm.dsa); addCertSigAlgOID(h, NISTObjectIdentifiers.dsa_with_sha256, HashAlgorithm.sha256, SignatureAlgorithm.dsa); addCertSigAlgOID(h, NISTObjectIdentifiers.dsa_with_sha384, HashAlgorithm.sha384, SignatureAlgorithm.dsa); addCertSigAlgOID(h, NISTObjectIdentifiers.dsa_with_sha512, HashAlgorithm.sha512, SignatureAlgorithm.dsa); addCertSigAlgOID(h, OIWObjectIdentifiers.dsaWithSHA1, HashAlgorithm.sha1, SignatureAlgorithm.dsa); addCertSigAlgOID(h, OIWObjectIdentifiers.sha1WithRSA, HashAlgorithm.sha1, SignatureAlgorithm.rsa); addCertSigAlgOID(h, PKCSObjectIdentifiers.sha1WithRSAEncryption, HashAlgorithm.sha1, SignatureAlgorithm.rsa); addCertSigAlgOID(h, PKCSObjectIdentifiers.sha224WithRSAEncryption, HashAlgorithm.sha224, SignatureAlgorithm.rsa); addCertSigAlgOID(h, PKCSObjectIdentifiers.sha256WithRSAEncryption, HashAlgorithm.sha256, SignatureAlgorithm.rsa); addCertSigAlgOID(h, PKCSObjectIdentifiers.sha384WithRSAEncryption, HashAlgorithm.sha384, SignatureAlgorithm.rsa); addCertSigAlgOID(h, PKCSObjectIdentifiers.sha512WithRSAEncryption, HashAlgorithm.sha512, SignatureAlgorithm.rsa); addCertSigAlgOID(h, X9ObjectIdentifiers.ecdsa_with_SHA1, HashAlgorithm.sha1, SignatureAlgorithm.ecdsa); addCertSigAlgOID(h, X9ObjectIdentifiers.ecdsa_with_SHA224, HashAlgorithm.sha224, SignatureAlgorithm.ecdsa); addCertSigAlgOID(h, X9ObjectIdentifiers.ecdsa_with_SHA256, HashAlgorithm.sha256, SignatureAlgorithm.ecdsa); addCertSigAlgOID(h, X9ObjectIdentifiers.ecdsa_with_SHA384, HashAlgorithm.sha384, SignatureAlgorithm.ecdsa); addCertSigAlgOID(h, X9ObjectIdentifiers.ecdsa_with_SHA512, HashAlgorithm.sha512, SignatureAlgorithm.ecdsa); addCertSigAlgOID(h, X9ObjectIdentifiers.id_dsa_with_sha1, HashAlgorithm.sha1, SignatureAlgorithm.dsa); addCertSigAlgOID(h, EACObjectIdentifiers.id_TA_ECDSA_SHA_1, HashAlgorithm.sha1, SignatureAlgorithm.ecdsa); addCertSigAlgOID(h, EACObjectIdentifiers.id_TA_ECDSA_SHA_224, HashAlgorithm.sha224, SignatureAlgorithm.ecdsa); addCertSigAlgOID(h, EACObjectIdentifiers.id_TA_ECDSA_SHA_256, HashAlgorithm.sha256, SignatureAlgorithm.ecdsa); addCertSigAlgOID(h, EACObjectIdentifiers.id_TA_ECDSA_SHA_384, HashAlgorithm.sha384, SignatureAlgorithm.ecdsa); addCertSigAlgOID(h, EACObjectIdentifiers.id_TA_ECDSA_SHA_512, HashAlgorithm.sha512, SignatureAlgorithm.ecdsa); addCertSigAlgOID(h, EACObjectIdentifiers.id_TA_RSA_v1_5_SHA_1, HashAlgorithm.sha1, SignatureAlgorithm.rsa); addCertSigAlgOID(h, EACObjectIdentifiers.id_TA_RSA_v1_5_SHA_256, HashAlgorithm.sha256, SignatureAlgorithm.rsa); addCertSigAlgOID(h, EACObjectIdentifiers.id_TA_RSA_PSS_SHA_256, HashAlgorithm.Intrinsic, SignatureAlgorithm.rsa_pss_pss_sha256); addCertSigAlgOID(h, EACObjectIdentifiers.id_TA_RSA_PSS_SHA_512, HashAlgorithm.Intrinsic, SignatureAlgorithm.rsa_pss_pss_sha512); addCertSigAlgOID(h, BSIObjectIdentifiers.ecdsa_plain_SHA1, HashAlgorithm.sha1, SignatureAlgorithm.ecdsa); addCertSigAlgOID(h, BSIObjectIdentifiers.ecdsa_plain_SHA224, HashAlgorithm.sha224, SignatureAlgorithm.ecdsa); addCertSigAlgOID(h, BSIObjectIdentifiers.ecdsa_plain_SHA256, HashAlgorithm.sha256, SignatureAlgorithm.ecdsa); addCertSigAlgOID(h, BSIObjectIdentifiers.ecdsa_plain_SHA384, HashAlgorithm.sha384, SignatureAlgorithm.ecdsa); addCertSigAlgOID(h, BSIObjectIdentifiers.ecdsa_plain_SHA512, HashAlgorithm.sha512, SignatureAlgorithm.ecdsa); addCertSigAlgOID(h, EdECObjectIdentifiers.id_Ed25519, HashAlgorithm.Intrinsic, SignatureAlgorithm.ed25519); addCertSigAlgOID(h, EdECObjectIdentifiers.id_Ed448, HashAlgorithm.Intrinsic, SignatureAlgorithm.ed448); return h; } public static final byte[] EMPTY_BYTES = new byte[0]; public static final short[] EMPTY_SHORTS = new short[0]; public static final int[] EMPTY_INTS = new int[0]; public static final long[] EMPTY_LONGS = new long[0]; /** @deprecated Use {@link TlsExtensionsUtils#EXT_signature_algorithms} instead. */ public static final Integer EXT_signature_algorithms = TlsExtensionsUtils.EXT_signature_algorithms; /** @deprecated Use {@link TlsExtensionsUtils#EXT_signature_algorithms_cert} instead. */ public static final Integer EXT_signature_algorithms_cert = TlsExtensionsUtils.EXT_signature_algorithms_cert; protected static short MINIMUM_HASH_STRICT = HashAlgorithm.sha1; protected static short MINIMUM_HASH_PREFERRED = HashAlgorithm.sha256; public static void checkUint8(short i) throws IOException { if (!isValidUint8(i)) { throw new TlsFatalAlert(AlertDescription.internal_error); } } public static void checkUint8(int i) throws IOException { if (!isValidUint8(i)) { throw new TlsFatalAlert(AlertDescription.internal_error); } } public static void checkUint8(long i) throws IOException { if (!isValidUint8(i)) { throw new TlsFatalAlert(AlertDescription.internal_error); } } public static void checkUint16(int i) throws IOException { if (!isValidUint16(i)) { throw new TlsFatalAlert(AlertDescription.internal_error); } } public static void checkUint16(long i) throws IOException { if (!isValidUint16(i)) { throw new TlsFatalAlert(AlertDescription.internal_error); } } public static void checkUint24(int i) throws IOException { if (!isValidUint24(i)) { throw new TlsFatalAlert(AlertDescription.internal_error); } } public static void checkUint24(long i) throws IOException { if (!isValidUint24(i)) { throw new TlsFatalAlert(AlertDescription.internal_error); } } public static void checkUint32(long i) throws IOException { if (!isValidUint32(i)) { throw new TlsFatalAlert(AlertDescription.internal_error); } } public static void checkUint48(long i) throws IOException { if (!isValidUint48(i)) { throw new TlsFatalAlert(AlertDescription.internal_error); } } public static void checkUint64(long i) throws IOException { if (!isValidUint64(i)) { throw new TlsFatalAlert(AlertDescription.internal_error); } } public static boolean isValidUint8(short i) { return (i & 0xFF) == i; } public static boolean isValidUint8(int i) { return (i & 0xFF) == i; } public static boolean isValidUint8(long i) { return (i & 0xFFL) == i; } public static boolean isValidUint16(int i) { return (i & 0xFFFF) == i; } public static boolean isValidUint16(long i) { return (i & 0xFFFFL) == i; } public static boolean isValidUint24(int i) { return (i & 0xFFFFFF) == i; } public static boolean isValidUint24(long i) { return (i & 0xFFFFFFL) == i; } public static boolean isValidUint32(long i) { return (i & 0xFFFFFFFFL) == i; } public static boolean isValidUint48(long i) { return (i & 0xFFFFFFFFFFFFL) == i; } public static boolean isValidUint64(long i) { return true; } public static boolean isSSL(TlsContext context) { return context.getServerVersion().isSSL(); } public static boolean isTLSv10(ProtocolVersion version) { return ProtocolVersion.TLSv10.isEqualOrEarlierVersionOf(version.getEquivalentTLSVersion()); } public static boolean isTLSv10(TlsContext context) { return isTLSv10(context.getServerVersion()); } public static boolean isTLSv11(ProtocolVersion version) { return ProtocolVersion.TLSv11.isEqualOrEarlierVersionOf(version.getEquivalentTLSVersion()); } public static boolean isTLSv11(TlsContext context) { return isTLSv11(context.getServerVersion()); } public static boolean isTLSv12(ProtocolVersion version) { return ProtocolVersion.TLSv12.isEqualOrEarlierVersionOf(version.getEquivalentTLSVersion()); } public static boolean isTLSv12(TlsContext context) { return isTLSv12(context.getServerVersion()); } public static boolean isTLSv13(ProtocolVersion version) { return ProtocolVersion.TLSv13.isEqualOrEarlierVersionOf(version.getEquivalentTLSVersion()); } public static boolean isTLSv13(TlsContext context) { return isTLSv13(context.getServerVersion()); } public static void writeUint8(short i, OutputStream output) throws IOException { output.write(i); } public static void writeUint8(int i, OutputStream output) throws IOException { output.write(i); } public static void writeUint8(short i, byte[] buf, int offset) { buf[offset] = (byte)i; } public static void writeUint8(int i, byte[] buf, int offset) { buf[offset] = (byte)i; } public static void writeUint16(int i, OutputStream output) throws IOException { output.write(i >>> 8); output.write(i); } public static void writeUint16(int i, byte[] buf, int offset) { buf[offset] = (byte)(i >>> 8); buf[offset + 1] = (byte)i; } public static void writeUint24(int i, OutputStream output) throws IOException { output.write((byte)(i >>> 16)); output.write((byte)(i >>> 8)); output.write((byte)i); } public static void writeUint24(int i, byte[] buf, int offset) { buf[offset] = (byte)(i >>> 16); buf[offset + 1] = (byte)(i >>> 8); buf[offset + 2] = (byte)i; } public static void writeUint32(long i, OutputStream output) throws IOException { output.write((byte)(i >>> 24)); output.write((byte)(i >>> 16)); output.write((byte)(i >>> 8)); output.write((byte)i); } public static void writeUint32(long i, byte[] buf, int offset) { buf[offset] = (byte)(i >>> 24); buf[offset + 1] = (byte)(i >>> 16); buf[offset + 2] = (byte)(i >>> 8); buf[offset + 3] = (byte)i; } public static void writeUint48(long i, OutputStream output) throws IOException { output.write((byte)(i >>> 40)); output.write((byte)(i >>> 32)); output.write((byte)(i >>> 24)); output.write((byte)(i >>> 16)); output.write((byte)(i >>> 8)); output.write((byte)i); } public static void writeUint48(long i, byte[] buf, int offset) { buf[offset] = (byte)(i >>> 40); buf[offset + 1] = (byte)(i >>> 32); buf[offset + 2] = (byte)(i >>> 24); buf[offset + 3] = (byte)(i >>> 16); buf[offset + 4] = (byte)(i >>> 8); buf[offset + 5] = (byte)i; } public static void writeUint64(long i, OutputStream output) throws IOException { output.write((byte)(i >>> 56)); output.write((byte)(i >>> 48)); output.write((byte)(i >>> 40)); output.write((byte)(i >>> 32)); output.write((byte)(i >>> 24)); output.write((byte)(i >>> 16)); output.write((byte)(i >>> 8)); output.write((byte)i); } public static void writeUint64(long i, byte[] buf, int offset) { buf[offset] = (byte)(i >>> 56); buf[offset + 1] = (byte)(i >>> 48); buf[offset + 2] = (byte)(i >>> 40); buf[offset + 3] = (byte)(i >>> 32); buf[offset + 4] = (byte)(i >>> 24); buf[offset + 5] = (byte)(i >>> 16); buf[offset + 6] = (byte)(i >>> 8); buf[offset + 7] = (byte)i; } public static void writeOpaque8(byte[] buf, OutputStream output) throws IOException { checkUint8(buf.length); writeUint8(buf.length, output); output.write(buf); } public static void writeOpaque8(byte[] data, byte[] buf, int off) throws IOException { checkUint8(data.length); writeUint8(data.length, buf, off); System.arraycopy(data, 0, buf, off + 1, data.length); } public static void writeOpaque16(byte[] buf, OutputStream output) throws IOException { checkUint16(buf.length); writeUint16(buf.length, output); output.write(buf); } public static void writeOpaque24(byte[] buf, OutputStream output) throws IOException { checkUint24(buf.length); writeUint24(buf.length, output); output.write(buf); } public static void writeUint8Array(short[] uints, OutputStream output) throws IOException { for (int i = 0; i < uints.length; ++i) { writeUint8(uints[i], output); } } public static void writeUint8Array(short[] uints, byte[] buf, int offset) throws IOException { for (int i = 0; i < uints.length; ++i) { writeUint8(uints[i], buf, offset); ++offset; } } public static void writeUint8ArrayWithUint8Length(short[] uints, OutputStream output) throws IOException { checkUint8(uints.length); writeUint8(uints.length, output); writeUint8Array(uints, output); } public static void writeUint8ArrayWithUint8Length(short[] uints, byte[] buf, int offset) throws IOException { checkUint8(uints.length); writeUint8(uints.length, buf, offset); writeUint8Array(uints, buf, offset + 1); } public static void writeUint16Array(int[] uints, OutputStream output) throws IOException { for (int i = 0; i < uints.length; ++i) { writeUint16(uints[i], output); } } public static void writeUint16Array(int[] uints, byte[] buf, int offset) throws IOException { for (int i = 0; i < uints.length; ++i) { writeUint16(uints[i], buf, offset); offset += 2; } } public static void writeUint16ArrayWithUint16Length(int[] uints, OutputStream output) throws IOException { int length = 2 * uints.length; checkUint16(length); writeUint16(length, output); writeUint16Array(uints, output); } public static void writeUint16ArrayWithUint16Length(int[] uints, byte[] buf, int offset) throws IOException { int length = 2 * uints.length; checkUint16(length); writeUint16(length, buf, offset); writeUint16Array(uints, buf, offset + 2); } public static byte[] decodeOpaque8(byte[] buf) throws IOException { return decodeOpaque8(buf, 0); } public static byte[] decodeOpaque8(byte[] buf, int minLength) throws IOException { if (buf == null) { throw new IllegalArgumentException("'buf' cannot be null"); } if (buf.length < 1) { throw new TlsFatalAlert(AlertDescription.decode_error); } short length = readUint8(buf, 0); if (buf.length != (length + 1) || length < minLength) { throw new TlsFatalAlert(AlertDescription.decode_error); } return copyOfRangeExact(buf, 1, buf.length); } public static byte[] decodeOpaque16(byte[] buf) throws IOException { return decodeOpaque16(buf, 0); } public static byte[] decodeOpaque16(byte[] buf, int minLength) throws IOException { if (buf == null) { throw new IllegalArgumentException("'buf' cannot be null"); } if (buf.length < 2) { throw new TlsFatalAlert(AlertDescription.decode_error); } int length = readUint16(buf, 0); if (buf.length != (length + 2) || length < minLength) { throw new TlsFatalAlert(AlertDescription.decode_error); } return copyOfRangeExact(buf, 2, buf.length); } public static short decodeUint8(byte[] buf) throws IOException { if (buf == null) { throw new IllegalArgumentException("'buf' cannot be null"); } if (buf.length != 1) { throw new TlsFatalAlert(AlertDescription.decode_error); } return readUint8(buf, 0); } public static short[] decodeUint8ArrayWithUint8Length(byte[] buf) throws IOException { if (buf == null) { throw new IllegalArgumentException("'buf' cannot be null"); } int count = readUint8(buf, 0); if (buf.length != (count + 1)) { throw new TlsFatalAlert(AlertDescription.decode_error); } short[] uints = new short[count]; for (int i = 0; i < count; ++i) { uints[i] = readUint8(buf, i + 1); } return uints; } public static int decodeUint16(byte[] buf) throws IOException { if (buf == null) { throw new IllegalArgumentException("'buf' cannot be null"); } if (buf.length != 2) { throw new TlsFatalAlert(AlertDescription.decode_error); } return readUint16(buf, 0); } public static long decodeUint32(byte[] buf) throws IOException { if (buf == null) { throw new IllegalArgumentException("'buf' cannot be null"); } if (buf.length != 4) { throw new TlsFatalAlert(AlertDescription.decode_error); } return readUint32(buf, 0); } public static byte[] encodeOpaque8(byte[] buf) throws IOException { checkUint8(buf.length); return Arrays.prepend(buf, (byte)buf.length); } public static byte[] encodeOpaque16(byte[] buf) throws IOException { return Arrays.concatenate(encodeUint16(buf.length), buf); } public static byte[] encodeUint8(short uint) throws IOException { checkUint8(uint); byte[] encoding = new byte[1]; writeUint8(uint, encoding, 0); return encoding; } public static byte[] encodeUint8ArrayWithUint8Length(short[] uints) throws IOException { byte[] result = new byte[1 + uints.length]; writeUint8ArrayWithUint8Length(uints, result, 0); return result; } public static byte[] encodeUint16(int uint) throws IOException { checkUint16(uint); byte[] encoding = new byte[2]; writeUint16(uint, encoding, 0); return encoding; } public static byte[] encodeUint16ArrayWithUint16Length(int[] uints) throws IOException { int length = 2 * uints.length; byte[] result = new byte[2 + length]; writeUint16ArrayWithUint16Length(uints, result, 0); return result; } public static byte[] encodeUint32(long uint) throws IOException { checkUint32(uint); byte[] encoding = new byte[4]; writeUint32(uint, encoding, 0); return encoding; } public static byte[] encodeVersion(ProtocolVersion version) throws IOException { return new byte[]{ (byte)version.getMajorVersion(), (byte)version.getMinorVersion() }; } public static short readUint8(InputStream input) throws IOException { int i = input.read(); if (i < 0) { throw new EOFException(); } return (short)i; } public static short readUint8(byte[] buf, int offset) { return (short)(buf[offset] & 0xff); } public static int readUint16(InputStream input) throws IOException { int i1 = input.read(); int i2 = input.read(); if (i2 < 0) { throw new EOFException(); } return (i1 << 8) | i2; } public static int readUint16(byte[] buf, int offset) { int n = (buf[offset] & 0xff) << 8; n |= (buf[++offset] & 0xff); return n; } public static int readUint24(InputStream input) throws IOException { int i1 = input.read(); int i2 = input.read(); int i3 = input.read(); if (i3 < 0) { throw new EOFException(); } return (i1 << 16) | (i2 << 8) | i3; } public static int readUint24(byte[] buf, int offset) { int n = (buf[offset] & 0xff) << 16; n |= (buf[++offset] & 0xff) << 8; n |= (buf[++offset] & 0xff); return n; } public static long readUint32(InputStream input) throws IOException { int i1 = input.read(); int i2 = input.read(); int i3 = input.read(); int i4 = input.read(); if (i4 < 0) { throw new EOFException(); } return ((i1 << 24) | (i2 << 16) | (i3 << 8) | i4) & 0xFFFFFFFFL; } public static long readUint32(byte[] buf, int offset) { int n = (buf[offset] & 0xff) << 24; n |= (buf[++offset] & 0xff) << 16; n |= (buf[++offset] & 0xff) << 8; n |= (buf[++offset] & 0xff); return n & 0xFFFFFFFFL; } public static long readUint48(InputStream input) throws IOException { int hi = readUint24(input); int lo = readUint24(input); return ((long)(hi & 0xffffffffL) << 24) | (long)(lo & 0xffffffffL); } public static long readUint48(byte[] buf, int offset) { int hi = readUint24(buf, offset); int lo = readUint24(buf, offset + 3); return ((long)(hi & 0xffffffffL) << 24) | (long)(lo & 0xffffffffL); } public static byte[] readAllOrNothing(int length, InputStream input) throws IOException { if (length < 1) { return EMPTY_BYTES; } byte[] buf = new byte[length]; int read = Streams.readFully(input, buf); if (read == 0) { return null; } if (read != length) { throw new EOFException(); } return buf; } public static byte[] readFully(int length, InputStream input) throws IOException { if (length < 1) { return EMPTY_BYTES; } byte[] buf = new byte[length]; if (length != Streams.readFully(input, buf)) { throw new EOFException(); } return buf; } public static void readFully(byte[] buf, InputStream input) throws IOException { int length = buf.length; if (length > 0 && length != Streams.readFully(input, buf)) { throw new EOFException(); } } public static byte[] readOpaque8(InputStream input) throws IOException { short length = readUint8(input); return readFully(length, input); } public static byte[] readOpaque8(InputStream input, int minLength) throws IOException { short length = readUint8(input); if (length < minLength) { throw new TlsFatalAlert(AlertDescription.decode_error); } return readFully(length, input); } public static byte[] readOpaque8(InputStream input, int minLength, int maxLength) throws IOException { short length = readUint8(input); if (length < minLength || maxLength < length) { throw new TlsFatalAlert(AlertDescription.decode_error); } return readFully(length, input); } public static byte[] readOpaque16(InputStream input) throws IOException { int length = readUint16(input); return readFully(length, input); } public static byte[] readOpaque16(InputStream input, int minLength) throws IOException { int length = readUint16(input); if (length < minLength) { throw new TlsFatalAlert(AlertDescription.decode_error); } return readFully(length, input); } public static byte[] readOpaque24(InputStream input) throws IOException { int length = readUint24(input); return readFully(length, input); } public static byte[] readOpaque24(InputStream input, int minLength) throws IOException { int length = readUint24(input); if (length < minLength) { throw new TlsFatalAlert(AlertDescription.decode_error); } return readFully(length, input); } public static short[] readUint8Array(int count, InputStream input) throws IOException { short[] uints = new short[count]; for (int i = 0; i < count; ++i) { uints[i] = readUint8(input); } return uints; } public static int[] readUint16Array(int count, InputStream input) throws IOException { int[] uints = new int[count]; for (int i = 0; i < count; ++i) { uints[i] = readUint16(input); } return uints; } public static ProtocolVersion readVersion(byte[] buf, int offset) throws IOException { try { return ProtocolVersion.get(buf[offset] & 0xFF, buf[offset + 1] & 0xFF); } catch (RuntimeException e) { throw new TlsFatalAlert(AlertDescription.decode_error, e); } } public static ProtocolVersion readVersion(InputStream input) throws IOException { int i1 = input.read(); int i2 = input.read(); if (i2 < 0) { throw new EOFException(); } try { return ProtocolVersion.get(i1, i2); } catch (RuntimeException e) { throw new TlsFatalAlert(AlertDescription.decode_error, e); } } public static ASN1Primitive readASN1Object(byte[] encoding) throws IOException { ASN1InputStream asn1 = new ASN1InputStream(encoding); ASN1Primitive result = asn1.readObject(); if (null == result) { throw new TlsFatalAlert(AlertDescription.decode_error); } if (null != asn1.readObject()) { throw new TlsFatalAlert(AlertDescription.decode_error); } return result; } public static ASN1Primitive readDERObject(byte[] encoding) throws IOException { /* * NOTE: The current ASN.1 parsing code can't enforce DER-only parsing, but since DER is * canonical, we can check it by re-encoding the result and comparing to the original. */ ASN1Primitive result = readASN1Object(encoding); byte[] check = result.getEncoded(ASN1Encoding.DER); if (!Arrays.areEqual(check, encoding)) { throw new TlsFatalAlert(AlertDescription.decode_error); } return result; } public static void writeGMTUnixTime(byte[] buf, int offset) { int t = (int)(System.currentTimeMillis() / 1000L); buf[offset] = (byte)(t >>> 24); buf[offset + 1] = (byte)(t >>> 16); buf[offset + 2] = (byte)(t >>> 8); buf[offset + 3] = (byte)t; } public static void writeVersion(ProtocolVersion version, OutputStream output) throws IOException { output.write(version.getMajorVersion()); output.write(version.getMinorVersion()); } public static void writeVersion(ProtocolVersion version, byte[] buf, int offset) { buf[offset] = (byte)version.getMajorVersion(); buf[offset + 1] = (byte)version.getMinorVersion(); } public static void addIfSupported(Vector supportedAlgs, TlsCrypto crypto, SignatureAndHashAlgorithm alg) { if (crypto.hasSignatureAndHashAlgorithm(alg)) { supportedAlgs.addElement(alg); } } public static void addIfSupported(Vector supportedGroups, TlsCrypto crypto, int namedGroup) { if (crypto.hasNamedGroup(namedGroup)) { supportedGroups.addElement(Integers.valueOf(namedGroup)); } } public static void addIfSupported(Vector supportedGroups, TlsCrypto crypto, int[] namedGroups) { for (int i = 0; i < namedGroups.length; ++i) { addIfSupported(supportedGroups, crypto, namedGroups[i]); } } public static boolean addToSet(Vector s, int i) { boolean result = !s.contains(Integers.valueOf(i)); if (result) { s.add(Integers.valueOf(i)); } return result; } public static Vector getDefaultDSSSignatureAlgorithms() { return getDefaultSignatureAlgorithms(SignatureAlgorithm.dsa); } public static Vector getDefaultECDSASignatureAlgorithms() { return getDefaultSignatureAlgorithms(SignatureAlgorithm.ecdsa); } public static Vector getDefaultRSASignatureAlgorithms() { return getDefaultSignatureAlgorithms(SignatureAlgorithm.rsa); } public static SignatureAndHashAlgorithm getDefaultSignatureAlgorithm(short signatureAlgorithm) { /* * RFC 5246 7.4.1.4.1. If the client does not send the signature_algorithms extension, * the server MUST do the following: * * - If the negotiated key exchange algorithm is one of (RSA, DHE_RSA, DH_RSA, RSA_PSK, * ECDH_RSA, ECDHE_RSA), behave as if client had sent the value {sha1,rsa}. * * - If the negotiated key exchange algorithm is one of (DHE_DSS, DH_DSS), behave as if * the client had sent the value {sha1,dsa}. * * - If the negotiated key exchange algorithm is one of (ECDH_ECDSA, ECDHE_ECDSA), * behave as if the client had sent value {sha1,ecdsa}. */ switch (signatureAlgorithm) { case SignatureAlgorithm.dsa: case SignatureAlgorithm.ecdsa: case SignatureAlgorithm.rsa: return SignatureAndHashAlgorithm.getInstance(HashAlgorithm.sha1, signatureAlgorithm); default: return null; } } public static Vector getDefaultSignatureAlgorithms(short signatureAlgorithm) { SignatureAndHashAlgorithm sigAndHashAlg = getDefaultSignatureAlgorithm(signatureAlgorithm); return null == sigAndHashAlg ? new Vector() : vectorOfOne(sigAndHashAlg); } public static Vector getDefaultSupportedSignatureAlgorithms(TlsContext context) { TlsCrypto crypto = context.getCrypto(); SignatureAndHashAlgorithm[] intrinsicSigAlgs = { SignatureAndHashAlgorithm.ed25519, SignatureAndHashAlgorithm.ed448, SignatureAndHashAlgorithm.rsa_pss_rsae_sha256, SignatureAndHashAlgorithm.rsa_pss_rsae_sha384, SignatureAndHashAlgorithm.rsa_pss_rsae_sha512, SignatureAndHashAlgorithm.rsa_pss_pss_sha256, SignatureAndHashAlgorithm.rsa_pss_pss_sha384, SignatureAndHashAlgorithm.rsa_pss_pss_sha512 }; short[] hashAlgorithms = new short[]{ HashAlgorithm.sha1, HashAlgorithm.sha224, HashAlgorithm.sha256, HashAlgorithm.sha384, HashAlgorithm.sha512 }; short[] signatureAlgorithms = new short[]{ SignatureAlgorithm.rsa, SignatureAlgorithm.dsa, SignatureAlgorithm.ecdsa }; Vector result = new Vector(); for (int i = 0; i < intrinsicSigAlgs.length; ++i) { addIfSupported(result, crypto, intrinsicSigAlgs[i]); } for (int i = 0; i < signatureAlgorithms.length; ++i) { for (int j = 0; j < hashAlgorithms.length; ++j) { addIfSupported(result, crypto, new SignatureAndHashAlgorithm(hashAlgorithms[j], signatureAlgorithms[i])); } } return result; } public static SignatureAndHashAlgorithm getSignatureAndHashAlgorithm(TlsContext context, TlsCredentialedSigner signerCredentials) throws IOException { SignatureAndHashAlgorithm signatureAndHashAlgorithm = null; if (isTLSv12(context)) { signatureAndHashAlgorithm = signerCredentials.getSignatureAndHashAlgorithm(); if (signatureAndHashAlgorithm == null) { throw new TlsFatalAlert(AlertDescription.internal_error); } } return signatureAndHashAlgorithm; } public static byte[] getExtensionData(Hashtable extensions, Integer extensionType) { return extensions == null ? null : (byte[])extensions.get(extensionType); } public static boolean hasExpectedEmptyExtensionData(Hashtable extensions, Integer extensionType, short alertDescription) throws IOException { byte[] extension_data = getExtensionData(extensions, extensionType); if (extension_data == null) { return false; } if (extension_data.length != 0) { throw new TlsFatalAlert(alertDescription); } return true; } public static TlsSession importSession(byte[] sessionID, SessionParameters sessionParameters) { return new TlsSessionImpl(sessionID, sessionParameters); } public static boolean isSignatureAlgorithmsExtensionAllowed(ProtocolVersion version) { return ProtocolVersion.TLSv12.isEqualOrEarlierVersionOf(version.getEquivalentTLSVersion()); } /** @deprecated Use {@link TlsExtensionsUtils#addSignatureAlgorithmsExtension(Hashtable, Vector)} instead. */ public static void addSignatureAlgorithmsExtension(Hashtable extensions, Vector supportedSignatureAlgorithms) throws IOException { TlsExtensionsUtils.addSignatureAlgorithmsExtension(extensions, supportedSignatureAlgorithms); } /** @deprecated Use {@link TlsExtensionsUtils#getSignatureAlgorithmsExtension(Hashtable)} instead. */ public static Vector getSignatureAlgorithmsExtension(Hashtable extensions) throws IOException { return TlsExtensionsUtils.getSignatureAlgorithmsExtension(extensions); } /** @deprecated Use {@link TlsExtensionsUtils#createSignatureAlgorithmsExtension(Vector)} instead. */ public static byte[] createSignatureAlgorithmsExtension(Vector supportedSignatureAlgorithms) throws IOException { return TlsExtensionsUtils.createSignatureAlgorithmsExtension(supportedSignatureAlgorithms); } /** @deprecated Use {@link TlsExtensionsUtils#readSignatureAlgorithmsExtension(byte[])} instead. */ public static Vector readSignatureAlgorithmsExtension(byte[] extensionData) throws IOException { return TlsExtensionsUtils.readSignatureAlgorithmsExtension(extensionData); } public static short getLegacyClientCertType(short signatureAlgorithm) { switch (signatureAlgorithm) { case SignatureAlgorithm.rsa: return ClientCertificateType.rsa_sign; case SignatureAlgorithm.dsa: return ClientCertificateType.dss_sign; case SignatureAlgorithm.ecdsa: return ClientCertificateType.ecdsa_sign; default: return -1; } } public static short getLegacySignatureAlgorithmClient(short clientCertificateType) { switch (clientCertificateType) { case ClientCertificateType.dss_sign: return SignatureAlgorithm.dsa; case ClientCertificateType.ecdsa_sign: return SignatureAlgorithm.ecdsa; case ClientCertificateType.rsa_sign: return SignatureAlgorithm.rsa; default: return -1; } } public static short getLegacySignatureAlgorithmClientCert(short clientCertificateType) { switch (clientCertificateType) { case ClientCertificateType.dss_sign: case ClientCertificateType.dss_fixed_dh: return SignatureAlgorithm.dsa; case ClientCertificateType.ecdsa_sign: case ClientCertificateType.ecdsa_fixed_ecdh: return SignatureAlgorithm.ecdsa; case ClientCertificateType.rsa_sign: case ClientCertificateType.rsa_fixed_dh: case ClientCertificateType.rsa_fixed_ecdh: return SignatureAlgorithm.rsa; default: return -1; } } public static short getLegacySignatureAlgorithmServer(int keyExchangeAlgorithm) { switch (keyExchangeAlgorithm) { case KeyExchangeAlgorithm.DHE_DSS: case KeyExchangeAlgorithm.SRP_DSS: return SignatureAlgorithm.dsa; case KeyExchangeAlgorithm.ECDHE_ECDSA: return SignatureAlgorithm.ecdsa; case KeyExchangeAlgorithm.DHE_RSA: case KeyExchangeAlgorithm.ECDHE_RSA: case KeyExchangeAlgorithm.SRP_RSA: return SignatureAlgorithm.rsa; default: return -1; } } static short getLegacySignatureAlgorithmServerCert(int keyExchangeAlgorithm) { switch (keyExchangeAlgorithm) { case KeyExchangeAlgorithm.DH_DSS: case KeyExchangeAlgorithm.DHE_DSS: case KeyExchangeAlgorithm.SRP_DSS: return SignatureAlgorithm.dsa; case KeyExchangeAlgorithm.ECDH_ECDSA: case KeyExchangeAlgorithm.ECDHE_ECDSA: return SignatureAlgorithm.ecdsa; case KeyExchangeAlgorithm.DH_RSA: case KeyExchangeAlgorithm.DHE_RSA: case KeyExchangeAlgorithm.ECDH_RSA: case KeyExchangeAlgorithm.ECDHE_RSA: case KeyExchangeAlgorithm.RSA: case KeyExchangeAlgorithm.RSA_PSK: case KeyExchangeAlgorithm.SRP_RSA: return SignatureAlgorithm.rsa; default: return -1; } } public static void encodeSupportedSignatureAlgorithms(Vector supportedSignatureAlgorithms, OutputStream output) throws IOException { if (supportedSignatureAlgorithms == null || supportedSignatureAlgorithms.size() < 1 || supportedSignatureAlgorithms.size() >= (1 << 15)) { throw new IllegalArgumentException( "'supportedSignatureAlgorithms' must have length from 1 to (2^15 - 1)"); } // supported_signature_algorithms int length = 2 * supportedSignatureAlgorithms.size(); checkUint16(length); writeUint16(length, output); for (int i = 0; i < supportedSignatureAlgorithms.size(); ++i) { SignatureAndHashAlgorithm entry = (SignatureAndHashAlgorithm)supportedSignatureAlgorithms.elementAt(i); if (entry.getSignature() == SignatureAlgorithm.anonymous) { /* * RFC 5246 7.4.1.4.1 The "anonymous" value is meaningless in this context but used * in Section 7.4.3. It MUST NOT appear in this extension. */ throw new IllegalArgumentException( "SignatureAlgorithm.anonymous MUST NOT appear in the signature_algorithms extension"); } entry.encode(output); } } public static Vector parseSupportedSignatureAlgorithms(InputStream input) throws IOException { // supported_signature_algorithms int length = readUint16(input); if (length < 2 || (length & 1) != 0) { throw new TlsFatalAlert(AlertDescription.decode_error); } int count = length / 2; Vector supportedSignatureAlgorithms = new Vector(count); for (int i = 0; i < count; ++i) { SignatureAndHashAlgorithm sigAndHashAlg = SignatureAndHashAlgorithm.parse(input); if (SignatureAlgorithm.anonymous != sigAndHashAlg.getSignature()) { supportedSignatureAlgorithms.addElement(sigAndHashAlg); } } return supportedSignatureAlgorithms; } public static void verifySupportedSignatureAlgorithm(Vector supportedSignatureAlgorithms, SignatureAndHashAlgorithm signatureAlgorithm) throws IOException { if (supportedSignatureAlgorithms == null || supportedSignatureAlgorithms.size() < 1 || supportedSignatureAlgorithms.size() >= (1 << 15)) { throw new IllegalArgumentException( "'supportedSignatureAlgorithms' must have length from 1 to (2^15 - 1)"); } if (signatureAlgorithm == null) { throw new IllegalArgumentException("'signatureAlgorithm' cannot be null"); } if (signatureAlgorithm.getSignature() == SignatureAlgorithm.anonymous || !containsSignatureAlgorithm(supportedSignatureAlgorithms, signatureAlgorithm)) { throw new TlsFatalAlert(AlertDescription.illegal_parameter); } } public static boolean containsSignatureAlgorithm(Vector supportedSignatureAlgorithms, SignatureAndHashAlgorithm signatureAlgorithm) throws IOException { for (int i = 0; i < supportedSignatureAlgorithms.size(); ++i) { SignatureAndHashAlgorithm entry = (SignatureAndHashAlgorithm)supportedSignatureAlgorithms.elementAt(i); if (entry.getHash() == signatureAlgorithm.getHash() && entry.getSignature() == signatureAlgorithm.getSignature()) { return true; } } return false; } public static boolean containsAnySignatureAlgorithm(Vector supportedSignatureAlgorithms, short signatureAlgorithm) { for (int i = 0; i < supportedSignatureAlgorithms.size(); ++i) { SignatureAndHashAlgorithm entry = (SignatureAndHashAlgorithm)supportedSignatureAlgorithms.elementAt(i); if (entry.getSignature() == signatureAlgorithm) { return true; } } return false; } public static TlsSecret PRF(SecurityParameters securityParameters, TlsSecret secret, String asciiLabel, byte[] seed, int length) { return secret.deriveUsingPRF(securityParameters.getPrfAlgorithm(), asciiLabel, seed, length); } public static TlsSecret PRF(TlsContext context, TlsSecret secret, String asciiLabel, byte[] seed, int length) { return PRF(context.getSecurityParametersHandshake(), secret, asciiLabel, seed, length); } public static byte[] copyOfRangeExact(byte[] original, int from, int to) { int newLength = to - from; byte[] copy = new byte[newLength]; System.arraycopy(original, from, copy, 0, newLength); return copy; } static byte[] concat(byte[] a, byte[] b) { byte[] c = new byte[a.length + b.length]; System.arraycopy(a, 0, c, 0, a.length); System.arraycopy(b, 0, c, a.length, b.length); return c; } static byte[] calculateEndPointHash(TlsContext context, String sigAlgOID, byte[] enc) { return calculateEndPointHash(context, sigAlgOID, enc, 0, enc.length); } static byte[] calculateEndPointHash(TlsContext context, String sigAlgOID, byte[] enc, int encOff, int encLen) { if (sigAlgOID != null) { SignatureAndHashAlgorithm sigAndHashAlg = getCertSigAndHashAlg(sigAlgOID); if (sigAndHashAlg != null) { short hashAlgorithm = sigAndHashAlg.getHash(); switch (hashAlgorithm) { case HashAlgorithm.md5: case HashAlgorithm.sha1: hashAlgorithm = HashAlgorithm.sha256; break; case HashAlgorithm.none: case HashAlgorithm.Intrinsic: return EMPTY_BYTES; } TlsHash hash = context.getCrypto().createHash(hashAlgorithm); if (hash != null) { hash.update(enc, encOff, encLen); return hash.calculateHash(); } } } return EMPTY_BYTES; } public static byte[] calculateExporterSeed(SecurityParameters securityParameters, byte[] context_value) { byte[] cr = securityParameters.getClientRandom(), sr = securityParameters.getServerRandom(); if (null == context_value) { return Arrays.concatenate(cr, sr); } if (!TlsUtils.isValidUint16(context_value.length)) { throw new IllegalArgumentException("'context_value' must have length less than 2^16 (or be null)"); } byte[] context_value_length = new byte[2]; TlsUtils.writeUint16(context_value.length, context_value_length, 0); return Arrays.concatenate(cr, sr, context_value_length, context_value); } static TlsSecret calculateMasterSecret(TlsContext context, TlsSecret preMasterSecret) { SecurityParameters sp = context.getSecurityParametersHandshake(); String asciiLabel; byte[] seed; if (sp.isExtendedMasterSecret()) { asciiLabel = ExporterLabel.extended_master_secret; seed = sp.getSessionHash(); } else { asciiLabel = ExporterLabel.master_secret; seed = concat(sp.getClientRandom(), sp.getServerRandom()); } return PRF(sp, preMasterSecret, asciiLabel, seed, 48); } static byte[] calculateVerifyData(TlsContext context, TlsHandshakeHash handshakeHash, boolean isServer) { SecurityParameters securityParameters = context.getSecurityParametersHandshake(); if (securityParameters.getNegotiatedVersion().isSSL()) { return SSL3Utils.calculateVerifyData(handshakeHash, isServer); } String asciiLabel = isServer ? ExporterLabel.server_finished : ExporterLabel.client_finished; byte[] prfHash = getCurrentPRFHash(handshakeHash); TlsSecret master_secret = securityParameters.getMasterSecret(); int verify_data_length = securityParameters.getVerifyDataLength(); return PRF(securityParameters, master_secret, asciiLabel, prfHash, verify_data_length).extract(); } public static short getHashAlgorithmForHMACAlgorithm(int macAlgorithm) { switch (macAlgorithm) { case MACAlgorithm.hmac_md5: return HashAlgorithm.md5; case MACAlgorithm.hmac_sha1: return HashAlgorithm.sha1; case MACAlgorithm.hmac_sha256: return HashAlgorithm.sha256; case MACAlgorithm.hmac_sha384: return HashAlgorithm.sha384; case MACAlgorithm.hmac_sha512: return HashAlgorithm.sha512; default: throw new IllegalArgumentException("specified MACAlgorithm not an HMAC: " + MACAlgorithm.getText(macAlgorithm)); } } public static short getHashAlgorithmForPRFAlgorithm(int prfAlgorithm) { switch (prfAlgorithm) { case PRFAlgorithm.ssl_prf_legacy: case PRFAlgorithm.tls_prf_legacy: throw new IllegalArgumentException("legacy PRF not a valid algorithm"); case PRFAlgorithm.tls_prf_sha256: return HashAlgorithm.sha256; case PRFAlgorithm.tls_prf_sha384: return HashAlgorithm.sha384; default: throw new IllegalArgumentException("unknown PRFAlgorithm: " + PRFAlgorithm.getText(prfAlgorithm)); } } public static ASN1ObjectIdentifier getOIDForHashAlgorithm(short hashAlgorithm) { switch (hashAlgorithm) { case HashAlgorithm.md5: return PKCSObjectIdentifiers.md5; case HashAlgorithm.sha1: return X509ObjectIdentifiers.id_SHA1; case HashAlgorithm.sha224: return NISTObjectIdentifiers.id_sha224; case HashAlgorithm.sha256: return NISTObjectIdentifiers.id_sha256; case HashAlgorithm.sha384: return NISTObjectIdentifiers.id_sha384; case HashAlgorithm.sha512: return NISTObjectIdentifiers.id_sha512; default: throw new IllegalArgumentException("invalid HashAlgorithm: " + HashAlgorithm.getText(hashAlgorithm)); } } static byte[] calculateSignatureHash(TlsContext context, SignatureAndHashAlgorithm algorithm, DigestInputBuffer buf) { TlsCrypto crypto = context.getCrypto(); TlsHash h = algorithm == null ? new CombinedHash(crypto) : crypto.createHash(algorithm.getHash()); SecurityParameters sp = context.getSecurityParametersHandshake(); byte[] cr = sp.getClientRandom(), sr = sp.getServerRandom(); h.update(cr, 0, cr.length); h.update(sr, 0, sr.length); buf.updateDigest(h); return h.calculateHash(); } static void sendSignatureInput(TlsContext context, DigestInputBuffer buf, OutputStream output) throws IOException { SecurityParameters securityParameters = context.getSecurityParametersHandshake(); // NOTE: The implicit copy here is intended (and important) output.write(Arrays.concatenate(securityParameters.getClientRandom(), securityParameters.getServerRandom())); buf.copyTo(output); output.close(); } static DigitallySigned generateCertificateVerify(TlsContext context, TlsCredentialedSigner credentialedSigner, TlsStreamSigner streamSigner, TlsHandshakeHash handshakeHash) throws IOException { /* * RFC 5246 4.7. digitally-signed element needs SignatureAndHashAlgorithm from TLS 1.2 */ SignatureAndHashAlgorithm signatureAndHashAlgorithm = getSignatureAndHashAlgorithm( context, credentialedSigner); byte[] signature; if (streamSigner != null) { handshakeHash.copyBufferTo(streamSigner.getOutputStream()); signature = streamSigner.getSignature(); } else { byte[] hash; if (signatureAndHashAlgorithm == null) { hash = context.getSecurityParametersHandshake().getSessionHash(); } else { hash = handshakeHash.getFinalHash(signatureAndHashAlgorithm.getHash()); } signature = credentialedSigner.generateRawSignature(hash); } return new DigitallySigned(signatureAndHashAlgorithm, signature); } static void verifyCertificateVerify(TlsServerContext serverContext, CertificateRequest certificateRequest, DigitallySigned certificateVerify, TlsHandshakeHash handshakeHash) throws IOException { SecurityParameters securityParameters = serverContext.getSecurityParametersHandshake(); Certificate clientCertificate = securityParameters.getPeerCertificate(); TlsCertificate verifyingCert = clientCertificate.getCertificateAt(0); SignatureAndHashAlgorithm sigAndHashAlg = certificateVerify.getAlgorithm(); short signatureAlgorithm; if (null == sigAndHashAlg) { signatureAlgorithm = verifyingCert.getLegacySignatureAlgorithm(); short clientCertType = getLegacyClientCertType(signatureAlgorithm); if (clientCertType < 0 || !Arrays.contains(certificateRequest.getCertificateTypes(), clientCertType)) { throw new TlsFatalAlert(AlertDescription.illegal_parameter); } } else { signatureAlgorithm = sigAndHashAlg.getSignature(); if (!isValidSignatureAlgorithmForCertificateVerify(signatureAlgorithm, certificateRequest.getCertificateTypes())) { throw new TlsFatalAlert(AlertDescription.illegal_parameter); } verifySupportedSignatureAlgorithm(certificateRequest.getSupportedSignatureAlgorithms(), sigAndHashAlg); } // Verify the CertificateVerify message contains a correct signature. boolean verified; try { TlsVerifier verifier = verifyingCert.createVerifier(signatureAlgorithm); TlsStreamVerifier streamVerifier = verifier.getStreamVerifier(certificateVerify); if (streamVerifier != null) { handshakeHash.copyBufferTo(streamVerifier.getOutputStream()); verified = streamVerifier.isVerified(); } else { byte[] hash; if (isTLSv12(serverContext)) { hash = handshakeHash.getFinalHash(sigAndHashAlg.getHash()); } else { hash = securityParameters.getSessionHash(); } verified = verifier.verifyRawSignature(certificateVerify, hash); } } catch (TlsFatalAlert e) { throw e; } catch (Exception e) { throw new TlsFatalAlert(AlertDescription.decrypt_error, e); } if (!verified) { throw new TlsFatalAlert(AlertDescription.decrypt_error); } } static void generateServerKeyExchangeSignature(TlsContext context, TlsCredentialedSigner credentials, DigestInputBuffer digestBuffer) throws IOException { /* * RFC 5246 4.7. digitally-signed element needs SignatureAndHashAlgorithm from TLS 1.2 */ SignatureAndHashAlgorithm algorithm = getSignatureAndHashAlgorithm(context, credentials); TlsStreamSigner streamSigner = credentials.getStreamSigner(); byte[] signature; if (streamSigner != null) { sendSignatureInput(context, digestBuffer, streamSigner.getOutputStream()); signature = streamSigner.getSignature(); } else { byte[] hash = calculateSignatureHash(context, algorithm, digestBuffer); signature = credentials.generateRawSignature(hash); } DigitallySigned digitallySigned = new DigitallySigned(algorithm, signature); digitallySigned.encode(digestBuffer); } static void verifyServerKeyExchangeSignature(TlsContext context, InputStream signatureInput, TlsCertificate serverCertificate, DigestInputBuffer digestBuffer) throws IOException { DigitallySigned digitallySigned = DigitallySigned.parse(context, signatureInput); SecurityParameters securityParameters = context.getSecurityParametersHandshake(); int keyExchangeAlgorithm = securityParameters.getKeyExchangeAlgorithm(); SignatureAndHashAlgorithm sigAndHashAlg = digitallySigned.getAlgorithm(); short signatureAlgorithm; if (sigAndHashAlg == null) { signatureAlgorithm = getLegacySignatureAlgorithmServer(keyExchangeAlgorithm); } else { signatureAlgorithm = sigAndHashAlg.getSignature(); if (!isValidSignatureAlgorithmForServerKeyExchange(signatureAlgorithm, keyExchangeAlgorithm)) { throw new TlsFatalAlert(AlertDescription.illegal_parameter); } Vector clientSigAlgs = securityParameters.getClientSigAlgs(); verifySupportedSignatureAlgorithm(clientSigAlgs, sigAndHashAlg); } TlsVerifier verifier = serverCertificate.createVerifier(signatureAlgorithm); TlsStreamVerifier streamVerifier = verifier.getStreamVerifier(digitallySigned); boolean verified; if (streamVerifier != null) { sendSignatureInput(context, digestBuffer, streamVerifier.getOutputStream()); verified = streamVerifier.isVerified(); } else { byte[] hash = calculateSignatureHash(context, sigAndHashAlg, digestBuffer); verified = verifier.verifyRawSignature(digitallySigned, hash); } if (!verified) { throw new TlsFatalAlert(AlertDescription.decrypt_error); } } static void trackHashAlgorithms(TlsHandshakeHash handshakeHash, Vector supportedSignatureAlgorithms) { if (supportedSignatureAlgorithms != null) { for (int i = 0; i < supportedSignatureAlgorithms.size(); ++i) { SignatureAndHashAlgorithm signatureAndHashAlgorithm = (SignatureAndHashAlgorithm) supportedSignatureAlgorithms.elementAt(i); short hashAlgorithm = signatureAndHashAlgorithm.getHash(); if (HashAlgorithm.Intrinsic == hashAlgorithm) { // TODO[RFC 8422] handshakeHash.forceBuffering(); } else if (HashAlgorithm.isRecognized(hashAlgorithm)) { handshakeHash.trackHashAlgorithm(hashAlgorithm); } else //if (HashAlgorithm.isPrivate(hashAlgorithm)) { // TODO Support values in the "Reserved for Private Use" range } } } } public static boolean hasSigningCapability(short clientCertificateType) { switch (clientCertificateType) { case ClientCertificateType.dss_sign: case ClientCertificateType.ecdsa_sign: case ClientCertificateType.rsa_sign: return true; default: return false; } } public static Vector vectorOfOne(Object obj) { Vector v = new Vector(1); v.addElement(obj); return v; } public static int getCipherType(int cipherSuite) { int encryptionAlgorithm = getEncryptionAlgorithm(cipherSuite); return getEncryptionAlgorithmType(encryptionAlgorithm); } public static int getEncryptionAlgorithm(int cipherSuite) { switch (cipherSuite) { case CipherSuite.TLS_DH_anon_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_PSK_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_RSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA: return EncryptionAlgorithm._3DES_EDE_CBC; case CipherSuite.TLS_DH_anon_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_DH_anon_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DH_DSS_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_DH_DSS_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DH_RSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_DH_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DHE_PSK_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_DHE_PSK_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_ECDH_anon_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_PSK_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_PSK_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_RSA_PSK_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_RSA_PSK_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_SRP_SHA_WITH_AES_128_CBC_SHA: return EncryptionAlgorithm.AES_128_CBC; case CipherSuite.TLS_AES_128_CCM_SHA256: case CipherSuite.TLS_DHE_PSK_WITH_AES_128_CCM: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM: case CipherSuite.TLS_ECDHE_PSK_WITH_AES_128_CCM_SHA256: case CipherSuite.TLS_PSK_WITH_AES_128_CCM: case CipherSuite.TLS_RSA_WITH_AES_128_CCM: return EncryptionAlgorithm.AES_128_CCM; case CipherSuite.TLS_AES_128_CCM_8_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM_8: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8: case CipherSuite.TLS_ECDHE_PSK_WITH_AES_128_CCM_8_SHA256: case CipherSuite.TLS_PSK_DHE_WITH_AES_128_CCM_8: case CipherSuite.TLS_PSK_WITH_AES_128_CCM_8: case CipherSuite.TLS_RSA_WITH_AES_128_CCM_8: return EncryptionAlgorithm.AES_128_CCM_8; case CipherSuite.TLS_AES_128_GCM_SHA256: case CipherSuite.TLS_DH_anon_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DH_DSS_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DH_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DHE_PSK_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_PSK_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_RSA_PSK_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_RSA_WITH_AES_128_GCM_SHA256: return EncryptionAlgorithm.AES_128_GCM; case CipherSuite.DRAFT_TLS_DHE_PSK_WITH_AES_128_OCB: case CipherSuite.DRAFT_TLS_DHE_RSA_WITH_AES_128_OCB: case CipherSuite.DRAFT_TLS_ECDHE_ECDSA_WITH_AES_128_OCB: case CipherSuite.DRAFT_TLS_ECDHE_PSK_WITH_AES_128_OCB: case CipherSuite.DRAFT_TLS_ECDHE_RSA_WITH_AES_128_OCB: case CipherSuite.DRAFT_TLS_PSK_WITH_AES_128_OCB: return EncryptionAlgorithm.AES_128_OCB_TAGLEN96; case CipherSuite.TLS_DH_anon_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_DH_anon_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_DH_DSS_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_DH_DSS_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_DH_RSA_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_DH_RSA_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_DHE_DSS_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_ECDH_anon_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_PSK_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_PSK_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_RSA_PSK_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_SRP_SHA_WITH_AES_256_CBC_SHA: return EncryptionAlgorithm.AES_256_CBC; case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CCM: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CCM: case CipherSuite.TLS_PSK_WITH_AES_256_CCM: case CipherSuite.TLS_RSA_WITH_AES_256_CCM: return EncryptionAlgorithm.AES_256_CCM; case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM_8: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8: case CipherSuite.TLS_PSK_DHE_WITH_AES_256_CCM_8: case CipherSuite.TLS_PSK_WITH_AES_256_CCM_8: case CipherSuite.TLS_RSA_WITH_AES_256_CCM_8: return EncryptionAlgorithm.AES_256_CCM_8; case CipherSuite.TLS_AES_256_GCM_SHA384: case CipherSuite.TLS_DH_anon_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DH_DSS_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DH_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DHE_DSS_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DHE_PSK_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_PSK_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_RSA_WITH_AES_256_GCM_SHA384: return EncryptionAlgorithm.AES_256_GCM; case CipherSuite.DRAFT_TLS_DHE_PSK_WITH_AES_256_OCB: case CipherSuite.DRAFT_TLS_DHE_RSA_WITH_AES_256_OCB: case CipherSuite.DRAFT_TLS_ECDHE_ECDSA_WITH_AES_256_OCB: case CipherSuite.DRAFT_TLS_ECDHE_PSK_WITH_AES_256_OCB: case CipherSuite.DRAFT_TLS_ECDHE_RSA_WITH_AES_256_OCB: case CipherSuite.DRAFT_TLS_PSK_WITH_AES_256_OCB: return EncryptionAlgorithm.AES_256_OCB_TAGLEN96; case CipherSuite.TLS_DH_anon_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_DH_DSS_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_DH_RSA_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_PSK_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_RSA_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256: return EncryptionAlgorithm.ARIA_128_CBC; case CipherSuite.TLS_DH_anon_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_DH_DSS_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_DH_RSA_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_PSK_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_RSA_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256: return EncryptionAlgorithm.ARIA_128_GCM; case CipherSuite.TLS_DH_anon_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_DH_DSS_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_DH_RSA_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_DHE_DSS_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_PSK_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_RSA_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384: return EncryptionAlgorithm.ARIA_256_CBC; case CipherSuite.TLS_DH_anon_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_DH_DSS_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_DH_RSA_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_DHE_DSS_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_PSK_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_RSA_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384: return EncryptionAlgorithm.ARIA_256_GCM; case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA: case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA: case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_CBC_SHA: case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256: return EncryptionAlgorithm.CAMELLIA_128_CBC; case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256: return EncryptionAlgorithm.CAMELLIA_128_GCM; case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA: case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA: case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_CBC_SHA: case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384: return EncryptionAlgorithm.CAMELLIA_256_CBC; case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384: return EncryptionAlgorithm.CAMELLIA_256_GCM; case CipherSuite.TLS_CHACHA20_POLY1305_SHA256: case CipherSuite.TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256: case CipherSuite.TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256: case CipherSuite.TLS_PSK_WITH_CHACHA20_POLY1305_SHA256: case CipherSuite.TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256: return EncryptionAlgorithm.CHACHA20_POLY1305; case CipherSuite.TLS_DHE_PSK_WITH_NULL_SHA: case CipherSuite.TLS_ECDH_anon_WITH_NULL_SHA: case CipherSuite.TLS_ECDH_ECDSA_WITH_NULL_SHA: case CipherSuite.TLS_ECDH_RSA_WITH_NULL_SHA: case CipherSuite.TLS_ECDHE_ECDSA_WITH_NULL_SHA: case CipherSuite.TLS_ECDHE_PSK_WITH_NULL_SHA: case CipherSuite.TLS_ECDHE_RSA_WITH_NULL_SHA: case CipherSuite.TLS_PSK_WITH_NULL_SHA: case CipherSuite.TLS_RSA_PSK_WITH_NULL_SHA: case CipherSuite.TLS_RSA_WITH_NULL_SHA: return EncryptionAlgorithm.NULL; case CipherSuite.TLS_DHE_PSK_WITH_NULL_SHA256: case CipherSuite.TLS_ECDHE_PSK_WITH_NULL_SHA256: case CipherSuite.TLS_PSK_WITH_NULL_SHA256: case CipherSuite.TLS_RSA_PSK_WITH_NULL_SHA256: case CipherSuite.TLS_RSA_WITH_NULL_SHA256: return EncryptionAlgorithm.NULL; case CipherSuite.TLS_DHE_PSK_WITH_NULL_SHA384: case CipherSuite.TLS_ECDHE_PSK_WITH_NULL_SHA384: case CipherSuite.TLS_PSK_WITH_NULL_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_NULL_SHA384: return EncryptionAlgorithm.NULL; case CipherSuite.TLS_DH_anon_WITH_SEED_CBC_SHA: case CipherSuite.TLS_DH_DSS_WITH_SEED_CBC_SHA: case CipherSuite.TLS_DH_RSA_WITH_SEED_CBC_SHA: case CipherSuite.TLS_DHE_DSS_WITH_SEED_CBC_SHA: case CipherSuite.TLS_DHE_RSA_WITH_SEED_CBC_SHA: case CipherSuite.TLS_RSA_WITH_SEED_CBC_SHA: return EncryptionAlgorithm.SEED_CBC; default: return -1; } } public static int getEncryptionAlgorithmType(int encryptionAlgorithm) { switch (encryptionAlgorithm) { case EncryptionAlgorithm.AES_128_CCM: case EncryptionAlgorithm.AES_128_CCM_8: case EncryptionAlgorithm.AES_128_GCM: case EncryptionAlgorithm.AES_128_OCB_TAGLEN96: case EncryptionAlgorithm.AES_256_CCM: case EncryptionAlgorithm.AES_256_CCM_8: case EncryptionAlgorithm.AES_256_GCM: case EncryptionAlgorithm.ARIA_128_GCM: case EncryptionAlgorithm.ARIA_256_GCM: case EncryptionAlgorithm.AES_256_OCB_TAGLEN96: case EncryptionAlgorithm.CAMELLIA_128_GCM: case EncryptionAlgorithm.CAMELLIA_256_GCM: case EncryptionAlgorithm.CHACHA20_POLY1305: return CipherType.aead; case EncryptionAlgorithm.RC2_CBC_40: case EncryptionAlgorithm.IDEA_CBC: case EncryptionAlgorithm.DES40_CBC: case EncryptionAlgorithm.DES_CBC: case EncryptionAlgorithm._3DES_EDE_CBC: case EncryptionAlgorithm.AES_128_CBC: case EncryptionAlgorithm.AES_256_CBC: case EncryptionAlgorithm.ARIA_128_CBC: case EncryptionAlgorithm.ARIA_256_CBC: case EncryptionAlgorithm.CAMELLIA_128_CBC: case EncryptionAlgorithm.CAMELLIA_256_CBC: case EncryptionAlgorithm.SEED_CBC: return CipherType.block; case EncryptionAlgorithm.NULL: case EncryptionAlgorithm.RC4_40: case EncryptionAlgorithm.RC4_128: return CipherType.stream; default: return -1; } } public static int getKeyExchangeAlgorithm(int cipherSuite) { switch (cipherSuite) { case CipherSuite.TLS_DH_anon_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_DH_anon_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_DH_anon_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DH_anon_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DH_anon_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_DH_anon_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_DH_anon_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DH_anon_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_DH_anon_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_DH_anon_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_DH_anon_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA: case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA: case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DH_anon_WITH_SEED_CBC_SHA: return KeyExchangeAlgorithm.DH_anon; case CipherSuite.TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_DH_DSS_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_DH_DSS_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DH_DSS_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DH_DSS_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_DH_DSS_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_DH_DSS_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DH_DSS_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_DH_DSS_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_DH_DSS_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_DH_DSS_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA: case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA: case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DH_DSS_WITH_SEED_CBC_SHA: return KeyExchangeAlgorithm.DH_DSS; case CipherSuite.TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_DH_RSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_DH_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DH_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DH_RSA_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_DH_RSA_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_DH_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DH_RSA_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_DH_RSA_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_DH_RSA_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_DH_RSA_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DH_RSA_WITH_SEED_CBC_SHA: return KeyExchangeAlgorithm.DH_RSA; case CipherSuite.TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_DHE_DSS_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DHE_DSS_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_DHE_DSS_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DHE_DSS_WITH_SEED_CBC_SHA: return KeyExchangeAlgorithm.DHE_DSS; case CipherSuite.TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_DHE_PSK_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_DHE_PSK_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DHE_PSK_WITH_AES_128_CCM: case CipherSuite.TLS_DHE_PSK_WITH_AES_128_GCM_SHA256: case CipherSuite.DRAFT_TLS_DHE_PSK_WITH_AES_128_OCB: case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CCM: case CipherSuite.TLS_DHE_PSK_WITH_AES_256_GCM_SHA384: case CipherSuite.DRAFT_TLS_DHE_PSK_WITH_AES_256_OCB: case CipherSuite.TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256: case CipherSuite.TLS_DHE_PSK_WITH_NULL_SHA: case CipherSuite.TLS_DHE_PSK_WITH_NULL_SHA256: case CipherSuite.TLS_DHE_PSK_WITH_NULL_SHA384: case CipherSuite.TLS_PSK_DHE_WITH_AES_128_CCM_8: case CipherSuite.TLS_PSK_DHE_WITH_AES_256_CCM_8: return KeyExchangeAlgorithm.DHE_PSK; case CipherSuite.TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM_8: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.DRAFT_TLS_DHE_RSA_WITH_AES_128_OCB: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM_8: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.DRAFT_TLS_DHE_RSA_WITH_AES_256_OCB: case CipherSuite.TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_SEED_CBC_SHA: return KeyExchangeAlgorithm.DHE_RSA; case CipherSuite.TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_ECDH_anon_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_ECDH_anon_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_ECDH_anon_WITH_NULL_SHA: return KeyExchangeAlgorithm.ECDH_anon; case CipherSuite.TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_ECDH_ECDSA_WITH_NULL_SHA: return KeyExchangeAlgorithm.ECDH_ECDSA; case CipherSuite.TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_NULL_SHA: return KeyExchangeAlgorithm.ECDH_RSA; case CipherSuite.TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: case CipherSuite.DRAFT_TLS_ECDHE_ECDSA_WITH_AES_128_OCB: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CCM: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384: case CipherSuite.DRAFT_TLS_ECDHE_ECDSA_WITH_AES_256_OCB: case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_NULL_SHA: return KeyExchangeAlgorithm.ECDHE_ECDSA; case CipherSuite.TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_PSK_WITH_AES_128_CCM_8_SHA256: case CipherSuite.TLS_ECDHE_PSK_WITH_AES_128_CCM_SHA256: case CipherSuite.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256: case CipherSuite.DRAFT_TLS_ECDHE_PSK_WITH_AES_128_OCB: case CipherSuite.TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384: case CipherSuite.DRAFT_TLS_ECDHE_PSK_WITH_AES_256_OCB: case CipherSuite.TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256: case CipherSuite.TLS_ECDHE_PSK_WITH_NULL_SHA: case CipherSuite.TLS_ECDHE_PSK_WITH_NULL_SHA256: case CipherSuite.TLS_ECDHE_PSK_WITH_NULL_SHA384: return KeyExchangeAlgorithm.ECDHE_PSK; case CipherSuite.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.DRAFT_TLS_ECDHE_RSA_WITH_AES_128_OCB: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.DRAFT_TLS_ECDHE_RSA_WITH_AES_256_OCB: case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_NULL_SHA: return KeyExchangeAlgorithm.ECDHE_RSA; case CipherSuite.TLS_AES_128_CCM_8_SHA256: case CipherSuite.TLS_AES_128_CCM_SHA256: case CipherSuite.TLS_AES_128_GCM_SHA256: case CipherSuite.TLS_AES_256_GCM_SHA384: case CipherSuite.TLS_CHACHA20_POLY1305_SHA256: return KeyExchangeAlgorithm.NULL; case CipherSuite.TLS_PSK_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_PSK_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_PSK_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_PSK_WITH_AES_128_CCM: case CipherSuite.TLS_PSK_WITH_AES_128_CCM_8: case CipherSuite.TLS_PSK_WITH_AES_128_GCM_SHA256: case CipherSuite.DRAFT_TLS_PSK_WITH_AES_128_OCB: case CipherSuite.TLS_PSK_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_PSK_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_PSK_WITH_AES_256_CCM: case CipherSuite.TLS_PSK_WITH_AES_256_CCM_8: case CipherSuite.TLS_PSK_WITH_AES_256_GCM_SHA384: case CipherSuite.DRAFT_TLS_PSK_WITH_AES_256_OCB: case CipherSuite.TLS_PSK_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_PSK_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_PSK_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_PSK_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_PSK_WITH_CHACHA20_POLY1305_SHA256: case CipherSuite.TLS_PSK_WITH_NULL_SHA: case CipherSuite.TLS_PSK_WITH_NULL_SHA256: case CipherSuite.TLS_PSK_WITH_NULL_SHA384: return KeyExchangeAlgorithm.PSK; case CipherSuite.TLS_RSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_RSA_WITH_AES_128_CCM: case CipherSuite.TLS_RSA_WITH_AES_128_CCM_8: case CipherSuite.TLS_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_RSA_WITH_AES_256_CCM: case CipherSuite.TLS_RSA_WITH_AES_256_CCM_8: case CipherSuite.TLS_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_RSA_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_RSA_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_RSA_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_RSA_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_CBC_SHA: case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_CBC_SHA: case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_RSA_WITH_NULL_SHA: case CipherSuite.TLS_RSA_WITH_NULL_SHA256: case CipherSuite.TLS_RSA_WITH_SEED_CBC_SHA: return KeyExchangeAlgorithm.RSA; case CipherSuite.TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_RSA_PSK_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_RSA_PSK_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_RSA_PSK_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_RSA_PSK_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_RSA_PSK_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256: case CipherSuite.TLS_RSA_PSK_WITH_NULL_SHA: case CipherSuite.TLS_RSA_PSK_WITH_NULL_SHA256: case CipherSuite.TLS_RSA_PSK_WITH_NULL_SHA384: return KeyExchangeAlgorithm.RSA_PSK; case CipherSuite.TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_SRP_SHA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_SRP_SHA_WITH_AES_256_CBC_SHA: return KeyExchangeAlgorithm.SRP; case CipherSuite.TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA: return KeyExchangeAlgorithm.SRP_DSS; case CipherSuite.TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA: return KeyExchangeAlgorithm.SRP_RSA; default: return -1; } } public static Vector getKeyExchangeAlgorithms(int[] cipherSuites) { Vector result = new Vector(); if (null != cipherSuites) { for (int i = 0; i < cipherSuites.length; ++i) { addToSet(result, getKeyExchangeAlgorithm(cipherSuites[i])); } result.removeElement(Integers.valueOf(-1)); } return result; } public static int getMACAlgorithm(int cipherSuite) { switch (cipherSuite) { case CipherSuite.TLS_AES_128_CCM_SHA256: case CipherSuite.TLS_AES_128_CCM_8_SHA256: case CipherSuite.TLS_AES_128_GCM_SHA256: case CipherSuite.TLS_AES_256_GCM_SHA384: case CipherSuite.TLS_CHACHA20_POLY1305_SHA256: case CipherSuite.TLS_DH_anon_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DH_anon_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DH_anon_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_DH_anon_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DH_DSS_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DH_DSS_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DH_DSS_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_DH_DSS_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DH_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DH_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DH_RSA_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_DH_RSA_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DHE_DSS_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DHE_DSS_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DHE_PSK_WITH_AES_128_CCM: case CipherSuite.TLS_DHE_PSK_WITH_AES_128_GCM_SHA256: case CipherSuite.DRAFT_TLS_DHE_PSK_WITH_AES_128_OCB: case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CCM: case CipherSuite.TLS_DHE_PSK_WITH_AES_256_GCM_SHA384: case CipherSuite.DRAFT_TLS_DHE_PSK_WITH_AES_256_OCB: case CipherSuite.TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM_8: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.DRAFT_TLS_DHE_RSA_WITH_AES_128_OCB: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM_8: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.DRAFT_TLS_DHE_RSA_WITH_AES_256_OCB: case CipherSuite.TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: case CipherSuite.DRAFT_TLS_ECDHE_ECDSA_WITH_AES_128_OCB: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CCM: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384: case CipherSuite.DRAFT_TLS_ECDHE_ECDSA_WITH_AES_256_OCB: case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256: case CipherSuite.TLS_ECDHE_PSK_WITH_AES_128_CCM_8_SHA256: case CipherSuite.TLS_ECDHE_PSK_WITH_AES_128_CCM_SHA256: case CipherSuite.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256: case CipherSuite.DRAFT_TLS_ECDHE_PSK_WITH_AES_128_OCB: case CipherSuite.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384: case CipherSuite.DRAFT_TLS_ECDHE_PSK_WITH_AES_256_OCB: case CipherSuite.TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.DRAFT_TLS_ECDHE_RSA_WITH_AES_128_OCB: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.DRAFT_TLS_ECDHE_RSA_WITH_AES_256_OCB: case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256: case CipherSuite.TLS_PSK_DHE_WITH_AES_128_CCM_8: case CipherSuite.TLS_PSK_DHE_WITH_AES_256_CCM_8: case CipherSuite.TLS_PSK_WITH_AES_128_CCM: case CipherSuite.TLS_PSK_WITH_AES_128_CCM_8: case CipherSuite.TLS_PSK_WITH_AES_128_GCM_SHA256: case CipherSuite.DRAFT_TLS_PSK_WITH_AES_128_OCB: case CipherSuite.TLS_PSK_WITH_AES_256_CCM: case CipherSuite.TLS_PSK_WITH_AES_256_CCM_8: case CipherSuite.TLS_PSK_WITH_AES_256_GCM_SHA384: case CipherSuite.DRAFT_TLS_PSK_WITH_AES_256_OCB: case CipherSuite.TLS_PSK_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_PSK_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_PSK_WITH_CHACHA20_POLY1305_SHA256: case CipherSuite.TLS_RSA_PSK_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_RSA_PSK_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256: case CipherSuite.TLS_RSA_WITH_AES_128_CCM: case CipherSuite.TLS_RSA_WITH_AES_128_CCM_8: case CipherSuite.TLS_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_RSA_WITH_AES_256_CCM: case CipherSuite.TLS_RSA_WITH_AES_256_CCM_8: case CipherSuite.TLS_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_RSA_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_RSA_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384: return MACAlgorithm._null; case CipherSuite.TLS_DH_anon_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_DH_anon_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_DH_anon_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA: case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA: case CipherSuite.TLS_DH_anon_WITH_SEED_CBC_SHA: case CipherSuite.TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_DH_DSS_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_DH_DSS_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA: case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA: case CipherSuite.TLS_DH_DSS_WITH_SEED_CBC_SHA: case CipherSuite.TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_DH_RSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_DH_RSA_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA: case CipherSuite.TLS_DH_RSA_WITH_SEED_CBC_SHA: case CipherSuite.TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_DHE_DSS_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA: case CipherSuite.TLS_DHE_DSS_WITH_SEED_CBC_SHA: case CipherSuite.TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_DHE_PSK_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_DHE_PSK_WITH_NULL_SHA: case CipherSuite.TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA: case CipherSuite.TLS_DHE_RSA_WITH_SEED_CBC_SHA: case CipherSuite.TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_ECDH_anon_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_ECDH_anon_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_ECDH_anon_WITH_NULL_SHA: case CipherSuite.TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_ECDH_ECDSA_WITH_NULL_SHA: case CipherSuite.TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_ECDH_RSA_WITH_NULL_SHA: case CipherSuite.TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_ECDHE_ECDSA_WITH_NULL_SHA: case CipherSuite.TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_ECDHE_PSK_WITH_NULL_SHA: case CipherSuite.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_ECDHE_RSA_WITH_NULL_SHA: case CipherSuite.TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_RSA_PSK_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_RSA_PSK_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_PSK_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_PSK_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_PSK_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_PSK_WITH_NULL_SHA: case CipherSuite.TLS_RSA_PSK_WITH_NULL_SHA: case CipherSuite.TLS_RSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_CBC_SHA: case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_CBC_SHA: case CipherSuite.TLS_RSA_WITH_NULL_SHA: case CipherSuite.TLS_RSA_WITH_SEED_CBC_SHA: case CipherSuite.TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_SRP_SHA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_SRP_SHA_WITH_AES_256_CBC_SHA: return MACAlgorithm.hmac_sha1; case CipherSuite.TLS_DH_anon_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DH_anon_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_DH_anon_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_DH_DSS_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DH_DSS_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_DH_DSS_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_DH_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DH_RSA_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_DH_RSA_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_DHE_PSK_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DHE_PSK_WITH_NULL_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_PSK_WITH_NULL_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_PSK_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_PSK_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_PSK_WITH_NULL_SHA256: case CipherSuite.TLS_RSA_PSK_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_RSA_PSK_WITH_NULL_SHA256: case CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_RSA_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_RSA_WITH_NULL_SHA256: return MACAlgorithm.hmac_sha256; case CipherSuite.TLS_DH_anon_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_DH_DSS_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_DH_RSA_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_DHE_DSS_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_DHE_PSK_WITH_NULL_SHA384: case CipherSuite.TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_PSK_WITH_NULL_SHA384: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_PSK_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_PSK_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_PSK_WITH_NULL_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_NULL_SHA384: case CipherSuite.TLS_RSA_WITH_ARIA_256_CBC_SHA384: return MACAlgorithm.hmac_sha384; default: return -1; } } public static ProtocolVersion getMinimumVersion(int cipherSuite) { switch (cipherSuite) { case CipherSuite.TLS_AES_128_CCM_SHA256: case CipherSuite.TLS_AES_128_CCM_8_SHA256: case CipherSuite.TLS_AES_128_GCM_SHA256: case CipherSuite.TLS_AES_256_GCM_SHA384: case CipherSuite.TLS_CHACHA20_POLY1305_SHA256: return ProtocolVersion.TLSv13; case CipherSuite.TLS_DH_anon_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DH_anon_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DH_anon_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_DH_anon_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DH_anon_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_DH_anon_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_DH_anon_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_DH_anon_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DH_DSS_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DH_DSS_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DH_DSS_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_DH_DSS_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DH_DSS_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_DH_DSS_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_DH_DSS_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_DH_DSS_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DH_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DH_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DH_RSA_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_DH_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DH_RSA_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_DH_RSA_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_DH_RSA_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_DH_RSA_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DHE_DSS_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_DHE_DSS_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DHE_PSK_WITH_AES_128_CCM: case CipherSuite.TLS_DHE_PSK_WITH_AES_128_GCM_SHA256: case CipherSuite.DRAFT_TLS_DHE_PSK_WITH_AES_128_OCB: case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CCM: case CipherSuite.TLS_DHE_PSK_WITH_AES_256_GCM_SHA384: case CipherSuite.DRAFT_TLS_DHE_PSK_WITH_AES_256_OCB: case CipherSuite.TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM_8: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.DRAFT_TLS_DHE_RSA_WITH_AES_128_OCB: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM_8: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.DRAFT_TLS_DHE_RSA_WITH_AES_256_OCB: case CipherSuite.TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: case CipherSuite.DRAFT_TLS_ECDHE_ECDSA_WITH_AES_128_OCB: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CCM: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384: case CipherSuite.DRAFT_TLS_ECDHE_ECDSA_WITH_AES_256_OCB: case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256: case CipherSuite.TLS_ECDHE_PSK_WITH_AES_128_CCM_8_SHA256: case CipherSuite.TLS_ECDHE_PSK_WITH_AES_128_CCM_SHA256: case CipherSuite.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256: case CipherSuite.DRAFT_TLS_ECDHE_PSK_WITH_AES_128_OCB: case CipherSuite.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384: case CipherSuite.DRAFT_TLS_ECDHE_PSK_WITH_AES_256_OCB: case CipherSuite.TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.DRAFT_TLS_ECDHE_RSA_WITH_AES_128_OCB: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.DRAFT_TLS_ECDHE_RSA_WITH_AES_256_OCB: case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256: case CipherSuite.TLS_PSK_DHE_WITH_AES_128_CCM_8: case CipherSuite.TLS_PSK_DHE_WITH_AES_256_CCM_8: case CipherSuite.TLS_PSK_WITH_AES_128_CCM: case CipherSuite.TLS_PSK_WITH_AES_128_CCM_8: case CipherSuite.TLS_PSK_WITH_AES_128_GCM_SHA256: case CipherSuite.DRAFT_TLS_PSK_WITH_AES_128_OCB: case CipherSuite.TLS_PSK_WITH_AES_256_CCM: case CipherSuite.TLS_PSK_WITH_AES_256_CCM_8: case CipherSuite.TLS_PSK_WITH_AES_256_GCM_SHA384: case CipherSuite.DRAFT_TLS_PSK_WITH_AES_256_OCB: case CipherSuite.TLS_PSK_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_PSK_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_PSK_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_PSK_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_PSK_WITH_CHACHA20_POLY1305_SHA256: case CipherSuite.TLS_RSA_PSK_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_RSA_PSK_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256: case CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_RSA_WITH_AES_128_CCM: case CipherSuite.TLS_RSA_WITH_AES_128_CCM_8: case CipherSuite.TLS_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_RSA_WITH_AES_256_CCM: case CipherSuite.TLS_RSA_WITH_AES_256_CCM_8: case CipherSuite.TLS_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_RSA_WITH_ARIA_128_CBC_SHA256: case CipherSuite.TLS_RSA_WITH_ARIA_128_GCM_SHA256: case CipherSuite.TLS_RSA_WITH_ARIA_256_CBC_SHA384: case CipherSuite.TLS_RSA_WITH_ARIA_256_GCM_SHA384: case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_RSA_WITH_NULL_SHA256: return ProtocolVersion.TLSv12; default: return ProtocolVersion.SSLv3; } } public static Vector getNamedGroupRoles(int[] cipherSuites) { return getNamedGroupRoles(getKeyExchangeAlgorithms(cipherSuites)); } public static Vector getNamedGroupRoles(Vector keyExchangeAlgorithms) { Vector result = new Vector(); for (int i = 0; i < keyExchangeAlgorithms.size(); ++i) { int keyExchangeAlgorithm = ((Integer)keyExchangeAlgorithms.elementAt(i)).intValue(); switch (keyExchangeAlgorithm) { case KeyExchangeAlgorithm.DH_anon: case KeyExchangeAlgorithm.DH_DSS: case KeyExchangeAlgorithm.DH_RSA: case KeyExchangeAlgorithm.DHE_DSS: case KeyExchangeAlgorithm.DHE_PSK: case KeyExchangeAlgorithm.DHE_RSA: { addToSet(result, NamedGroupRole.dh); break; } case KeyExchangeAlgorithm.ECDH_anon: case KeyExchangeAlgorithm.ECDH_RSA: case KeyExchangeAlgorithm.ECDHE_PSK: case KeyExchangeAlgorithm.ECDHE_RSA: { addToSet(result, NamedGroupRole.ecdh); break; } case KeyExchangeAlgorithm.ECDH_ECDSA: case KeyExchangeAlgorithm.ECDHE_ECDSA: { addToSet(result, NamedGroupRole.ecdh); addToSet(result, NamedGroupRole.ecdsa); break; } } } return result; } public static boolean isAEADCipherSuite(int cipherSuite) throws IOException { return CipherType.aead == getCipherType(cipherSuite); } public static boolean isBlockCipherSuite(int cipherSuite) throws IOException { return CipherType.block == getCipherType(cipherSuite); } public static boolean isStreamCipherSuite(int cipherSuite) throws IOException { return CipherType.stream == getCipherType(cipherSuite); } public static boolean isValidCipherSuiteForSignatureAlgorithms(int cipherSuite, Vector sigAlgs) { int keyExchangeAlgorithm = getKeyExchangeAlgorithm(cipherSuite); switch (keyExchangeAlgorithm) { case KeyExchangeAlgorithm.DHE_RSA: case KeyExchangeAlgorithm.ECDHE_RSA: case KeyExchangeAlgorithm.SRP_RSA: return sigAlgs.contains(Shorts.valueOf(SignatureAlgorithm.rsa)) || sigAlgs.contains(Shorts.valueOf(SignatureAlgorithm.rsa_pss_rsae_sha256)) || sigAlgs.contains(Shorts.valueOf(SignatureAlgorithm.rsa_pss_rsae_sha384)) || sigAlgs.contains(Shorts.valueOf(SignatureAlgorithm.rsa_pss_rsae_sha512)) || sigAlgs.contains(Shorts.valueOf(SignatureAlgorithm.rsa_pss_pss_sha256)) || sigAlgs.contains(Shorts.valueOf(SignatureAlgorithm.rsa_pss_pss_sha384)) || sigAlgs.contains(Shorts.valueOf(SignatureAlgorithm.rsa_pss_pss_sha512)); case KeyExchangeAlgorithm.DHE_DSS: case KeyExchangeAlgorithm.SRP_DSS: return sigAlgs.contains(Shorts.valueOf(SignatureAlgorithm.dsa)); case KeyExchangeAlgorithm.ECDHE_ECDSA: return sigAlgs.contains(Shorts.valueOf(SignatureAlgorithm.ecdsa)) || sigAlgs.contains(Shorts.valueOf(SignatureAlgorithm.ed25519)) || sigAlgs.contains(Shorts.valueOf(SignatureAlgorithm.ed448)); case KeyExchangeAlgorithm.DH_anon: case KeyExchangeAlgorithm.ECDH_anon: case KeyExchangeAlgorithm.NULL: default: return true; } } public static boolean isValidCipherSuiteForVersion(int cipherSuite, ProtocolVersion version) { version = version.getEquivalentTLSVersion(); ProtocolVersion minimumVersion = getMinimumVersion(cipherSuite); if (minimumVersion == version) { return true; } if (!minimumVersion.isEarlierVersionOf(version)) { return false; } return ProtocolVersion.TLSv13.isEqualOrEarlierVersionOf(minimumVersion) || ProtocolVersion.TLSv13.isLaterVersionOf(version); } static boolean isValidSignatureAlgorithmForCertificateVerify(short signatureAlgorithm, short[] clientCertificateTypes) { for (int i = 0; i < clientCertificateTypes.length; ++i) { if (isValidSignatureAlgorithmForClientCertType(signatureAlgorithm, clientCertificateTypes[i])) { return true; } } return false; } static boolean isValidSignatureAlgorithmForClientCertType(short signatureAlgorithm, short clientCertificateType) { switch (clientCertificateType) { case ClientCertificateType.rsa_sign: switch (signatureAlgorithm) { case SignatureAlgorithm.rsa: case SignatureAlgorithm.rsa_pss_rsae_sha256: case SignatureAlgorithm.rsa_pss_rsae_sha384: case SignatureAlgorithm.rsa_pss_rsae_sha512: case SignatureAlgorithm.rsa_pss_pss_sha256: case SignatureAlgorithm.rsa_pss_pss_sha384: case SignatureAlgorithm.rsa_pss_pss_sha512: return true; default: return false; } case ClientCertificateType.dss_sign: return SignatureAlgorithm.dsa == signatureAlgorithm; case ClientCertificateType.ecdsa_sign: switch (signatureAlgorithm) { case SignatureAlgorithm.ecdsa: case SignatureAlgorithm.ed25519: case SignatureAlgorithm.ed448: return true; default: return false; } default: return false; } } static boolean isValidSignatureAlgorithmForServerKeyExchange(short signatureAlgorithm, int keyExchangeAlgorithm) { // TODO [tls13] switch (keyExchangeAlgorithm) { case KeyExchangeAlgorithm.DHE_RSA: case KeyExchangeAlgorithm.ECDHE_RSA: case KeyExchangeAlgorithm.SRP_RSA: switch (signatureAlgorithm) { case SignatureAlgorithm.rsa: case SignatureAlgorithm.rsa_pss_rsae_sha256: case SignatureAlgorithm.rsa_pss_rsae_sha384: case SignatureAlgorithm.rsa_pss_rsae_sha512: case SignatureAlgorithm.rsa_pss_pss_sha256: case SignatureAlgorithm.rsa_pss_pss_sha384: case SignatureAlgorithm.rsa_pss_pss_sha512: return true; default: return false; } case KeyExchangeAlgorithm.DHE_DSS: case KeyExchangeAlgorithm.SRP_DSS: return SignatureAlgorithm.dsa == signatureAlgorithm; case KeyExchangeAlgorithm.ECDHE_ECDSA: switch (signatureAlgorithm) { case SignatureAlgorithm.ecdsa: case SignatureAlgorithm.ed25519: case SignatureAlgorithm.ed448: return true; default: return false; } default: return false; } } public static SignatureAndHashAlgorithm chooseSignatureAndHashAlgorithm(TlsContext context, Vector sigHashAlgs, short signatureAlgorithm) throws IOException { if (!isTLSv12(context)) { return null; } if (sigHashAlgs == null) { sigHashAlgs = getDefaultSignatureAlgorithms(signatureAlgorithm); } SignatureAndHashAlgorithm result = null; for (int i = 0; i < sigHashAlgs.size(); ++i) { SignatureAndHashAlgorithm sigHashAlg = (SignatureAndHashAlgorithm)sigHashAlgs.elementAt(i); if (sigHashAlg.getSignature() == signatureAlgorithm) { short hash = sigHashAlg.getHash(); if (hash < MINIMUM_HASH_STRICT) { continue; } if (result == null) { result = sigHashAlg; continue; } short current = result.getHash(); if (current < MINIMUM_HASH_PREFERRED) { if (hash > current) { result = sigHashAlg; } } else if (hash >= MINIMUM_HASH_PREFERRED) { if (hash < current) { result = sigHashAlg; } } } } if (result == null) { throw new TlsFatalAlert(AlertDescription.internal_error); } return result; } public static Vector getUsableSignatureAlgorithms(Vector sigHashAlgs) { if (sigHashAlgs == null) { Vector v = new Vector(3); v.addElement(Shorts.valueOf(SignatureAlgorithm.rsa)); v.addElement(Shorts.valueOf(SignatureAlgorithm.dsa)); v.addElement(Shorts.valueOf(SignatureAlgorithm.ecdsa)); return v; } Vector v = new Vector(); for (int i = 0; i < sigHashAlgs.size(); ++i) { SignatureAndHashAlgorithm sigHashAlg = (SignatureAndHashAlgorithm)sigHashAlgs.elementAt(i); if (sigHashAlg.getHash() >= MINIMUM_HASH_STRICT) { Short sigAlg = Shorts.valueOf(sigHashAlg.getSignature()); if (!v.contains(sigAlg)) { v.addElement(sigAlg); } } } return v; } public static int[] getCommonCipherSuites(int[] peerCipherSuites, int[] localCipherSuites, boolean useLocalOrder) { int[] ordered = peerCipherSuites, unordered = localCipherSuites; if (useLocalOrder) { ordered = localCipherSuites; unordered = peerCipherSuites; } int count = 0, limit = Math.min(ordered.length, unordered.length); int[] candidates = new int[limit]; for (int i = 0; i < ordered.length; ++i) { int candidate = ordered[i]; if (!contains(candidates, 0, count, candidate) && Arrays.contains(unordered, candidate)) { candidates[count++] = candidate; } } if (count < limit) { candidates = Arrays.copyOf(candidates, count); } return candidates; } public static int[] getSupportedCipherSuites(TlsCrypto crypto, int[] suites) { return getSupportedCipherSuites(crypto, suites, suites.length); } public static int[] getSupportedCipherSuites(TlsCrypto crypto, int[] suites, int suitesCount) { int[] supported = new int[suitesCount]; int count = 0; for (int i = 0; i < suitesCount; ++i) { int suite = suites[i]; if (isSupportedCipherSuite(crypto, suite)) { supported[count++] = suite; } } if (count < suitesCount) { supported = Arrays.copyOf(supported, count); } return supported; } public static boolean isSupportedCipherSuite(TlsCrypto crypto, int cipherSuite) { return isSupportedKeyExchange(crypto, getKeyExchangeAlgorithm(cipherSuite)) && crypto.hasEncryptionAlgorithm(getEncryptionAlgorithm(cipherSuite)) && crypto.hasMacAlgorithm(getMACAlgorithm(cipherSuite)); } public static boolean isSupportedKeyExchange(TlsCrypto crypto, int keyExchangeAlgorithm) { switch (keyExchangeAlgorithm) { case KeyExchangeAlgorithm.DH_anon: case KeyExchangeAlgorithm.DH_DSS: case KeyExchangeAlgorithm.DH_RSA: case KeyExchangeAlgorithm.DHE_PSK: return crypto.hasDHAgreement(); case KeyExchangeAlgorithm.DHE_DSS: return crypto.hasDHAgreement() && crypto.hasSignatureAlgorithm(SignatureAlgorithm.dsa); case KeyExchangeAlgorithm.DHE_RSA: return crypto.hasDHAgreement() && hasAnyRSASigAlgs(crypto); case KeyExchangeAlgorithm.ECDH_anon: case KeyExchangeAlgorithm.ECDH_ECDSA: case KeyExchangeAlgorithm.ECDH_RSA: case KeyExchangeAlgorithm.ECDHE_PSK: return crypto.hasECDHAgreement(); case KeyExchangeAlgorithm.ECDHE_ECDSA: return crypto.hasECDHAgreement() && (crypto.hasSignatureAlgorithm(SignatureAlgorithm.ecdsa) || crypto.hasSignatureAlgorithm(SignatureAlgorithm.ed25519) || crypto.hasSignatureAlgorithm(SignatureAlgorithm.ed448)); case KeyExchangeAlgorithm.ECDHE_RSA: return crypto.hasECDHAgreement() && hasAnyRSASigAlgs(crypto); case KeyExchangeAlgorithm.NULL: case KeyExchangeAlgorithm.PSK: return true; case KeyExchangeAlgorithm.RSA: case KeyExchangeAlgorithm.RSA_PSK: return crypto.hasRSAEncryption(); case KeyExchangeAlgorithm.SRP: return crypto.hasSRPAuthentication(); case KeyExchangeAlgorithm.SRP_DSS: return crypto.hasSRPAuthentication() && crypto.hasSignatureAlgorithm(SignatureAlgorithm.dsa); case KeyExchangeAlgorithm.SRP_RSA: return crypto.hasSRPAuthentication() && hasAnyRSASigAlgs(crypto); default: return false; } } static boolean hasAnyRSASigAlgs(TlsCrypto crypto) { return crypto.hasSignatureAlgorithm(SignatureAlgorithm.rsa) || crypto.hasSignatureAlgorithm(SignatureAlgorithm.rsa_pss_rsae_sha256) || crypto.hasSignatureAlgorithm(SignatureAlgorithm.rsa_pss_rsae_sha384) || crypto.hasSignatureAlgorithm(SignatureAlgorithm.rsa_pss_rsae_sha512) || crypto.hasSignatureAlgorithm(SignatureAlgorithm.rsa_pss_pss_sha256) || crypto.hasSignatureAlgorithm(SignatureAlgorithm.rsa_pss_pss_sha384) || crypto.hasSignatureAlgorithm(SignatureAlgorithm.rsa_pss_pss_sha512); } static byte[] getCurrentPRFHash(TlsHandshakeHash handshakeHash) { return handshakeHash.forkPRFHash().calculateHash(); } static void sealHandshakeHash(TlsContext context, TlsHandshakeHash handshakeHash, boolean forceBuffering) { if (forceBuffering || !context.getCrypto().hasAllRawSignatureAlgorithms()) { handshakeHash.forceBuffering(); } handshakeHash.sealHashAlgorithms(); } private static TlsKeyExchange createKeyExchangeClient(TlsClient client, int keyExchange) throws IOException { TlsKeyExchangeFactory factory = client.getKeyExchangeFactory(); switch (keyExchange) { case KeyExchangeAlgorithm.DH_anon: return factory.createDHanonKeyExchangeClient(keyExchange, client.getDHGroupVerifier()); case KeyExchangeAlgorithm.DH_DSS: case KeyExchangeAlgorithm.DH_RSA: return factory.createDHKeyExchange(keyExchange); case KeyExchangeAlgorithm.DHE_DSS: case KeyExchangeAlgorithm.DHE_RSA: return factory.createDHEKeyExchangeClient(keyExchange, client.getDHGroupVerifier()); case KeyExchangeAlgorithm.ECDH_anon: return factory.createECDHanonKeyExchangeClient(keyExchange); case KeyExchangeAlgorithm.ECDH_ECDSA: case KeyExchangeAlgorithm.ECDH_RSA: return factory.createECDHKeyExchange(keyExchange); case KeyExchangeAlgorithm.ECDHE_ECDSA: case KeyExchangeAlgorithm.ECDHE_RSA: return factory.createECDHEKeyExchangeClient(keyExchange); case KeyExchangeAlgorithm.RSA: return factory.createRSAKeyExchange(keyExchange); case KeyExchangeAlgorithm.DHE_PSK: return factory.createPSKKeyExchangeClient(keyExchange, client.getPSKIdentity(), client.getDHGroupVerifier()); case KeyExchangeAlgorithm.ECDHE_PSK: case KeyExchangeAlgorithm.PSK: case KeyExchangeAlgorithm.RSA_PSK: return factory.createPSKKeyExchangeClient(keyExchange, client.getPSKIdentity(), null); case KeyExchangeAlgorithm.SRP: case KeyExchangeAlgorithm.SRP_DSS: case KeyExchangeAlgorithm.SRP_RSA: return factory.createSRPKeyExchangeClient(keyExchange, client.getSRPIdentity(), client.getSRPConfigVerifier()); default: /* * Note: internal error here; the TlsProtocol implementation verifies that the * server-selected cipher suite was in the list of client-offered cipher suites, so if * we now can't produce an implementation, we shouldn't have offered it! */ throw new TlsFatalAlert(AlertDescription.internal_error); } } private static TlsKeyExchange createKeyExchangeServer(TlsServer server, int keyExchange) throws IOException { TlsKeyExchangeFactory factory = server.getKeyExchangeFactory(); switch (keyExchange) { case KeyExchangeAlgorithm.DH_anon: return factory.createDHanonKeyExchangeServer(keyExchange, server.getDHConfig()); case KeyExchangeAlgorithm.DH_DSS: case KeyExchangeAlgorithm.DH_RSA: return factory.createDHKeyExchange(keyExchange); case KeyExchangeAlgorithm.DHE_DSS: case KeyExchangeAlgorithm.DHE_RSA: return factory.createDHEKeyExchangeServer(keyExchange, server.getDHConfig()); case KeyExchangeAlgorithm.ECDH_anon: return factory.createECDHanonKeyExchangeServer(keyExchange, server.getECDHConfig()); case KeyExchangeAlgorithm.ECDH_ECDSA: case KeyExchangeAlgorithm.ECDH_RSA: return factory.createECDHKeyExchange(keyExchange); case KeyExchangeAlgorithm.ECDHE_ECDSA: case KeyExchangeAlgorithm.ECDHE_RSA: return factory.createECDHEKeyExchangeServer(keyExchange, server.getECDHConfig()); case KeyExchangeAlgorithm.RSA: return factory.createRSAKeyExchange(keyExchange); case KeyExchangeAlgorithm.DHE_PSK: return factory.createPSKKeyExchangeServer(keyExchange, server.getPSKIdentityManager(), server.getDHConfig(), null); case KeyExchangeAlgorithm.ECDHE_PSK: return factory.createPSKKeyExchangeServer(keyExchange, server.getPSKIdentityManager(), null, server.getECDHConfig()); case KeyExchangeAlgorithm.PSK: case KeyExchangeAlgorithm.RSA_PSK: return factory.createPSKKeyExchangeServer(keyExchange, server.getPSKIdentityManager(), null, null); case KeyExchangeAlgorithm.SRP: case KeyExchangeAlgorithm.SRP_DSS: case KeyExchangeAlgorithm.SRP_RSA: return factory.createSRPKeyExchangeServer(keyExchange, server.getSRPLoginParameters()); default: /* * Note: internal error here; the TlsProtocol implementation verifies that the * server-selected cipher suite was in the list of client-offered cipher suites, so if * we now can't produce an implementation, we shouldn't have offered it! */ throw new TlsFatalAlert(AlertDescription.internal_error); } } private static TlsKeyExchange initKeyExchange(TlsContext context, TlsKeyExchange keyExchange) throws IOException { keyExchange.init(context); /* * Process the raw signature_algorithms extension sent by the client (if any) into an * effective value based on the negotiated protocol version and/or the defaults for the * selected key exchange. */ SecurityParameters securityParameters = context.getSecurityParametersHandshake(); if (isSignatureAlgorithmsExtensionAllowed(context.getServerVersion())) { if (null == securityParameters.getClientSigAlgs()) { short signatureAlgorithm = getLegacySignatureAlgorithmServerCert( securityParameters.getKeyExchangeAlgorithm()); securityParameters.clientSigAlgs = getDefaultSignatureAlgorithms(signatureAlgorithm); } if (null == securityParameters.getClientSigAlgsCert()) { securityParameters.clientSigAlgsCert = securityParameters.getClientSigAlgs(); } } else { securityParameters.clientSigAlgs = null; securityParameters.clientSigAlgsCert = null; } return keyExchange; } static TlsKeyExchange initKeyExchangeClient(TlsClientContext context, TlsClient client) throws IOException { SecurityParameters securityParameters = context.getSecurityParametersHandshake(); int cipherSuite = securityParameters.getCipherSuite(); securityParameters.keyExchangeAlgorithm = getKeyExchangeAlgorithm(cipherSuite); TlsKeyExchange keyExchange = createKeyExchangeClient(client, securityParameters.getKeyExchangeAlgorithm()); return initKeyExchange(context, keyExchange); } static TlsKeyExchange initKeyExchangeServer(TlsServerContext context, TlsServer server) throws IOException { SecurityParameters securityParameters = context.getSecurityParametersHandshake(); int cipherSuite = securityParameters.getCipherSuite(); securityParameters.keyExchangeAlgorithm = getKeyExchangeAlgorithm(cipherSuite); TlsKeyExchange keyExchange = createKeyExchangeServer(server, securityParameters.getKeyExchangeAlgorithm()); return initKeyExchange(context, keyExchange); } static TlsCipher initCipher(TlsContext context) throws IOException { SecurityParameters securityParameters = context.getSecurityParametersHandshake(); int cipherSuite = securityParameters.getCipherSuite(); int encryptionAlgorithm = TlsUtils.getEncryptionAlgorithm(cipherSuite); int macAlgorithm = TlsUtils.getMACAlgorithm(cipherSuite); if (encryptionAlgorithm < 0 || macAlgorithm < 0) { throw new TlsFatalAlert(AlertDescription.internal_error); } TlsSecret masterSecret = context.getSecurityParametersHandshake().getMasterSecret(); return masterSecret.createCipher(new TlsCryptoParameters(context), encryptionAlgorithm, macAlgorithm); } static void checkSigAlgOfClientCerts(TlsContext context, Certificate clientCertificate, CertificateRequest certificateRequest) throws IOException { Vector supportedSignatureAlgorithms = certificateRequest.getSupportedSignatureAlgorithms(); for (int i = 0; i < clientCertificate.getLength(); ++i) { String sigAlgOID = clientCertificate.getCertificateAt(i).getSigAlgOID(); SignatureAndHashAlgorithm sigAndHashAlg = getCertSigAndHashAlg(sigAlgOID); boolean valid = false; if (null == sigAndHashAlg) { // We don't recognize the 'signatureAlgorithm' of the certificate } else if (null == supportedSignatureAlgorithms) { short[] certificateTypes = certificateRequest.getCertificateTypes(); for (int j = 0; j < certificateTypes.length; ++j) { if (sigAndHashAlg.getSignature() == getLegacySignatureAlgorithmClientCert(certificateTypes[j])) { valid = true; break; } } } else { /* * RFC 5246 7.4.2. If the client provided a "signature_algorithms" extension, then * all certificates provided by the server MUST be signed by a hash/signature algorithm * pair that appears in that extension. */ valid = containsSignatureAlgorithm(supportedSignatureAlgorithms, sigAndHashAlg); } if (!valid) { throw new TlsFatalAlert(AlertDescription.bad_certificate); } } } static void checkSigAlgOfServerCerts(TlsContext context, Certificate serverCertificate) throws IOException { SecurityParameters securityParameters = context.getSecurityParametersHandshake(); Vector clientSigAlgsCert = securityParameters.getClientSigAlgsCert(); for (int i = 0; i < serverCertificate.getLength(); ++i) { String sigAlgOID = serverCertificate.getCertificateAt(i).getSigAlgOID(); SignatureAndHashAlgorithm sigAndHashAlg = getCertSigAndHashAlg(sigAlgOID); boolean valid = false; if (null == sigAndHashAlg) { // We don't recognize the 'signatureAlgorithm' of the certificate } else if (null == clientSigAlgsCert) { /* * RFC 4346 7.4.2. Unless otherwise specified, the signing algorithm for the * certificate MUST be the same as the algorithm for the certificate key. */ short signatureAlgorithm = getLegacySignatureAlgorithmServerCert( securityParameters.getKeyExchangeAlgorithm()); valid = (signatureAlgorithm == sigAndHashAlg.getSignature()); } else { /* * RFC 5246 7.4.2. If the client provided a "signature_algorithms" extension, then * all certificates provided by the server MUST be signed by a hash/signature algorithm * pair that appears in that extension. */ valid = containsSignatureAlgorithm(clientSigAlgsCert, sigAndHashAlg); } if (!valid) { throw new TlsFatalAlert(AlertDescription.bad_certificate); } } } static void checkTlsFeatures(Certificate serverCertificate, Hashtable clientExtensions, Hashtable serverExtensions) throws IOException { /* * RFC 7633 4.3.3. A client MUST treat a certificate with a TLS feature extension as an * invalid certificate if the features offered by the server do not contain all features * present in both the client's ClientHello message and the TLS feature extension. */ byte[] tlsFeatures = serverCertificate.getCertificateAt(0).getExtension(TlsObjectIdentifiers.id_pe_tlsfeature); if (tlsFeatures != null) { Enumeration tlsExtensions = ((ASN1Sequence)readDERObject(tlsFeatures)).getObjects(); while (tlsExtensions.hasMoreElements()) { BigInteger tlsExtension = ((ASN1Integer)tlsExtensions.nextElement()).getPositiveValue(); if (tlsExtension.bitLength() <= 16) { Integer extensionType = Integers.valueOf(tlsExtension.intValue()); if (clientExtensions.containsKey(extensionType) && !serverExtensions.containsKey(extensionType)) { throw new TlsFatalAlert(AlertDescription.certificate_unknown); } } } } } static void processClientCertificate(TlsServerContext serverContext, Certificate clientCertificate, CertificateRequest certificateRequest, TlsKeyExchange keyExchange, TlsServer server) throws IOException { SecurityParameters securityParameters = serverContext.getSecurityParametersHandshake(); if (null != securityParameters.getPeerCertificate()) { throw new TlsFatalAlert(AlertDescription.unexpected_message); } if (null == certificateRequest) { throw new TlsFatalAlert(AlertDescription.internal_error); } if (clientCertificate.isEmpty()) { /* * NOTE: We tolerate SSLv3 clients sending an empty chain, although "If no suitable * certificate is available, the client should send a no_certificate alert instead". */ keyExchange.skipClientCredentials(); } else { if (server.shouldCheckSigAlgOfPeerCerts()) { checkSigAlgOfClientCerts(serverContext, clientCertificate, certificateRequest); } keyExchange.processClientCertificate(clientCertificate); } securityParameters.peerCertificate = clientCertificate; /* * RFC 5246 7.4.6. If the client does not send any certificates, the server MAY at its * discretion either continue the handshake without client authentication, or respond with a * fatal handshake_failure alert. Also, if some aspect of the certificate chain was * unacceptable (e.g., it was not signed by a known, trusted CA), the server MAY at its * discretion either continue the handshake (considering the client unauthenticated) or send * a fatal alert. */ server.notifyClientCertificate(clientCertificate); } static void processServerCertificate(TlsClientContext clientContext, TlsClient client, CertificateStatus serverCertificateStatus, TlsKeyExchange keyExchange, TlsAuthentication clientAuthentication, Hashtable clientExtensions, Hashtable serverExtensions) throws IOException { SecurityParameters securityParameters = clientContext.getSecurityParametersHandshake(); if (null == clientAuthentication) { // There was no server certificate message; check it's OK keyExchange.skipServerCredentials(); securityParameters.tlsServerEndPoint = EMPTY_BYTES; return; } Certificate serverCertificate = securityParameters.getPeerCertificate(); checkTlsFeatures(serverCertificate, clientExtensions, serverExtensions); if (client.shouldCheckSigAlgOfPeerCerts()) { checkSigAlgOfServerCerts(clientContext, serverCertificate); } keyExchange.processServerCertificate(serverCertificate); clientAuthentication.notifyServerCertificate(new TlsServerCertificateImpl(serverCertificate, serverCertificateStatus)); } static SignatureAndHashAlgorithm getCertSigAndHashAlg(String sigAlgOID) { return (SignatureAndHashAlgorithm)CERT_SIG_ALG_OIDS.get(sigAlgOID); } static CertificateRequest validateCertificateRequest(CertificateRequest certificateRequest, TlsKeyExchange keyExchange) throws IOException { short[] validClientCertificateTypes = keyExchange.getClientCertificateTypes(); if (validClientCertificateTypes == null || validClientCertificateTypes.length < 1) { throw new TlsFatalAlert(AlertDescription.unexpected_message); } certificateRequest = normalizeCertificateRequest(certificateRequest, validClientCertificateTypes); if (certificateRequest == null) { throw new TlsFatalAlert(AlertDescription.illegal_parameter); } return certificateRequest; } static CertificateRequest normalizeCertificateRequest(CertificateRequest certificateRequest, short[] validClientCertificateTypes) { if (containsAll(validClientCertificateTypes, certificateRequest.getCertificateTypes())) { return certificateRequest; } short[] retained = retainAll(certificateRequest.getCertificateTypes(), validClientCertificateTypes); if (retained.length < 1) { return null; } return new CertificateRequest(retained, certificateRequest.getSupportedSignatureAlgorithms(), certificateRequest.getCertificateAuthorities()); } static boolean contains(int[] buf, int off, int len, int value) { for (int i = 0; i < len; ++i) { if (value == buf[off + i]) { return true; } } return false; } static boolean containsAll(short[] container, short[] elements) { for (int i = 0; i < elements.length; ++i) { if (!Arrays.contains(container, elements[i])) { return false; } } return true; } static short[] retainAll(short[] retainer, short[] elements) { short[] retained = new short[Math.min(retainer.length, elements.length)]; int count = 0; for (int i = 0; i < elements.length; ++i) { if (Arrays.contains(retainer, elements[i])) { retained[count++] = elements[i]; } } return truncate(retained, count); } static short[] truncate(short[] a, int n) { if (n < a.length) { return a; } short[] t = new short[n]; System.arraycopy(a, 0, t, 0, n); return t; } static TlsCredentialedAgreement requireAgreementCredentials(TlsCredentials credentials) throws IOException { if (!(credentials instanceof TlsCredentialedAgreement)) { throw new TlsFatalAlert(AlertDescription.internal_error); } return (TlsCredentialedAgreement)credentials; } static TlsCredentialedDecryptor requireDecryptorCredentials(TlsCredentials credentials) throws IOException { if (!(credentials instanceof TlsCredentialedDecryptor)) { throw new TlsFatalAlert(AlertDescription.internal_error); } return (TlsCredentialedDecryptor)credentials; } static TlsCredentialedSigner requireSignerCredentials(TlsCredentials credentials) throws IOException { if (!(credentials instanceof TlsCredentialedSigner)) { throw new TlsFatalAlert(AlertDescription.internal_error); } return (TlsCredentialedSigner)credentials; } private static void checkDowngradeMarker(byte[] randomBlock, byte[] downgradeMarker) throws IOException { byte[] bytes = copyOfRangeExact(randomBlock, randomBlock.length - downgradeMarker.length, randomBlock.length); if (Arrays.constantTimeAreEqual(bytes, downgradeMarker)) { throw new TlsFatalAlert(AlertDescription.illegal_parameter); } } static void checkDowngradeMarker(ProtocolVersion version, byte[] randomBlock) throws IOException { version = version.getEquivalentTLSVersion(); if (version.isEqualOrEarlierVersionOf(ProtocolVersion.TLSv11)) { checkDowngradeMarker(randomBlock, DOWNGRADE_TLS11); } if (version.isEqualOrEarlierVersionOf(ProtocolVersion.TLSv12)) { checkDowngradeMarker(randomBlock, DOWNGRADE_TLS12); } } static void writeDowngradeMarker(ProtocolVersion version, byte[] randomBlock) throws IOException { version = version.getEquivalentTLSVersion(); byte[] marker; if (ProtocolVersion.TLSv12 == version) { marker = DOWNGRADE_TLS12; } else if (version.isEqualOrEarlierVersionOf(ProtocolVersion.TLSv11)) { marker = DOWNGRADE_TLS11; } else { throw new TlsFatalAlert(AlertDescription.internal_error); } System.arraycopy(marker, 0, randomBlock, randomBlock.length - marker.length, marker.length); } static void receiveServerCertificate(TlsClientContext clientContext, ByteArrayInputStream buf) throws IOException { SecurityParameters securityParameters = clientContext.getSecurityParametersHandshake(); if (null != securityParameters.getPeerCertificate()) { throw new TlsFatalAlert(AlertDescription.unexpected_message); } ByteArrayOutputStream endPointHash = new ByteArrayOutputStream(); Certificate serverCertificate = Certificate.parse(clientContext, buf, endPointHash); TlsProtocol.assertEmpty(buf); if (serverCertificate.isEmpty()) { throw new TlsFatalAlert(AlertDescription.bad_certificate); } securityParameters.peerCertificate = serverCertificate; securityParameters.tlsServerEndPoint = endPointHash.toByteArray(); } public static boolean containsNonAscii(byte[] bs) { for (int i = 0; i < bs.length; ++i) { int c = bs[i] & 0xFF;; if (c >= 0x80) { return true; } } return false; } public static boolean containsNonAscii(String s) { for (int i = 0; i < s.length(); ++i) { int c = s.charAt(i); if (c >= 0x80) { return true; } } return false; } static Hashtable addEarlyKeySharesToClientHello(TlsContext context, TlsClient client, Hashtable clientExtensions) throws IOException { if (!TlsUtils.isTLSv13(context.getClientVersion())) { return null; } Hashtable clientAgreements = new Hashtable(); Vector clientShares = new Vector(); collectEarlyKeyShares(context.getCrypto(), client, clientExtensions, clientAgreements, clientShares); TlsExtensionsUtils.addKeyShareClientHello(clientExtensions, clientShares); return clientAgreements; } private static void collectEarlyKeyShares(TlsCrypto crypto, TlsClient client, Hashtable clientExtensions, Hashtable clientAgreements, Vector clientShares) throws IOException { Vector earlyGroups = client.getEarlyKeyShareGroups(); if (null == earlyGroups || earlyGroups.isEmpty()) { return; } int[] offeredGroups = TlsExtensionsUtils.getSupportedGroupsExtension(clientExtensions); if (null == offeredGroups || offeredGroups.length < 1) { return; } for (int i = 0; i < offeredGroups.length; ++i) { int offeredGroup = offeredGroups[i]; Integer offeredGroupElement = Integers.valueOf(offeredGroup); if (!earlyGroups.contains(offeredGroupElement) || clientAgreements.containsKey(offeredGroupElement) || !crypto.hasNamedGroup(offeredGroup)) { continue; } TlsAgreement agreement = null; if (NamedGroup.refersToASpecificCurve(offeredGroup)) { if (crypto.hasECDHAgreement()) { agreement = crypto.createECDomain(new TlsECConfig(offeredGroup)).createECDH(); } } else if (NamedGroup.refersToASpecificFiniteField(offeredGroup)) { if (crypto.hasDHAgreement()) { agreement = crypto.createDHDomain(new TlsDHConfig(offeredGroup, true)).createDH(); } } if (null != agreement) { byte[] key_exchange = agreement.generateEphemeral(); KeyShareEntry clientShare = new KeyShareEntry(offeredGroup, key_exchange); clientShares.addElement(clientShare); clientAgreements.put(offeredGroupElement, agreement); } } } static byte[] readEncryptedPMS(TlsContext context, InputStream input) throws IOException { if (isSSL(context)) { return SSL3Utils.readEncryptedPMS(input); } return readOpaque16(input); } static void writeEncryptedPMS(TlsContext context, byte[] encryptedPMS, OutputStream output) throws IOException { if (isSSL(context)) { SSL3Utils.writeEncryptedPMS(encryptedPMS, output); } else { writeOpaque16(encryptedPMS, output); } } static byte[] getSessionID(TlsSession tlsSession) { if (null != tlsSession) { byte[] sessionID = tlsSession.getSessionID(); if (null != sessionID && sessionID.length > 0 && sessionID.length <= 32) { return sessionID; } } return EMPTY_BYTES; } }
package name.abuchen.portfolio.ui.dialogs.transactions; import static name.abuchen.portfolio.ui.util.FormDataFactory.startingWith; import static name.abuchen.portfolio.ui.util.SWTHelper.amountWidth; import static name.abuchen.portfolio.ui.util.SWTHelper.currencyWidth; import static name.abuchen.portfolio.ui.util.SWTHelper.widest; import java.text.MessageFormat; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.inject.Inject; import javax.inject.Named; import org.eclipse.core.databinding.beans.BeanProperties; import org.eclipse.e4.core.di.extensions.Preference; import org.eclipse.e4.ui.services.IServiceConstants; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.databinding.swt.WidgetProperties; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import name.abuchen.portfolio.model.Account; import name.abuchen.portfolio.model.AccountTransaction; import name.abuchen.portfolio.model.Client; import name.abuchen.portfolio.model.Security; import name.abuchen.portfolio.money.CurrencyConverter; import name.abuchen.portfolio.money.CurrencyConverterImpl; import name.abuchen.portfolio.money.ExchangeRateProviderFactory; import name.abuchen.portfolio.money.Values; import name.abuchen.portfolio.snapshot.ClientSnapshot; import name.abuchen.portfolio.snapshot.PortfolioSnapshot; import name.abuchen.portfolio.snapshot.SecurityPosition; import name.abuchen.portfolio.ui.Messages; import name.abuchen.portfolio.ui.UIConstants; import name.abuchen.portfolio.ui.dialogs.transactions.AccountTransactionModel.Properties; import name.abuchen.portfolio.ui.util.DateTimePicker; import name.abuchen.portfolio.ui.util.FormDataFactory; import name.abuchen.portfolio.ui.util.LabelOnly; import name.abuchen.portfolio.ui.util.SimpleDateTimeSelectionProperty; @SuppressWarnings("restriction") public class AccountTransactionDialog extends AbstractTransactionDialog // NOSONAR { @Inject private Client client; @Preference(value = UIConstants.Preferences.USE_INDIRECT_QUOTATION) @Inject private boolean useIndirectQuotation = false; private Menu contextMenu; @Inject public AccountTransactionDialog(@Named(IServiceConstants.ACTIVE_SHELL) Shell parentShell) { super(parentShell); } @PostConstruct private void createModel(ExchangeRateProviderFactory factory, AccountTransaction.Type type) // NOSONAR { AccountTransactionModel m = new AccountTransactionModel(client, type); m.setExchangeRateProviderFactory(factory); setModel(m); // set account only if exactly one exists // (otherwise force user to choose) List<Account> activeAccounts = client.getActiveAccounts(); if (activeAccounts.size() == 1) m.setAccount(activeAccounts.get(0)); } private AccountTransactionModel model() { return (AccountTransactionModel) this.model; } @Override protected void createFormElements(Composite editArea) // NOSONAR { // input elements // security ComboInput securities = null; if (model().supportsSecurity()) securities = setupSecurities(editArea); // account ComboInput accounts = new ComboInput(editArea, Messages.ColumnAccount); accounts.value.setInput(including(client.getActiveAccounts(), model().getAccount())); accounts.bindValue(Properties.account.name(), Messages.MsgMissingAccount); accounts.bindCurrency(Properties.accountCurrencyCode.name()); // date Label lblDate = new Label(editArea, SWT.RIGHT); lblDate.setText(Messages.ColumnDate); DateTimePicker valueDate = new DateTimePicker(editArea); context.bindValue(new SimpleDateTimeSelectionProperty().observe(valueDate.getControl()), BeanProperties.value(Properties.date.name()).observe(model)); // shares Input shares = new Input(editArea, Messages.ColumnShares); shares.bindValue(Properties.shares.name(), Messages.ColumnShares, Values.Share, false); shares.setVisible(model().supportsShares()); Button btnShares = new Button(editArea, SWT.ARROW | SWT.DOWN); btnShares.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { showSharesContextMenu(); } }); btnShares.setVisible(model().supportsShares()); editArea.addDisposeListener(e -> AccountTransactionDialog.this.widgetDisposed()); // other input fields String totalLabel = model().supportsTaxUnits() ? Messages.ColumnGrossValue : getTotalLabel(); Input fxGrossAmount = new Input(editArea, totalLabel); fxGrossAmount.bindValue(Properties.fxGrossAmount.name(), totalLabel, Values.Amount, true); fxGrossAmount.bindCurrency(Properties.fxCurrencyCode.name()); Input exchangeRate = new Input(editArea, useIndirectQuotation ? "/ " : "x "); //$NON-NLS-1$ //$NON-NLS-2$ exchangeRate.bindBigDecimal( useIndirectQuotation ? Properties.inverseExchangeRate.name() : Properties.exchangeRate.name(), Values.ExchangeRate.pattern()); exchangeRate.bindCurrency(useIndirectQuotation ? Properties.inverseExchangeRateCurrencies.name() : Properties.exchangeRateCurrencies.name()); model().addPropertyChangeListener(Properties.exchangeRate.name(), e -> exchangeRate.value.setToolTipText(AbstractModel.createCurrencyToolTip( model().getExchangeRate(), model().getAccountCurrencyCode(), model().getSecurityCurrencyCode()))); Input grossAmount = new Input(editArea, "="); //$NON-NLS-1$ grossAmount.bindValue(Properties.grossAmount.name(), totalLabel, Values.Amount, true); grossAmount.bindCurrency(Properties.accountCurrencyCode.name()); // taxes Label plusForexTaxes = new Label(editArea, SWT.NONE); plusForexTaxes.setText("+"); //$NON-NLS-1$ plusForexTaxes.setVisible(model().supportsTaxUnits()); Input forexTaxes = new Input(editArea, Messages.ColumnTaxes); forexTaxes.bindValue(Properties.fxTaxes.name(), Messages.ColumnTaxes, Values.Amount, false); forexTaxes.bindCurrency(Properties.fxCurrencyCode.name()); forexTaxes.setVisible(model().supportsTaxUnits()); Input taxes = new Input(editArea, Messages.ColumnTaxes); taxes.bindValue(Properties.taxes.name(), Messages.ColumnTaxes, Values.Amount, false); taxes.bindCurrency(Properties.accountCurrencyCode.name()); taxes.setVisible(model().supportsTaxUnits()); taxes.label.setVisible(false); // will only show if no fx available // total Input total = new Input(editArea, getTotalLabel()); total.bindValue(Properties.total.name(), Messages.ColumnTotal, Values.Amount, false); total.bindCurrency(Properties.accountCurrencyCode.name()); total.setVisible(model().supportsTaxUnits()); // note Label lblNote = new Label(editArea, SWT.LEFT); lblNote.setText(Messages.ColumnNote); Text valueNote = new Text(editArea, SWT.BORDER); context.bindValue(WidgetProperties.text(SWT.Modify).observe(valueNote), BeanProperties.value(Properties.note.name()).observe(model)); // form layout int widest = widest(securities != null ? securities.label : null, accounts.label, lblDate, shares.label, fxGrossAmount.label, lblNote); FormDataFactory forms; if (securities != null) { forms = startingWith(securities.value.getControl(), securities.label).suffix(securities.currency) .thenBelow(accounts.value.getControl()).label(accounts.label).suffix(accounts.currency); startingWith(securities.label).width(widest); } else { forms = startingWith(accounts.value.getControl(), accounts.label).suffix(accounts.currency); startingWith(accounts.label).width(widest); } int amountWidth = amountWidth(grossAmount.value); int currencyWidth = currencyWidth(fxGrossAmount.currency); // date // shares forms = forms.thenBelow(valueDate.getControl()).label(lblDate) .thenBelow(shares.value).width(amountWidth).label(shares.label).suffix(btnShares) // fxAmount - exchange rate - amount .thenBelow(fxGrossAmount.value).width(amountWidth).label(fxGrossAmount.label) .thenRight(fxGrossAmount.currency).width(currencyWidth) .thenRight(exchangeRate.label) .thenRight(exchangeRate.value).width(amountWidth) .thenRight(exchangeRate.currency).width(amountWidth) .thenRight(grossAmount.label) .thenRight(grossAmount.value).width(amountWidth) .thenRight(grossAmount.currency).width(currencyWidth); // forexTaxes - taxes if (model().supportsTaxUnits()) { startingWith(grossAmount.value) .thenBelow(taxes.value).width(amountWidth).label(taxes.label).suffix(taxes.currency) .thenBelow(total.value).width(amountWidth).label(total.label).thenRight(total.currency) .width(currencyWidth); startingWith(taxes.value).thenLeft(plusForexTaxes).thenLeft(forexTaxes.currency).width(currencyWidth) .thenLeft(forexTaxes.value).width(amountWidth).thenLeft(forexTaxes.label); forms = startingWith(total.value); } // note forms.thenBelow(valueNote).left(accounts.value.getControl()).right(grossAmount.value).label(lblNote); // hide / show exchange rate if necessary model.addPropertyChangeListener(Properties.exchangeRateCurrencies.name(), event -> { // NOSONAR String securityCurrency = model().getSecurityCurrencyCode(); String accountCurrency = model().getAccountCurrencyCode(); // make exchange rate visible if both are set but different boolean isFxVisible = securityCurrency.length() > 0 && accountCurrency.length() > 0 && !securityCurrency.equals(accountCurrency); exchangeRate.setVisible(isFxVisible); grossAmount.setVisible(isFxVisible); forexTaxes.setVisible(isFxVisible && model().supportsShares()); plusForexTaxes.setVisible(isFxVisible && model().supportsShares()); taxes.label.setVisible(!isFxVisible && model().supportsShares()); // in case fx taxes have been entered if (!isFxVisible) model().setFxTaxes(0); // move input fields to have a nicer layout if (isFxVisible) startingWith(grossAmount.value).thenBelow(taxes.value); else startingWith(fxGrossAmount.value).thenBelow(taxes.value); editArea.layout(); }); WarningMessages warnings = new WarningMessages(this); warnings.add(() -> model().getDate().isAfter(LocalDate.now()) ? Messages.MsgDateIsInTheFuture : null); model.addPropertyChangeListener(Properties.date.name(), e -> warnings.check()); model.firePropertyChange(Properties.exchangeRateCurrencies.name(), "", model().getExchangeRateCurrencies()); //$NON-NLS-1$ } private ComboInput setupSecurities(Composite editArea) { List<Security> activeSecurities = new ArrayList<>(); activeSecurities.addAll(including(client.getActiveSecurities(), model().getSecurity())); // add empty security only if it has not been added previously // --> happens when editing an existing transaction if (model().supportsOptionalSecurity() && !activeSecurities.contains(AccountTransactionModel.EMPTY_SECURITY)) activeSecurities.add(0, AccountTransactionModel.EMPTY_SECURITY); ComboInput securities = new ComboInput(editArea, Messages.ColumnSecurity); securities.value.setInput(activeSecurities); securities.bindValue(Properties.security.name(), Messages.MsgMissingSecurity); securities.bindCurrency(Properties.securityCurrencyCode.name()); return securities; } private void showSharesContextMenu() { if (contextMenu == null) { MenuManager menuMgr = new MenuManager("#PopupMenu"); //$NON-NLS-1$ menuMgr.setRemoveAllWhenShown(true); menuMgr.addMenuListener(this::sharesMenuAboutToShow); contextMenu = menuMgr.createContextMenu(getShell()); } contextMenu.setVisible(true); } private void sharesMenuAboutToShow(IMenuManager manager) // NOSONAR { manager.add(new LabelOnly(Messages.DividendsDialogTitleShares)); CurrencyConverter converter = new CurrencyConverterImpl(model.getExchangeRateProviderFactory(), client.getBaseCurrency()); ClientSnapshot snapshot = ClientSnapshot.create(client, converter, model().getDate()); if (snapshot != null && model().getSecurity() != null) { PortfolioSnapshot jointPortfolio = snapshot.getJointPortfolio(); addAction(manager, jointPortfolio, Messages.ColumnSharesOwned); List<PortfolioSnapshot> list = snapshot.getPortfolios(); if (list.size() > 1) { for (PortfolioSnapshot ps : list) addAction(manager, ps, ps.getSource().getName()); } } manager.add(new Action(Messages.DividendsDialogLabelSpecialDistribution) { @Override public void run() { model().setShares(0); } }); } private void addAction(IMenuManager manager, PortfolioSnapshot portfolio, final String label) { final SecurityPosition position = portfolio.getPositionsBySecurity().get(model().getSecurity()); if (position != null) { Action action = new Action(MessageFormat.format(Messages.DividendsDialogLabelPortfolioSharesHeld, Values.Share.format(position.getShares()), label, Values.Date.format(portfolio.getTime()))) { @Override public void run() { model().setShares(position.getShares()); } }; manager.add(action); } } private void widgetDisposed() { if (contextMenu != null && !contextMenu.isDisposed()) contextMenu.dispose(); } private String getTotalLabel() // NOSONAR { switch (model().getType()) { case TAXES: case FEES: case INTEREST_CHARGE: case REMOVAL: return Messages.ColumnDebitNote; case INTEREST: case TAX_REFUND: case DIVIDENDS: case DEPOSIT: return Messages.ColumnCreditNote; case BUY: case SELL: case TRANSFER_IN: case TRANSFER_OUT: default: throw new UnsupportedOperationException(); } } @Override public void setAccount(Account account) { model().setAccount(account); } @Override public void setSecurity(Security security) { model().setSecurity(security); } public void setTransaction(Account account, AccountTransaction transaction) { model().setSource(account, transaction); } }
/** * Beacon component to find shortest paths based on dijkstra's algorithm */ package net.beaconcontroller.routing.dijkstra; import java.util.HashMap; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.TreeMap; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.beaconcontroller.core.IOFSwitch; import net.beaconcontroller.routing.IRoutingEngine; import net.beaconcontroller.routing.Link; import net.beaconcontroller.routing.Route; import net.beaconcontroller.routing.RouteId; import net.beaconcontroller.topology.ITopologyAware; /** * Beacon component to find shortest paths based on dijkstra's algorithm * * @author Mandeep Dhami (mandeep.dhami@bigswitch.com) */ public class RoutingImpl implements IRoutingEngine, ITopologyAware { public static final int MAX_LINK_WEIGHT = 1000; public static final int MAX_PATH_WEIGHT = Integer.MAX_VALUE - MAX_LINK_WEIGHT - 1; public static final int PATH_CACHE_SIZE = 1000; protected static Logger log; protected ReentrantReadWriteLock lock; protected HashMap<Long, TreeMap<Short, Link>> network; protected HashMap<Long, HashMap<Long, Link>> nexthoplinkmaps; protected HashMap<Long, HashMap<Long, Long>> nexthopnodemaps; protected LRUHashMap<RouteId, Route> pathcache; protected class NextHop { public HashMap<Long, Link> links = null; public HashMap<Long, Long> nodes = null; } public RoutingImpl() { log = LoggerFactory.getLogger(RoutingImpl.class); lock = new ReentrantReadWriteLock(); network = new HashMap<Long, TreeMap<Short, Link>>(); nexthoplinkmaps = new HashMap<Long, HashMap<Long, Link>>(); nexthopnodemaps = new HashMap<Long, HashMap<Long, Long>>(); pathcache = new LRUHashMap<RouteId, Route>(PATH_CACHE_SIZE); log.info("Initialized Dijkstra RouterImpl"); } @Override public boolean routeExists(Long srcId, Long dstId) { // self route check if (srcId.equals(dstId)) return true; // Check if next hop exists lock.readLock().lock(); HashMap<Long, Long> nexthopnodes = nexthopnodemaps.get(srcId); boolean exists = (nexthopnodes!=null) && (nexthopnodes.get(dstId)!=null); lock.readLock().unlock(); return exists; } @Override public void clear() { lock.writeLock().lock(); network.clear(); pathcache.clear(); nexthoplinkmaps.clear(); nexthopnodemaps.clear(); lock.writeLock().unlock(); } @Override public Route getRoute(IOFSwitch src, IOFSwitch dst) { return getRoute(src.getId(), dst.getId()); } @Override public Route getRoute(Long srcId, Long dstId) { lock.readLock().lock(); RouteId id = new RouteId(srcId, dstId); Route result = null; if (pathcache.containsKey(id)) { result = pathcache.get(id); } else { result = buildroute(id, srcId, dstId); pathcache.put(id, result); } lock.readLock().unlock(); log.debug("getRoute: {} -> {}", id, result); return result; } private Route buildroute(RouteId id, Long srcId, Long dstId) { LinkedList<Link> path = null; HashMap<Long, Link> nexthoplinks = nexthoplinkmaps.get(srcId); HashMap<Long, Long> nexthopnodes = nexthopnodemaps.get(srcId); if (!network.containsKey(srcId)) { // This is a switch that is not connected to any other switch // hence there was no update for links (and hence it is not in the network) log.debug("buildroute: Standalone switch: {}", srcId); // The only possible non-null path for this case is if (srcId == dstId) path = new LinkedList<Link>(); } else if ((nexthoplinks!=null) && (nexthoplinks.get(dstId)!=null) && (nexthopnodes!=null) && (nexthopnodes.get(dstId)!=null)) { // A valid path exits, calculate it path = new LinkedList<Link>(); while (srcId != dstId) { Link l = nexthoplinks.get(dstId); path.addFirst(l); dstId = nexthopnodes.get(dstId); } } // else, no path exists, and path == null Route result = null; if (path != null) result = new Route(id, path); log.debug("buildroute: {}", result); return result; } @Override public void linkUpdate(IOFSwitch src, short srcPort, IOFSwitch dst, short dstPort, boolean added) { update(src.getId(), srcPort, dst.getId(), dstPort, added); } @Override public void update(Long srcId, Integer srcPort, Long dstId, Integer dstPort, boolean added) { update(srcId, srcPort.shortValue(), dstId, dstPort.shortValue(), added); } @Override public void update(Long srcId, Short srcPort, Long dstId, Short dstPort, boolean added) { lock.writeLock().lock(); boolean network_updated = false; TreeMap<Short, Link> src = network.get(srcId); if (src == null) { log.debug("update: new node: {}", srcId); src = new TreeMap<Short, Link>(); network.put(srcId, src); network_updated = true; } TreeMap<Short, Link> dst = network.get(dstId); if (dst == null) { log.debug("update: new node: {}", dstId); dst = new TreeMap<Short, Link>(); network.put(dstId, dst); network_updated = true; } if (added) { Link srcLink = new Link(srcPort, dstPort, dstId); if (src.containsKey(srcPort)) { log.debug("update: unexpected link add request - srcPort in use src, link: {}, {}", srcId, src.get(srcPort)); } log.debug("update: added link: {}, {}", srcId, srcLink); src.put(srcPort, srcLink); network_updated = true; } else { // Only remove if that link actually exists. if (src.containsKey(srcPort) && src.get(srcPort).getDst()==dstId) { log.debug("update: removed link: {}, {}", srcId, srcPort); src.remove(srcPort); network_updated = true; } else { log.debug("update: unexpected link delete request (ignored) - src, port: {}, {}", srcId, srcPort); log.debug("update: current port value is being kept: {}", src.get(srcPort)); } } if (network_updated) { recalculate(); log.debug("update: dijkstra recalulated"); } else { log.debug("update: dijkstra not recalculated"); } lock.writeLock().unlock(); return; } private void recalculate() { pathcache.clear(); nexthoplinkmaps.clear(); nexthopnodemaps.clear(); for (Long node : network.keySet()) { NextHop nexthop = dijkstra(node); nexthoplinkmaps.put(node, nexthop.links); nexthopnodemaps.put(node, nexthop.nodes); } return; } private class NodeDist implements Comparable<NodeDist> { private Long node; public Long getNode() { return node; } private int dist; public int getDist() { return dist; } public NodeDist(Long node, int dist) { this.node = node; this.dist = dist; } public int compareTo(NodeDist o) { return o.dist - this.dist; } } private NextHop dijkstra(Long src) { HashMap<Long, Link> nexthoplinks = new HashMap<Long, Link>(); HashMap<Long, Long> nexthopnodes = new HashMap<Long, Long>(); HashMap<Long, Integer> dist = new HashMap<Long, Integer>(); for (Long node: network.keySet()) { nexthoplinks.put(node, null); nexthopnodes.put(node, null); dist.put(node, MAX_PATH_WEIGHT); } HashMap<Long, Boolean> seen = new HashMap<Long, Boolean>(); PriorityQueue<NodeDist> nodeq = new PriorityQueue<NodeDist>(); nodeq.add(new NodeDist(src, 0)); while (nodeq.peek() != null) { NodeDist n = nodeq.poll(); Long cnode = n.getNode(); int cdist = n.getDist(); if (cdist >= MAX_PATH_WEIGHT) break; if (seen.containsKey(cnode)) continue; seen.put(cnode, true); TreeMap<Short,Link> ports = network.get(cnode); for (Short port : ports.keySet()) { Link link = ports.get(port); Long neighbor = link.getDst(); int ndist = cdist + 1; // the weight of the link, always 1 in current version of beacon. if (ndist < dist.get(neighbor)) { dist.put(neighbor, ndist); nexthoplinks.put(neighbor, link); nexthopnodes.put(neighbor, cnode); nodeq.add(new NodeDist(neighbor, ndist)); } } } NextHop ret = new NextHop(); ret.links = nexthoplinks; ret.nodes = nexthopnodes; return ret; } public void startUp() {} public void shutDown() {} }
package de.lessvoid.nifty.controls.checkbox.controller; import de.lessvoid.nifty.Nifty; import de.lessvoid.nifty.controls.CheckBox; import de.lessvoid.nifty.controls.checkbox.CheckboxControl; import de.lessvoid.nifty.controls.checkbox.builder.CheckboxBuilder; import de.lessvoid.nifty.elements.Element; import de.lessvoid.nifty.loaderv2.types.ControlType; import de.lessvoid.nifty.loaderv2.types.ElementType; import de.lessvoid.nifty.screen.Screen; import org.junit.Before; import org.junit.Test; import static org.easymock.EasyMock.createMock; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.expectLastCall; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; import static org.junit.Assert.assertEquals; public class CreateCheckBoxControlTest { private Nifty niftyMock; private Screen screenMock; private Element parentMock; private Element checkBoxElementMock; private CheckboxControl checkBoxControlMock; private ControlType controlTypeMock; @Before public void setup() { niftyMock = createMock(Nifty.class); screenMock = createMock(Screen.class); parentMock = createMock(Element.class); checkBoxElementMock = createMock(Element.class); checkBoxControlMock = createMock(CheckboxControl.class); controlTypeMock = createMock(ControlType.class); } @Test public void testCreateWithId() { replay(screenMock, controlTypeMock, checkBoxControlMock); expect(niftyMock.createElementFromType(screenMock, parentMock, controlTypeMock)).andReturn(checkBoxElementMock); replay(niftyMock); expect(parentMock.getNifty()).andReturn(niftyMock); expect(parentMock.getScreen()).andReturn(screenMock); parentMock.layoutElements(); expectLastCall(); replay(parentMock); expect(checkBoxElementMock.getNiftyControl(CheckBox.class)).andReturn(checkBoxControlMock); replay(checkBoxElementMock); CheckboxBuilder checkboxBuilder = new CheckboxBuilder("0815") { @Override public ElementType buildElementType() { return controlTypeMock; } }; CheckBox checkBoxControl = checkboxBuilder.build(niftyMock, screenMock, parentMock) .getNiftyControl(CheckBox.class); assertEquals(checkBoxControlMock, checkBoxControl); verify(niftyMock); verify(parentMock); verify(checkBoxElementMock); verify(checkBoxControlMock); } }
package com.yahoo.vespa.hosted.node.admin.configserver.noderepository; import com.yahoo.vespa.hosted.dockerapi.DockerImage; import java.util.Objects; public class NodeAttributes { private Long restartGeneration = null; private Long rebootGeneration = null; private DockerImage dockerImage = null; private String hardwareDivergence = null; public NodeAttributes() { } public NodeAttributes withRestartGeneration(Long restartGeneration) { this.restartGeneration = restartGeneration; return this; } public NodeAttributes withRebootGeneration(Long rebootGeneration) { this.rebootGeneration = rebootGeneration; return this; } public NodeAttributes withDockerImage(DockerImage dockerImage) { this.dockerImage = dockerImage; return this; } public NodeAttributes withHardwareDivergence(String hardwareDivergence) { this.hardwareDivergence = hardwareDivergence; return this; } public Long getRestartGeneration() { return restartGeneration; } public Long getRebootGeneration() { return rebootGeneration; } public DockerImage getDockerImage() { return dockerImage; } public String getHardwareDivergence() { return hardwareDivergence; } @Override public int hashCode() { return Objects.hash(restartGeneration, rebootGeneration, dockerImage, hardwareDivergence); } @Override public boolean equals(final Object o) { if (!(o instanceof NodeAttributes)) { return false; } final NodeAttributes other = (NodeAttributes) o; return Objects.equals(restartGeneration, other.restartGeneration) && Objects.equals(rebootGeneration, other.rebootGeneration) && Objects.equals(dockerImage, other.dockerImage) && Objects.equals(hardwareDivergence, other.hardwareDivergence); } @Override public String toString() { return "NodeAttributes{" + "restartGeneration=" + restartGeneration + ", rebootGeneration=" + rebootGeneration + ", dockerImage=" + dockerImage.asString() + ", hardwareDivergence='" + hardwareDivergence + '\'' + '}'; } }
package cz.mzk.mapseries.github; import cz.mzk.mapseries.Constants; import cz.mzk.mapseries.Pair; import cz.mzk.mapseries.dao.AdminManager; import java.io.IOException; import java.io.Serializable; import java.net.URI; import java.util.ArrayList; import java.util.Arrays; import java.util.Base64; import java.util.Calendar; import java.util.LinkedList; import java.util.List; import javax.ejb.EJB; import javax.enterprise.context.SessionScoped; import javax.inject.Inject; import javax.inject.Named; import javax.servlet.http.HttpSession; import org.apache.commons.io.IOUtils; import org.apache.http.Consts; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URIBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.eclipse.egit.github.core.Blob; import org.eclipse.egit.github.core.Commit; import org.eclipse.egit.github.core.CommitUser; import org.eclipse.egit.github.core.Reference; import org.eclipse.egit.github.core.Repository; import org.eclipse.egit.github.core.Tree; import org.eclipse.egit.github.core.TreeEntry; import org.eclipse.egit.github.core.TypedResource; import org.eclipse.egit.github.core.User; import org.eclipse.egit.github.core.client.GitHubClient; import org.eclipse.egit.github.core.service.DataService; import org.eclipse.egit.github.core.service.RepositoryService; import org.eclipse.egit.github.core.service.UserService; import org.jboss.logging.Logger; import org.json.JSONObject; /** * @author Erich Duda <dudaerich@gmail.com> */ @Named @SessionScoped public class GithubService implements Serializable { private static final Logger LOG = Logger.getLogger(GithubService.class); @Inject private HttpSession httpSession; @EJB private AdminManager adminManager; private String token; private String userName; private String login; public String authenticate(String code) throws Exception { try { URI githubUri = new URIBuilder() .setScheme("https") .setHost("github.com") .setPath("/login/oauth/access_token") .build(); List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("client_id", Constants.GITHUB_CLIENT_ID)); params.add(new BasicNameValuePair("client_secret", Constants.GITHUB_CLIENT_SECRET)); params.add(new BasicNameValuePair("code", code)); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, Consts.UTF_8); HttpPost httpPost = new HttpPost(githubUri); httpPost.setEntity(entity); httpPost.addHeader("Accept", "application/json"); httpPost.addHeader("Accept-Charset", "utf-8"); CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse httpResponse = httpClient.execute(httpPost); String jsonString = IOUtils.toString( httpResponse.getEntity().getContent(), "UTF-8"); JSONObject jsonObject = new JSONObject(jsonString); if (jsonObject.has("access_token")) { token = jsonObject.getString("access_token"); return token; } else { String error = jsonObject.optString("error", "Unexpected error"); throw new Exception(error); } } catch (Exception e) { throw new Exception(e); } } public void logout() { httpSession.invalidate(); } public boolean isAuthenticate() { return token != null; } public boolean isAdmin() { String login = getLogin(); return adminManager.isAdmin(login); } public String getUserName() { if (userName == null) { UserService service = new UserService(getGithubClient()); try { userName = service.getUser().getName(); } catch (IOException e) { LOG.error(e.getMessage(), e); userName = ""; } } return userName; } public String getLogin() { if (login == null) { UserService service = new UserService(getGithubClient()); try { login = service.getUser().getLogin(); } catch (IOException e) { LOG.error(e.getMessage(), e); login = ""; } } return login; } public void saveFile(String commitMessage, String path, String content) throws Exception { GitHubClient githubClient = getGithubClient(); DataService dataService = new DataService(githubClient); RepositoryService repositoryService = new RepositoryService(githubClient); UserService userService = new UserService(githubClient); User user = userService.getUser(); Repository repository = repositoryService.getRepository(Constants.REPO_USER, Constants.REPO_NAME); Blob blob = new Blob(); blob.setContent(content); blob.setEncoding("utf-8"); String blobSha = dataService.createBlob(repository, blob); TreeEntry treeEntry = new TreeEntry(); treeEntry.setSha(blobSha); treeEntry.setPath(path); treeEntry.setType("blob"); treeEntry.setMode("100644"); Reference reference = dataService.getReference(repository, "heads/master"); Commit masterCommit = dataService.getCommit(repository, reference.getObject().getSha()); Tree tree = dataService.createTree(repository, Arrays.asList(treeEntry), masterCommit.getTree().getSha()); CommitUser commitUser = new CommitUser(); commitUser.setDate(Calendar.getInstance().getTime()); commitUser.setName(getOrDefault(user.getName(), "")); commitUser.setEmail(getOrDefault(user.getEmail(), "")); Commit commit = new Commit(); commit.setMessage(commitMessage); commit.setParents(Arrays.asList(masterCommit)); commit.setTree(tree); commit.setAuthor(commitUser); commit.setCommitter(commitUser); Commit newCommit = dataService.createCommit(repository, commit); TypedResource typedResource = new TypedResource(); typedResource.setSha(newCommit.getSha()); Reference newReference = new Reference(); newReference.setRef(reference.getRef()); newReference.setObject(typedResource); dataService.editReference(repository, newReference); } public String loadFile(String path) throws Exception { GitHubClient githubClient = getGithubClient(); DataService dataService = new DataService(githubClient); RepositoryService repositoryService = new RepositoryService(githubClient); Repository repository = repositoryService.getRepository(Constants.REPO_USER, Constants.REPO_NAME); Reference reference = dataService.getReference(repository, "heads/master"); Tree tree = dataService.getTree(repository, reference.getObject().getSha()); LinkedList<Pair<String, TreeEntry>> front = new LinkedList<>(); for (TreeEntry treeEntry : tree.getTree()) { front.addFirst(new Pair<>("", treeEntry)); } while (!front.isEmpty()) { Pair<String, TreeEntry> pair = front.removeLast(); if ("tree".equals(pair.getRight().getType())) { Tree t = dataService.getTree(repository, pair.getRight().getSha()); for (TreeEntry te : t.getTree()) { front.addFirst(new Pair<>(String.format("%s/%s", pair.getLeft(), pair.getRight().getPath()), te)); } } else { String treePath = String.format("%s/%s", pair.getLeft(), pair.getRight().getPath()); if (path.equals(treePath)) { Blob blob = dataService.getBlob(repository, pair.getRight().getSha()); String content = blob.getContent().replaceAll("\\s+", ""); LOG.infof("\"%s\"", content); return new String(Base64.getDecoder().decode(content)); } } } return null; } private GitHubClient getGithubClient() { GitHubClient gitHubClient = new GitHubClient(); String githubToken = getGithubToken(); if (githubToken != null) { gitHubClient.setOAuth2Token(getGithubToken()); } return gitHubClient; } private String getGithubToken() { if (token == null) { return null; } else { return token; } } private static String getOrDefault(String val, String def) { if (val == null) { return def; } return val; } }
package org.eclipse.dawnsci.plotting.api.remote; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.dawnsci.plotting.api.IPlotActionSystem; import org.eclipse.dawnsci.plotting.api.IPlottingSystem; import org.eclipse.dawnsci.plotting.api.PlotType; import org.eclipse.dawnsci.plotting.api.annotation.IAnnotation; import org.eclipse.dawnsci.plotting.api.axis.IAxis; import org.eclipse.dawnsci.plotting.api.axis.IClickListener; import org.eclipse.dawnsci.plotting.api.axis.IPositionListener; import org.eclipse.dawnsci.plotting.api.region.IRegion; import org.eclipse.dawnsci.plotting.api.region.IRegion.RegionType; import org.eclipse.dawnsci.plotting.api.region.IRegionListener; import org.eclipse.dawnsci.plotting.api.trace.ColorOption; import org.eclipse.dawnsci.plotting.api.trace.IImageStackTrace; import org.eclipse.dawnsci.plotting.api.trace.IImageTrace; import org.eclipse.dawnsci.plotting.api.trace.IIsosurfaceTrace; import org.eclipse.dawnsci.plotting.api.trace.ILineStackTrace; import org.eclipse.dawnsci.plotting.api.trace.ILineTrace; import org.eclipse.dawnsci.plotting.api.trace.IMulti2DTrace; import org.eclipse.dawnsci.plotting.api.trace.IPlane3DTrace; import org.eclipse.dawnsci.plotting.api.trace.IScatter3DTrace; import org.eclipse.dawnsci.plotting.api.trace.ISurfaceTrace; import org.eclipse.dawnsci.plotting.api.trace.ITrace; import org.eclipse.dawnsci.plotting.api.trace.ITraceListener; import org.eclipse.dawnsci.plotting.api.trace.IVectorTrace; import org.eclipse.dawnsci.plotting.api.trace.IVolumeRenderTrace; import org.eclipse.dawnsci.plotting.api.trace.TraceEvent; import org.eclipse.dawnsci.plotting.api.trace.TraceWillPlotEvent; import org.eclipse.january.dataset.IDataset; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.widgets.Control; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IWorkbenchPart; /** * Will be a thread safe version of all the plotting system methods. * * @author Matthew Gerring * */ public class ThreadSafePlottingSystem<T> extends ThreadSafeObject implements IPlottingSystem<T> { private IPlottingSystem<T> delegate; public ThreadSafePlottingSystem(IPlottingSystem<T> delegate) throws Exception { super(delegate); this.delegate = delegate; } @Override public IImageTrace createImageTrace(String traceName) { return new ThreadSafeTrace((IImageTrace)call(getMethodName(Thread.currentThread().getStackTrace()), traceName)); } public Control setControl(Control alternative, boolean isToolbar) { throw new RuntimeException("Expert method "+getMethodName(Thread.currentThread().getStackTrace())+" is not allowed in remote mode!"); } @Override public ILineTrace createLineTrace(String traceName) { return new ThreadSafeTrace((ILineTrace)call(getMethodName(Thread.currentThread().getStackTrace()), traceName)); } @Override public IVectorTrace createVectorTrace(String traceName) { return new ThreadSafeTrace((IVectorTrace)call(getMethodName(Thread.currentThread().getStackTrace()), traceName)); } @Override public ISurfaceTrace createSurfaceTrace(String traceName) { return new ThreadSafeTrace((ISurfaceTrace)call(getMethodName(Thread.currentThread().getStackTrace()), traceName)); } @Override public IIsosurfaceTrace createIsosurfaceTrace(String traceName) { return new ThreadSafeTrace((IIsosurfaceTrace)call(getMethodName(Thread.currentThread().getStackTrace()), traceName)); } @Override public IVolumeRenderTrace createVolumeRenderTrace(String traceName) { return new ThreadSafeTrace((IVolumeRenderTrace)call(getMethodName(Thread.currentThread().getStackTrace()), traceName)); } @Override public IPlane3DTrace createPlane3DTrace(String traceName) { return new ThreadSafeTrace((IPlane3DTrace)call(getMethodName(Thread.currentThread().getStackTrace()), traceName)); } @Override public IMulti2DTrace createMulti2DTrace(String traceName) { return new ThreadSafeTrace((IMulti2DTrace)call(getMethodName(Thread.currentThread().getStackTrace()), traceName)); } @Override public ILineStackTrace createLineStackTrace(String traceName) { return new ThreadSafeTrace((ILineStackTrace)call(getMethodName(Thread.currentThread().getStackTrace()), traceName)); } @Override public IScatter3DTrace createScatter3DTrace(String traceName) { return new ThreadSafeTrace((IScatter3DTrace)call(getMethodName(Thread.currentThread().getStackTrace()), traceName)); } @Override public IImageStackTrace createImageStackTrace(String traceName) { return new ThreadSafeTrace((IImageStackTrace)call(getMethodName(Thread.currentThread().getStackTrace()), traceName)); } @Override public void addTrace(ITrace trace) { if (trace instanceof ThreadSafeTrace) trace = ((ThreadSafeTrace)trace).getDelegate(); call(getMethodName(Thread.currentThread().getStackTrace()), trace); } @Override public void removeTrace(ITrace trace) { if (trace instanceof ThreadSafeTrace) trace = ((ThreadSafeTrace)trace).getDelegate(); call(getMethodName(Thread.currentThread().getStackTrace()), trace); } @Override public ITrace getTrace(String name) { ITrace trace = delegate.getTrace(name); if (trace==null) return null; return new ThreadSafeTrace(trace); } @Override public Collection<ITrace> getTraces() { return getThreadSafe(delegate.getTraces()); } private List<ITrace> getThreadSafe(Collection<ITrace> traces) { if (traces==null) return null; if (traces.isEmpty()) return Collections.emptyList(); List<ITrace> ret = new ArrayList<ITrace>(traces.size()); for (ITrace iTrace : traces) ret.add(new ThreadSafeTrace(iTrace)); return ret; } @Override public Collection<ITrace> getTraces(Class<? extends ITrace> clazz) { return getThreadSafe(delegate.getTraces(clazz)); } @Override public void addTraceListener(ITraceListener l) { delegate.addTraceListener(l); } @Override public void removeTraceListener(ITraceListener l) { delegate.removeTraceListener(l); } @Override public void renameTrace(ITrace trace, String name) throws Exception { if (trace instanceof ThreadSafeTrace) trace = ((ThreadSafeTrace)trace).getDelegate(); call(getMethodName(Thread.currentThread().getStackTrace()), trace, name); } @Override public IRegion createRegion(String name, RegionType regionType) throws Exception { return (IRegion)call(getMethodName(Thread.currentThread().getStackTrace()), name, regionType); } @Override public void addRegion(IRegion region) { call(getMethodName(Thread.currentThread().getStackTrace()), region); } @Override public void removeRegion(IRegion region) { call(getMethodName(Thread.currentThread().getStackTrace()), region); } @Override public IRegion getRegion(String name) { return delegate.getRegion(name); } @Override public Collection<IRegion> getRegions(RegionType type) { return delegate.getRegions(type); } @Override public boolean addRegionListener(IRegionListener l) { return delegate.addRegionListener(l); } @Override public boolean removeRegionListener(IRegionListener l) { return delegate.removeRegionListener(l); } @Override public void clearRegions() { call(getMethodName(Thread.currentThread().getStackTrace())); } @Override public void clearTraces() { call(getMethodName(Thread.currentThread().getStackTrace())); } @Override public Collection<IRegion> getRegions() { return delegate.getRegions(); } @Override public void renameRegion(IRegion region, String name) { call(getMethodName(Thread.currentThread().getStackTrace()), region, name); } @Override public IAxis createAxis(String title, boolean isYAxis, int side) { return new ThreadSafeAxis((IAxis)call(getMethodName(Thread.currentThread().getStackTrace()), new Class[]{String.class, boolean.class, int.class}, title, isYAxis, side)); } @Override public IAxis getSelectedYAxis() { return new ThreadSafeAxis(delegate.getSelectedYAxis()); } @Override public void setSelectedYAxis(IAxis yAxis) { if (yAxis instanceof ThreadSafeAxis) yAxis = ((ThreadSafeAxis)yAxis).getDelegate(); call(getMethodName(Thread.currentThread().getStackTrace()), yAxis); } @Override public IAxis getSelectedXAxis() { return new ThreadSafeAxis(delegate.getSelectedXAxis()); } @Override public void setSelectedXAxis(IAxis xAxis) { if (xAxis instanceof ThreadSafeAxis) xAxis = ((ThreadSafeAxis)xAxis).getDelegate(); call(getMethodName(Thread.currentThread().getStackTrace()), xAxis); } @Override public void autoscaleAxes() { call(getMethodName(Thread.currentThread().getStackTrace())); } @Override public IAnnotation createAnnotation(String name) throws Exception { return (IAnnotation)call(getMethodName(Thread.currentThread().getStackTrace()), name); } @Override public void addAnnotation(IAnnotation annot) { call(getMethodName(Thread.currentThread().getStackTrace()), annot); } @Override public void removeAnnotation(IAnnotation annot) { call(getMethodName(Thread.currentThread().getStackTrace()), annot); } @Override public IAnnotation getAnnotation(String name) { return delegate.getAnnotation(name); } @Override public void clearAnnotations() { call(getMethodName(Thread.currentThread().getStackTrace())); } @Override public void renameAnnotation(IAnnotation annotation, String name) { call(getMethodName(Thread.currentThread().getStackTrace()), annotation, name); } @Override public void printPlotting() { call(getMethodName(Thread.currentThread().getStackTrace())); } @Override public void copyPlotting() { call(getMethodName(Thread.currentThread().getStackTrace())); } @Override public String savePlotting(String filename) throws Exception { return (String)call(getMethodName(Thread.currentThread().getStackTrace()), filename); } @Override public void savePlotting(String filename, String filetype) throws Exception { call(getMethodName(Thread.currentThread().getStackTrace()), filename, filetype); } @Override public String getTitle() { return (String)call(getMethodName(Thread.currentThread().getStackTrace())); } @Override public void setTitle(String title) { call(getMethodName(Thread.currentThread().getStackTrace()), title); } @Override public void setTitleColor(Color color) { call(getMethodName(Thread.currentThread().getStackTrace()), color); } @Override public void setBackgroundColor(Color color) { call(getMethodName(Thread.currentThread().getStackTrace()), color); } @Override public void createPlotPart(T parent, String plotName, IActionBars bars, PlotType hint, IWorkbenchPart part) { throw new RuntimeException("Cannot call createPlotPart, only allowed to use this from python!"); } @Override public String getPlotName() { return delegate.getPlotName(); } @Override public List<ITrace> createPlot1D(IDataset x, List<? extends IDataset> ys, IProgressMonitor monitor) { return getThreadSafe(delegate.createPlot1D(x, ys, monitor)); } @Override public List<ITrace> createPlot1D(IDataset x, List<? extends IDataset> ys, String title, IProgressMonitor monitor) { return getThreadSafe(delegate.createPlot1D(x, ys, title, monitor)); } @Override public List<ITrace> updatePlot1D(IDataset x, List<? extends IDataset> ys, IProgressMonitor monitor) { return getThreadSafe(delegate.updatePlot1D(x, ys, monitor)); } @Override public ITrace createPlot2D(IDataset image, List<? extends IDataset> axes, IProgressMonitor monitor) { return new ThreadSafeTrace(createPlot2D(image, axes, monitor)); } @Override public ITrace updatePlot2D(IDataset image, List<? extends IDataset> axes, IProgressMonitor monitor) { return new ThreadSafeTrace(delegate.updatePlot2D(image, axes, monitor)); } @Override public void setPlotType(PlotType plotType) { call(getMethodName(Thread.currentThread().getStackTrace()), plotType); } @Override public void append(String dataSetName, Number xValue, Number yValue, IProgressMonitor monitor) throws Exception { delegate.append(dataSetName, xValue, yValue, monitor); } @Override public void reset() { delegate.reset(); } @Override public void resetAxes() { delegate.resetAxes(); } @Override public void clear() { delegate.clear(); } @Override public void dispose() { call(getMethodName(Thread.currentThread().getStackTrace())); } @Override public void repaint() { call(getMethodName(Thread.currentThread().getStackTrace())); } @Override public void repaint(boolean autoScale) { call(getMethodName(Thread.currentThread().getStackTrace()), new Class[]{boolean.class}, autoScale); } @Override public T getPlotComposite() { return (T) delegate.getPlotComposite(); } @Override public ISelectionProvider getSelectionProvider() { return delegate.getSelectionProvider(); } @Override public PlotType getPlotType() { return delegate.getPlotType(); } @Override public boolean is2D() { return delegate.is2D(); } @Override public IActionBars getActionBars() { return delegate.getActionBars(); } @Override public IPlotActionSystem getPlotActionSystem() { return delegate.getPlotActionSystem(); } @Override public void setDefaultCursor(int cursorType) { call(getMethodName(Thread.currentThread().getStackTrace()), new Class[]{int.class}, cursorType); } @Override public IAxis removeAxis(IAxis axis) { if (axis instanceof ThreadSafeAxis) axis = ((ThreadSafeAxis)axis).getDelegate(); return (IAxis)call(getMethodName(Thread.currentThread().getStackTrace()), axis); } @SuppressWarnings("unchecked") @Override public List<IAxis> getAxes() { List<IAxis> axes = (List<IAxis>)call(getMethodName(Thread.currentThread().getStackTrace())); if (axes==null) return null; List<IAxis> ret = new ArrayList<IAxis>(axes.size()); for (IAxis iAxis : axes) ret.add(new ThreadSafeAxis(iAxis)); return ret; } @Override public IAxis getAxis(String name) { return new ThreadSafeAxis((IAxis)call(getMethodName(Thread.currentThread().getStackTrace()), name)); } @Override public void addPositionListener(IPositionListener l) { call(getMethodName(Thread.currentThread().getStackTrace()), new Class[]{IPositionListener.class}, l); } @Override public void removePositionListener(IPositionListener l) { call(getMethodName(Thread.currentThread().getStackTrace()), new Class[]{IPositionListener.class}, l); } @Override public void setKeepAspect(boolean b) { call(getMethodName(Thread.currentThread().getStackTrace()), new Class[] { boolean.class }, b); } @Override public boolean isShowIntensity() { return (Boolean)call(getMethodName(Thread.currentThread().getStackTrace())); } @Override public void setShowIntensity(boolean b) { call(getMethodName(Thread.currentThread().getStackTrace()), new Class[] { boolean.class }, b); } @Override public boolean isShowValueLabels() { return (Boolean)call(getMethodName(Thread.currentThread().getStackTrace())); } @Override public void setShowValueLabels(boolean b) { call(getMethodName(Thread.currentThread().getStackTrace()), new Class[] { boolean.class }, b); } @Override public void setShowLegend(boolean b) { call(getMethodName(Thread.currentThread().getStackTrace()), new Class[] { boolean.class }, b); } @SuppressWarnings("unchecked") @Override public Object getAdapter(@SuppressWarnings("rawtypes") Class adapter) { return call(getMethodName(Thread.currentThread().getStackTrace()), new Class[] { adapter }, adapter); } @Override public boolean isDisposed() { return (Boolean)call(getMethodName(Thread.currentThread().getStackTrace())); } @Override public void setColorOption(ColorOption colorOption) { call(getMethodName(Thread.currentThread().getStackTrace()), new Class[] { ColorOption.class }, colorOption); } @Override public boolean isRescale() { return (Boolean)call(getMethodName(Thread.currentThread().getStackTrace())); } @Override public void setRescale(boolean rescale) { call(getMethodName(Thread.currentThread().getStackTrace()), new Class[] { boolean.class }, rescale); } @Override public void setFocus() { call(getMethodName(Thread.currentThread().getStackTrace())); } public boolean isXFirst() { return (Boolean)call(getMethodName(Thread.currentThread().getStackTrace())); } /** * Set if the first plot is the x-axis. * @param xFirst */ public void setXFirst(boolean xFirst) { call(getMethodName(Thread.currentThread().getStackTrace()), new Class[]{boolean.class}, xFirst); } public void fireWillPlot(final TraceWillPlotEvent evt) { call(getMethodName(Thread.currentThread().getStackTrace()), evt); } /** * May be used to force a trace to fire update listeners in the plotting system. * @param evt */ public void fireTraceUpdated(final TraceEvent evt) { call(getMethodName(Thread.currentThread().getStackTrace()), evt); } public void fireTraceAdded(final TraceEvent evt) { call(getMethodName(Thread.currentThread().getStackTrace()), evt); } @Override public IWorkbenchPart getPart() { return (IWorkbenchPart)call(getMethodName(Thread.currentThread().getStackTrace())); } @Override public List<ITrace> createPlot1D(IDataset x, List<? extends IDataset> ys, List<String> dataNames, String title, IProgressMonitor monitor) { return getThreadSafe(delegate.createPlot1D(x,ys,dataNames, title, monitor)); } @Override public List<ITrace> updatePlot1D(IDataset x, List<? extends IDataset> ys, List<String> dataNames, IProgressMonitor monitor) { return getThreadSafe(delegate.updatePlot1D( x,ys,dataNames, monitor)); } @Override public List<ITrace> updatePlot1D(IDataset x, List<? extends IDataset> ys, String plotTitle, IProgressMonitor monitor) { return getThreadSafe(delegate.updatePlot1D( x,ys, plotTitle, monitor)); } @Override public ITrace createPlot2D(IDataset image, List<? extends IDataset> axes, String dataName, IProgressMonitor monitor) { return new ThreadSafeTrace(delegate.createPlot2D(image, axes, dataName, monitor)); } @Override public ITrace updatePlot2D(IDataset image, List<? extends IDataset> axes, String dataName, IProgressMonitor monitor) { return new ThreadSafeTrace(delegate.updatePlot2D(image, axes, dataName, monitor)); } @Override public void setEnabled(boolean enabled) { call(getMethodName(Thread.currentThread().getStackTrace()), new Class[]{boolean.class}, enabled); } @Override public boolean isEnabled() { return (Boolean)call(getMethodName(Thread.currentThread().getStackTrace())); } @Override public void addClickListener(IClickListener l) { call(getMethodName(Thread.currentThread().getStackTrace()), new Class[]{IClickListener.class}, l); } @Override public void removeClickListener(IClickListener l) { call(getMethodName(Thread.currentThread().getStackTrace()), new Class[]{IClickListener.class}, l); } @Override public void clearRegionTool() { call(getMethodName(Thread.currentThread().getStackTrace())); } @Override public void printScaledPlotting() { call(getMethodName(Thread.currentThread().getStackTrace())); } @Override public void moveTrace(String oldName, String name) { call(getMethodName(Thread.currentThread().getStackTrace()), oldName, name); } @Override public <U extends ITrace> U createTrace(String traceName, Class<U> clazz) { return delegate.createTrace(traceName, clazz); } @Override public List<Class<? extends ITrace>> getRegisteredTraceClasses() { return delegate.getRegisteredTraceClasses(); } }
package com.thaiopensource.xml.infer; import org.relaxng.datatype.DatatypeLibrary; import org.relaxng.datatype.Datatype; import org.relaxng.datatype.DatatypeException; import org.relaxng.datatype.DatatypeLibraryFactory; import com.thaiopensource.util.Uri; import com.thaiopensource.xml.util.WellKnownNamespaces; public class DatatypeRepertoire { static private final int TOKEN_TYPICAL_MAX_LENGTH = 32; static private final int BINARY_TYPICAL_MIN_LENGTH = 128; static private final String[] typeNames = { "boolean", // XXX add int? "integer", "decimal", "double", "NCName", "NMTOKEN", "time", "date", "dateTime", "duration", "hexBinary", "base64Binary", "anyURI" }; static public class Type { private final Datatype dt; private final String name; private final int index; private Type(Datatype dt, String name, int index) { this.dt = dt; this.name = name; this.index = index; } public boolean matches(String value) { return dt.isValid(value, null); } public boolean isTypical(String value) { return value.length() < TOKEN_TYPICAL_MAX_LENGTH; } public String getName() { return name; } public int getIndex() { return index; } } static public class BinaryType extends Type { private BinaryType(Datatype dt, String name, int index) { super(dt, name, index); } public boolean isTypical(String value) { return value.length() > BINARY_TYPICAL_MIN_LENGTH; } } static public class UriType extends Type { private UriType(Datatype dt, String name, int index) { super(dt, name, index); } public boolean isTypical(String value) { return Uri.isAbsolute(value); } } private final Type[] types = new Type[typeNames.length]; private int nTypes = 0; DatatypeRepertoire(DatatypeLibraryFactory factory) { DatatypeLibrary lib = factory.createDatatypeLibrary(WellKnownNamespaces.XML_SCHEMA_DATATYPES); if (lib == null) return; for (int i = 0; i < types.length; i++) { try { types[nTypes] = makeType(typeNames[i], lib.createDatatype(typeNames[i]), i); nTypes++; } catch (DatatypeException e) { } } } public int size() { return nTypes; } Type get(int i) { return types[i]; } static private Type makeType(String typeName, Datatype dt, int index) { if (typeName.equals("anyURI")) return new UriType(dt, typeName, index); else if (typeName.equals("base64Binary") || typeName.equals("hexBinary")) return new BinaryType(dt, typeName, index); return new Type(dt, typeName, index); } public static String getUri() { return WellKnownNamespaces.XML_SCHEMA_DATATYPES; } }
package org.eclipse.mylyn.internal.bugzilla.ui.editor; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.fieldassist.ContentProposalAdapter; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.mylyn.internal.bugzilla.core.BugzillaCorePlugin; import org.eclipse.mylyn.internal.bugzilla.core.BugzillaReportElement; import org.eclipse.mylyn.internal.bugzilla.ui.BugzillaUiPlugin; import org.eclipse.mylyn.tasks.core.RepositoryTaskAttribute; import org.eclipse.mylyn.tasks.ui.editors.AbstractNewRepositoryTaskEditor; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorSite; import org.eclipse.ui.fieldassist.ContentAssistCommandAdapter; import org.eclipse.ui.forms.editor.FormEditor; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.forms.widgets.Section; /** * An editor used to view a locally created bug that does not yet exist on a repository. * * @author Rob Elves */ public class NewBugzillaTaskEditor extends AbstractNewRepositoryTaskEditor { protected Text assignedTo; public NewBugzillaTaskEditor(FormEditor editor) { super(editor); } @Override public void init(IEditorSite site, IEditorInput input) { super.init(site, input); setExpandAttributeSection(true); } @Override protected void saveTaskOffline(IProgressMonitor progressMonitor) { String text = descriptionTextViewer.getTextWidget().getText(); if (repository.getVersion().startsWith("2.18")) { text = BugzillaUiPlugin.formatTextToLineWrap(text, true); descriptionTextViewer.getTextWidget().setText(text); } super.saveTaskOffline(progressMonitor); } @Override protected void createPeopleLayout(Composite composite) { FormToolkit toolkit = getManagedForm().getToolkit(); Section peopleSection = createSection(composite, getSectionLabel(SECTION_NAME.PEOPLE_SECTION)); GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).grab(true, true).applyTo(peopleSection); Composite peopleComposite = toolkit.createComposite(peopleSection); GridLayout layout = new GridLayout(2, false); layout.marginRight = 5; peopleComposite.setLayout(layout); GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).grab(true, true).applyTo(peopleComposite); addAssignedTo(peopleComposite); //addSelfToCC(peopleComposite); addCCList(peopleComposite); getManagedForm().getToolkit().paintBordersFor(peopleComposite); peopleSection.setClient(peopleComposite); peopleSection.setEnabled(true); } @Override public void submitToRepository() { if (summaryText.getText().equals("")) { MessageDialog.openInformation(this.getSite().getShell(), "Submit Error", "Please provide a brief summary with new reports."); summaryText.setFocus(); return; } else if (descriptionTextViewer.getTextWidget().getText().equals("")) { MessageDialog.openInformation(this.getSite().getShell(), "Submit Error", "Please proved a detailed summary with new reports"); descriptionTextViewer.getTextWidget().setFocus(); return; } RepositoryTaskAttribute attribute = taskData.getAttribute(BugzillaReportElement.COMPONENT.getKeyString()); String componentValue = attribute.getValue(); if (componentValue.equals("")) { MessageDialog.openInformation(this.getSite().getShell(), "Submit Error", "Please select a component with new reports"); descriptionTextViewer.getTextWidget().setFocus(); return; } super.submitToRepository(); } @Override protected void createCustomAttributeLayout(Composite composite) { RepositoryTaskAttribute attribute = this.taskData.getAttribute(BugzillaReportElement.DEPENDSON.getKeyString()); if (attribute != null && !attribute.isReadOnly()) { Label label = createLabel(composite, attribute); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label); Composite textFieldComposite = getManagedForm().getToolkit().createComposite(composite); GridLayout textLayout = new GridLayout(); textLayout.marginWidth = 1; textLayout.marginHeight = 3; textLayout.verticalSpacing = 3; textFieldComposite.setLayout(textLayout); GridData textData = new GridData(GridData.HORIZONTAL_ALIGN_FILL); textData.horizontalSpan = 1; textData.widthHint = 135; final Text text = createTextField(textFieldComposite, attribute, SWT.FLAT); text.setLayoutData(textData); getManagedForm().getToolkit().paintBordersFor(textFieldComposite); } attribute = this.taskData.getAttribute(BugzillaReportElement.BLOCKED.getKeyString()); if (attribute != null && !attribute.isReadOnly()) { Label label = createLabel(composite, attribute); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label); Composite textFieldComposite = getManagedForm().getToolkit().createComposite(composite); GridLayout textLayout = new GridLayout(); textLayout.marginWidth = 1; textLayout.marginHeight = 3; textLayout.verticalSpacing = 3; textFieldComposite.setLayout(textLayout); GridData textData = new GridData(GridData.HORIZONTAL_ALIGN_FILL); textData.horizontalSpan = 1; textData.widthHint = 135; final Text text = createTextField(textFieldComposite, attribute, SWT.FLAT); text.setLayoutData(textData); getManagedForm().getToolkit().paintBordersFor(textFieldComposite); } } @Override protected boolean hasContentAssist(RepositoryTaskAttribute attribute) { return BugzillaReportElement.NEWCC.getKeyString().equals(attribute.getId()); } /** * FIXME: A lot of duplicated code here between this and BugzillaTaskEditor */ @Override protected void addAssignedTo(Composite peopleComposite) { RepositoryTaskAttribute assignedAttribute = taskData.getAttribute(RepositoryTaskAttribute.USER_ASSIGNED); if (assignedAttribute != null) { String bugzillaVersion; try { bugzillaVersion = BugzillaCorePlugin.getRepositoryConfiguration(repository, false).getInstallVersion(); } catch (CoreException e1) { // ignore bugzillaVersion = "2.18"; } if (bugzillaVersion.compareTo("3.1") < 0) { // old bugzilla workflow is used super.addAssignedTo(peopleComposite); return; } Label label = createLabel(peopleComposite, assignedAttribute); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label); if (assignedAttribute.isReadOnly()) { assignedTo = createTextField(peopleComposite, assignedAttribute, SWT.FLAT | SWT.READ_ONLY); } else { assignedTo = createTextField(peopleComposite, assignedAttribute, SWT.FLAT); } GridDataFactory.fillDefaults().hint(150, SWT.DEFAULT).applyTo(assignedTo); assignedTo.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { String sel = assignedTo.getText(); RepositoryTaskAttribute a = taskData.getAttribute(RepositoryTaskAttribute.USER_ASSIGNED); if (!(a.getValue().equals(sel))) { a.setValue(sel); markDirty(true); } } }); ContentAssistCommandAdapter adapter = applyContentAssist(assignedTo, createContentProposalProvider(assignedAttribute)); ILabelProvider propsalLabelProvider = createProposalLabelProvider(assignedAttribute); if (propsalLabelProvider != null) { adapter.setLabelProvider(propsalLabelProvider); } adapter.setProposalAcceptanceStyle(ContentProposalAdapter.PROPOSAL_REPLACE); FormToolkit toolkit = getManagedForm().getToolkit(); Label dummylabel = toolkit.createLabel(peopleComposite, ""); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(dummylabel); RepositoryTaskAttribute attribute = taskData.getAttribute(BugzillaReportElement.SET_DEFAULT_ASSIGNEE.getKeyString()); if (attribute == null) { taskData.setAttributeValue(BugzillaReportElement.SET_DEFAULT_ASSIGNEE.getKeyString(), "0"); attribute = taskData.getAttribute(BugzillaReportElement.SET_DEFAULT_ASSIGNEE.getKeyString()); } addButtonField(peopleComposite, attribute, SWT.CHECK); } } private Button addButtonField(Composite rolesComposite, RepositoryTaskAttribute attribute, int style) { if (attribute == null) { return null; } String name = attribute.getName(); if (hasOutgoingChange(attribute)) { name += "*"; } final Button button = getManagedForm().getToolkit().createButton(rolesComposite, name, style); if (!attribute.isReadOnly()) { button.setData(attribute); button.setSelection(attribute.getValue().equals("1")); button.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); button.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { String sel = "1"; if (!button.getSelection()) { sel = "0"; } RepositoryTaskAttribute a = (RepositoryTaskAttribute) button.getData(); a.setValue(sel); attributeChanged(a); } }); } return button; } }
package com.conveyal.r5.labeling; import com.conveyal.osmlib.Way; import com.conveyal.r5.point_to_point.builder.SpeedConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.measure.converter.UnitConverter; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import static javax.measure.unit.NonSI.KILOMETERS_PER_HOUR; import static javax.measure.unit.NonSI.KNOT; import static javax.measure.unit.NonSI.MILES_PER_HOUR; import static javax.measure.unit.SI.METERS_PER_SECOND; /** * Gets information about max speeds based on highway tags from build-config * And for each way reads maxspeed tags and returns max speeds. * If maxspeed isn't specified then uses highway tags. Otherwise returns default max speed. */ public class SpeedLabeler { private static final Logger LOG = LoggerFactory.getLogger(SpeedLabeler.class); private static final Pattern maxSpeedPattern = Pattern.compile("^([0-9][\\.0-9]+?)(?:[ ]?(kmh|km/h|kmph|kph|mph|knots))?$"); private static Map<String, Float> highwaySpeedMap; // FIXME this is probably not supposed to be static. private Float defaultSpeed; public SpeedLabeler(SpeedConfig speedConfig) { //Converts all speeds from units to m/s UnitConverter unitConverter = null; //TODO: move this to SpeedConfig? switch (speedConfig.units) { case KMH: unitConverter = KILOMETERS_PER_HOUR.getConverterTo(METERS_PER_SECOND); break; case MPH: unitConverter = MILES_PER_HOUR.getConverterTo(METERS_PER_SECOND); break; case KNOTS: unitConverter = KNOT.getConverterTo(METERS_PER_SECOND); break; } highwaySpeedMap = new HashMap<>(speedConfig.values.size()); //TODO: add validation so that this could assume correct tags for (Map.Entry<String, Integer> highwaySpeed: speedConfig.values.entrySet()) { highwaySpeedMap.put(highwaySpeed.getKey(), (float) unitConverter.convert(highwaySpeed.getValue())); } defaultSpeed = (float) unitConverter.convert(speedConfig.defaultSpeed); } /** * @return maxspeed in m/s, looking first at maxspeed tags and falling back on highway type heuristics */ public float getSpeedMS(Way way, boolean back) { // first, check for maxspeed tags Float speed = null; if (way.hasTag("maxspeed:motorcar")) speed = getMetersSecondFromSpeed(way.getTag("maxspeed:motorcar")); if (speed == null && !back && way.hasTag("maxspeed:forward")) speed = getMetersSecondFromSpeed(way.getTag("maxspeed:forward")); if (speed == null && back && way.hasTag("maxspeed:reverse")) speed = getMetersSecondFromSpeed(way.getTag("maxspeed:reverse")); if (speed == null && way.hasTag("maxspeed:lanes")) { for (String lane : way.getTag("maxspeed:lanes").split("\\|")) { Float currentSpeed = getMetersSecondFromSpeed(lane); // Pick the largest speed from the tag // currentSpeed might be null if it was invalid, for instance 10|fast|20 if (currentSpeed != null && (speed == null || currentSpeed > speed)) speed = currentSpeed; } } if (way.hasTag("maxspeed") && speed == null) speed = getMetersSecondFromSpeed(way.getTag("maxspeed")); // this would be bad, as the segment could never be traversed by an automobile // The small epsilon is to account for possible rounding errors if (speed != null && speed < 0.0001) { LOG.warn("Automobile speed of {} based on OSM maxspeed tags. Ignoring these tags.", speed); speed = null; } // if there was a defined speed and it's not 0, we're done if (speed != null) return speed; if (way.getTag("highway") != null) { String highwayType = way.getTag("highway").toLowerCase().trim(); return highwaySpeedMap.getOrDefault(highwayType, defaultSpeed); } else { //TODO: figure out what kind of roads are without highway tags return defaultSpeed; } } /** * Returns speed in ms from text speed from OSM * * @author Matt Conway * @param speed * @return */ private Float getMetersSecondFromSpeed(String speed) { Matcher m = maxSpeedPattern.matcher(speed); if (!m.matches()) return null; float originalUnits; try { originalUnits = (float) Double.parseDouble(m.group(1)); } catch (NumberFormatException e) { LOG.warn("Could not parse max speed {}", m.group(1)); return null; } String units = m.group(2); if (units == null || units.equals("")) units = "kmh"; // we'll be doing quite a few string comparisons here units = units.intern(); float metersSecond; if (units == "kmh" || units == "km/h" || units == "kmph" || units == "kph") metersSecond = 0.277778f * originalUnits; else if (units == "mph") metersSecond = 0.446944f * originalUnits; else if (units == "knots") metersSecond = 0.514444f * originalUnits; else return null; return metersSecond; } }
package be.ibridge.kettle.trans.step.sql; import java.util.ArrayList; import be.ibridge.kettle.core.Const; import be.ibridge.kettle.core.Result; import be.ibridge.kettle.core.Row; import be.ibridge.kettle.core.database.Database; import be.ibridge.kettle.core.exception.KettleException; import be.ibridge.kettle.core.exception.KettleStepException; import be.ibridge.kettle.core.value.Value; import be.ibridge.kettle.trans.Trans; import be.ibridge.kettle.trans.TransMeta; import be.ibridge.kettle.trans.step.BaseStep; import be.ibridge.kettle.trans.step.StepDataInterface; import be.ibridge.kettle.trans.step.StepInterface; import be.ibridge.kettle.trans.step.StepMeta; import be.ibridge.kettle.trans.step.StepMetaInterface; /** * Execute one or more SQL statements in a script, one time or parameterised (for every row) * * @author Matt * @since 10-sep-2005 */ public class ExecSQL extends BaseStep implements StepInterface { private ExecSQLMeta meta; private ExecSQLData data; public ExecSQL(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans) { super(stepMeta, stepDataInterface, copyNr, transMeta, trans); } public static final Row getResultRow(Result result, String upd, String ins, String del, String read) { Row row = new Row(); if (upd!=null && upd.length()>0) { Value rowsUpdated = new Value(upd, result.getNrLinesUpdated()); rowsUpdated.setLength(9); row.addValue(rowsUpdated); } if (ins!=null && ins.length()>0) { Value rowsInserted = new Value(ins, result.getNrLinesOutput()); rowsInserted.setLength(9); row.addValue(rowsInserted); } if (del!=null && del.length()>0) { Value rowsDeleted = new Value(del, result.getNrLinesDeleted()); rowsDeleted.setLength(9); row.addValue(rowsDeleted); } if (read!=null && read.length()>0) { Value rowsRead = new Value(read, result.getNrLinesRead()); rowsRead.setLength(9); row.addValue(rowsRead); } return row; } public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException { meta=(ExecSQLMeta)smi; data=(ExecSQLData)sdi; Row row = null; if (!meta.isExecutedEachInputRow()) { row = getResultRow(data.result, meta.getUpdateField(), meta.getInsertField(), meta.getDeleteField(), meta.getReadField()); putRow(row); setOutputDone(); // Stop processing, this is all we do! return false; } row = getRow(); if (row==null) // no more input to be expected... { setOutputDone(); return false; } StringBuffer sql = new StringBuffer( meta.getSql() ); if (first) // we just got started { first=false; // Find the indexes of the arguments data.argumentIndexes = new int[meta.getArguments().length]; for (int i=0;i<meta.getArguments().length;i++) { data.argumentIndexes[i] = row.searchValueIndex(meta.getArguments()[i]); if (data.argumentIndexes[i]<0) { logError(Messages.getString("ExecSQL.Log.ErrorFindingField")+meta.getArguments()[i]+"]"); //$NON-NLS-1$ //$NON-NLS-2$ throw new KettleStepException(Messages.getString("ExecSQL.Exception.CouldNotFindField",meta.getArguments()[i])); //$NON-NLS-1$ //$NON-NLS-2$ } } // Find the locations of the question marks in the String... // We replace the question marks with the values... // We ignore quotes etc. to make inserts easier... data.markerPositions = new ArrayList(); int len = sql.length(); int pos = len-1; while (pos>=0) { if (sql.charAt(pos)=='?') data.markerPositions.add(new Integer(pos)); // save the marker position pos } } // Replace the values in the SQL string... for (int i=0;i<data.markerPositions.size();i++) { Value value = row.getValue( data.argumentIndexes[data.markerPositions.size()-i-1]); int pos = ((Integer)data.markerPositions.get(i)).intValue(); sql.replace(pos, pos+1, value.getString()); // replace the '?' with the String in the row. } if (log.isRowLevel()) logRowlevel(Messages.getString("ExecSQL.Log.ExecutingSQLScript")+Const.CR+sql); //$NON-NLS-1$ data.result = data.db.execStatements(sql.toString()); Row add = getResultRow(data.result, meta.getUpdateField(), meta.getInsertField(), meta.getDeleteField(), meta.getReadField()); row.addRow(add); if (!data.db.isAutoCommit()) data.db.commit(); putRow(row); // send it out! if ((linesWritten>0) && (linesWritten%Const.ROWS_UPDATE)==0) logBasic(Messages.getString("ExecSQL.Log.LineNumber")+linesWritten); //$NON-NLS-1$ return true; } public void dispose(StepMetaInterface smi, StepDataInterface sdi) { meta=(ExecSQLMeta)smi; data=(ExecSQLData)sdi; logBasic(Messages.getString("ExecSQL.Log.FinishingReadingQuery")); //$NON-NLS-1$ data.db.disconnect(); super.dispose(smi, sdi); } /** Stop the running query */ public void stopRunning(StepMetaInterface smi, StepDataInterface sdi) throws KettleException { meta=(ExecSQLMeta)smi; data=(ExecSQLData)sdi; if (data.db!=null) data.db.cancelQuery(); } public boolean init(StepMetaInterface smi, StepDataInterface sdi) { meta=(ExecSQLMeta)smi; data=(ExecSQLData)sdi; if (super.init(smi, sdi)) { data.db=new Database(meta.getDatabaseMeta()); // Connect to the database try { data.db.connect(); if (log.isDetailed()) logDetailed(Messages.getString("ExecSQL.Log.ConnectedToDB")); //$NON-NLS-1$ // If the SQL needs to be executed once, this is a starting step somewhere. if (!meta.isExecutedEachInputRow()) { data.result = data.db.execStatements(meta.getSql()); } return true; } catch(KettleException e) { logError(Messages.getString("ExecSQL.Log.ErrorOccurred")+e.getMessage()); //$NON-NLS-1$ setErrors(1); stopAll(); } } return false; } // Run is were the action happens! public void run() { try { logBasic(Messages.getString("ExecSQL.Log.StartingToRun")); //$NON-NLS-1$ while (!isStopped() && processRow(meta, data) ); } catch(Exception e) { logError(Messages.getString("ExecSQL.Log.UnexpectedError")+" : "+e.toString()); //$NON-NLS-1$ //$NON-NLS-2$ logError(Const.getStackTracker(e)); setErrors(1); stopAll(); } finally { dispose(meta, data); logSummary(); markStop(); } } }
package com.hyperwallet.clientsdk; import com.fasterxml.jackson.core.type.TypeReference; import com.hyperwallet.clientsdk.model.*; import com.hyperwallet.clientsdk.util.HyperwalletApiClient; import com.hyperwallet.clientsdk.util.HyperwalletEncryption; import com.hyperwallet.clientsdk.util.HyperwalletJsonUtil; import org.apache.commons.lang3.StringUtils; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Locale; import java.util.TimeZone; /** * The Hyperwallet Client */ public class Hyperwallet { public static final String VERSION = "1.4.2"; private final HyperwalletApiClient apiClient; private final String programToken; private final String url; /** * Create Hyperwallet SDK instance * * @param username API key assigned * @param password API Password assigned * @param programToken API program token * @param server API server url * @param hyperwalletEncryption API encryption data */ public Hyperwallet(final String username, final String password, final String programToken, final String server, final HyperwalletEncryption hyperwalletEncryption) { apiClient = new HyperwalletApiClient(username, password, VERSION, hyperwalletEncryption); this.programToken = programToken; this.url = StringUtils.isEmpty(server) ? "https://api.sandbox.hyperwallet.com/rest/v4" : server + "/rest/v4"; } /** * Create Hyperwallet SDK instance * * @param username API key assigned * @param password API Password assigned * @param programToken API program token * @param server API serer url */ public Hyperwallet(final String username, final String password, final String programToken, final String server) { this(username, password, programToken, server, null); } /** * Create Hyperwallet SDK instance * * @param username API key assigned * @param password API password * @param programToken API program token assigned */ public Hyperwallet(final String username, final String password, final String programToken) { this(username, password, programToken, null, null); } /** * Create Hyperwallet SDK instance * * @param username API key assigned * @param password API password * @param programToken API program token assigned * @param hyperwalletEncryption API encryption data */ public Hyperwallet(final String username, final String password, final String programToken, final HyperwalletEncryption hyperwalletEncryption) { this(username, password, programToken, null, hyperwalletEncryption); } /** * Create Hyperwallet SDK instance * * @param username API key assigned * @param password API password */ public Hyperwallet(final String username, final String password) { this(username, password, null); } // Users /** * Create a User * * @param user Hyperwallet user representation * @return HyperwalletUser created User */ public HyperwalletUser createUser(HyperwalletUser user) { if (user == null) { throw new HyperwalletException("User is required"); } if (!StringUtils.isEmpty(user.getToken())) { throw new HyperwalletException("User token may not be present"); } user = copy(user); user.setStatus(null); user.setCreatedOn(null); return apiClient.post(url + "/users", user, HyperwalletUser.class); } /** * Get User * * @param token user account token * @return HyperwalletUser retreived user */ public HyperwalletUser getUser(String token) { if (StringUtils.isEmpty(token)) { throw new HyperwalletException("User token is required"); } return apiClient.get(url + "/users/" + token, HyperwalletUser.class); } /** * Update User * * @param user Hyperwallet User representation object * @return HyperwalletUser updated user object */ public HyperwalletUser updateUser(HyperwalletUser user) { if (user == null) { throw new HyperwalletException("User is required"); } if (StringUtils.isEmpty(user.getToken())) { throw new HyperwalletException("User token is required"); } return apiClient.put(url + "/users/" + user.getToken(), user, HyperwalletUser.class); } /** * List Users * * @return HyperwalletList of HyperwalletUser */ public HyperwalletList<HyperwalletUser> listUsers() { return listUsers(null); } /** * List Users * * @param options List filter option * @return HyperwalletList of HyperwalletUser */ public HyperwalletList<HyperwalletUser> listUsers(HyperwalletPaginationOptions options) { String url = paginate(this.url + "/users", options); return apiClient.get(url, new TypeReference<HyperwalletList<HyperwalletUser>>() { }); } /** * Create Business Stakeholder * * @param stakeholder Hyperwallet Stakeholder representation * @param userToken String * @return HyperwalletBusinessStakeholder created Stakeholder */ public HyperwalletBusinessStakeholder createBusinessStakeholder(String userToken, HyperwalletBusinessStakeholder stakeholder) { if (stakeholder == null) { throw new HyperwalletException("Stakeholder is required"); } if (userToken == null) { throw new HyperwalletException("User token may not be present"); } stakeholder = copy(stakeholder); return apiClient.post(url + "/users/"+ userToken + "/business-stakeholders", stakeholder, HyperwalletBusinessStakeholder.class); } /** * Update Business Stakeholder * * @param userToken String * @param stakeholder Hyperwallet Stakeholder representation * @return HyperwalletBusinessStakeholder updated Stakeholder */ public HyperwalletBusinessStakeholder updateBusinessStakeholder(String userToken, HyperwalletBusinessStakeholder stakeholder) { if (stakeholder == null) { throw new HyperwalletException("Stakeholder is required"); } if (userToken == null) { throw new HyperwalletException("User token may not be present"); } if (stakeholder.getToken() == null || stakeholder.getToken().equals("")) { throw new HyperwalletException("Stakeholder token may not be present"); } stakeholder = copy(stakeholder); return apiClient.put(url + "/users/" + userToken + "/business-stakeholders/" + stakeholder.getToken(), stakeholder, HyperwalletBusinessStakeholder.class); } /** * List BusinessStakeholders * * @param userToken String * @return HyperwalletList of HyperwalletBusinessStakeholder */ public HyperwalletList<HyperwalletBusinessStakeholder> listBusinessStakeholders(String userToken) { if (userToken == null) { throw new HyperwalletException("User token may not be present"); } return listBusinessStakeholders(userToken, null); } /** * List BusinessStakeholders * * @param userToken String * @param options List filter option * @return HyperwalletList of HyperwalletBusinessStakeholder */ public HyperwalletList<HyperwalletBusinessStakeholder> listBusinessStakeholders(String userToken, HyperwalletPaginationOptions options) { if (userToken == null) { throw new HyperwalletException("User token may not be present"); } String url = paginate(this.url + "/users/" + userToken + "/business-stakeholders", options); return apiClient.get(url, new TypeReference<HyperwalletList<HyperwalletBusinessStakeholder>>() { }); } /** * Get Authentication Token * * @param token user account token * @return HyperwalletAuthenticationToken retreived authentication token */ public HyperwalletAuthenticationToken getAuthenticationToken(String token) { if (StringUtils.isEmpty(token)) { throw new HyperwalletException("User token is required"); } String urlString = url + "/users/" + token + "/authentication-token"; return apiClient.post(urlString, null, HyperwalletAuthenticationToken.class); } /** * Get User Status Transition * * @param userToken User token * @param statusTransitionToken Status transition token * @return HyperwalletStatusTransition */ public HyperwalletStatusTransition getUserStatusTransition(String userToken, String statusTransitionToken) { if (StringUtils.isEmpty(userToken)) { throw new HyperwalletException("User token is required"); } if (StringUtils.isEmpty(statusTransitionToken)) { throw new HyperwalletException("Transition token is required"); } return apiClient.get(url + "/users/" + userToken + "/status-transitions/" + statusTransitionToken, HyperwalletStatusTransition.class); } /** * List All User Status Transition information * * @param userToken User token * @return HyperwalletList of HyperwalletStatusTransition */ public HyperwalletList<HyperwalletStatusTransition> listUserStatusTransitions(String userToken) { return listUserStatusTransitions(userToken, null); } /** * List Prepaid Card Status Transition information * * @param userToken User token * @param options List filter option * @return HyperwalletList of HyperwalletStatusTransition */ public HyperwalletList<HyperwalletStatusTransition> listUserStatusTransitions(String userToken, HyperwalletPaginationOptions options) { if (StringUtils.isEmpty(userToken)) { throw new HyperwalletException("User token is required"); } String url = paginate(this.url + "/users/" + userToken + "/status-transitions", options); return apiClient.get(url, new TypeReference<HyperwalletList<HyperwalletStatusTransition>>() { }); } // Prepaid Cards /** * Create Prepaid Card * * @param prepaidCard Prepaid Card object to create * @return HyperwalletPrepaidCard Prepaid Card object created */ public HyperwalletPrepaidCard createPrepaidCard(HyperwalletPrepaidCard prepaidCard) { if (prepaidCard == null) { throw new HyperwalletException("Prepaid Card is required"); } if (StringUtils.isEmpty(prepaidCard.getUserToken())) { throw new HyperwalletException("User token is required"); } if (!StringUtils.isEmpty(prepaidCard.getToken())) { throw new HyperwalletException("Prepaid Card token may not be present"); } if (prepaidCard.getType() == null) { prepaidCard.setType(HyperwalletTransferMethod.Type.PREPAID_CARD); } prepaidCard = copy(prepaidCard); prepaidCard.setStatus(null); prepaidCard.setCardType(null); prepaidCard.setCreatedOn(null); prepaidCard.setTransferMethodCountry(null); prepaidCard.setTransferMethodCurrency(null); prepaidCard.setCardNumber(null); prepaidCard.setCardBrand(null); prepaidCard.setDateOfExpiry(null); return apiClient.post(url + "/users/" + prepaidCard.getUserToken() + "/prepaid-cards", prepaidCard, HyperwalletPrepaidCard.class); } /** * Get Prepaid Card * * @param userToken User token assigned * @param prepaidCardToken Prepaid Card token * @return HyperwalletPrepaidCard Prepaid Card */ public HyperwalletPrepaidCard getPrepaidCard(String userToken, String prepaidCardToken) { if (StringUtils.isEmpty(userToken)) { throw new HyperwalletException("User token is required"); } if (StringUtils.isEmpty(prepaidCardToken)) { throw new HyperwalletException("Prepaid Card token is required"); } return apiClient.get(url + "/users/" + userToken + "/prepaid-cards/" + prepaidCardToken, HyperwalletPrepaidCard.class); } /** * Update Prepaid Card * * @param prepaidCard Prepaid Card object to create * @return HyperwalletPrepaidCard Prepaid Card object created */ public HyperwalletPrepaidCard updatePrepaidCard(HyperwalletPrepaidCard prepaidCard) { if (prepaidCard == null) { throw new HyperwalletException("Prepaid Card is required"); } if (StringUtils.isEmpty(prepaidCard.getUserToken())) { throw new HyperwalletException("User token is required"); } if (StringUtils.isEmpty(prepaidCard.getToken())) { throw new HyperwalletException("Prepaid Card token is required"); } return apiClient.put(url + "/users/" + prepaidCard.getUserToken() + "/prepaid-cards/" + prepaidCard.getToken(), prepaidCard, HyperwalletPrepaidCard.class); } /** * List User's Prepaid Card * * @param userToken User token assigned * @return HyperwalletList of HyperwalletPrepaidCard */ public HyperwalletList<HyperwalletPrepaidCard> listPrepaidCards(String userToken) { return listPrepaidCards(userToken, null); } /** * List User's Prepaid Card * * @param userToken User token assigned * @param options List filter option * @return HyperwalletList of HyperwalletPrepaidCard */ public HyperwalletList<HyperwalletPrepaidCard> listPrepaidCards(String userToken, HyperwalletPaginationOptions options) { if (StringUtils.isEmpty(userToken)) { throw new HyperwalletException("User token is required"); } String url = paginate(this.url + "/users/" + userToken + "/prepaid-cards", options); return apiClient.get(url, new TypeReference<HyperwalletList<HyperwalletPrepaidCard>>() { }); } /** * Suspend a prepaid card * * @param userToken User token * @param prepaidCardToken Prepaid card token * @return The status transition */ public HyperwalletStatusTransition suspendPrepaidCard(String userToken, String prepaidCardToken) { return createPrepaidCardStatusTransition(userToken, prepaidCardToken, new HyperwalletStatusTransition(HyperwalletStatusTransition.Status.SUSPENDED)); } /** * Unsuspend a prepaid card * * @param userToken User token * @param prepaidCardToken Prepaid card token * @return The status transition */ public HyperwalletStatusTransition unsuspendPrepaidCard(String userToken, String prepaidCardToken) { return createPrepaidCardStatusTransition(userToken, prepaidCardToken, new HyperwalletStatusTransition(HyperwalletStatusTransition.Status.UNSUSPENDED)); } /** * Mark a prepaid card as lost or stolen * * @param userToken User token * @param prepaidCardToken Prepaid card token * @return The status transition */ public HyperwalletStatusTransition lostOrStolenPrepaidCard(String userToken, String prepaidCardToken) { return createPrepaidCardStatusTransition(userToken, prepaidCardToken, new HyperwalletStatusTransition(HyperwalletStatusTransition.Status.LOST_OR_STOLEN)); } /** * Deactivate a prepaid card * * @param userToken User token * @param prepaidCardToken Prepaid card token * @return The status transition */ public HyperwalletStatusTransition deactivatePrepaidCard(String userToken, String prepaidCardToken) { return createPrepaidCardStatusTransition(userToken, prepaidCardToken, new HyperwalletStatusTransition(HyperwalletStatusTransition.Status.DE_ACTIVATED)); } /** * Lock a prepaid card * * @param userToken User token * @param prepaidCardToken Prepaid card token * @return The status transition */ public HyperwalletStatusTransition lockPrepaidCard(String userToken, String prepaidCardToken) { return createPrepaidCardStatusTransition(userToken, prepaidCardToken, new HyperwalletStatusTransition(HyperwalletStatusTransition.Status.LOCKED)); } /** * Unlock a prepaid card * * @param userToken User token * @param prepaidCardToken Prepaid card token * @return The status transition */ public HyperwalletStatusTransition unlockPrepaidCard(String userToken, String prepaidCardToken) { return createPrepaidCardStatusTransition(userToken, prepaidCardToken, new HyperwalletStatusTransition(HyperwalletStatusTransition.Status.UNLOCKED)); } /** * Create Prepaid Card Status Transition * * @param userToken User token * @param prepaidCardToken Prepaid Card token * @param transition Status transition information * @return HyperwalletStatusTransition new status for Prepaid Card */ public HyperwalletStatusTransition createPrepaidCardStatusTransition(String userToken, String prepaidCardToken, HyperwalletStatusTransition transition) { if (transition == null) { throw new HyperwalletException("Transition is required"); } if (StringUtils.isEmpty(userToken)) { throw new HyperwalletException("User token is required"); } if (StringUtils.isEmpty(prepaidCardToken)) { throw new HyperwalletException("Prepaid Card token is required"); } if (!StringUtils.isEmpty(transition.getToken())) { throw new HyperwalletException("Status Transition token may not be present"); } transition = copy(transition); transition.setCreatedOn(null); transition.setFromStatus(null); transition.setToStatus(null); return apiClient.post(url + "/users/" + userToken + "/prepaid-cards/" + prepaidCardToken + "/status-transitions", transition, HyperwalletStatusTransition.class); } /** * Get Prepaid Card Status Transition * * @param userToken User token * @param prepaidCardToken Prepaid Card token * @param statusTransitionToken Status transition token * @return HyperwalletStatusTransition */ public HyperwalletStatusTransition getPrepaidCardStatusTransition(String userToken, String prepaidCardToken, String statusTransitionToken) { if (StringUtils.isEmpty(userToken)) { throw new HyperwalletException("User token is required"); } if (StringUtils.isEmpty(prepaidCardToken)) { throw new HyperwalletException("Prepaid Card token is required"); } if (StringUtils.isEmpty(statusTransitionToken)) { throw new HyperwalletException("Transition token is required"); } return apiClient.get(url + "/users/" + userToken + "/prepaid-cards/" + prepaidCardToken + "/status-transitions/" + statusTransitionToken, HyperwalletStatusTransition.class); } /** * List All Prepaid Card Status Transition information * * @param userToken User token * @param prepaidCardToken Prepaid Card token * @return HyperwalletList of HyperwalletStatusTransition */ public HyperwalletList<HyperwalletStatusTransition> listPrepaidCardStatusTransitions(String userToken, String prepaidCardToken) { return listPrepaidCardStatusTransitions(userToken, prepaidCardToken, null); } /** * List Prepaid Card Status Transition information * * @param userToken User token * @param prepaidCardToken Prepaid Card token * @param options List filter option * @return HyperwalletList of HyperwalletStatusTransition */ public HyperwalletList<HyperwalletStatusTransition> listPrepaidCardStatusTransitions(String userToken, String prepaidCardToken, HyperwalletPaginationOptions options) { if (StringUtils.isEmpty(userToken)) { throw new HyperwalletException("User token is required"); } if (StringUtils.isEmpty(prepaidCardToken)) { throw new HyperwalletException("Prepaid Card token is required"); } String url = paginate(this.url + "/users/" + userToken + "/prepaid-cards/" + prepaidCardToken + "/status-transitions", options); return apiClient.get(url, new TypeReference<HyperwalletList<HyperwalletStatusTransition>>() { }); } // Bank Cards /** * Create Bank Card * * @param bankCard Bank Card object to create * @return HyperwalletBankCard Bank Card object created */ public HyperwalletBankCard createBankCard(HyperwalletBankCard bankCard) { if (bankCard == null) { throw new HyperwalletException("Bank Card is required"); } if (StringUtils.isEmpty(bankCard.getUserToken())) { throw new HyperwalletException("User token is required"); } if (!StringUtils.isEmpty(bankCard.getToken())) { throw new HyperwalletException("Bank Card token may not be present"); } if (bankCard.getType() == null) { bankCard.setType(HyperwalletTransferMethod.Type.BANK_CARD); } bankCard = copy(bankCard); bankCard.setStatus(null); bankCard.setCardType(null); bankCard.setCreatedOn(null); bankCard.setCardBrand(null); return apiClient.post(url + "/users/" + bankCard.getUserToken() + "/bank-cards", bankCard, HyperwalletBankCard.class); } /** * Get Bank Card * * @param userToken User token assigned * @param bankCardToken Bank Card token * @return HyperwalletBankCard Bank Card */ public HyperwalletBankCard getBankCard(String userToken, String bankCardToken) { if (StringUtils.isEmpty(userToken)) { throw new HyperwalletException("User token is required"); } if (StringUtils.isEmpty(bankCardToken)) { throw new HyperwalletException("Bank Card token is required"); } return apiClient.get(url + "/users/" + userToken + "/bank-cards/" + bankCardToken, HyperwalletBankCard.class); } /** * Update Bank Card * * @param bankCard Bank Card object to create * @return HyperwalletBankCard Bank Card object created */ public HyperwalletBankCard updateBankCard(HyperwalletBankCard bankCard) { if (bankCard == null) { throw new HyperwalletException("Bank Card is required"); } if (StringUtils.isEmpty(bankCard.getUserToken())) { throw new HyperwalletException("User token is required"); } if (StringUtils.isEmpty(bankCard.getToken())) { throw new HyperwalletException("Bank Card token is required"); } return apiClient.put(url + "/users/" + bankCard.getUserToken() + "/bank-cards/" + bankCard.getToken(), bankCard, HyperwalletBankCard.class); } /** * List User's Bank Card * * @param userToken User token assigned * @return HyperwalletList of HyperwalletBankCard */ public HyperwalletList<HyperwalletBankCard> listBankCards(String userToken) { return listBankCards(userToken, null); } /** * List User's Bank Card * * @param userToken User token assigned * @param options List filter option * @return HyperwalletList of HyperwalletBankCard */ public HyperwalletList<HyperwalletBankCard> listBankCards(String userToken, HyperwalletPaginationOptions options) { if (StringUtils.isEmpty(userToken)) { throw new HyperwalletException("User token is required"); } String url = paginate(this.url + "/users/" + userToken + "/bank-cards", options); return apiClient.get(url, new TypeReference<HyperwalletList<HyperwalletBankCard>>() { }); } /** * Deactivate a bank card * * @param userToken User token * @param bankCardToken Bank card token * @return The status transition */ public HyperwalletStatusTransition deactivateBankCard(String userToken, String bankCardToken) { return deactivateBankCard(userToken, bankCardToken, null); } /** * Deactivate a bank card * * @param userToken User token * @param bankCardToken Bank card token * @param notes Comments regarding the status change * @return The status transition */ public HyperwalletStatusTransition deactivateBankCard(String userToken, String bankCardToken, String notes) { return createBankCardStatusTransition(userToken, bankCardToken, new HyperwalletStatusTransition(HyperwalletStatusTransition.Status.DE_ACTIVATED).notes(notes)); } /** * Create Bank Card Status Transition * * @param userToken User token * @param bankCardToken Bank Card token * @param transition Status transition information * @return HyperwalletStatusTransition new status for Bank Card */ public HyperwalletStatusTransition createBankCardStatusTransition(String userToken, String bankCardToken, HyperwalletStatusTransition transition) { if (transition == null) { throw new HyperwalletException("Transition is required"); } if (StringUtils.isEmpty(userToken)) { throw new HyperwalletException("User token is required"); } if (StringUtils.isEmpty(bankCardToken)) { throw new HyperwalletException("Bank Card token is required"); } if (!StringUtils.isEmpty(transition.getToken())) { throw new HyperwalletException("Status Transition token may not be present"); } transition = copy(transition); transition.setCreatedOn(null); transition.setFromStatus(null); transition.setToStatus(null); return apiClient.post(url + "/users/" + userToken + "/bank-cards/" + bankCardToken + "/status-transitions", transition, HyperwalletStatusTransition.class); } /** * Get Bank Card Status Transition * * @param userToken User token * @param bankCardToken Bank Card token * @param statusTransitionToken Status transition token * @return HyperwalletStatusTransition */ public HyperwalletStatusTransition getBankCardStatusTransition(String userToken, String bankCardToken, String statusTransitionToken) { if (StringUtils.isEmpty(userToken)) { throw new HyperwalletException("User token is required"); } if (StringUtils.isEmpty(bankCardToken)) { throw new HyperwalletException("Bank Card token is required"); } if (StringUtils.isEmpty(statusTransitionToken)) { throw new HyperwalletException("Transition token is required"); } return apiClient.get(url + "/users/" + userToken + "/bank-cards/" + bankCardToken + "/status-transitions/" + statusTransitionToken, HyperwalletStatusTransition.class); } /** * List All Bank Card Status Transition information * * @param userToken User token * @param bankCardToken Bank Card token * @return HyperwalletList of HyperwalletStatusTransition */ public HyperwalletList<HyperwalletStatusTransition> listBankCardStatusTransitions(String userToken, String bankCardToken) { return listBankCardStatusTransitions(userToken, bankCardToken, null); } /** * List Bank Card Status Transition information * * @param userToken User token * @param bankCardToken Bank Card token * @param options List filter option * @return HyperwalletList of HyperwalletStatusTransition */ public HyperwalletList<HyperwalletStatusTransition> listBankCardStatusTransitions(String userToken, String bankCardToken, HyperwalletPaginationOptions options) { if (StringUtils.isEmpty(userToken)) { throw new HyperwalletException("User token is required"); } if (StringUtils.isEmpty(bankCardToken)) { throw new HyperwalletException("Bank Card token is required"); } String url = paginate(this.url + "/users/" + userToken + "/bank-cards/" + bankCardToken + "/status-transitions", options); return apiClient.get(url, new TypeReference<HyperwalletList<HyperwalletStatusTransition>>() { }); } // Paper Checks /** * Create Paper Check * * @param paperCheck Paper Check object to create * @return HyperwalletPaperCheck Paper Check object created */ public HyperwalletPaperCheck createPaperCheck(HyperwalletPaperCheck paperCheck) { if (paperCheck == null) { throw new HyperwalletException("Paper Check is required"); } if (StringUtils.isEmpty(paperCheck.getUserToken())) { throw new HyperwalletException("User token is required"); } if (!StringUtils.isEmpty(paperCheck.getToken())) { throw new HyperwalletException("Paper Check token may not be present"); } if (paperCheck.getType() == null) { paperCheck.setType(HyperwalletTransferMethod.Type.PAPER_CHECK); } paperCheck = copy(paperCheck); paperCheck.setStatus(null); paperCheck.setCreatedOn(null); return apiClient.post(url + "/users/" + paperCheck.getUserToken() + "/paper-checks", paperCheck, HyperwalletPaperCheck.class); } /** * Get Paper Check * * @param userToken User token assigned * @param paperCheckToken Paper Check token * @return HyperwalletPaperCheck Paper Check */ public HyperwalletPaperCheck getPaperCheck(String userToken, String paperCheckToken) { if (StringUtils.isEmpty(userToken)) { throw new HyperwalletException("User token is required"); } if (StringUtils.isEmpty(paperCheckToken)) { throw new HyperwalletException("Paper Check token is required"); } return apiClient.get(url + "/users/" + userToken + "/paper-checks/" + paperCheckToken, HyperwalletPaperCheck.class); } /** * Update Paper Check * * @param paperCheck Paper Check object to create * @return HyperwalletPaperCheck Paper Check object created */ public HyperwalletPaperCheck updatePaperCheck(HyperwalletPaperCheck paperCheck) { if (paperCheck == null) { throw new HyperwalletException("Paper Check is required"); } if (StringUtils.isEmpty(paperCheck.getUserToken())) { throw new HyperwalletException("User token is required"); } if (StringUtils.isEmpty(paperCheck.getToken())) { throw new HyperwalletException("Paper Check token is required"); } return apiClient.put(url + "/users/" + paperCheck.getUserToken() + "/paper-checks/" + paperCheck.getToken(), paperCheck, HyperwalletPaperCheck.class); } /** * List User's Paper Check * * @param userToken User token assigned * @return HyperwalletList of HyperwalletPaperCheck */ public HyperwalletList<HyperwalletPaperCheck> listPaperChecks(String userToken) { return listPaperChecks(userToken, null); } /** * List User's Paper Check * * @param userToken User token assigned * @param options List filter option * @return HyperwalletList of HyperwalletPaperCheck */ public HyperwalletList<HyperwalletPaperCheck> listPaperChecks(String userToken, HyperwalletPaginationOptions options) { if (StringUtils.isEmpty(userToken)) { throw new HyperwalletException("User token is required"); } String url = paginate(this.url + "/users/" + userToken + "/paper-checks", options); return apiClient.get(url, new TypeReference<HyperwalletList<HyperwalletPaperCheck>>() { }); } /** * Deactivate a Paper Check * * @param userToken User token * @param paperCheckToken Paper Check token * @return The status transition */ public HyperwalletStatusTransition deactivatePaperCheck(String userToken, String paperCheckToken) { return deactivatePaperCheck(userToken, paperCheckToken, null); } /** * Deactivate a Paper Check * * @param userToken User token * @param paperCheckToken Paper Check token * @return The status transition */ public HyperwalletStatusTransition deactivatePaperCheck(String userToken, String paperCheckToken, String notes) { return createPaperCheckStatusTransition(userToken, paperCheckToken, new HyperwalletStatusTransition(HyperwalletStatusTransition.Status.DE_ACTIVATED).notes(notes)); } /** * Create Paper Check Status Transition * * @param userToken User token * @param paperCheckToken Paper Check token * @param transition Status transition information * @return HyperwalletStatusTransition new status for Paper Check */ public HyperwalletStatusTransition createPaperCheckStatusTransition(String userToken, String paperCheckToken, HyperwalletStatusTransition transition) { if (transition == null) { throw new HyperwalletException("Transition is required"); } if (StringUtils.isEmpty(userToken)) { throw new HyperwalletException("User token is required"); } if (StringUtils.isEmpty(paperCheckToken)) { throw new HyperwalletException("Paper Check token is required"); } if (!StringUtils.isEmpty(transition.getToken())) { throw new HyperwalletException("Status Transition token may not be present"); } transition = copy(transition); transition.setCreatedOn(null); transition.setFromStatus(null); transition.setToStatus(null); return apiClient.post(url + "/users/" + userToken + "/paper-checks/" + paperCheckToken + "/status-transitions", transition, HyperwalletStatusTransition.class); } /** * Get Paper Check Status Transition * * @param userToken User token * @param paperCheckToken Paper Check token * @param statusTransitionToken Status transition token * @return HyperwalletStatusTransition */ public HyperwalletStatusTransition getPaperCheckStatusTransition(String userToken, String paperCheckToken, String statusTransitionToken) { if (StringUtils.isEmpty(userToken)) { throw new HyperwalletException("User token is required"); } if (StringUtils.isEmpty(paperCheckToken)) { throw new HyperwalletException("Paper Check token is required"); } if (StringUtils.isEmpty(statusTransitionToken)) { throw new HyperwalletException("Transition token is required"); } return apiClient.get(url + "/users/" + userToken + "/paper-checks/" + paperCheckToken + "/status-transitions/" + statusTransitionToken, HyperwalletStatusTransition.class); } /** * List All Paper Check Status Transition information * * @param userToken User token * @param paperCheckToken Paper Check token * @return HyperwalletList of HyperwalletStatusTransition */ public HyperwalletList<HyperwalletStatusTransition> listPaperCheckStatusTransitions(String userToken, String paperCheckToken) { return listPaperCheckStatusTransitions(userToken, paperCheckToken, null); } /** * List Paper Check Status Transition information * * @param userToken User token * @param paperCheckToken Paper Check token * @param options List filter option * @return HyperwalletList of HyperwalletStatusTransition */ public HyperwalletList<HyperwalletStatusTransition> listPaperCheckStatusTransitions(String userToken, String paperCheckToken, HyperwalletPaginationOptions options) { if (StringUtils.isEmpty(userToken)) { throw new HyperwalletException("User token is required"); } if (StringUtils.isEmpty(paperCheckToken)) { throw new HyperwalletException("Paper Check token is required"); } String url = paginate(this.url + "/users/" + userToken + "/paper-checks/" + paperCheckToken + "/status-transitions", options); return apiClient.get(url, new TypeReference<HyperwalletList<HyperwalletStatusTransition>>() { }); } // Transfers /** * Create Transfer Request * * @param transfer HyperwalletTransfer object to create * @return HyperwalletTransfer Transfer object created */ public HyperwalletTransfer createTransfer(HyperwalletTransfer transfer) { if (transfer == null) { throw new HyperwalletException("Transfer is required"); } if (StringUtils.isEmpty(transfer.getSourceToken())) { throw new HyperwalletException("Source token is required"); } if (StringUtils.isEmpty(transfer.getDestinationToken())) { throw new HyperwalletException("Destination token is required"); } if (StringUtils.isEmpty(transfer.getClientTransferId())) { throw new HyperwalletException("ClientTransferId is required"); } transfer = copy(transfer); transfer.setStatus(null); transfer.setCreatedOn(null); transfer.setExpiresOn(null); return apiClient.post(url + "/transfers", transfer, HyperwalletTransfer.class); } /** * Get Transfer Request * * @param transferToken Transfer token assigned * @return HyperwalletTransfer Transfer */ public HyperwalletTransfer getTransfer(String transferToken) { if (StringUtils.isEmpty(transferToken)) { throw new HyperwalletException("Transfer token is required"); } return apiClient.get(url + "/transfers/" + transferToken, HyperwalletTransfer.class); } /** * List Transfer Requests * * @param options List filter option * @return HyperwalletList of HyperwalletTransfer */ public HyperwalletList<HyperwalletTransfer> listTransfers(HyperwalletTransferListOptions options) { String url = paginate(this.url + "/transfers", options); if (options != null) { url = addParameter(url, "sourceToken", options.getSourceToken()); url = addParameter(url, "destinationToken", options.getDestinationToken()); } return apiClient.get(url, new TypeReference<HyperwalletList<HyperwalletTransfer>>() { }); } /** * List Transfer Requests * * @return HyperwalletList of HyperwalletTransfer */ public HyperwalletList<HyperwalletTransfer> listTransfers() { return listTransfers(null); } /** * Create Transfer Status Transition * * @param transferToken Transfer token assigned * @return HyperwalletStatusTransition new status for Transfer Request */ public HyperwalletStatusTransition createTransferStatusTransition(String transferToken, HyperwalletStatusTransition transition) { if (transition == null) { throw new HyperwalletException("Transition is required"); } if (StringUtils.isEmpty(transferToken)) { throw new HyperwalletException("Transfer token is required"); } if (!StringUtils.isEmpty(transition.getToken())) { throw new HyperwalletException("Status Transition token may not be present"); } transition = copy(transition); transition.setCreatedOn(null); transition.setFromStatus(null); transition.setToStatus(null); return apiClient.post(url + "/transfers/" + transferToken + "/status-transitions", transition, HyperwalletStatusTransition.class); } // PayPal Accounts /** * Create PayPal Account Request * * @param payPalAccount HyperwalletPayPalAccount object to create * @return HyperwalletPayPalAccount created PayPal account for the specified user */ public HyperwalletPayPalAccount createPayPalAccount(HyperwalletPayPalAccount payPalAccount) { if (payPalAccount == null) { throw new HyperwalletException("PayPal Account is required"); } if (StringUtils.isEmpty(payPalAccount.getUserToken())) { throw new HyperwalletException("User token is required"); } if (StringUtils.isEmpty(payPalAccount.getTransferMethodCountry())) { throw new HyperwalletException("Transfer Method Country is required"); } if (StringUtils.isEmpty(payPalAccount.getTransferMethodCurrency())) { throw new HyperwalletException("Transfer Method Currency is required"); } if (StringUtils.isEmpty(payPalAccount.getEmail())) { throw new HyperwalletException("Email is required"); } if (!StringUtils.isEmpty(payPalAccount.getToken())) { throw new HyperwalletException("PayPal Account token may not be present"); } if (payPalAccount.getType() == null) { payPalAccount.setType(HyperwalletTransferMethod.Type.PAYPAL_ACCOUNT); } payPalAccount = copy(payPalAccount); payPalAccount.setStatus(null); payPalAccount.setCreatedOn(null); return apiClient.post(url + "/users/" + payPalAccount.getUserToken() + "/paypal-accounts", payPalAccount, HyperwalletPayPalAccount.class); } /** * Get PayPal Account Request * * @param userToken User token assigned * @param payPalAccountToken PayPal Account token assigned * @return HyperwalletPayPalAccount PayPal Account */ public HyperwalletPayPalAccount getPayPalAccount(String userToken, String payPalAccountToken) { if (StringUtils.isEmpty(userToken)) { throw new HyperwalletException("User token is required"); } if (StringUtils.isEmpty(payPalAccountToken)) { throw new HyperwalletException("PayPal Account token is required"); } return apiClient.get(url + "/users/" + userToken + "/paypal-accounts/" + payPalAccountToken, HyperwalletPayPalAccount.class); } /** * List PayPal Accounts * * @param userToken User token assigned * @param options List filter option * @return HyperwalletList of HyperwalletPayPalAccount */ public HyperwalletList<HyperwalletPayPalAccount> listPayPalAccounts(String userToken, HyperwalletPaginationOptions options) { if (StringUtils.isEmpty(userToken)) { throw new HyperwalletException("User token is required"); } String url = paginate(this.url + "/users/" + userToken + "/paypal-accounts", options); return apiClient.get(url, new TypeReference<HyperwalletList<HyperwalletPayPalAccount>>() { }); } /** * List PayPal Accounts * * @param userToken User token assigned * @return HyperwalletList of HyperwalletPayPalAccount */ public HyperwalletList<HyperwalletPayPalAccount> listPayPalAccounts(String userToken) { return listPayPalAccounts(userToken, null); } /** * Deactivate PayPal Account * * @param userToken User token * @param payPalAccountToken PayPal Account token * @return HyperwalletStatusTransition deactivated PayPal account */ public HyperwalletStatusTransition deactivatePayPalAccount(String userToken, String payPalAccountToken) { return deactivatePayPalAccount(userToken, payPalAccountToken, null); } /** * Deactivate PayPal Account * * @param userToken User token * @param payPalAccountToken PayPal Account token * @param notes Comments regarding the status change * @return HyperwalletStatusTransition deactivated PayPal account */ public HyperwalletStatusTransition deactivatePayPalAccount(String userToken, String payPalAccountToken, String notes) { return createPayPalAccountStatusTransition(userToken, payPalAccountToken, new HyperwalletStatusTransition(HyperwalletStatusTransition.Status.DE_ACTIVATED).notes(notes)); } /** * Create PayPal Account Status Transition * * @param userToken User token * @param payPalAccountToken PayPal Account token * @param transition Status transition information * @return HyperwalletStatusTransition new status for PayPal Account */ public HyperwalletStatusTransition createPayPalAccountStatusTransition(String userToken, String payPalAccountToken, HyperwalletStatusTransition transition) { if (transition == null) { throw new HyperwalletException("Transition is required"); } if (StringUtils.isEmpty(userToken)) { throw new HyperwalletException("User token is required"); } if (StringUtils.isEmpty(payPalAccountToken)) { throw new HyperwalletException("PayPal Account token is required"); } if (!StringUtils.isEmpty(transition.getToken())) { throw new HyperwalletException("Status Transition token may not be present"); } transition = copy(transition); transition.setCreatedOn(null); transition.setFromStatus(null); transition.setToStatus(null); return apiClient.post(url + "/users/" + userToken + "/paypal-accounts/" + payPalAccountToken + "/status-transitions", transition, HyperwalletStatusTransition.class); } /** * Get PayPal Account Status Transition * * @param userToken User token * @param payPalAccountToken PayPal Account token * @param statusTransitionToken Status transition token * @return HyperwalletStatusTransition */ public HyperwalletStatusTransition getPayPalAccountStatusTransition(String userToken, String payPalAccountToken, String statusTransitionToken) { if (StringUtils.isEmpty(userToken)) { throw new HyperwalletException("User token is required"); } if (StringUtils.isEmpty(payPalAccountToken)) { throw new HyperwalletException("PayPal Account token is required"); } if (StringUtils.isEmpty(statusTransitionToken)) { throw new HyperwalletException("Transition token is required"); } return apiClient.get(url + "/users/" + userToken + "/paypal-accounts/" + payPalAccountToken + "/status-transitions/" + statusTransitionToken, HyperwalletStatusTransition.class); } /** * List All PayPal Account Status Transition information * * @param userToken User token * @param payPalAccountToken PayPal Account token * @return HyperwalletList of HyperwalletStatusTransition */ public HyperwalletList<HyperwalletStatusTransition> listPayPalAccountStatusTransitions(String userToken, String payPalAccountToken) { return listPayPalAccountStatusTransitions(userToken, payPalAccountToken, null); } /** * List PayPal Account Status Transition information * * @param userToken User token * @param payPalAccountToken PayPal Account token * @param options List filter option * @return HyperwalletList of HyperwalletStatusTransition */ public HyperwalletList<HyperwalletStatusTransition> listPayPalAccountStatusTransitions(String userToken, String payPalAccountToken, HyperwalletPaginationOptions options) { if (StringUtils.isEmpty(userToken)) { throw new HyperwalletException("User token is required"); } if (StringUtils.isEmpty(payPalAccountToken)) { throw new HyperwalletException("PayPal Account token is required"); } String url = paginate(this.url + "/users/" + userToken + "/paypal-accounts/" + payPalAccountToken + "/status-transitions", options); return apiClient.get(url, new TypeReference<HyperwalletList<HyperwalletStatusTransition>>() { }); } // Bank Accounts /** * Create Bank Account * * @param bankAccount bank account representation * @return HyperwalletBankAccount created bank account for the specicic user */ public HyperwalletBankAccount createBankAccount(HyperwalletBankAccount bankAccount) { if (bankAccount == null) { throw new HyperwalletException("Bank Account is required"); } if (StringUtils.isEmpty(bankAccount.getUserToken())) { throw new HyperwalletException("User token is required"); } if (!StringUtils.isEmpty(bankAccount.getToken())) { throw new HyperwalletException("Bank Account token may not be present"); } bankAccount = copy(bankAccount); bankAccount.createdOn(null); bankAccount.setStatus(null); return apiClient.post(url + "/users/" + bankAccount.getUserToken() + "/bank-accounts", bankAccount, HyperwalletBankAccount.class); } /** * Get Bank Account * * @param userToken User token assigned * @param transferMethodToken Bank account token assigned * @return HyperwalletBankAccount bank account information */ public HyperwalletBankAccount getBankAccount(String userToken, String transferMethodToken) { if (StringUtils.isEmpty(userToken)) { throw new HyperwalletException("User token is required"); } if (StringUtils.isEmpty(transferMethodToken)) { throw new HyperwalletException("Bank Account token is required"); } return apiClient.get(url + "/users/" + userToken + "/bank-accounts/" + transferMethodToken, HyperwalletBankAccount.class); } /** * Update Bank Account * * @param bankAccount Bank Account to update. * @return HyperwalletBankAccount updated Bank Account */ public HyperwalletBankAccount updateBankAccount(HyperwalletBankAccount bankAccount) { if (bankAccount == null) { throw new HyperwalletException("Bank Account is required"); } if (StringUtils.isEmpty(bankAccount.getUserToken())) { throw new HyperwalletException("User token is required"); } if (StringUtils.isEmpty(bankAccount.getToken())) { throw new HyperwalletException("Bank Account token is required"); } return apiClient.put(url + "/users/" + bankAccount.getUserToken() + "/bank-accounts/" + bankAccount.getToken(), bankAccount, HyperwalletBankAccount.class); } /** * List Bank Accounts * * @param userToken User token assigned * @return HyperwalletList of HyperwalletBankAccount */ public HyperwalletList<HyperwalletBankAccount> listBankAccounts(String userToken) { return listBankAccounts(userToken, null); } /** * List Bank Accounts * * @param userToken User token assigned * @param options List filter option * @return HyperwalletList of HyperwalletBankAccount */ public HyperwalletList<HyperwalletBankAccount> listBankAccounts(String userToken, HyperwalletPaginationOptions options) { if (StringUtils.isEmpty(userToken)) { throw new HyperwalletException("User token is required"); } String url = paginate(this.url + "/users/" + userToken + "/bank-accounts", options); return apiClient.get(url, new TypeReference<HyperwalletList<HyperwalletBankAccount>>() { }); } /** * Deactivate Bank Account * * @param userToken User token * @param bankAccountToken Bank Account token * @return HyperwalletStatusTransition deactivated bank account */ public HyperwalletStatusTransition deactivateBankAccount(String userToken, String bankAccountToken) { return createBankAccountStatusTransition(userToken, bankAccountToken, new HyperwalletStatusTransition(HyperwalletStatusTransition.Status.DE_ACTIVATED)); } /** * Create Bank Account Status Transition * * @param userToken User token * @param bankAccountToken Bank Account token * @param transition Status transition information * @return HyperwalletStatusTransition */ public HyperwalletStatusTransition createBankAccountStatusTransition(String userToken, String bankAccountToken, HyperwalletStatusTransition transition) { if (transition == null) { throw new HyperwalletException("Transition is required"); } if (StringUtils.isEmpty(userToken)) { throw new HyperwalletException("User token is required"); } if (StringUtils.isEmpty(bankAccountToken)) { throw new HyperwalletException("Bank Account token is required"); } if (!StringUtils.isEmpty(transition.getToken())) { throw new HyperwalletException("Status Transition token may not be present"); } transition = copy(transition); transition.setCreatedOn(null); transition.setFromStatus(null); transition.setToStatus(null); return apiClient.post(url + "/users/" + userToken + "/bank-accounts/" + bankAccountToken + "/status-transitions", transition, HyperwalletStatusTransition.class); } /** * List All Bank Account Status Transition * * @param userToken User token * @param bankAccountToken Bank Account token * @return HyperwalletList of HyperwalletStatusTransition */ public HyperwalletList<HyperwalletStatusTransition> listBankAccountStatusTransitions(String userToken, String bankAccountToken) { return listBankAccountStatusTransitions(userToken, bankAccountToken, null); } /** * List Bank Account Status Transition * * @param userToken User token * @param bankAccountToken Bank Account token * @param options List filter option * @return HyperwalletList of HyperwalletStatusTransition */ public HyperwalletList<HyperwalletStatusTransition> listBankAccountStatusTransitions(String userToken, String bankAccountToken, HyperwalletPaginationOptions options) { if (StringUtils.isEmpty(userToken)) { throw new HyperwalletException("User token is required"); } if (StringUtils.isEmpty(bankAccountToken)) { throw new HyperwalletException("Bank Account token is required"); } String url = paginate(this.url + "/users/" + userToken + "/bank-accounts/" + bankAccountToken + "/status-transitions", options); return apiClient.get(url, new TypeReference<HyperwalletList<HyperwalletStatusTransition>>() { }); } // Balances /** * List all User's Balances * * @param userToken User token assigned * @return HyperwalletList of HyperwalletBalance */ public HyperwalletList<HyperwalletBalance> listBalancesForUser(String userToken) { return listBalancesForUser(userToken, null); } /** * List all User's Balances * * @param userToken User token assigned * @param options List filter option * @return HyperwalletList list of HyperwalletBalance */ public HyperwalletList<HyperwalletBalance> listBalancesForUser(String userToken, HyperwalletBalanceListOptions options) { if (StringUtils.isEmpty(userToken)) { throw new HyperwalletException("User token is required"); } String url = this.url + "/users/" + userToken + "/balances"; if (options != null) { url = addParameter(url, "currency", options.getCurrency()); url = addParameter(url, "sortBy", options.getSortBy()); url = addParameter(url, "offset", options.getOffset()); url = addParameter(url, "limit", options.getLimit()); } return apiClient.get(url, new TypeReference<HyperwalletList<HyperwalletBalance>>() { }); } /** * List all Program account balances * * @param accountToken Account token assigned * @param programToken Program token assigned * @return HyperwalletList of HyperwalletBalance */ public HyperwalletList<HyperwalletBalance> listBalancesForAccount(String programToken, String accountToken) { return listBalancesForAccount(programToken, accountToken, null); } /** * List all Program account balances * * @param accountToken Account token assigned * @param programToken Program token assigned * @param options List filter option * @return HyperwalletList list of HyperwalletBalance */ public HyperwalletList<HyperwalletBalance> listBalancesForAccount(String programToken, String accountToken, HyperwalletBalanceListOptions options) { if (StringUtils.isEmpty(programToken)) { throw new HyperwalletException("Program token is required"); } if (StringUtils.isEmpty(accountToken)) { throw new HyperwalletException("Account token is required"); } String url = this.url + "/programs/" + programToken + "/accounts/" + accountToken + "/balances"; if (options != null) { url = addParameter(url, "currency", options.getCurrency()); url = addParameter(url, "sortBy", options.getSortBy()); url = addParameter(url, "offset", options.getOffset()); url = addParameter(url, "limit", options.getLimit()); } return apiClient.get(url, new TypeReference<HyperwalletList<HyperwalletBalance>>() { }); } /** * List all User's Prepaid Card Balances * * @param userToken User token assigned * @param prepaidCardToken Prepaid Card token assigned from User's Prepaid Card * @return HyperwalletList of HyperwalletBalances */ public HyperwalletList<HyperwalletBalance> listBalancesForPrepaidCard(String userToken, String prepaidCardToken) { return listBalancesForPrepaidCard(userToken, prepaidCardToken, null); } /** * List all User's Prepaid Card Balances * * @param userToken User token assigned * @param prepaidCardToken Prepaid Card token assigned from User's Prepaid Card * @param options List filter option * @return HyperwalletList of HyperwalletBalances */ public HyperwalletList<HyperwalletBalance> listBalancesForPrepaidCard(String userToken, String prepaidCardToken, HyperwalletBalanceListOptions options) { if (StringUtils.isEmpty(userToken)) { throw new HyperwalletException("User token is required"); } if (StringUtils.isEmpty(prepaidCardToken)) { throw new HyperwalletException("Prepaid Card token is required"); } String url = this.url + "/users/" + userToken + "/prepaid-cards/" + prepaidCardToken + "/balances"; if (options != null) { url = addParameter(url, "sortBy", options.getSortBy()); url = addParameter(url, "offset", options.getOffset()); url = addParameter(url, "limit", options.getLimit()); } return apiClient.get(url, new TypeReference<HyperwalletList<HyperwalletBalance>>() { }); } // Payments /** * Create Payment * * @param payment Payment * @return HyperwalletPayment created payment information */ public HyperwalletPayment createPayment(HyperwalletPayment payment) { if (payment == null) { throw new HyperwalletException("Payment is required"); } if (!StringUtils.isEmpty(payment.getToken())) { throw new HyperwalletException("Payment token may not be present"); } payment = copy(payment); payment.setCreatedOn(null); return apiClient.post(url + "/payments", payment, HyperwalletPayment.class); } /** * Get Payment * * @param paymentToken Payment token * @return HyperwalletPayment */ public HyperwalletPayment getPayment(String paymentToken) { if (StringUtils.isEmpty(paymentToken)) { throw new HyperwalletException("Payment token is required"); } return apiClient.get(url + "/payments/" + paymentToken, HyperwalletPayment.class); } /** * List all Payments * * @return HyperwalletList of HyperwalletPayment */ public HyperwalletList<HyperwalletPayment> listPayments() { return listPayments(null); } /** * List all Payments * * @param options List filter option * @return HyperwalletList of HyperwalletPayment */ public HyperwalletList<HyperwalletPayment> listPayments(HyperwalletPaymentListOptions options) { String url = paginate(this.url + "/payments", options); if (options != null) { url = addParameter(url, "releasedOn", convert(options.getReleasedOn())); url = addParameter(url, "currency", options.getCurrency()); } return apiClient.get(url, new TypeReference<HyperwalletList<HyperwalletPayment>>() { }); } /** * Create Payment Status Transition * * @param paymentToken Payment token * @param transition Status transition information * @return HyperwalletStatusTransition new status for Payment */ public HyperwalletStatusTransition createPaymentStatusTransition(String paymentToken, HyperwalletStatusTransition transition) { if (transition == null) { throw new HyperwalletException("Transition is required"); } if (StringUtils.isEmpty(paymentToken)) { throw new HyperwalletException("Payment token is required"); } if (!StringUtils.isEmpty(transition.getToken())) { throw new HyperwalletException("Status Transition token may not be present"); } transition = copy(transition); transition.setCreatedOn(null); transition.setFromStatus(null); transition.setToStatus(null); return apiClient.post(url + "/payments/" + paymentToken + "/status-transitions", transition, HyperwalletStatusTransition.class); } /** * Get Payment Status Transition * * @param paymentToken Payment token * @param statusTransitionToken Status transition token * @return HyperwalletStatusTransition */ public HyperwalletStatusTransition getPaymentStatusTransition(String paymentToken, String statusTransitionToken) { if (StringUtils.isEmpty(paymentToken)) { throw new HyperwalletException("Payment token is required"); } if (StringUtils.isEmpty(statusTransitionToken)) { throw new HyperwalletException("Transition token is required"); } return apiClient.get(url + "/payments/" + paymentToken + "/status-transitions/" + statusTransitionToken, HyperwalletStatusTransition.class); } /** * List All Payment Status Transition information * * @param paymentToken Payment token * @return HyperwalletList of HyperwalletStatusTransition */ public HyperwalletList<HyperwalletStatusTransition> listPaymentStatusTransitions( String paymentToken) { return listPaymentStatusTransitions(paymentToken, null); } /** * List Payment Status Transition information * * @param paymentToken Payment token * @param options List filter option * @return HyperwalletList of HyperwalletStatusTransition */ public HyperwalletList<HyperwalletStatusTransition> listPaymentStatusTransitions(String paymentToken, HyperwalletPaginationOptions options) { if (StringUtils.isEmpty(paymentToken)) { throw new HyperwalletException("Payment token is required"); } String url = paginate(this.url + "/payments/" + paymentToken + "/status-transitions", options); return apiClient.get(url, new TypeReference<HyperwalletList<HyperwalletStatusTransition>>() { }); } // Programs /** * Get Program * * @param programToken Program token * @return HyperwalletProgram */ public HyperwalletProgram getProgram(String programToken) { if (StringUtils.isEmpty(programToken)) { throw new HyperwalletException("Program token is required"); } return apiClient.get(url + "/programs/" + programToken, HyperwalletProgram.class); } // Program Accounts /** * Get Programs Account * * @param programToken Program token * @param accountToken Program account token * @return HyperwalletAccount */ public HyperwalletAccount getProgramAccount(String programToken, String accountToken) { if (StringUtils.isEmpty(programToken)) { throw new HyperwalletException("Program token is required"); } if (StringUtils.isEmpty(accountToken)) { throw new HyperwalletException("Account token is required"); } return apiClient.get(url + "/programs/" + programToken + "/accounts/" + accountToken, HyperwalletAccount.class); } // Transfer Method Configurations /** * Get Transfer Method Configuration * * @param userToken User token * @param country Country * @param currency Currency * @param type Type of Transfer Method to retrieve * @param profileType Type of User profile * @return HyperwalletTransferMethodConfiguration */ public HyperwalletTransferMethodConfiguration getTransferMethodConfiguration(String userToken, String country, String currency, HyperwalletTransferMethod.Type type, HyperwalletUser.ProfileType profileType) { if (StringUtils.isEmpty(userToken)) { throw new HyperwalletException("User token is required"); } if (StringUtils.isEmpty(country)) { throw new HyperwalletException("Country is required"); } if (StringUtils.isEmpty(currency)) { throw new HyperwalletException("Currency is required"); } if (type == null) { throw new HyperwalletException("Type is required"); } if (profileType == null) { throw new HyperwalletException("Profile Type is required"); } return apiClient.get(url + "/transfer-method-configurations" + "?userToken=" + userToken + "&country=" + country + "&currency=" + currency + "&type=" + type.name() + "&profileType=" + profileType.name(), HyperwalletTransferMethodConfiguration.class); } /** * List all Transfer Method Configuration associated with User * * @param userToken User token * @return HyperwalletList of HyperwalletTransferMethodConfiguration */ public HyperwalletList<HyperwalletTransferMethodConfiguration> listTransferMethodConfigurations(String userToken) { return listTransferMethodConfigurations(userToken, null); } /** * List all Transfer Method Configuration associated with User * * @param userToken User token * @param options List filter options * @return HyperwalletList of HyperwalletTransferMethodConfiguration */ public HyperwalletList<HyperwalletTransferMethodConfiguration> listTransferMethodConfigurations(String userToken, HyperwalletPaginationOptions options) { if (StringUtils.isEmpty(userToken)) { throw new HyperwalletException("User token is required"); } String url = paginate(this.url + "/transfer-method-configurations?userToken=" + userToken, options); return apiClient.get(url, new TypeReference<HyperwalletList<HyperwalletTransferMethodConfiguration>>() { }); } // Receipts /** * List all program account receipts * * @param programToken Program token * @param accountToken Program account token * @return HyperwalletList of HyperwalletReceipt */ public HyperwalletList<HyperwalletReceipt> listReceiptsForProgramAccount(String programToken, String accountToken) { return listReceiptsForProgramAccount(programToken, accountToken, null); } /** * List all program account receipts * * @param programToken Program token * @param accountToken Program account token * @param options List filter options * @return HyperwalletList of HyperwalletReceipt */ public HyperwalletList<HyperwalletReceipt> listReceiptsForProgramAccount(String programToken, String accountToken, HyperwalletReceiptPaginationOptions options) { if (StringUtils.isEmpty(programToken)) { throw new HyperwalletException("Program token is required"); } if (StringUtils.isEmpty(accountToken)) { throw new HyperwalletException("Account token is required"); } String url = paginate(this.url + "/programs/" + programToken + "/accounts/" + accountToken + "/receipts", options); if (options != null && options.getType() != null) { url = addParameter(url, "type", options.getType().name()); } return apiClient.get(url, new TypeReference<HyperwalletList<HyperwalletReceipt>>() { }); } /** * List all user receipts * * @param userToken User token * @return HyperwalletList of HyperwalletReceipt */ public HyperwalletList<HyperwalletReceipt> listReceiptsForUser(String userToken) { return listReceiptsForUser(userToken, null); } /** * List all user receipts * * @param userToken Program token * @param options List filter options * @return HyperwalletList of HyperwalletReceipt */ public HyperwalletList<HyperwalletReceipt> listReceiptsForUser(String userToken, HyperwalletReceiptPaginationOptions options) { if (StringUtils.isEmpty(userToken)) { throw new HyperwalletException("User token is required"); } String url = paginate(this.url + "/users/" + userToken + "/receipts", options); if (options != null && options.getType() != null) { url = addParameter(url, "type", options.getType().name()); } return apiClient.get(url, new TypeReference<HyperwalletList<HyperwalletReceipt>>() { }); } /** * List all prepaid card receipts * * @param userToken User token * @param prepaidCardToken Prepaid card token * @return HyperwalletList of HyperwalletReceipt */ public HyperwalletList<HyperwalletReceipt> listReceiptsForPrepaidCard(String userToken, String prepaidCardToken) { return listReceiptsForPrepaidCard(userToken, prepaidCardToken, null); } /** * List all prepaid card receipts * * @param userToken User token * @param prepaidCardToken Prepaid card token * @param options List filter options * @return HyperwalletList of HyperwalletReceipt */ public HyperwalletList<HyperwalletReceipt> listReceiptsForPrepaidCard(String userToken, String prepaidCardToken, HyperwalletReceiptPaginationOptions options) { if (StringUtils.isEmpty(userToken)) { throw new HyperwalletException("User token is required"); } if (StringUtils.isEmpty(prepaidCardToken)) { throw new HyperwalletException("Prepaid card token is required"); } String url = paginate(this.url + "/users/" + userToken + "/prepaid-cards/" + prepaidCardToken + "/receipts", options); if (options != null && options.getType() != null) { url = addParameter(url, "type", options.getType().name()); } return apiClient.get(url, new TypeReference<HyperwalletList<HyperwalletReceipt>>() { }); } // Webhook Notification /** * Retrieve webhook event notification * * @param webhookToken Webhook token * @return HyperwalletWebhookNotification * */ public HyperwalletWebhookNotification getWebhookEvent(String webhookToken) { if (StringUtils.isEmpty(webhookToken)) { throw new HyperwalletException("Webhook token is required"); } return apiClient.get(url + "/webhook-notifications/" + webhookToken, HyperwalletWebhookNotification.class); } /** * List all webhook event notifications * * @return HyperwalletList of HyperwalletWebhookNotification * */ public HyperwalletList<HyperwalletWebhookNotification> listWebhookEvents() { return listWebhookEvents(null); } /** * List all webhook event notifications * * @param options List filter options * @return HyperwalletList of HyperwalletWebhookNotification * */ public HyperwalletList<HyperwalletWebhookNotification> listWebhookEvents(HyperwalletWebhookNotificationPaginationOptions options) { String url = paginate(this.url + "/webhook-notifications", options); if (options != null && options.getType() != null) { url = addParameter(url, "type", options.getType()); } return apiClient.get(url, new TypeReference<HyperwalletList<HyperwalletWebhookNotification>>() {}); } // Transfer Methods /** * Create a Transfer Method * * @param jsonCacheToken String JSON cache token * @param transferMethod TransferMethod object to create * @return HyperwalletTransferMethod Transfer Method object created */ public HyperwalletTransferMethod createTransferMethod(String jsonCacheToken, HyperwalletTransferMethod transferMethod) { if (transferMethod == null || StringUtils.isEmpty(transferMethod.getUserToken())) { throw new HyperwalletException("User token is required"); } if (StringUtils.isEmpty(jsonCacheToken)) { throw new HyperwalletException("JSON token is required"); } transferMethod = copy(transferMethod); transferMethod.setToken(null); transferMethod.setStatus(null); transferMethod.setCreatedOn(null); HashMap<String, String> headers = new HashMap<String, String>(); headers.put("Json-Cache-Token", jsonCacheToken); return apiClient.post(url + "/users/" + transferMethod.getUserToken() + "/transfer-methods", transferMethod, HyperwalletTransferMethod.class, headers); } /** * Create a Transfer Method * * @param jsonCacheToken String JSON cache token * @param userToken String user token * @return HyperwalletTransferMethod Transfer Method object created */ public HyperwalletTransferMethod createTransferMethod(String jsonCacheToken, String userToken) { if (StringUtils.isEmpty(userToken)) { throw new HyperwalletException("User token is required"); } if (StringUtils.isEmpty(jsonCacheToken)) { throw new HyperwalletException("JSON token is required"); } HyperwalletTransferMethod transferMethod = new HyperwalletTransferMethod(); transferMethod.setUserToken(userToken); HashMap<String, String> headers = new HashMap<String, String>(); headers.put("Json-Cache-Token", jsonCacheToken); return apiClient.post(url + "/users/" + transferMethod.getUserToken() + "/transfer-methods", transferMethod, HyperwalletTransferMethod.class, headers); } // Internal utils private String paginate(String url, HyperwalletPaginationOptions options) { if (options == null) { return url; } url = addParameter(url, "createdAfter", convert(options.getCreatedAfter())); url = addParameter(url, "createdBefore", convert(options.getCreatedBefore())); url = addParameter(url, "sortBy", options.getSortBy()); url = addParameter(url, "offset", options.getOffset()); url = addParameter(url, "limit", options.getLimit()); return url; } private String addParameter(String url, String key, Object value) { if (url == null || key == null || value == null) { return url; } return url + (url.indexOf("?") == -1 ? "?" : "&") + key + "=" + value; } private String convert(Date in) { if (in == null) { return null; } DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); return dateFormat.format(in); } private void setProgramToken(HyperwalletUser user) { if (user != null && user.getProgramToken() == null) { user.setProgramToken(this.programToken); } } private void setProgramToken(HyperwalletPayment payment) { if (payment != null && payment.getProgramToken() == null) { payment.setProgramToken(this.programToken); } } private HyperwalletUser copy(HyperwalletUser user) { user = HyperwalletJsonUtil.fromJson(HyperwalletJsonUtil.toJson(user), HyperwalletUser.class); setProgramToken(user); return user; } private HyperwalletPayment copy(HyperwalletPayment payment) { payment = HyperwalletJsonUtil.fromJson(HyperwalletJsonUtil.toJson(payment), HyperwalletPayment.class); setProgramToken(payment); return payment; } private HyperwalletPrepaidCard copy(HyperwalletPrepaidCard method) { method = HyperwalletJsonUtil.fromJson(HyperwalletJsonUtil.toJson(method), HyperwalletPrepaidCard.class); return method; } private HyperwalletBusinessStakeholder copy(HyperwalletBusinessStakeholder method) { method = HyperwalletJsonUtil.fromJson(HyperwalletJsonUtil.toJson(method), HyperwalletBusinessStakeholder.class); return method; } private HyperwalletBankCard copy(HyperwalletBankCard card) { card = HyperwalletJsonUtil.fromJson(HyperwalletJsonUtil.toJson(card), HyperwalletBankCard.class); return card; } private HyperwalletPaperCheck copy(HyperwalletPaperCheck check) { check = HyperwalletJsonUtil.fromJson(HyperwalletJsonUtil.toJson(check), HyperwalletPaperCheck.class); return check; } private HyperwalletBankAccount copy(HyperwalletBankAccount method) { method = HyperwalletJsonUtil.fromJson(HyperwalletJsonUtil.toJson(method), HyperwalletBankAccount.class); return method; } private HyperwalletStatusTransition copy(HyperwalletStatusTransition statusTransition) { statusTransition = HyperwalletJsonUtil.fromJson(HyperwalletJsonUtil.toJson(statusTransition), HyperwalletStatusTransition.class); return statusTransition; } private HyperwalletTransferMethod copy(HyperwalletTransferMethod transferMethod) { transferMethod = HyperwalletJsonUtil.fromJson(HyperwalletJsonUtil.toJson(transferMethod), HyperwalletTransferMethod.class); return transferMethod; } private HyperwalletTransfer copy(HyperwalletTransfer transfer) { transfer = HyperwalletJsonUtil.fromJson(HyperwalletJsonUtil.toJson(transfer), HyperwalletTransfer.class); return transfer; } private HyperwalletPayPalAccount copy(HyperwalletPayPalAccount payPalAccount) { payPalAccount = HyperwalletJsonUtil.fromJson(HyperwalletJsonUtil.toJson(payPalAccount), HyperwalletPayPalAccount.class); return payPalAccount; } }
package ca.cumulonimbus.pressurenetsdk; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.security.MessageDigest; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import android.app.Service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.database.Cursor; import android.database.sqlite.SQLiteDatabaseLockedException; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.location.Location; import android.net.ConnectivityManager; import android.os.BatteryManager; import android.os.Build; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.Messenger; import android.os.PowerManager; import android.os.RemoteException; import android.preference.PreferenceManager; import android.provider.Settings.Secure; /** * Represent developer-facing pressureNET API Background task; manage and run * everything Handle Intents * * @author jacob * */ public class CbService extends Service { private CbDataCollector dataCollector; private CbLocationManager locationManager; private CbSettingsHandler settingsHandler; private CbDb db; public CbService service = this; private String mAppDir; IBinder mBinder; ReadingSender sender; Message recentMsg; String serverURL = CbConfiguration.SERVER_URL; public static String ACTION_SEND_MEASUREMENT = "ca.cumulonimbus.pressurenetsdk.ACTION_SEND_MEASUREMENT"; public static String ACTION_REGISTER = "ca.cumulonimbus.pressurenetsdk.ACTION_REGISTER"; // Service Interaction API Messages public static final int MSG_OKAY = 0; public static final int MSG_STOP = 1; public static final int MSG_GET_BEST_LOCATION = 2; public static final int MSG_BEST_LOCATION = 3; public static final int MSG_GET_BEST_PRESSURE = 4; public static final int MSG_BEST_PRESSURE = 5; public static final int MSG_START_AUTOSUBMIT = 6; public static final int MSG_STOP_AUTOSUBMIT = 7; public static final int MSG_SET_SETTINGS = 8; public static final int MSG_GET_SETTINGS = 9; public static final int MSG_SETTINGS = 10; // Live sensor streaming public static final int MSG_START_STREAM = 11; public static final int MSG_DATA_STREAM = 12; public static final int MSG_STOP_STREAM = 13; // PressureNet Live API public static final int MSG_GET_LOCAL_RECENTS = 14; public static final int MSG_LOCAL_RECENTS = 15; public static final int MSG_GET_API_RECENTS = 16; public static final int MSG_API_RECENTS = 17; public static final int MSG_MAKE_API_CALL = 18; public static final int MSG_API_RESULT_COUNT = 19; // PressureNet API Cache public static final int MSG_CLEAR_LOCAL_CACHE = 20; public static final int MSG_REMOVE_FROM_PRESSURENET = 21; public static final int MSG_CLEAR_API_CACHE = 22; // Current Conditions public static final int MSG_ADD_CURRENT_CONDITION = 23; public static final int MSG_GET_CURRENT_CONDITIONS = 24; public static final int MSG_CURRENT_CONDITIONS = 25; // Sending Data public static final int MSG_SEND_OBSERVATION = 26; public static final int MSG_SEND_CURRENT_CONDITION = 27; // Current Conditions API public static final int MSG_MAKE_CURRENT_CONDITIONS_API_CALL = 28; // Notifications public static final int MSG_CHANGE_NOTIFICATION = 31; // Data management public static final int MSG_COUNT_LOCAL_OBS = 32; public static final int MSG_COUNT_API_CACHE = 33; public static final int MSG_COUNT_LOCAL_OBS_TOTALS = 34; public static final int MSG_COUNT_API_CACHE_TOTALS = 35; // Graphing public static final int MSG_GET_API_RECENTS_FOR_GRAPH = 36; public static final int MSG_API_RECENTS_FOR_GRAPH = 37; // Success / Failure notification for data submission public static final int MSG_DATA_RESULT = 38; // Statistics public static final int MSG_MAKE_STATS_CALL = 39; public static final int MSG_STATS = 40; // External Weather Services public static final int MSG_GET_EXTERNAL_LOCAL_EXPANDED = 41; public static final int MSG_EXTERNAL_LOCAL_EXPANDED = 42; // User contributions summary public static final int MSG_GET_CONTRIBUTIONS = 43; public static final int MSG_CONTRIBUTIONS = 44; // Database info, test suites/debugging public static final int MSG_GET_DATABASE_INFO = 45; // Multitenancy Support public static final int MSG_GET_PRIMARY_APP = 46; public static final int MSG_IS_PRIMARY = 47; // Localized Current conditions public static final int MSG_GET_LOCAL_CONDITIONS = 48; public static final int MSG_LOCAL_CONDITIONS = 49; // Intents public static final String PRESSURE_CHANGE_ALERT = "ca.cumulonimbus.pressurenetsdk.PRESSURE_CHANGE_ALERT"; public static final String LOCAL_CONDITIONS_ALERT = "ca.cumulonimbus.pressurenetsdk.LOCAL_CONDITIONS_ALERT"; public static final String PRESSURE_SENT_TOAST = "ca.cumulonimbus.pressurenetsdk.PRESSURE_SENT_TOAST"; public static final String CONDITION_SENT_TOAST = "ca.cumulonimbus.pressurenetsdk.CONDITION_SENT_TOAST"; // Support for new sensor type constants private final int TYPE_AMBIENT_TEMPERATURE = 13; private final int TYPE_RELATIVE_HUMIDITY = 12; long lastAPICall = System.currentTimeMillis(); long lastConditionNotification = System.currentTimeMillis() - (1000 * 60 * 60 * 6); private CbObservation collectedObservation; private final Handler mHandler = new Handler(); Messenger mMessenger = new Messenger(new IncomingHandler()); ArrayList<CbObservation> offlineBuffer = new ArrayList<CbObservation>(); private long lastPressureChangeAlert = 0; private Messenger lastMessenger; private boolean fromUser = false; CbAlarm alarm = new CbAlarm(); double recentPressureReading = 0.0; int recentPressureAccuracy = 0; int batchReadingCount = 0; private long lastSubmit = 0; private PowerManager.WakeLock wl; private boolean hasBarometer = true; ArrayList<CbSensorStreamer> activeStreams = new ArrayList<CbSensorStreamer>(); /** * Collect data from onboard sensors and store locally * * @author jacob * */ public class CbDataCollector implements SensorEventListener { private SensorManager sm; Sensor pressureSensor; private final int TYPE_AMBIENT_TEMPERATURE = 13; private final int TYPE_RELATIVE_HUMIDITY = 12; private ArrayList<CbObservation> recentObservations = new ArrayList<CbObservation>(); int stopSoonCalls = 0; public ArrayList<CbObservation> getRecentObservations() { return recentObservations; } /** * Access the database to fetch recent, locally-recorded observations * * @return */ public ArrayList<CbObservation> getRecentDatabaseObservations() { ArrayList<CbObservation> recentDbList = new ArrayList<CbObservation>(); CbDb db = new CbDb(getApplicationContext()); db.open(); Cursor c = db.fetchAllObservations(); while (c.moveToNext()) { CbObservation obs = new CbObservation(); Location location = new Location("network"); location.setLatitude(c.getDouble(1)); location.setLongitude(c.getDouble(2)); location.setAltitude(c.getDouble(3)); location.setAccuracy(c.getInt(4)); location.setProvider(c.getString(5)); obs.setLocation(location); obs.setObservationType(c.getString(6)); obs.setObservationUnit(c.getString(7)); obs.setObservationValue(c.getDouble(8)); obs.setSharing(c.getString(9)); obs.setTime(c.getInt(10)); obs.setTimeZoneOffset(c.getInt(11)); obs.setUser_id(c.getString(12)); recentDbList.add(obs); } db.close(); return recentDbList; } public void setRecentObservations( ArrayList<CbObservation> recentObservations) { this.recentObservations = recentObservations; } /** * Start collecting sensor data. * * @param m * @return */ public boolean startCollectingData() { batchReadingCount = 0; stopSoonCalls = 0; sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE); pressureSensor = sm.getDefaultSensor(Sensor.TYPE_PRESSURE); if(wl!=null) { log("cbservice startcollectingdata wakelock " + wl.isHeld()); if(!wl.isHeld()) { log("cbservice startcollectingdata no wakelock, bailing"); return false; } } boolean collecting = false; try { if(sm != null) { if (pressureSensor != null) { log("cbservice sensor SDK " + android.os.Build.VERSION.SDK_INT + ""); if(android.os.Build.VERSION.SDK_INT == 19) { collecting = sm.registerListener(this, pressureSensor,SensorManager.SENSOR_DELAY_UI); // , 100000); } else { collecting = sm.registerListener(this, pressureSensor,SensorManager.SENSOR_DELAY_UI); } } else { log("cbservice pressure sensor is null"); } } else { log("cbservice sm is null"); } return collecting; } catch (Exception e) { log("cbservice sensor error " + e.getMessage()); e.printStackTrace(); return collecting; } } /** * Stop collecting sensor data */ public void stopCollectingData() { log("cbservice stop collecting data"); // sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE); if(sm!=null) { log("cbservice sensormanager not null, unregistering"); sm.unregisterListener(this); sm = null; } else { log("cbservice sensormanager null, walk away"); /* sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE); sm.unregisterListener(this); sm = null; */ } } public CbDataCollector() { } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { if (sensor.getType() == Sensor.TYPE_PRESSURE) { recentPressureAccuracy = accuracy; log("cbservice accuracy changed, new barometer accuracy " + recentPressureAccuracy); } } @Override public void onSensorChanged(SensorEvent event) { if (event.sensor.getType() == Sensor.TYPE_PRESSURE) { if(event.values.length > 0) { if(event.values[0] >= 0) { log("cbservice sensor; new pressure reading " + event.values[0]); recentPressureReading = event.values[0]; } else { log("cbservice sensor; pressure reading is 0 or negative" + event.values[0]); } } else { log("cbservice sensor; no event values"); } } if(stopSoonCalls<=1) { stopSoon(); } /* batchReadingCount++; if(batchReadingCount>2) { log("batch readings " + batchReadingCount + ", stopping"); stopCollectingData(); } else { log("batch readings " + batchReadingCount + ", not stopping"); } */ } private class SensorStopper implements Runnable { @Override public void run() { stopCollectingData(); } } private void stopSoon() { stopSoonCalls++; SensorStopper stop = new SensorStopper(); mHandler.postDelayed(stop, 100); } } /** * Collect data from onboard sensors and store locally * * @author jacob * */ public class CbSensorStreamer implements SensorEventListener { public int sensorId; private Messenger replyTo; private SensorManager sm; Sensor sensor; /** * Start collecting sensor data. * * @param m * @return */ public void startSendingData() { sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE); sensor = sm.getDefaultSensor(sensorId); try { if(sm != null) { if (sensor != null) { log("CbService streamer registering sensorID " + sensorId); sm.registerListener(this, sensor, SensorManager.SENSOR_DELAY_UI); } else { log("cbservice streaming sensor is null"); } } else { log("cbservice sm is null"); } } catch (Exception e) { log("cbservice sensor error " + e.getMessage()); } } /** * Stop collecting sensor data */ public void stopSendingData() { log("cbservice streaming stop collecting data"); if(sm!=null) { log("cbservice streaming sensormanager not null, unregistering"); sm.unregisterListener(this); sm = null; } else { log("cbservice streaming sensormanager null, walk away"); } } public CbSensorStreamer(int id, Messenger reply) { this.sensorId = id; this.replyTo = reply; } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { if (sensor.getType() == sensorId) { } } @Override public void onSensorChanged(SensorEvent event) { if (event.sensor.getType() == sensorId) { // new sensor reading CbObservation obs = new CbObservation(); obs.setObservationValue(event.values[0]); try { replyTo.send(Message.obtain(null, MSG_DATA_STREAM, obs)); } catch (RemoteException re) { re.printStackTrace(); } } } } /** * Check if a sensor is already being used in an active stream * to avoid multiple listeners on the same sensor. * @param sensorId * @return */ private boolean isSensorStreaming(int sensorId) { for(CbSensorStreamer s : activeStreams) { if (s.sensorId == sensorId) { return true; } } return false; } /** * Start live sensor streaming from the service * to the app. MSG_START_STREAM */ public void startSensorStream(int sensorId, Messenger reply) { if(!isSensorStreaming(sensorId)) { log("CbService starting live sensor streaming " + sensorId); CbSensorStreamer streamer = new CbSensorStreamer(sensorId, reply); activeStreams.add(streamer); streamer.startSendingData(); } else { log("CbService not starting live sensor streaming " + sensorId + ", already streaming"); } } /** * Stop live sensor streaming. MSG_STOP_STREAM */ public void stopSensorStream(int sensorId) { if(isSensorStreaming(sensorId)) { log("CbService stopping live sensor streaming " + sensorId); for(CbSensorStreamer s : activeStreams) { if (s.sensorId == sensorId) { s.stopSendingData(); activeStreams.remove(s); break; } } } else { log("CbService not stopping live sensor streaming " + sensorId + " sensor not running"); } } /** * Find all the data for an observation. * * Location, Measurement values, etc. * * @return */ public CbObservation collectNewObservation() { try { CbObservation pressureObservation = new CbObservation(); log("cb collecting new observation"); // Location values locationManager = new CbLocationManager(getApplicationContext()); locationManager.startGettingLocations(); // Measurement values pressureObservation = buildPressureObservation(); pressureObservation.setLocation(locationManager .getCurrentBestLocation()); log("returning pressure obs: " + pressureObservation.getObservationValue()); return pressureObservation; } catch (Exception e) { //e.printStackTrace(); return null; } } private class LocationStopper implements Runnable { @Override public void run() { try { //System.out.println("locationmanager stop getting locations"); locationManager.stopGettingLocations(); } catch (Exception e) { //e.printStackTrace(); } } } /** * Send a single reading. TODO: Combine with ReadingSender for less code duplication. * ReadingSender. Fix that. */ public class SingleReadingSender implements Runnable { @Override public void run() { checkForLocalConditionReports(); if(settingsHandler == null) { log("single reading sender, loading settings from prefs"); loadSetttingsFromPreferences(); } log("collecting and submitting single " + settingsHandler.getServerURL()); CbObservation singleObservation = new CbObservation(); if (hasBarometer && settingsHandler.isCollectingData()) { // Collect dataCollector = new CbDataCollector(); dataCollector.startCollectingData(); singleObservation = collectNewObservation(); if (singleObservation.getObservationValue() != 0.0) { // Store in database db.open(); long count = db.addObservation(singleObservation); db.close(); try { if (settingsHandler.isSharingData()) { if(! settingsHandler.getShareLevel().equals("Nobody")) { // Send if we're online if (isNetworkAvailable()) { log("cbservice online and sending single"); singleObservation .setClientKey(CbConfiguration.API_KEY); fromUser = true; sendCbObservation(singleObservation); fromUser = false; // also check and send the offline buffer if (offlineBuffer.size() > 0) { log("sending " + offlineBuffer.size() + " offline buffered obs"); for (CbObservation singleOffline : offlineBuffer) { sendCbObservation(singleObservation); } offlineBuffer.clear(); } } else { log("didn't send, not sharing data; i.e., offline"); // / offline buffer variable // TODO: put this in the DB to survive longer offlineBuffer.add(singleObservation); } } else { log("cbservice didn't send, sharing=Nobody"); } } } catch (Exception e) { //e.printStackTrace(); } } } } } /** * Check if we have a barometer. Use info to disable menu items, choose to * run the service or not, etc. */ private boolean checkBarometer() { PackageManager packageManager = this.getPackageManager(); hasBarometer = packageManager .hasSystemFeature(PackageManager.FEATURE_SENSOR_BAROMETER); return hasBarometer; } /** * Collect and send data in a different thread. This runs itself every * "settingsHandler.getDataCollectionFrequency()" milliseconds */ private class ReadingSender implements Runnable { public void run() { checkForLocalConditionReports(); long now = System.currentTimeMillis(); if(now - lastSubmit < 2000) { log("cbservice readingsender too soon, bailing"); return; } // retrieve updated settings settingsHandler = new CbSettingsHandler(getApplicationContext()); settingsHandler = settingsHandler.getSettings(); log("collecting and submitting " + settingsHandler.getServerURL()); boolean okayToGo = true; // Check if we're supposed to be charging and if we are. // Bail if appropriate if (settingsHandler.isOnlyWhenCharging()) { if (!isCharging()) { okayToGo = false; } } if(!hasBarometer) { okayToGo = false; } if (okayToGo && settingsHandler.isCollectingData()) { // Collect // start collecting data dataCollector = new CbDataCollector(); dataCollector.startCollectingData(); CbObservation singleObservation = new CbObservation(); singleObservation = collectNewObservation(); if (singleObservation != null) { if (singleObservation.getObservationValue() != 0.0) { // Store in database db.open(); long count = db.addObservation(singleObservation); db.close(); try { if (settingsHandler.isSharingData()) { if(! settingsHandler.getShareLevel().equals("Nobody")) { // Send if we're online if (isNetworkAvailable()) { lastSubmit = System.currentTimeMillis(); log("cbservice online and sending"); singleObservation .setClientKey(CbConfiguration.API_KEY); sendCbObservation(singleObservation); // also check and send the offline buffer if (offlineBuffer.size() > 0) { log("sending " + offlineBuffer.size() + " offline buffered obs"); for (CbObservation singleOffline : offlineBuffer) { sendCbObservation(singleObservation); } offlineBuffer.clear(); } } else { log("didn't send"); // / offline buffer variable // TODO: put this in the DB to survive // longer offlineBuffer.add(singleObservation); } } else { log("cbservice not sending, sharing=Nobody"); } } else { log("cbservice not sharing data, didn't send"); } // If notifications are enabled, log("is send notif " + settingsHandler.isSendNotifications()); if (settingsHandler.isSendNotifications()) { // check for pressure local trend changes and // notify // the client // ensure this only happens every once in a // while long rightNow = System.currentTimeMillis(); long sixHours = 1000 * 60 * 60 * 6; if (rightNow - lastPressureChangeAlert > (sixHours)) { long timeLength = 1000 * 60 * 60 * 3; db.open(); Cursor localCursor = db.runLocalAPICall( -90, 90, -180, 180, System.currentTimeMillis() - (timeLength), System.currentTimeMillis(), 1000); ArrayList<CbObservation> recents = new ArrayList<CbObservation>(); while (localCursor.moveToNext()) { // just need observation value, time, // and // location CbObservation obs = new CbObservation(); obs.setObservationValue(localCursor .getDouble(8)); obs.setTime(localCursor.getLong(10)); Location location = new Location( "network"); location.setLatitude(localCursor .getDouble(1)); location.setLongitude(localCursor .getDouble(2)); obs.setLocation(location); recents.add(obs); } String tendencyChange = CbScience .changeInTrend(recents); db.close(); log("cbservice tendency changes: " + tendencyChange); if (tendencyChange.contains(",") && (!tendencyChange.toLowerCase() .contains("unknown"))) { String[] tendencies = tendencyChange .split(","); if (!tendencies[0] .equals(tendencies[1])) { log("Trend change! " + tendencyChange); Intent intent = new Intent(); intent.setAction(PRESSURE_CHANGE_ALERT); intent.putExtra("ca.cumulonimbus.pressurenetsdk.tendencyChange", tendencyChange); sendBroadcast(intent); try { if (lastMessenger != null) { lastMessenger .send(Message .obtain(null, MSG_CHANGE_NOTIFICATION, tendencyChange)); } else { log("readingsender didn't send notif, no lastMessenger"); } } catch (Exception e) { //e.printStackTrace(); } lastPressureChangeAlert = rightNow; // TODO: saveinprefs; } else { log("tendency equal"); } } } else { // wait log("tendency; hasn't been 6h, min wait time yet"); } } } catch (Exception e) { //e.printStackTrace(); } } } else { log("singleobservation is null, not sending"); } } else { log("cbservice is not collecting data."); } } } /** * Put together all the information that defines * an observation and store it in a single object. * @return */ public CbObservation buildPressureObservation() { CbObservation pressureObservation = new CbObservation(); pressureObservation.setTime(System.currentTimeMillis()); pressureObservation.setTimeZoneOffset(Calendar.getInstance() .getTimeZone().getRawOffset()); pressureObservation.setUser_id(getID()); pressureObservation.setObservationType("pressure"); pressureObservation.setObservationValue(recentPressureReading); pressureObservation.setObservationUnit("mbar"); // pressureObservation.setSensor(sm.getSensorList(Sensor.TYPE_PRESSURE).get(0)); pressureObservation.setSharing(settingsHandler.getShareLevel()); pressureObservation.setVersionNumber(getSDKVersion()); pressureObservation.setPackageName(getApplication().getPackageName()); log("cbservice buildobs, share level " + settingsHandler.getShareLevel() + " " + getID()); return pressureObservation; } /** * Return the version number of the SDK sending this reading * @return */ public String getSDKVersion() { return CbConfiguration.SDK_VERSION; } /** * Periodically check to see if someone has * reported a current condition nearby. If it's * appropriate, send a notification */ private void checkForLocalConditionReports() { if (settingsHandler.isSendNotifications()) { long now = System.currentTimeMillis(); long minWaitTime = 1000 * 60 * 60; if(now - minWaitTime > lastConditionNotification) { if(locationManager == null) { locationManager = new CbLocationManager(getApplicationContext()); } log("cbservice checking for local conditions reports"); // it has been long enough; make a conditions API call // for the local area CbApi conditionApi = new CbApi(getApplicationContext()); CbApiCall conditionApiCall = buildLocalConditionsApiCall(); if(conditionApiCall!=null) { log("cbservice making conditions api call for local reports"); conditionApi.makeAPICall(conditionApiCall, service, mMessenger, "Conditions"); // TODO: store this more permanently lastConditionNotification = now; } } else { log("cbservice not checking for local conditions, too recent"); } } } /** * Make a CbApiCall object for local conditions * @return */ public CbApiCall buildLocalConditionsApiCall() { CbApiCall conditionApiCall = new CbApiCall(); conditionApiCall.setCallType("Conditions"); Location location = new Location("network"); location.setLatitude(0); location.setLongitude(0); if(locationManager != null) { location = locationManager.getCurrentBestLocation(); if(location != null) { conditionApiCall.setMinLat(location.getLatitude() - .1); conditionApiCall.setMaxLat(location.getLatitude() + .1); conditionApiCall.setMinLon(location.getLongitude() - .1); conditionApiCall.setMaxLon(location.getLongitude() + .1); conditionApiCall.setStartTime(System.currentTimeMillis() - (1000 * 60 * 60)); conditionApiCall.setEndTime(System.currentTimeMillis()); return conditionApiCall; } else { return null; } } else { log("cbservice not checking location condition reports, no locationmanager"); return null; } } /** * Check for network connection, return true * if we're online. * * @return */ public boolean isNetworkAvailable() { log("is net available?"); ConnectivityManager cm = (ConnectivityManager) this .getSystemService(Context.CONNECTIVITY_SERVICE); // test for connection if (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isAvailable() && cm.getActiveNetworkInfo().isConnected()) { log("yes"); return true; } else { log("no"); return false; } } /** * Stop all listeners, active sensors, etc, and shut down. * */ public void stopAutoSubmit() { if (locationManager != null) { locationManager.stopGettingLocations(); } if (dataCollector != null) { dataCollector.stopCollectingData(); } log("cbservice stop autosubmit"); // alarm.cancelAlarm(getApplicationContext()); } /** * Send the observation to the server * * @param observation * @return */ public boolean sendCbObservation(CbObservation observation) { try { CbDataSender sender = new CbDataSender(getApplicationContext()); settingsHandler = settingsHandler.getSettings(); if(settingsHandler.getServerURL().equals("")) { log("cbservice settings are empty; defaults"); //loadSetttingsFromPreferences(); // settingsHandler = settingsHandler.getSettings(); } log("sendCbObservation with wakelock " + wl.isHeld() + " and settings " + settingsHandler); sender.setSettings(settingsHandler, locationManager, lastMessenger, fromUser); sender.execute(observation.getObservationAsParams()); return true; } catch (Exception e) { return false; } } /** * Send a new account to the server * * @param account * @return */ public boolean sendCbAccount(CbAccount account) { try { CbDataSender sender = new CbDataSender(getApplicationContext()); sender.setSettings(settingsHandler, locationManager, null, true); sender.execute(account.getAccountAsParams()); fromUser = false; return true; } catch (Exception e) { return false; } } /** * Send the current condition to the server * * @param observation * @return */ public boolean sendCbCurrentCondition(CbCurrentCondition condition) { log("sending cbcurrent condition"); try { CbDataSender sender = new CbDataSender(getApplicationContext()); fromUser = true; sender.setSettings(settingsHandler, locationManager, lastMessenger, fromUser); sender.execute(condition.getCurrentConditionAsParams()); fromUser = false; return true; } catch (Exception e) { return false; } } /** * Start the periodic data collection. */ public void startSubmit() { log("CbService: Starting to auto-collect and submit data."); fromUser = false; if (!alarm.isRepeating()) { settingsHandler = settingsHandler.getSettings(); log("cbservice alarm not repeating, starting alarm at " + settingsHandler.getDataCollectionFrequency()); alarm.setAlarm(getApplicationContext(), settingsHandler.getDataCollectionFrequency()); } else { log("cbservice startsubmit, alarm is already repeating. restarting at " + settingsHandler.getDataCollectionFrequency()); alarm.restartAlarm(getApplicationContext(), settingsHandler.getDataCollectionFrequency()); } } @Override public void onDestroy() { log("cbservice on destroy"); stopAutoSubmit(); unregisterReceiver(receiver); super.onDestroy(); } @Override public void onCreate() { setUpFiles(); log("cb on create"); settingsHandler = new CbSettingsHandler(getApplicationContext()); settingsHandler.getSettings(); db = new CbDb(getApplicationContext()); fromUser = false; prepForRegistration(); super.onCreate(); } /** * SDK registration */ private void prepForRegistration() { IntentFilter filter = new IntentFilter(); filter.addAction(CbService.ACTION_REGISTER); registerReceiver(receiver, filter); } /** * Check charge state for preferences. * */ public boolean isCharging() { // Check battery and charging status IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); Intent batteryStatus = getApplicationContext().registerReceiver(null, ifilter); // Are we charging / charged? int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1); boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL; return isCharging; } /** * Each app registers with the SDK. Send the package name * to */ private void sendRegistrationInfo() { log("SDKTESTS: sending registration info"); Intent intent = new Intent(ACTION_REGISTER); intent.putExtra("packagename", getApplicationContext().getPackageName()); intent.putExtra("time", System.currentTimeMillis()); sendBroadcast(intent); } private final BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(ACTION_REGISTER)) { String registeredName = intent.getStringExtra("packagename"); Long registeredTime = intent.getLongExtra("time", 0); log("SDKTESTS: registering " + registeredName + " registered at " + registeredTime); // addRegistration db.open(); db.addRegistration(registeredName, registeredTime); // check status if(db.isPrimaryApp()) { log("SDKTESTS: " + getApplicationContext().getPackageName() + " is primary"); } else { log("SDKTESTS: " + getApplicationContext().getPackageName() + " is not primary"); } db.close(); } } }; /** * Start running background data collection methods. * */ @Override public int onStartCommand(Intent intent, int flags, int startId) { log("cbservice onstartcommand"); checkBarometer(); // wakelock management if(wl!=null) { log("cbservice wakelock not null:"); if(wl.isHeld()) { log("cbservice existing wakelock; releasing"); wl.release(); } else { log("cbservice wakelock not null but no existing lock"); } } PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP , "CbService"); // PARTIAL_WAKE_LOCK wl.acquire(1000); log("cbservice acquiring wakelock " + wl.isHeld()); dataCollector = new CbDataCollector(); try { if (intent != null) { if (intent.getAction() != null) { if (intent.getAction().equals(ACTION_SEND_MEASUREMENT)) { // send just a single measurement fromUser = false; log("sending single observation, request from intent"); sendSingleObs(); return START_NOT_STICKY; } } else if (intent.getBooleanExtra("alarm", false)) { // This runs when the service is started from the alarm. // Submit a data point log("cbservice alarm firing, sending data"); settingsHandler = new CbSettingsHandler(getApplicationContext()); settingsHandler = settingsHandler.getSettings(); removeOldSDKApps(); sendRegistrationInfo(); if(settingsHandler.isSharingData()) { //dataCollector.startCollectingData(); startWithIntent(intent, true); } else { log("cbservice not sharing data"); } LocationStopper stop = new LocationStopper(); mHandler.postDelayed(stop, 1000 * 3); return START_NOT_STICKY; } else { // Check the database log("starting service with db"); startWithDatabase(); return START_NOT_STICKY; } } } catch (Exception e) { log("cbservice onstartcommand exception " + e.getMessage()); } super.onStartCommand(intent, flags, startId); return START_NOT_STICKY; } public void removeAllUninstalledApps() { db.open(); db.close(); } private void removeOldSDKApps() { db.open(); db.removeOldSDKApps(1); db.close(); } /** * Convert time ago text to ms. TODO: not this. values in xml. * * @param timeAgo * @return */ public static long stringTimeToLongHack(String timeAgo) { if (timeAgo.equals("1 minute")) { return 1000 * 60; } else if (timeAgo.equals("5 minutes")) { return 1000 * 60 * 5; } else if (timeAgo.equals("10 minutes")) { return 1000 * 60 * 10; } else if (timeAgo.equals("30 minutes")) { return 1000 * 60 * 30; } else if (timeAgo.equals("1 hour")) { return 1000 * 60 * 60; } else if (timeAgo.equals("3 hours")) { return 1000 * 60 * 60 * 3; } else if(timeAgo.equals("6 hours")) { return 1000 * 60 * 60 * 6; } else if(timeAgo.equals("12 hours")) { return 1000 * 60 * 60 * 12; } return 1000 * 60 * 10; } public void loadSetttingsFromPreferences() { log("cbservice loading settings from prefs"); settingsHandler = new CbSettingsHandler(getApplicationContext()); settingsHandler.setServerURL(serverURL); settingsHandler.setAppID(getApplication().getPackageName()); SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(this); String preferenceCollectionFrequency = sharedPreferences.getString( "autofrequency", "10 minutes"); boolean preferenceShareData = sharedPreferences.getBoolean( "autoupdate", true); String preferenceShareLevel = sharedPreferences.getString( "sharing_preference", "Us, Researchers and Forecasters"); boolean preferenceSendNotifications = sharedPreferences.getBoolean( "send_notifications", false); settingsHandler .setDataCollectionFrequency(stringTimeToLongHack(preferenceCollectionFrequency)); settingsHandler.setSendNotifications(preferenceSendNotifications); boolean useGPS = sharedPreferences.getBoolean("use_gps", true); boolean onlyWhenCharging = sharedPreferences.getBoolean( "only_when_charging", false); settingsHandler.setUseGPS(useGPS); settingsHandler.setOnlyWhenCharging(onlyWhenCharging); settingsHandler.setSharingData(preferenceShareData); settingsHandler.setShareLevel(preferenceShareLevel); // Seems like new settings. Try adding to the db. settingsHandler.saveSettings(); } public void startWithIntent(Intent intent, boolean fromAlarm) { try { if (!fromAlarm) { // We arrived here from the user (i.e., not the alarm) // start/(update?) the alarm startSubmit(); } else { // alarm. Go! ReadingSender reading = new ReadingSender(); mHandler.post(reading); } } catch (Exception e) { for (StackTraceElement ste : e.getStackTrace()) { log(ste.getMethodName() + ste.getLineNumber()); } } } public void startWithDatabase() { try { db.open(); // Check the database for Settings initialization settingsHandler = new CbSettingsHandler(getApplicationContext()); Cursor allSettings = db.fetchSettingByApp(getPackageName()); log("cb intent null; checking db, size " + allSettings.getCount()); if (allSettings.moveToFirst()) { settingsHandler.setAppID(allSettings.getString(1)); settingsHandler.setDataCollectionFrequency(allSettings .getLong(2)); settingsHandler.setServerURL(serverURL); int sendNotifications = allSettings.getInt(4); int useGPS = allSettings.getInt(5); int onlyWhenCharging = allSettings.getInt(6); int sharingData = allSettings.getInt(7); settingsHandler.setShareLevel(allSettings.getString(9)); boolean boolCharging = (onlyWhenCharging > 0); boolean boolGPS = (useGPS > 0); boolean boolSendNotifications = (sendNotifications > 0); boolean boolSharingData = (sharingData > 0); log("only when charging processed " + boolCharging + " gps " + boolGPS); settingsHandler.setSendNotifications(boolSendNotifications); settingsHandler.setOnlyWhenCharging(boolCharging); settingsHandler.setUseGPS(boolGPS); settingsHandler.setSharingData(boolSharingData); settingsHandler.saveSettings(); } log("cbservice startwithdb, " + settingsHandler); ReadingSender reading = new ReadingSender(); mHandler.post(reading); startSubmit(); db.close(); } catch (Exception e) { for (StackTraceElement ste : e.getStackTrace()) { log(ste.getMethodName() + ste.getLineNumber()); } } } /** * Handler of incoming messages from clients. */ class IncomingHandler extends Handler { @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_STOP: log("message. bound service says stop"); try { alarm.cancelAlarm(getApplicationContext()); } catch(Exception e) { } break; case MSG_GET_BEST_LOCATION: log("cbservice message. bound service requesting location"); if (locationManager != null) { Location best = locationManager.getCurrentBestLocation(); try { log("service sending best location"); msg.replyTo.send(Message.obtain(null, MSG_BEST_LOCATION, best)); } catch (RemoteException re) { re.printStackTrace(); } } else { log("error: location null, not returning"); } break; case MSG_GET_BEST_PRESSURE: log("message. bound service requesting pressure. not responding"); break; case MSG_START_AUTOSUBMIT: // log("start autosubmit"); // startWithDatabase(); break; case MSG_STOP_AUTOSUBMIT: log("cbservice stop autosubmit"); stopAutoSubmit(); break; case MSG_GET_SETTINGS: log("get settings"); if(settingsHandler != null) { settingsHandler.getSettings(); } else { settingsHandler = new CbSettingsHandler(getApplicationContext()); settingsHandler.getSettings(); } try { msg.replyTo.send(Message.obtain(null, MSG_SETTINGS, settingsHandler)); } catch (RemoteException re) { re.printStackTrace(); } break; case MSG_START_STREAM: int sensorToStream = msg.arg1; startSensorStream(sensorToStream, msg.replyTo); break; case MSG_STOP_STREAM: int sensorToStop = msg.arg1; stopSensorStream(sensorToStop); break; case MSG_SET_SETTINGS: settingsHandler = (CbSettingsHandler) msg.obj; log("cbservice set settings " + settingsHandler); settingsHandler.saveSettings(); startSubmit(); break; case MSG_GET_LOCAL_RECENTS: log("get local recents"); recentMsg = msg; CbApiCall apiCall = (CbApiCall) msg.obj; if (apiCall == null) { // log("apicall null, bailing"); break; } // run API call db.open(); Cursor cursor = db.runLocalAPICall(apiCall.getMinLat(), apiCall.getMaxLat(), apiCall.getMinLon(), apiCall.getMaxLon(), apiCall.getStartTime(), apiCall.getEndTime(), 2000); ArrayList<CbObservation> results = new ArrayList<CbObservation>(); while (cursor.moveToNext()) { // TODO: This is duplicated in CbDataCollector. Fix that CbObservation obs = new CbObservation(); Location location = new Location("network"); location.setLatitude(cursor.getDouble(1)); location.setLongitude(cursor.getDouble(2)); location.setAltitude(cursor.getDouble(3)); location.setAccuracy(cursor.getInt(4)); location.setProvider(cursor.getString(5)); obs.setLocation(location); obs.setObservationType(cursor.getString(6)); obs.setObservationUnit(cursor.getString(7)); obs.setObservationValue(cursor.getDouble(8)); obs.setSharing(cursor.getString(9)); obs.setTime(cursor.getLong(10)); obs.setTimeZoneOffset(cursor.getInt(11)); obs.setUser_id(cursor.getString(12)); results.add(obs); } db.close(); log("cbservice: " + results.size() + " local api results"); try { msg.replyTo.send(Message.obtain(null, MSG_LOCAL_RECENTS, results)); } catch (RemoteException re) { re.printStackTrace(); } break; case MSG_GET_API_RECENTS: CbApiCall apiCacheCall = (CbApiCall) msg.obj; log("get api recents " + apiCacheCall.toString()); // run API call try { db.open(); Cursor cacheCursor = db.runAPICacheCall( apiCacheCall.getMinLat(), apiCacheCall.getMaxLat(), apiCacheCall.getMinLon(), apiCacheCall.getMaxLon(), apiCacheCall.getStartTime(), apiCacheCall.getEndTime(), apiCacheCall.getLimit()); ArrayList<CbObservation> cacheResults = new ArrayList<CbObservation>(); while (cacheCursor.moveToNext()) { CbObservation obs = new CbObservation(); Location location = new Location("network"); location.setLatitude(cacheCursor.getDouble(1)); location.setLongitude(cacheCursor.getDouble(2)); location.setAltitude(cacheCursor.getDouble(3)); obs.setLocation(location); obs.setObservationValue(cacheCursor.getDouble(4)); obs.setTime(cacheCursor.getLong(5)); cacheResults.add(obs); } // and get a few recent local results Cursor localCursor = db.runLocalAPICall( apiCacheCall.getMinLat(), apiCacheCall.getMaxLat(), apiCacheCall.getMinLon(), apiCacheCall.getMaxLon(), apiCacheCall.getStartTime(), apiCacheCall.getEndTime(), 5); ArrayList<CbObservation> localResults = new ArrayList<CbObservation>(); while (localCursor.moveToNext()) { CbObservation obs = new CbObservation(); Location location = new Location("network"); location.setLatitude(localCursor.getDouble(1)); location.setLongitude(localCursor.getDouble(2)); obs.setLocation(location); obs.setObservationValue(localCursor.getDouble(8)); obs.setTime(localCursor.getLong(10)); localResults.add(obs); } db.close(); cacheResults.addAll(localResults); try { msg.replyTo.send(Message.obtain(null, MSG_API_RECENTS, cacheResults)); } catch (RemoteException re) { // re.printStackTrace(); } } catch (Exception e) { } break; case MSG_GET_API_RECENTS_FOR_GRAPH: // TODO: Put this in a method. It's a copy+paste from // GET_API_RECENTS CbApiCall apiCacheCallGraph = (CbApiCall) msg.obj; log("get api recents " + apiCacheCallGraph.toString()); // run API call db.open(); Cursor cacheCursorGraph = db.runAPICacheCall( apiCacheCallGraph.getMinLat(), apiCacheCallGraph.getMaxLat(), apiCacheCallGraph.getMinLon(), apiCacheCallGraph.getMaxLon(), apiCacheCallGraph.getStartTime(), apiCacheCallGraph.getEndTime(), apiCacheCallGraph.getLimit()); ArrayList<CbObservation> cacheResultsGraph = new ArrayList<CbObservation>(); while (cacheCursorGraph.moveToNext()) { CbObservation obs = new CbObservation(); Location location = new Location("network"); location.setLatitude(cacheCursorGraph.getDouble(1)); location.setLongitude(cacheCursorGraph.getDouble(2)); obs.setLocation(location); obs.setObservationValue(cacheCursorGraph.getDouble(3)); obs.setTime(cacheCursorGraph.getLong(4)); cacheResultsGraph.add(obs); } db.close(); try { msg.replyTo.send(Message.obtain(null, MSG_API_RECENTS_FOR_GRAPH, cacheResultsGraph)); } catch (RemoteException re) { re.printStackTrace(); } break; case MSG_MAKE_API_CALL: CbApi api = new CbApi(getApplicationContext()); CbApiCall liveApiCall = (CbApiCall) msg.obj; liveApiCall.setCallType("Readings"); long timeDiff = System.currentTimeMillis() - lastAPICall; deleteOldData(); lastAPICall = api.makeAPICall(liveApiCall, service, msg.replyTo, "Readings"); break; case MSG_MAKE_CURRENT_CONDITIONS_API_CALL: CbApi conditionApi = new CbApi(getApplicationContext()); CbApiCall conditionApiCall = (CbApiCall) msg.obj; conditionApiCall.setCallType("Conditions"); conditionApi.makeAPICall(conditionApiCall, service, msg.replyTo, "Conditions"); break; case MSG_CLEAR_LOCAL_CACHE: db.open(); db.clearLocalCache(); long count = db.getUserDataCount(); db.close(); try { msg.replyTo.send(Message.obtain(null, MSG_COUNT_LOCAL_OBS_TOTALS, (int) count, 0)); } catch (RemoteException re) { re.printStackTrace(); } break; case MSG_REMOVE_FROM_PRESSURENET: // TODO: Implement a secure system to remove user data break; case MSG_CLEAR_API_CACHE: db.open(); db.clearAPICache(); long countCache = db.getDataCacheCount(); db.close(); try { msg.replyTo.send(Message.obtain(null, MSG_COUNT_API_CACHE_TOTALS, (int) countCache, 0)); } catch (RemoteException re) { //re.printStackTrace(); } break; case MSG_ADD_CURRENT_CONDITION: CbCurrentCondition cc = (CbCurrentCondition) msg.obj; try { db.open(); db.addCondition(cc); db.close(); } catch(SQLiteDatabaseLockedException dble) { } break; case MSG_GET_CURRENT_CONDITIONS: recentMsg = msg; CbApiCall currentConditionAPI = (CbApiCall) msg.obj; ArrayList<CbCurrentCondition> conditions = getCurrentConditionsFromLocalAPI(currentConditionAPI); try { msg.replyTo.send(Message.obtain(null, MSG_CURRENT_CONDITIONS, conditions)); } catch (RemoteException re) { re.printStackTrace(); } break; case MSG_SEND_CURRENT_CONDITION: CbCurrentCondition condition = (CbCurrentCondition) msg.obj; if (settingsHandler == null) { settingsHandler = new CbSettingsHandler( getApplicationContext()); settingsHandler.setServerURL(serverURL); settingsHandler .setAppID(getApplication().getPackageName()); } try { condition .setSharing_policy(settingsHandler.getShareLevel()); sendCbCurrentCondition(condition); } catch (Exception e) { //e.printStackTrace(); } break; case MSG_SEND_OBSERVATION: log("sending single observation, request from app"); sendSingleObs(); break; case MSG_COUNT_LOCAL_OBS: db.open(); long countLocalObsOnly = db.getUserDataCount(); db.close(); try { msg.replyTo.send(Message.obtain(null, MSG_COUNT_LOCAL_OBS_TOTALS, (int) countLocalObsOnly, 0)); } catch (RemoteException re) { re.printStackTrace(); } break; case MSG_COUNT_API_CACHE: db.open(); long countCacheOnly = db.getDataCacheCount(); db.close(); try { msg.replyTo.send(Message .obtain(null, MSG_COUNT_API_CACHE_TOTALS, (int) countCacheOnly, 0)); } catch (RemoteException re) { re.printStackTrace(); } break; case MSG_CHANGE_NOTIFICATION: log("cbservice dead code, change notification"); break; case MSG_API_RESULT_COUNT: log("cbservice msg_api_result_count"); // Current conditions API call for (made for local conditions alerts) // returns here. // potentially notify about nearby conditions CbApiCall localConditions = buildLocalCurrentConditionsCall(1); ArrayList<CbCurrentCondition> localRecentConditions = getCurrentConditionsFromLocalAPI(localConditions); Intent intent = new Intent(); intent.setAction(CbService.LOCAL_CONDITIONS_ALERT); if(localRecentConditions!=null) { if(localRecentConditions.size()> 0) { intent.putExtra("ca.cumulonimbus.pressurenetsdk.conditionNotification", localRecentConditions.get(0)); sendBroadcast(intent); } } break; case MSG_MAKE_STATS_CALL: log("CbService received message to make stats API call"); CbStatsAPICall statsCall = (CbStatsAPICall) msg.obj; CbApi statsApi = new CbApi(getApplicationContext()); statsApi.makeStatsAPICall(statsCall, service, msg.replyTo); break; case MSG_GET_CONTRIBUTIONS: CbContributions contrib = new CbContributions(); db.open(); contrib.setPressureAllTime(db.getAllTimePressureCount()); contrib.setPressureLast24h(db.getLast24hPressureCount()); contrib.setPressureLast7d(db.getLast7dPressureCount()); contrib.setConditionsAllTime(db.getAllTimeConditionCount(getID())); contrib.setConditionsLastWeek(db.getLast7dConditionCount(getID())); contrib.setConditionsLastDay(db.getLastDayConditionCount(getID())); db.close(); try { msg.replyTo.send(Message .obtain(null, MSG_CONTRIBUTIONS, contrib)); } catch (RemoteException re) { // re.printStackTrace(); } break; case MSG_GET_DATABASE_INFO: db.open(); long localObsCount = db.getUserDataCount(); db.close(); log("SDKTESTS: CbService says localObsCount is " + localObsCount); /* try { msg.replyTo.send(Message.obtain(null, MSG_COUNT_LOCAL_OBS_TOTALS, (int) countLocalObsOnly2, 0)); } catch (RemoteException re) { re.printStackTrace(); } */ break; case MSG_GET_PRIMARY_APP: db.open(); boolean primary = db.isPrimaryApp(); int p = (primary==true) ? 1 : 0; db.close(); try { msg.replyTo.send(Message.obtain(null, MSG_IS_PRIMARY, p, 0)); } catch (RemoteException re) { re.printStackTrace(); } break; case MSG_GET_LOCAL_CONDITIONS: recentMsg = msg; CbApiCall localConditionsAPI = buildLocalCurrentConditionsCall(2); ArrayList<CbCurrentCondition> localCurrentConditions = getCurrentConditionsFromLocalAPI(localConditionsAPI); try { msg.replyTo.send(Message.obtain(null, MSG_LOCAL_CONDITIONS, localCurrentConditions)); } catch (RemoteException re) { re.printStackTrace(); } break; default: super.handleMessage(msg); } } } private ArrayList<CbCurrentCondition> getCurrentConditionsFromLocalAPI(CbApiCall currentConditionAPI) { ArrayList<CbCurrentCondition> conditions = new ArrayList<CbCurrentCondition>(); try { db.open(); Cursor ccCursor = db.getCurrentConditions( currentConditionAPI.getMinLat(), currentConditionAPI.getMaxLat(), currentConditionAPI.getMinLon(), currentConditionAPI.getMaxLon(), currentConditionAPI.getStartTime(), currentConditionAPI.getEndTime(), 1000); while (ccCursor.moveToNext()) { CbCurrentCondition cur = new CbCurrentCondition(); Location location = new Location("network"); double latitude = ccCursor.getDouble(1); double longitude = ccCursor.getDouble(2); location.setLatitude(latitude); location.setLongitude(longitude); cur.setLat(latitude); cur.setLon(longitude); location.setAltitude(ccCursor.getDouble(3)); location.setAccuracy(ccCursor.getInt(4)); location.setProvider(ccCursor.getString(5)); cur.setLocation(location); cur.setSharing_policy(ccCursor.getString(6)); cur.setTime(ccCursor.getLong(7)); cur.setTzoffset(ccCursor.getInt(8)); cur.setUser_id(ccCursor.getString(9)); cur.setGeneral_condition(ccCursor.getString(10)); cur.setWindy(ccCursor.getString(11)); cur.setFog_thickness(ccCursor.getString(12)); cur.setCloud_type(ccCursor.getString(13)); cur.setPrecipitation_type(ccCursor.getString(14)); cur.setPrecipitation_amount(ccCursor.getDouble(15)); cur.setPrecipitation_unit(ccCursor.getString(16)); cur.setThunderstorm_intensity(ccCursor.getString(17)); cur.setUser_comment(ccCursor.getString(18)); conditions.add(cur); } } catch (Exception e) { log("cbservice get_current_conditions failed " + e.getMessage()); } finally { db.close(); } return conditions; } private CbApiCall buildLocalCurrentConditionsCall(double hoursAgo) { log("building map conditions call for hours: " + hoursAgo); long startTime = System.currentTimeMillis() - (int) ((hoursAgo * 60 * 60 * 1000)); long endTime = System.currentTimeMillis(); CbApiCall api = new CbApiCall(); double minLat = 0; double maxLat = 0; double minLon = 0; double maxLon = 0; try { Location lastKnown = locationManager.getCurrentBestLocation(); if(lastKnown.getLatitude() != 0) { minLat = lastKnown.getLatitude() - .1; maxLat = lastKnown.getLatitude() + .1; minLon = lastKnown.getLongitude() - .1; maxLon = lastKnown.getLongitude() + .1; } else { log("no location, bailing on csll"); return null; } api.setMinLat(minLat); api.setMaxLat(maxLat); api.setMinLon(minLon); api.setMaxLon(maxLon); api.setStartTime(startTime); api.setEndTime(endTime); api.setLimit(500); api.setCallType("Conditions"); } catch(NullPointerException npe) { } return api; } public void sendSingleObs() { if (settingsHandler != null) { if (settingsHandler.getServerURL() == null) { settingsHandler.getSettings(); } } SingleReadingSender singleSender = new SingleReadingSender(); mHandler.post(singleSender); } /** * Remove older data from cache to keep the size reasonable * * @return */ public void deleteOldData() { log("deleting old data"); db.open(); db.deleteOldCacheData(); db.close(); } public boolean notifyAPIResult(Messenger reply, int count) { try { if (reply == null) { log("cannot notify, reply is null"); } else { reply.send(Message.obtain(null, MSG_API_RESULT_COUNT, count, 0)); } } catch (RemoteException re) { re.printStackTrace(); } catch (NullPointerException npe) { //npe.printStackTrace(); } return false; } public boolean notifyAPIStats(Messenger reply, ArrayList<CbStats> statsResult) { try { if (reply == null) { log("cannot notify, reply is null"); } else { log("cbservice notifying, " + statsResult.size()); reply.send(Message.obtain(null, MSG_STATS, statsResult)); } } catch (RemoteException re) { re.printStackTrace(); } catch (NullPointerException npe) { npe.printStackTrace(); } return false; } public CbObservation recentPressureFromDatabase() { CbObservation obs = new CbObservation(); double pressure = 0.0; try { long rowId = db.fetchObservationMaxID(); Cursor c = db.fetchObservation(rowId); while (c.moveToNext()) { pressure = c.getDouble(8); } log(pressure + " pressure from db"); if (pressure == 0.0) { log("returning null"); return null; } obs.setObservationValue(pressure); return obs; } catch (Exception e) { obs.setObservationValue(pressure); return obs; } } /** * Get a hash'd device ID * * @return */ public String getID() { try { MessageDigest md = MessageDigest.getInstance("MD5"); String actual_id = Secure.getString(getApplicationContext() .getContentResolver(), Secure.ANDROID_ID); byte[] bytes = actual_id.getBytes(); byte[] digest = md.digest(bytes); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < digest.length; i++) { hexString.append(Integer.toHexString(0xFF & digest[i])); } return hexString.toString(); } catch (Exception e) { return " } } // Used to write a log to SD card. Not used unless logging enabled. public void setUpFiles() { try { File homeDirectory = getExternalFilesDir(null); if (homeDirectory != null) { mAppDir = homeDirectory.getAbsolutePath(); } } catch (Exception e) { //e.printStackTrace(); } } // Log data to SD card for debug purposes. // To enable logging, ensure the Manifest allows writing to SD card. public void logToFile(String text) { try { OutputStream output = new FileOutputStream(mAppDir + "/log.txt", true); String logString = (new Date()).toString() + ": " + text + "\n"; output.write(logString.getBytes()); output.close(); } catch (FileNotFoundException e) { //e.printStackTrace(); } catch (IOException ioe) { //ioe.printStackTrace(); } } @Override public IBinder onBind(Intent intent) { log("on bind"); return mMessenger.getBinder(); } @Override public void onRebind(Intent intent) { log("on rebind"); super.onRebind(intent); } public void log(String message) { if(CbConfiguration.DEBUG_MODE) { logToFile(message); System.out.println(message); } } public CbDataCollector getDataCollector() { return dataCollector; } public void setDataCollector(CbDataCollector dataCollector) { this.dataCollector = dataCollector; } public CbLocationManager getLocationManager() { return locationManager; } public void setLocationManager(CbLocationManager locationManager) { this.locationManager = locationManager; } }
package folioxml.translation; import folioxml.core.InvalidMarkupException; import folioxml.css.CssClassCleaner; import folioxml.folio.FolioToken; import folioxml.slx.SlxToken; import java.net.MalformedURLException; import java.net.URL; import java.util.regex.Pattern; /** * Doesn't deal with Popup links (PW), although named popup links are handled. * @author nathanael * */ public class FolioLinkUtils{ //WW is a subset of PL, syntax the same. //<PL:Style,"url,file,exe"> //<WW:Style,"address"> //<QL:Style, query> //<JL:Jump,""> - added Jan 21,09. //<PX:Style,NamedPopupID> //<OL:Style,ObjectName,(opt)Class Name, Infobase Name, ZM (scale to fit) //<DL:Style,DataObjectName> //<ML:Style,"FolioMenuCommand"> //<UL:Style, user defined> //<EN:Style Name,"Query",Width,Height,"Title"> End note link //<link href="" infobase="" jumpdestination="" popupId="" program="" dataobject="" objectname="" scaleobject="" objectclass="" userdefined="" query="" recordsWithHits="" popupQuery="" public static boolean isOpeningLinkTag(FolioToken t){ return (!t.isClosing() && t.matches("^UL|QL|PL|OL|PX|WW|JL|EN|DL|ML$")); } public static boolean isClosingLinkTag(FolioToken t){ if (t.matches("EL")) return true; if (t.isClosing() && t.matches("^UL|QL|PL|OL|PX|WW|JL|EN|DL|ML$")) return true; return false; } public static SlxToken translate(FolioToken t) throws InvalidMarkupException{ if (t.matches("UL")) { System.out.println("User link (unsupported Folio token):"); System.out.println(t.text); return FolioSlxTranslator.tryCommentOut(t, "UL"); //We comment out user links - we have no way to map them. } if (isClosingLinkTag(t)) return new SlxToken("</link>"); else if (isOpeningLinkTag(t)){ if (t.count() < 2 && !t.matches("UL")) throw new InvalidMarkupException("All links (PL, WW, QL, JL, PX, OL, DL, ML) except User Link (UL) must provide at least 2 arguments.",t); SlxToken st = new SlxToken("<link>").set("class",t.get(0)); //Class is always first. if (t.matches("WW|PL")) { //Web and program links. Program links are a superset of web links. Use Href for web addresses, program for exe's and documents. String cmd =t.get(1); if (isUrl(cmd) || t.matches("WW")) st.set("href",cmd); //Href for these. PL may use a local path or .exe.... If it's a valid URL, use href. else st.set("program",cmd); //TODO: path variable expansion "%%" = path to infobase. "%?" = path to folio views. if (t.count() > 2) throw new InvalidMarkupException("WW, PL, and DL links can only have 2 arguments.",t); } else if (t.matches("QL")) { //Query link st.set("query", t.get(1)); int ix = 2; while(ix < t.count()){ String opt= t.get(ix); if (opt.equalsIgnoreCase("RH")) st.set("showOnlyHitRecords", "true"); else if (st.get("infobase") == null) st.set("infobase", opt); else throw new InvalidMarkupException("Unrecognized option " + opt,t); ix++; } }else if (t.matches("OL")){ //Object link st.set("objectName", t.get(1)); int ix = 2; //May20,2011 - BUG: if Class name is blank, the infobase name will be used instead. //Added logic to use as infobase name if it contains '.nfo'. while(ix < t.count()){ String opt= t.get(ix); if (opt.equalsIgnoreCase("ZM")) st.set("zoomFit", "true"); else{ if (st.get("infobase") == null && opt.toLowerCase().contains(".nfo")) st.set("infobase", opt); //If it has .nfo, the class name must have been omitted. else if (st.get("className") == null) st.set("className", opt); //Fill class name first else if (st.get("infobase") == null) st.set("infobase", opt); //Then infobase else throw new InvalidMarkupException("Unrecognized option " + opt,t); } ix++; } //Data link } else if (t.matches("DL")){ //Data link. References object definition. st.set("dataLink", t.get(1)); //Changed from objectName to dataLink Feb 2 , 2010. Conflicted with object links, and they don't have anything in common. if (t.count() > 2) throw new InvalidMarkupException("WW, PL, and DL links can only have 2 arguments.",t); //Menu link } else if (t.matches("ML")){ st.set("menu", t.get(1)); if (t.count() > 2) throw new InvalidMarkupException("ML (Menu links) can only have 2 arguments.",t); //Popup link } else if (t.matches("PX")){ st.set("popupTitle", t.get(1)); if (t.count() > 2) throw new InvalidMarkupException("PX (Named popup links) can only have 2 arguments.",t); //Jump link }else if (t.matches("JL")){ st.set("jumpDestination", "_" + t.get(1)); if (t.count() > 2) st.set("infobase", t.get(2)); if (t.count() > 3) throw new InvalidMarkupException("JL (Jump link) may only have 3 arguments." + t.text); //End note link (popup query link) }else if (t.matches("EN")){ st.set("query", t.get(1)); if (t.count() == 5){ st.set("popupWidth", t.get(2)); st.set("popupHeight", t.get(3)); st.set("title", t.get(4)); }else if (t.count() == 3){ st.set("title", t.get(2)); }else if (t.count() > 2){ throw new InvalidMarkupException("EN (End note link) may only have 2, 3, or 5 arguments" + t.text); } } else{ throw new InvalidMarkupException("Link not supported: " + t.text); } return st; } return null; } /** * HAAACK. Not tested, not verified, not thought through. * @param t * @param css * @return * @throws InvalidMarkupException */ public static String translateToFolio(SlxToken t, CssClassCleaner css) throws InvalidMarkupException{ assert(t.matches("a|link")); /* Incoming tokens will be 'resolved', merged with their definitions. * I think this means that type="link" and style="?????" */ /* <link> (ghost tag 2/2) <link href="" infobase="" jumpdestination="" popupTitle="" program="" dataobject="" objectname="" scaleobject="" objectclass="" userdefined="" query="" recordsWithHits="" popupQuery="" /> Links cannot overlap or nest inside other links. Link tags can be either opening or closing, but </EL> is often used to close all types if links instead of the starting tag. Program link <PL:Style,"url,file,exe"> <link class="style" program="url, file, or exe"> Web link <WW:Style,"address"> <link class="style" href="address"> WW is a subset of PL, syntax the same. Object link <OL:Style,ObjectName,(opt)Class Name, Infobase Name, ZM (scale to fit) Data link <DL:Style,DataObjectName> Named popup link <PX:Style,NamedPopupID> Menu link <ML:Style,"FolioMenuCommand"> User Link <UL:Style, user defined> Jump link <JL:Style,"jump destination"> <link class="style" jumpdestination="jump destination"> Query link <QL:Style, query> <link class="style" query="query"> End note link EN ?? End link EL </link> */ String style = css.findOriginalName(t); if (t.isClosing()) return "<EL>"; if (!t.isOpening()) return null; if (t.get("program") != null) return "<PL:\"" + style + "\",\"" + t.get("program") + "\">"; if (t.get("href") != null) return "<WW:\"" + style + "\",\"" + t.get("href") + "\">"; if (t.get("dataLink") != null) return "<DL:\"" + style + "\",\"" + t.get("dataLink") + "\">"; if (t.get("popupTitle") != null) return "<PX:\"" + style + "\",\"" + t.get("popupTitle") + "\">"; if (t.get("menu") != null) return "<ML:\"" + style + "\",\"" + t.get("menu") + "\">"; if (t.get("jumpDestination") != null) { if (t.get("infobase") != null)return "<JL:\"" + style + "\",\"" + t.get("jumpdestination") + "\",\"" + t.get("infobase") + "\">"; else return "<JL:\"" + style + "\",\"" + t.get("jumpdestination") + "\">"; } /* else if (t.matches("QL")) { //Query link st.set("query", t.get(1)); int ix = 2; while(ix < t.count()){ String opt= t.get(ix); if (opt.equalsIgnoreCase("RH")) st.set("showOnlyHitRecords", "true"); else if (st.get("infobase") == null) st.set("infobase", opt); else throw new InvalidMarkupException("Unrecognized option " + opt,t); ix++; } }else if (t.matches("OL")){ //Object link st.set("objectName", t.get(1)); int ix = 2; while(ix < t.count()){ String opt= t.get(ix); if (opt.equalsIgnoreCase("ZM")) st.set("zoomFit", "true"); else if (st.get("className") == null) st.set("className", opt); //Fill class name first else if (st.get("infobase") == null) st.set("infobase", opt); //Then infobase else throw new InvalidMarkupException("Unrecognized option " + opt,t); ix++; } */ if (t.get("query") != null) { String s ="<QL:\"" + style + "\",\"" + t.get("query"); if ("true".equalsIgnoreCase(t.get("showOnlyHitRecords"))) s += ",RH"; if (t.get("infobase") != null) s+= ",\"" + t.get("infobase") + "\""; return s + ">"; } if (t.get("objectName") != null) { String s ="<OL:\"" + style + "\",\"" + t.get("objectName"); if (t.get("className") != null) s+= ",\"" + t.get("className") + "\""; if (t.get("infobase") != null) s+= ",\"" + t.get("infobase") + "\""; if ("true".equalsIgnoreCase(t.get("zoomFit"))) s += ",ZM"; return s + ">"; } throw new InvalidMarkupException("Failed to translate link to folio: " + t.toTokenString()); } //SCHEME: ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) protected static Pattern scheme = Pattern.compile("^[a-zA-Z][A-Za-z0-9+.-]*:\\/\\/");//\\G\\s++(\\w[\\w-:]*+)(?:\\s*+=\\s*+\"([^\"]*+)\"|\\s*+=\\s*+'([^']*+)'|\\s*+=\\s*+([^\\s=/>]*+)|(\\s*?))"); protected static Pattern simpleDomain = Pattern.compile("^[a-zA-Z][A-Za-z0-9+.-]*:\\/\\/");//\\G\\s++(\\w[\\w-:]*+)(?:\\s*+=\\s*+\"([^\"]*+)\"|\\s*+=\\s*+'([^']*+)'|\\s*+=\\s*+([^\\s=/>]*+)|(\\s*?))"); private static boolean isUrl(String s){ s = s.trim();//Trim whitespace boolean missingScheme = false; if (!scheme.matcher(s).find()){ //No scheme specified. //if (s.indexOf('\\') > -1) return false; //It means we have a windows path. //missingScheme = true; return false; } try{ URL u = new URL(s); //if (missingScheme && !TokenUtils.fastMatches(regex, u.getHost())) return true; }catch(MalformedURLException e){ return false; } } }
package com.intellij.psi.impl.source.codeStyle.lineIndent; import com.intellij.formatting.FormattingMode; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.RangeMarker; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; import com.intellij.psi.codeStyle.CodeStyleManager; import com.intellij.psi.text.BlockSupport; import com.intellij.util.concurrency.AppExecutorUtil; import com.intellij.util.text.CharArrayUtil; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @ApiStatus.Internal public class FormatterBasedIndentAdjuster { private final static int MAX_SYNCHRONOUS_ADJUSTMENT_DOC_SIZE = 100000; private FormatterBasedIndentAdjuster() { } public static void scheduleIndentAdjustment(@NotNull Project project, @NotNull Document document, int offset) { PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(document); if (file != null) { IndentAdjusterRunnable fixer = new IndentAdjusterRunnable(project, document, file, offset); PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project); if (isSynchronousAdjustment(document, file)) { documentManager.commitDocument(document); } fixer.run(); } } private static boolean isSynchronousAdjustment(@NotNull Document document, @NotNull PsiFile file) { return ApplicationManager.getApplication().isUnitTestMode() || document.getTextLength() <= MAX_SYNCHRONOUS_ADJUSTMENT_DOC_SIZE && !BlockSupport.isTooDeep(file); } public static class IndentAdjusterRunnable implements Runnable { private final Project myProject; private final int myLine; private final Document myDocument; private final PsiFile myFile; public IndentAdjusterRunnable(@NotNull Project project, @NotNull Document document, @NotNull PsiFile file, int offset) { myProject = project; myDocument = document; myLine = myDocument.getLineNumber(offset); myFile = file; } @Override public void run() { int lineStart = myDocument.getLineStartOffset(myLine); int indentEnd = CharArrayUtil.shiftForward(myDocument.getCharsSequence(), lineStart, " \t"); RangeMarker indentMarker = myDocument.createRangeMarker(lineStart, indentEnd); CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(myProject); if (isSynchronousAdjustment(myDocument, myFile)) { updateIndent(indentMarker, codeStyleManager.getLineIndent(myFile, lineStart, FormattingMode.ADJUST_INDENT_ON_ENTER)); } else { ReadAction .nonBlocking(() -> codeStyleManager.getLineIndent(myFile, lineStart, FormattingMode.ADJUST_INDENT_ON_ENTER)) .withDocumentsCommitted(myProject) .finishOnUiThread(ModalityState.NON_MODAL, indentString -> updateIndent(indentMarker, indentString)) .submit(AppExecutorUtil.getAppExecutorService()); } } private void updateIndent(@NotNull RangeMarker indentMarker, @Nullable String newIndent) { if (newIndent != null) { CommandProcessor.getInstance().runUndoTransparentAction( () -> ApplicationManager.getApplication().runWriteAction(() -> { myDocument.replaceString(indentMarker.getStartOffset(), indentMarker.getEndOffset(), newIndent); indentMarker.dispose(); })); } } } }
package com.gdxjam.test.assets; import com.badlogic.ashley.core.PooledEngine; import com.badlogic.gdx.InputMultiplexer; import com.badlogic.gdx.input.GestureDetector; import com.badlogic.gdx.math.Vector2; import com.gdxjam.Assets; import com.gdxjam.GameManager; import com.gdxjam.input.DesktopGestureListener; import com.gdxjam.input.DesktopInputProcessor; import com.gdxjam.screens.AbstractScreen; import com.gdxjam.systems.InputSystem; import com.gdxjam.utils.Constants; import com.gdxjam.utils.EntityFactory; public class AssetPlaygroundScreen extends AbstractScreen { PooledEngine engine; InputMultiplexer input; @Override public void show() { super.show(); engine = GameManager.initEngine(); engine.getSystem(InputSystem.class).add( new DesktopInputProcessor(engine), new GestureDetector(new DesktopGestureListener(engine))); EntityFactory.createBackgroundArt(new Vector2( (Constants.WORLD_WIDTH_METERS / 2) - (Constants.WORLD_WIDTH_METERS / 2), (Constants.WORLD_HEIGHT_METERS / 2) - (Constants.WORLD_HEIGHT_METERS / 2)), Constants.WORLD_WIDTH_METERS, Constants.WORLD_HEIGHT_METERS, Assets.space.space); EntityFactory.createBackgroundArt(new Vector2(10, 10), 10, 10, Assets.space.largePlanetGreen); EntityFactory.createBackgroundArt(new Vector2(20, 20), 10, 10, Assets.space.largePlanetRed); } @Override public void render(float delta) { super.render(delta); engine.update(delta); } }
package lucee.commons.date; import java.util.Calendar; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.TimeZone; import lucee.runtime.engine.ThreadLocalPageContext; import lucee.runtime.op.Caster; import lucee.runtime.type.dt.DateTime; public class JREDateTimeUtil extends DateTimeUtil { private static CalendarThreadLocal _calendar=new CalendarThreadLocal(); private static CalendarThreadLocal calendar=new CalendarThreadLocal(); private static LocaleCalendarThreadLocal _localeCalendar=new LocaleCalendarThreadLocal(); private static LocaleCalendarThreadLocal localeCalendar=new LocaleCalendarThreadLocal(); //Calendar string; JREDateTimeUtil() { } @Override long _toTime(TimeZone tz, int year, int month, int day, int hour,int minute, int second, int milliSecond) { if(tz==null)tz=ThreadLocalPageContext.getTimeZone(tz); Calendar time = _getThreadCalendar(tz); time.set(year,month-1,day,hour,minute,second); time.set(Calendar.MILLISECOND,milliSecond); return time.getTimeInMillis(); } private static int _get(TimeZone tz, DateTime dt, int field) { Calendar c = _getThreadCalendar(tz); c.setTimeInMillis(dt.getTime()); return c.get(field); } private static int _get(Locale l,TimeZone tz, DateTime dt, int field) { Calendar c = _getThreadCalendar(l,tz); c.setTimeInMillis(dt.getTime()); return c.get(field); } @Override public int getYear(TimeZone tz, DateTime dt) { return _get(tz,dt,Calendar.YEAR); } @Override public int getMonth(TimeZone tz, DateTime dt) { return _get(tz,dt,Calendar.MONTH)+1; } @Override public int getDay(TimeZone tz, DateTime dt) { return _get(tz,dt,Calendar.DAY_OF_MONTH); } @Override public int getHour(TimeZone tz, DateTime dt) { return _get(tz,dt,Calendar.HOUR_OF_DAY); } @Override public int getMinute(TimeZone tz, DateTime dt) { return _get(tz,dt,Calendar.MINUTE); } @Override public int getSecond(TimeZone tz, DateTime dt) { return _get(tz,dt,Calendar.SECOND); } @Override public int getMilliSecond(TimeZone tz, DateTime dt) { return _get(tz,dt,Calendar.MILLISECOND); } @Override public synchronized int getDayOfYear(Locale locale,TimeZone tz, DateTime dt) { return _get(locale,tz,dt,Calendar.DAY_OF_YEAR); } @Override public synchronized int getDayOfWeek(Locale locale,TimeZone tz, DateTime dt) { return _get(locale,tz,dt,Calendar.DAY_OF_WEEK); } @Override public synchronized int getFirstDayOfMonth(TimeZone tz, DateTime dt) { Calendar c = _getThreadCalendar(tz); c.setTimeInMillis(dt.getTime()); c.set(Calendar.DATE,1); return c.get(Calendar.DAY_OF_YEAR); } @Override public synchronized int getWeekOfYear(Locale locale,TimeZone tz, DateTime dt) { Calendar c=_getThreadCalendar(locale,tz); c.setTimeInMillis(dt.getTime()); int week=c.get(Calendar.WEEK_OF_YEAR); if(week==1 && c.get(Calendar.MONTH)==Calendar.DECEMBER) { if(isLeapYear(c.get(Calendar.YEAR)) && c.get(Calendar.DAY_OF_WEEK)==1){ return 54; } return 53; } return week; } @Override public synchronized long getMilliSecondsInDay(TimeZone tz,long time) { Calendar c = _getThreadCalendar(tz); c.setTimeInMillis(time); return (c.get(Calendar.HOUR_OF_DAY)*3600000)+ (c.get(Calendar.MINUTE)*60000)+ (c.get(Calendar.SECOND)*1000)+ (c.get(Calendar.MILLISECOND)); } @Override public synchronized int getDaysInMonth(TimeZone tz, DateTime dt) { Calendar c = _getThreadCalendar(tz); c.setTimeInMillis(dt.getTime()); return daysInMonth(c.get(Calendar.YEAR), c.get(Calendar.MONTH)+1); } @Override public String toString(DateTime dt, TimeZone tz) { Calendar c = _getThreadCalendar(tz); c.setTimeInMillis(dt.getTime()); //"HH:mm:ss" StringBuilder sb=new StringBuilder(); sb.append("{ts '"); toString(sb,c.get(Calendar.YEAR),4); sb.append("-"); toString(sb,c.get(Calendar.MONTH)+1,2); sb.append("-"); toString(sb,c.get(Calendar.DATE),2); sb.append(" "); toString(sb,c.get(Calendar.HOUR_OF_DAY),2); sb.append(":"); toString(sb,c.get(Calendar.MINUTE),2); sb.append(":"); toString(sb,c.get(Calendar.SECOND),2); sb.append("'}"); return sb.toString(); } public static Calendar newInstance(TimeZone tz,Locale l) { if(tz==null)tz=ThreadLocalPageContext.getTimeZone(); return Calendar.getInstance(tz,l); } /** * important:this function returns always the same instance for a specific thread, * so make sure only use one thread calendar instance at time. * @return calendar instance */ public static Calendar getThreadCalendar(){ Calendar c = calendar.get(); c.clear(); return c; } /** * important:this function returns always the same instance for a specific thread, * so make sure only use one thread calendar instance at time. * @return calendar instance */ public static Calendar getThreadCalendar(TimeZone tz){ Calendar c = calendar.get(); c.clear(); if(tz==null)tz=ThreadLocalPageContext.getTimeZone(); c.setTimeZone(tz); return c; } /** * important:this function returns always the same instance for a specific thread, * so make sure only use one thread calendar instance at time. * @return calendar instance */ public static Calendar getThreadCalendar(Locale l,TimeZone tz){ if(tz==null)tz=ThreadLocalPageContext.getTimeZone(); Calendar c = localeCalendar.get(tz,l); c.setTimeZone(tz); return c; } /* * internally we use a other instance to avoid conflicts */ private static Calendar _getThreadCalendar(TimeZone tz){ Calendar c = _calendar.get(); c.clear(); if(tz==null)tz=ThreadLocalPageContext.getTimeZone(); c.setTimeZone(tz); return c; } /* * internally we use a other instance to avoid conflicts */ private static Calendar _getThreadCalendar(Locale l,TimeZone tz){ Calendar c = _localeCalendar.get(tz,l); if(tz==null)tz=ThreadLocalPageContext.getTimeZone(); c.setTimeZone(tz); return c; } static void toString(StringBuilder sb,int i, int amount) { String str = Caster.toString(i); amount = amount - str.length(); while( amount sb.append( '0'); } sb.append(str); } } class CalendarThreadLocal extends ThreadLocal<Calendar> { @Override protected synchronized Calendar initialValue() { return Calendar.getInstance(); } } class LocaleCalendarThreadLocal extends ThreadLocal<Map<String,Calendar>> { @Override protected synchronized Map<String,Calendar> initialValue() { return new HashMap<String, Calendar>(); } public Calendar get(TimeZone tz,Locale l) { Map<String, Calendar> map = get(); Calendar c = map.get(l+":"+tz); if(c==null) { c=JREDateTimeUtil.newInstance(tz,l); map.put(l+":"+tz, c); } else c.clear(); return c; } }
package org.bouncycastle.math.ec; import org.bouncycastle.util.Arrays; import java.math.BigInteger; class LongArray { // private static long DEINTERLEAVE_MASK = 0x5555555555555555L; /* * This expands 8 bit indices into 16 bit contents (high bit 14), by inserting 0s between bits. * In a binary field, this operation is the same as squaring an 8 bit number. */ private static final int[] INTERLEAVE2_TABLE = new int[] { 0x0000, 0x0001, 0x0004, 0x0005, 0x0010, 0x0011, 0x0014, 0x0015, 0x0040, 0x0041, 0x0044, 0x0045, 0x0050, 0x0051, 0x0054, 0x0055, 0x0100, 0x0101, 0x0104, 0x0105, 0x0110, 0x0111, 0x0114, 0x0115, 0x0140, 0x0141, 0x0144, 0x0145, 0x0150, 0x0151, 0x0154, 0x0155, 0x0400, 0x0401, 0x0404, 0x0405, 0x0410, 0x0411, 0x0414, 0x0415, 0x0440, 0x0441, 0x0444, 0x0445, 0x0450, 0x0451, 0x0454, 0x0455, 0x0500, 0x0501, 0x0504, 0x0505, 0x0510, 0x0511, 0x0514, 0x0515, 0x0540, 0x0541, 0x0544, 0x0545, 0x0550, 0x0551, 0x0554, 0x0555, 0x1000, 0x1001, 0x1004, 0x1005, 0x1010, 0x1011, 0x1014, 0x1015, 0x1040, 0x1041, 0x1044, 0x1045, 0x1050, 0x1051, 0x1054, 0x1055, 0x1100, 0x1101, 0x1104, 0x1105, 0x1110, 0x1111, 0x1114, 0x1115, 0x1140, 0x1141, 0x1144, 0x1145, 0x1150, 0x1151, 0x1154, 0x1155, 0x1400, 0x1401, 0x1404, 0x1405, 0x1410, 0x1411, 0x1414, 0x1415, 0x1440, 0x1441, 0x1444, 0x1445, 0x1450, 0x1451, 0x1454, 0x1455, 0x1500, 0x1501, 0x1504, 0x1505, 0x1510, 0x1511, 0x1514, 0x1515, 0x1540, 0x1541, 0x1544, 0x1545, 0x1550, 0x1551, 0x1554, 0x1555, 0x4000, 0x4001, 0x4004, 0x4005, 0x4010, 0x4011, 0x4014, 0x4015, 0x4040, 0x4041, 0x4044, 0x4045, 0x4050, 0x4051, 0x4054, 0x4055, 0x4100, 0x4101, 0x4104, 0x4105, 0x4110, 0x4111, 0x4114, 0x4115, 0x4140, 0x4141, 0x4144, 0x4145, 0x4150, 0x4151, 0x4154, 0x4155, 0x4400, 0x4401, 0x4404, 0x4405, 0x4410, 0x4411, 0x4414, 0x4415, 0x4440, 0x4441, 0x4444, 0x4445, 0x4450, 0x4451, 0x4454, 0x4455, 0x4500, 0x4501, 0x4504, 0x4505, 0x4510, 0x4511, 0x4514, 0x4515, 0x4540, 0x4541, 0x4544, 0x4545, 0x4550, 0x4551, 0x4554, 0x4555, 0x5000, 0x5001, 0x5004, 0x5005, 0x5010, 0x5011, 0x5014, 0x5015, 0x5040, 0x5041, 0x5044, 0x5045, 0x5050, 0x5051, 0x5054, 0x5055, 0x5100, 0x5101, 0x5104, 0x5105, 0x5110, 0x5111, 0x5114, 0x5115, 0x5140, 0x5141, 0x5144, 0x5145, 0x5150, 0x5151, 0x5154, 0x5155, 0x5400, 0x5401, 0x5404, 0x5405, 0x5410, 0x5411, 0x5414, 0x5415, 0x5440, 0x5441, 0x5444, 0x5445, 0x5450, 0x5451, 0x5454, 0x5455, 0x5500, 0x5501, 0x5504, 0x5505, 0x5510, 0x5511, 0x5514, 0x5515, 0x5540, 0x5541, 0x5544, 0x5545, 0x5550, 0x5551, 0x5554, 0x5555 }; /* * This expands 7 bit indices into 21 bit contents (high bit 18), by inserting 0s between bits. */ private static final int[] INTERLEAVE3_TABLE = new int[] { 0x00000, 0x00001, 0x00008, 0x00009, 0x00040, 0x00041, 0x00048, 0x00049, 0x00200, 0x00201, 0x00208, 0x00209, 0x00240, 0x00241, 0x00248, 0x00249, 0x01000, 0x01001, 0x01008, 0x01009, 0x01040, 0x01041, 0x01048, 0x01049, 0x01200, 0x01201, 0x01208, 0x01209, 0x01240, 0x01241, 0x01248, 0x01249, 0x08000, 0x08001, 0x08008, 0x08009, 0x08040, 0x08041, 0x08048, 0x08049, 0x08200, 0x08201, 0x08208, 0x08209, 0x08240, 0x08241, 0x08248, 0x08249, 0x09000, 0x09001, 0x09008, 0x09009, 0x09040, 0x09041, 0x09048, 0x09049, 0x09200, 0x09201, 0x09208, 0x09209, 0x09240, 0x09241, 0x09248, 0x09249, 0x40000, 0x40001, 0x40008, 0x40009, 0x40040, 0x40041, 0x40048, 0x40049, 0x40200, 0x40201, 0x40208, 0x40209, 0x40240, 0x40241, 0x40248, 0x40249, 0x41000, 0x41001, 0x41008, 0x41009, 0x41040, 0x41041, 0x41048, 0x41049, 0x41200, 0x41201, 0x41208, 0x41209, 0x41240, 0x41241, 0x41248, 0x41249, 0x48000, 0x48001, 0x48008, 0x48009, 0x48040, 0x48041, 0x48048, 0x48049, 0x48200, 0x48201, 0x48208, 0x48209, 0x48240, 0x48241, 0x48248, 0x48249, 0x49000, 0x49001, 0x49008, 0x49009, 0x49040, 0x49041, 0x49048, 0x49049, 0x49200, 0x49201, 0x49208, 0x49209, 0x49240, 0x49241, 0x49248, 0x49249 }; /* * This expands 8 bit indices into 32 bit contents (high bit 28), by inserting 0s between bits. */ private static final int[] INTERLEAVE4_TABLE = new int[] { 0x00000000, 0x00000001, 0x00000010, 0x00000011, 0x00000100, 0x00000101, 0x00000110, 0x00000111, 0x00001000, 0x00001001, 0x00001010, 0x00001011, 0x00001100, 0x00001101, 0x00001110, 0x00001111, 0x00010000, 0x00010001, 0x00010010, 0x00010011, 0x00010100, 0x00010101, 0x00010110, 0x00010111, 0x00011000, 0x00011001, 0x00011010, 0x00011011, 0x00011100, 0x00011101, 0x00011110, 0x00011111, 0x00100000, 0x00100001, 0x00100010, 0x00100011, 0x00100100, 0x00100101, 0x00100110, 0x00100111, 0x00101000, 0x00101001, 0x00101010, 0x00101011, 0x00101100, 0x00101101, 0x00101110, 0x00101111, 0x00110000, 0x00110001, 0x00110010, 0x00110011, 0x00110100, 0x00110101, 0x00110110, 0x00110111, 0x00111000, 0x00111001, 0x00111010, 0x00111011, 0x00111100, 0x00111101, 0x00111110, 0x00111111, 0x01000000, 0x01000001, 0x01000010, 0x01000011, 0x01000100, 0x01000101, 0x01000110, 0x01000111, 0x01001000, 0x01001001, 0x01001010, 0x01001011, 0x01001100, 0x01001101, 0x01001110, 0x01001111, 0x01010000, 0x01010001, 0x01010010, 0x01010011, 0x01010100, 0x01010101, 0x01010110, 0x01010111, 0x01011000, 0x01011001, 0x01011010, 0x01011011, 0x01011100, 0x01011101, 0x01011110, 0x01011111, 0x01100000, 0x01100001, 0x01100010, 0x01100011, 0x01100100, 0x01100101, 0x01100110, 0x01100111, 0x01101000, 0x01101001, 0x01101010, 0x01101011, 0x01101100, 0x01101101, 0x01101110, 0x01101111, 0x01110000, 0x01110001, 0x01110010, 0x01110011, 0x01110100, 0x01110101, 0x01110110, 0x01110111, 0x01111000, 0x01111001, 0x01111010, 0x01111011, 0x01111100, 0x01111101, 0x01111110, 0x01111111, 0x10000000, 0x10000001, 0x10000010, 0x10000011, 0x10000100, 0x10000101, 0x10000110, 0x10000111, 0x10001000, 0x10001001, 0x10001010, 0x10001011, 0x10001100, 0x10001101, 0x10001110, 0x10001111, 0x10010000, 0x10010001, 0x10010010, 0x10010011, 0x10010100, 0x10010101, 0x10010110, 0x10010111, 0x10011000, 0x10011001, 0x10011010, 0x10011011, 0x10011100, 0x10011101, 0x10011110, 0x10011111, 0x10100000, 0x10100001, 0x10100010, 0x10100011, 0x10100100, 0x10100101, 0x10100110, 0x10100111, 0x10101000, 0x10101001, 0x10101010, 0x10101011, 0x10101100, 0x10101101, 0x10101110, 0x10101111, 0x10110000, 0x10110001, 0x10110010, 0x10110011, 0x10110100, 0x10110101, 0x10110110, 0x10110111, 0x10111000, 0x10111001, 0x10111010, 0x10111011, 0x10111100, 0x10111101, 0x10111110, 0x10111111, 0x11000000, 0x11000001, 0x11000010, 0x11000011, 0x11000100, 0x11000101, 0x11000110, 0x11000111, 0x11001000, 0x11001001, 0x11001010, 0x11001011, 0x11001100, 0x11001101, 0x11001110, 0x11001111, 0x11010000, 0x11010001, 0x11010010, 0x11010011, 0x11010100, 0x11010101, 0x11010110, 0x11010111, 0x11011000, 0x11011001, 0x11011010, 0x11011011, 0x11011100, 0x11011101, 0x11011110, 0x11011111, 0x11100000, 0x11100001, 0x11100010, 0x11100011, 0x11100100, 0x11100101, 0x11100110, 0x11100111, 0x11101000, 0x11101001, 0x11101010, 0x11101011, 0x11101100, 0x11101101, 0x11101110, 0x11101111, 0x11110000, 0x11110001, 0x11110010, 0x11110011, 0x11110100, 0x11110101, 0x11110110, 0x11110111, 0x11111000, 0x11111001, 0x11111010, 0x11111011, 0x11111100, 0x11111101, 0x11111110, 0x11111111 }; /* * This expands 7 bit indices into 35 bit contents (high bit 30), by inserting 0s between bits. */ private static final int[] INTERLEAVE5_TABLE = new int[] { 0x00000000, 0x00000001, 0x00000020, 0x00000021, 0x00000400, 0x00000401, 0x00000420, 0x00000421, 0x00008000, 0x00008001, 0x00008020, 0x00008021, 0x00008400, 0x00008401, 0x00008420, 0x00008421, 0x00100000, 0x00100001, 0x00100020, 0x00100021, 0x00100400, 0x00100401, 0x00100420, 0x00100421, 0x00108000, 0x00108001, 0x00108020, 0x00108021, 0x00108400, 0x00108401, 0x00108420, 0x00108421, 0x02000000, 0x02000001, 0x02000020, 0x02000021, 0x02000400, 0x02000401, 0x02000420, 0x02000421, 0x02008000, 0x02008001, 0x02008020, 0x02008021, 0x02008400, 0x02008401, 0x02008420, 0x02008421, 0x02100000, 0x02100001, 0x02100020, 0x02100021, 0x02100400, 0x02100401, 0x02100420, 0x02100421, 0x02108000, 0x02108001, 0x02108020, 0x02108021, 0x02108400, 0x02108401, 0x02108420, 0x02108421, 0x40000000, 0x40000001, 0x40000020, 0x40000021, 0x40000400, 0x40000401, 0x40000420, 0x40000421, 0x40008000, 0x40008001, 0x40008020, 0x40008021, 0x40008400, 0x40008401, 0x40008420, 0x40008421, 0x40100000, 0x40100001, 0x40100020, 0x40100021, 0x40100400, 0x40100401, 0x40100420, 0x40100421, 0x40108000, 0x40108001, 0x40108020, 0x40108021, 0x40108400, 0x40108401, 0x40108420, 0x40108421, 0x42000000, 0x42000001, 0x42000020, 0x42000021, 0x42000400, 0x42000401, 0x42000420, 0x42000421, 0x42008000, 0x42008001, 0x42008020, 0x42008021, 0x42008400, 0x42008401, 0x42008420, 0x42008421, 0x42100000, 0x42100001, 0x42100020, 0x42100021, 0x42100400, 0x42100401, 0x42100420, 0x42100421, 0x42108000, 0x42108001, 0x42108020, 0x42108021, 0x42108400, 0x42108401, 0x42108420, 0x42108421 }; /* * This expands 9 bit indices into 63 bit (long) contents (high bit 56), by inserting 0s between bits. */ private static final long[] INTERLEAVE7_TABLE = new long[] { 0x0000000000000000L, 0x0000000000000001L, 0x0000000000000080L, 0x0000000000000081L, 0x0000000000004000L, 0x0000000000004001L, 0x0000000000004080L, 0x0000000000004081L, 0x0000000000200000L, 0x0000000000200001L, 0x0000000000200080L, 0x0000000000200081L, 0x0000000000204000L, 0x0000000000204001L, 0x0000000000204080L, 0x0000000000204081L, 0x0000000010000000L, 0x0000000010000001L, 0x0000000010000080L, 0x0000000010000081L, 0x0000000010004000L, 0x0000000010004001L, 0x0000000010004080L, 0x0000000010004081L, 0x0000000010200000L, 0x0000000010200001L, 0x0000000010200080L, 0x0000000010200081L, 0x0000000010204000L, 0x0000000010204001L, 0x0000000010204080L, 0x0000000010204081L, 0x0000000800000000L, 0x0000000800000001L, 0x0000000800000080L, 0x0000000800000081L, 0x0000000800004000L, 0x0000000800004001L, 0x0000000800004080L, 0x0000000800004081L, 0x0000000800200000L, 0x0000000800200001L, 0x0000000800200080L, 0x0000000800200081L, 0x0000000800204000L, 0x0000000800204001L, 0x0000000800204080L, 0x0000000800204081L, 0x0000000810000000L, 0x0000000810000001L, 0x0000000810000080L, 0x0000000810000081L, 0x0000000810004000L, 0x0000000810004001L, 0x0000000810004080L, 0x0000000810004081L, 0x0000000810200000L, 0x0000000810200001L, 0x0000000810200080L, 0x0000000810200081L, 0x0000000810204000L, 0x0000000810204001L, 0x0000000810204080L, 0x0000000810204081L, 0x0000040000000000L, 0x0000040000000001L, 0x0000040000000080L, 0x0000040000000081L, 0x0000040000004000L, 0x0000040000004001L, 0x0000040000004080L, 0x0000040000004081L, 0x0000040000200000L, 0x0000040000200001L, 0x0000040000200080L, 0x0000040000200081L, 0x0000040000204000L, 0x0000040000204001L, 0x0000040000204080L, 0x0000040000204081L, 0x0000040010000000L, 0x0000040010000001L, 0x0000040010000080L, 0x0000040010000081L, 0x0000040010004000L, 0x0000040010004001L, 0x0000040010004080L, 0x0000040010004081L, 0x0000040010200000L, 0x0000040010200001L, 0x0000040010200080L, 0x0000040010200081L, 0x0000040010204000L, 0x0000040010204001L, 0x0000040010204080L, 0x0000040010204081L, 0x0000040800000000L, 0x0000040800000001L, 0x0000040800000080L, 0x0000040800000081L, 0x0000040800004000L, 0x0000040800004001L, 0x0000040800004080L, 0x0000040800004081L, 0x0000040800200000L, 0x0000040800200001L, 0x0000040800200080L, 0x0000040800200081L, 0x0000040800204000L, 0x0000040800204001L, 0x0000040800204080L, 0x0000040800204081L, 0x0000040810000000L, 0x0000040810000001L, 0x0000040810000080L, 0x0000040810000081L, 0x0000040810004000L, 0x0000040810004001L, 0x0000040810004080L, 0x0000040810004081L, 0x0000040810200000L, 0x0000040810200001L, 0x0000040810200080L, 0x0000040810200081L, 0x0000040810204000L, 0x0000040810204001L, 0x0000040810204080L, 0x0000040810204081L, 0x0002000000000000L, 0x0002000000000001L, 0x0002000000000080L, 0x0002000000000081L, 0x0002000000004000L, 0x0002000000004001L, 0x0002000000004080L, 0x0002000000004081L, 0x0002000000200000L, 0x0002000000200001L, 0x0002000000200080L, 0x0002000000200081L, 0x0002000000204000L, 0x0002000000204001L, 0x0002000000204080L, 0x0002000000204081L, 0x0002000010000000L, 0x0002000010000001L, 0x0002000010000080L, 0x0002000010000081L, 0x0002000010004000L, 0x0002000010004001L, 0x0002000010004080L, 0x0002000010004081L, 0x0002000010200000L, 0x0002000010200001L, 0x0002000010200080L, 0x0002000010200081L, 0x0002000010204000L, 0x0002000010204001L, 0x0002000010204080L, 0x0002000010204081L, 0x0002000800000000L, 0x0002000800000001L, 0x0002000800000080L, 0x0002000800000081L, 0x0002000800004000L, 0x0002000800004001L, 0x0002000800004080L, 0x0002000800004081L, 0x0002000800200000L, 0x0002000800200001L, 0x0002000800200080L, 0x0002000800200081L, 0x0002000800204000L, 0x0002000800204001L, 0x0002000800204080L, 0x0002000800204081L, 0x0002000810000000L, 0x0002000810000001L, 0x0002000810000080L, 0x0002000810000081L, 0x0002000810004000L, 0x0002000810004001L, 0x0002000810004080L, 0x0002000810004081L, 0x0002000810200000L, 0x0002000810200001L, 0x0002000810200080L, 0x0002000810200081L, 0x0002000810204000L, 0x0002000810204001L, 0x0002000810204080L, 0x0002000810204081L, 0x0002040000000000L, 0x0002040000000001L, 0x0002040000000080L, 0x0002040000000081L, 0x0002040000004000L, 0x0002040000004001L, 0x0002040000004080L, 0x0002040000004081L, 0x0002040000200000L, 0x0002040000200001L, 0x0002040000200080L, 0x0002040000200081L, 0x0002040000204000L, 0x0002040000204001L, 0x0002040000204080L, 0x0002040000204081L, 0x0002040010000000L, 0x0002040010000001L, 0x0002040010000080L, 0x0002040010000081L, 0x0002040010004000L, 0x0002040010004001L, 0x0002040010004080L, 0x0002040010004081L, 0x0002040010200000L, 0x0002040010200001L, 0x0002040010200080L, 0x0002040010200081L, 0x0002040010204000L, 0x0002040010204001L, 0x0002040010204080L, 0x0002040010204081L, 0x0002040800000000L, 0x0002040800000001L, 0x0002040800000080L, 0x0002040800000081L, 0x0002040800004000L, 0x0002040800004001L, 0x0002040800004080L, 0x0002040800004081L, 0x0002040800200000L, 0x0002040800200001L, 0x0002040800200080L, 0x0002040800200081L, 0x0002040800204000L, 0x0002040800204001L, 0x0002040800204080L, 0x0002040800204081L, 0x0002040810000000L, 0x0002040810000001L, 0x0002040810000080L, 0x0002040810000081L, 0x0002040810004000L, 0x0002040810004001L, 0x0002040810004080L, 0x0002040810004081L, 0x0002040810200000L, 0x0002040810200001L, 0x0002040810200080L, 0x0002040810200081L, 0x0002040810204000L, 0x0002040810204001L, 0x0002040810204080L, 0x0002040810204081L, 0x0100000000000000L, 0x0100000000000001L, 0x0100000000000080L, 0x0100000000000081L, 0x0100000000004000L, 0x0100000000004001L, 0x0100000000004080L, 0x0100000000004081L, 0x0100000000200000L, 0x0100000000200001L, 0x0100000000200080L, 0x0100000000200081L, 0x0100000000204000L, 0x0100000000204001L, 0x0100000000204080L, 0x0100000000204081L, 0x0100000010000000L, 0x0100000010000001L, 0x0100000010000080L, 0x0100000010000081L, 0x0100000010004000L, 0x0100000010004001L, 0x0100000010004080L, 0x0100000010004081L, 0x0100000010200000L, 0x0100000010200001L, 0x0100000010200080L, 0x0100000010200081L, 0x0100000010204000L, 0x0100000010204001L, 0x0100000010204080L, 0x0100000010204081L, 0x0100000800000000L, 0x0100000800000001L, 0x0100000800000080L, 0x0100000800000081L, 0x0100000800004000L, 0x0100000800004001L, 0x0100000800004080L, 0x0100000800004081L, 0x0100000800200000L, 0x0100000800200001L, 0x0100000800200080L, 0x0100000800200081L, 0x0100000800204000L, 0x0100000800204001L, 0x0100000800204080L, 0x0100000800204081L, 0x0100000810000000L, 0x0100000810000001L, 0x0100000810000080L, 0x0100000810000081L, 0x0100000810004000L, 0x0100000810004001L, 0x0100000810004080L, 0x0100000810004081L, 0x0100000810200000L, 0x0100000810200001L, 0x0100000810200080L, 0x0100000810200081L, 0x0100000810204000L, 0x0100000810204001L, 0x0100000810204080L, 0x0100000810204081L, 0x0100040000000000L, 0x0100040000000001L, 0x0100040000000080L, 0x0100040000000081L, 0x0100040000004000L, 0x0100040000004001L, 0x0100040000004080L, 0x0100040000004081L, 0x0100040000200000L, 0x0100040000200001L, 0x0100040000200080L, 0x0100040000200081L, 0x0100040000204000L, 0x0100040000204001L, 0x0100040000204080L, 0x0100040000204081L, 0x0100040010000000L, 0x0100040010000001L, 0x0100040010000080L, 0x0100040010000081L, 0x0100040010004000L, 0x0100040010004001L, 0x0100040010004080L, 0x0100040010004081L, 0x0100040010200000L, 0x0100040010200001L, 0x0100040010200080L, 0x0100040010200081L, 0x0100040010204000L, 0x0100040010204001L, 0x0100040010204080L, 0x0100040010204081L, 0x0100040800000000L, 0x0100040800000001L, 0x0100040800000080L, 0x0100040800000081L, 0x0100040800004000L, 0x0100040800004001L, 0x0100040800004080L, 0x0100040800004081L, 0x0100040800200000L, 0x0100040800200001L, 0x0100040800200080L, 0x0100040800200081L, 0x0100040800204000L, 0x0100040800204001L, 0x0100040800204080L, 0x0100040800204081L, 0x0100040810000000L, 0x0100040810000001L, 0x0100040810000080L, 0x0100040810000081L, 0x0100040810004000L, 0x0100040810004001L, 0x0100040810004080L, 0x0100040810004081L, 0x0100040810200000L, 0x0100040810200001L, 0x0100040810200080L, 0x0100040810200081L, 0x0100040810204000L, 0x0100040810204001L, 0x0100040810204080L, 0x0100040810204081L, 0x0102000000000000L, 0x0102000000000001L, 0x0102000000000080L, 0x0102000000000081L, 0x0102000000004000L, 0x0102000000004001L, 0x0102000000004080L, 0x0102000000004081L, 0x0102000000200000L, 0x0102000000200001L, 0x0102000000200080L, 0x0102000000200081L, 0x0102000000204000L, 0x0102000000204001L, 0x0102000000204080L, 0x0102000000204081L, 0x0102000010000000L, 0x0102000010000001L, 0x0102000010000080L, 0x0102000010000081L, 0x0102000010004000L, 0x0102000010004001L, 0x0102000010004080L, 0x0102000010004081L, 0x0102000010200000L, 0x0102000010200001L, 0x0102000010200080L, 0x0102000010200081L, 0x0102000010204000L, 0x0102000010204001L, 0x0102000010204080L, 0x0102000010204081L, 0x0102000800000000L, 0x0102000800000001L, 0x0102000800000080L, 0x0102000800000081L, 0x0102000800004000L, 0x0102000800004001L, 0x0102000800004080L, 0x0102000800004081L, 0x0102000800200000L, 0x0102000800200001L, 0x0102000800200080L, 0x0102000800200081L, 0x0102000800204000L, 0x0102000800204001L, 0x0102000800204080L, 0x0102000800204081L, 0x0102000810000000L, 0x0102000810000001L, 0x0102000810000080L, 0x0102000810000081L, 0x0102000810004000L, 0x0102000810004001L, 0x0102000810004080L, 0x0102000810004081L, 0x0102000810200000L, 0x0102000810200001L, 0x0102000810200080L, 0x0102000810200081L, 0x0102000810204000L, 0x0102000810204001L, 0x0102000810204080L, 0x0102000810204081L, 0x0102040000000000L, 0x0102040000000001L, 0x0102040000000080L, 0x0102040000000081L, 0x0102040000004000L, 0x0102040000004001L, 0x0102040000004080L, 0x0102040000004081L, 0x0102040000200000L, 0x0102040000200001L, 0x0102040000200080L, 0x0102040000200081L, 0x0102040000204000L, 0x0102040000204001L, 0x0102040000204080L, 0x0102040000204081L, 0x0102040010000000L, 0x0102040010000001L, 0x0102040010000080L, 0x0102040010000081L, 0x0102040010004000L, 0x0102040010004001L, 0x0102040010004080L, 0x0102040010004081L, 0x0102040010200000L, 0x0102040010200001L, 0x0102040010200080L, 0x0102040010200081L, 0x0102040010204000L, 0x0102040010204001L, 0x0102040010204080L, 0x0102040010204081L, 0x0102040800000000L, 0x0102040800000001L, 0x0102040800000080L, 0x0102040800000081L, 0x0102040800004000L, 0x0102040800004001L, 0x0102040800004080L, 0x0102040800004081L, 0x0102040800200000L, 0x0102040800200001L, 0x0102040800200080L, 0x0102040800200081L, 0x0102040800204000L, 0x0102040800204001L, 0x0102040800204080L, 0x0102040800204081L, 0x0102040810000000L, 0x0102040810000001L, 0x0102040810000080L, 0x0102040810000081L, 0x0102040810004000L, 0x0102040810004001L, 0x0102040810004080L, 0x0102040810004081L, 0x0102040810200000L, 0x0102040810200001L, 0x0102040810200080L, 0x0102040810200081L, 0x0102040810204000L, 0x0102040810204001L, 0x0102040810204080L, 0x0102040810204081L }; // For toString(); must have length 64 private static final String ZEROES = "0000000000000000000000000000000000000000000000000000000000000000"; final static byte[] bitLengths = { 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }; // TODO make m fixed for the LongArray, and hence compute T once and for all private long[] m_ints; public LongArray(int intLen) { m_ints = new long[intLen]; } public LongArray(long[] ints) { m_ints = ints; } public LongArray(long[] ints, int off, int len) { if (off == 0 && len == ints.length) { m_ints = ints; } else { m_ints = new long[len]; System.arraycopy(ints, off, m_ints, 0, len); } } public LongArray(BigInteger bigInt) { if (bigInt == null || bigInt.signum() < 0) { throw new IllegalArgumentException("invalid F2m field value"); } if (bigInt.signum() == 0) { m_ints = new long[] { 0L }; return; } byte[] barr = bigInt.toByteArray(); int barrLen = barr.length; int barrStart = 0; if (barr[0] == 0) { // First byte is 0 to enforce highest (=sign) bit is zero. // In this case ignore barr[0]. barrLen barrStart = 1; } int intLen = (barrLen + 7) / 8; m_ints = new long[intLen]; int iarrJ = intLen - 1; int rem = barrLen % 8 + barrStart; long temp = 0; int barrI = barrStart; if (barrStart < rem) { for (; barrI < rem; barrI++) { temp <<= 8; int barrBarrI = barr[barrI] & 0xFF; temp |= barrBarrI; } m_ints[iarrJ--] = temp; } for (; iarrJ >= 0; iarrJ { temp = 0; for (int i = 0; i < 8; i++) { temp <<= 8; int barrBarrI = barr[barrI++] & 0xFF; temp |= barrBarrI; } m_ints[iarrJ] = temp; } } public boolean isZero() { long[] a = m_ints; for (int i = 0; i < a.length; ++i) { if (a[i] != 0L) { return false; } } return true; } public int getUsedLength() { return getUsedLengthFrom(m_ints.length); } public int getUsedLengthFrom(int from) { long[] a = m_ints; from = Math.min(from, a.length); if (from < 1) { return 0; } // Check if first element will act as sentinel if (a[0] != 0) { while (a[--from] == 0) { } return from + 1; } do { if (a[--from] != 0) { return from + 1; } } while (from > 0); return 0; } public int degree() { int i = m_ints.length; long w; do { if (i == 0) { return 0; } w = m_ints[--i]; } while (w == 0); return (i << 6) + bitLength(w); } private static int bitLength(long w) { int u = (int)(w >>> 32), b; if (u == 0) { u = (int)w; b = 0; } else { b = 32; } int t = u >>> 16, k; if (t == 0) { t = u >>> 8; k = (t == 0) ? bitLengths[u] : 8 + bitLengths[t]; } else { int v = t >>> 8; k = (v == 0) ? 16 + bitLengths[t] : 24 + bitLengths[v]; } return b + k; } private long[] resizedInts(int newLen) { long[] newInts = new long[newLen]; System.arraycopy(m_ints, 0, newInts, 0, Math.min(m_ints.length, newLen)); return newInts; } public BigInteger toBigInteger() { int usedLen = getUsedLength(); if (usedLen == 0) { return ECConstants.ZERO; } long highestInt = m_ints[usedLen - 1]; byte[] temp = new byte[8]; int barrI = 0; boolean trailingZeroBytesDone = false; for (int j = 7; j >= 0; j { byte thisByte = (byte)(highestInt >>> (8 * j)); if (trailingZeroBytesDone || (thisByte != 0)) { trailingZeroBytesDone = true; temp[barrI++] = thisByte; } } int barrLen = 8 * (usedLen - 1) + barrI; byte[] barr = new byte[barrLen]; for (int j = 0; j < barrI; j++) { barr[j] = temp[j]; } // Highest value int is done now for (int iarrJ = usedLen - 2; iarrJ >= 0; iarrJ { long mi = m_ints[iarrJ]; for (int j = 7; j >= 0; j { barr[barrI++] = (byte)(mi >>> (8 * j)); } } return new BigInteger(1, barr); } private static long shiftLeft(long[] x, int count) { long prev = 0; for (int i = 0; i < count; ++i) { long next = x[i]; x[i] = (next << 1) | prev; prev = next >>> 63; } return prev; } public LongArray addOne() { if (m_ints.length == 0) { return new LongArray(new long[]{ 1L }); } int resultLen = Math.max(1, getUsedLength()); long[] ints = resizedInts(resultLen); ints[0] ^= 1L; return new LongArray(ints); } private void addShiftedByBits(LongArray other, int bits) { int words = bits >>> 6; int shift = bits & 0x3F; if (shift == 0) { addShiftedByWords(other, words); return; } int otherUsedLen = other.getUsedLength(); if (otherUsedLen == 0) { return; } int minLen = otherUsedLen + words + 1; if (minLen > m_ints.length) { m_ints = resizedInts(minLen); } int shiftInv = 64 - shift; long prev = 0; for (int i = 0; i < otherUsedLen; ++i) { long next = other.m_ints[i]; m_ints[i + words] ^= (next << shift) | prev; prev = next >>> shiftInv; } m_ints[otherUsedLen + words] ^= prev; } private static long addShiftedByBits(long[] x, int xOff, long[] y, int yOff, int count, int shift) { int shiftInv = 64 - shift; long prev = 0; for (int i = 0; i < count; ++i) { long next = y[yOff + i]; x[xOff + i] ^= (next << shift) | prev; prev = next >>> shiftInv; } return prev; } public void addShiftedByWords(LongArray other, int words) { int otherUsedLen = other.getUsedLength(); if (otherUsedLen == 0) { return; } int minLen = otherUsedLen + words; if (minLen > m_ints.length) { m_ints = resizedInts(minLen); } for (int i = 0; i < otherUsedLen; i++) { m_ints[words + i] ^= other.m_ints[i]; } } private static void add(long[] x, int xOff, long[] y, int yOff, int count) { for (int i = 0; i < count; ++i) { x[xOff + i] ^= y[yOff + i]; } } private static void distribute(long[] x, int dst1, int dst2, int src, int count) { for (int i = 0; i < count; ++i) { long v = x[src + i]; x[dst1 + i] ^= v; x[dst2 + i] ^= v; } } public int getLength() { return m_ints.length; } private static void flipWord(long[] buf, int off, int bit, long word) { int n = off + (bit >>> 6); int shift = bit & 0x3F; if (shift == 0) { buf[n] ^= word; } else { buf[n] ^= word << shift; word >>>= (64 - shift); if (word != 0) { buf[++n] ^= word; } } } // private static long getWord(long[] buf, int off, int len, int bit) // int n = off + (bit >>> 6); // int shift = bit & 0x3F; // if (shift == 0) // return buf[n]; // long result = buf[n] >>> shift; // if (++n < len) // result |= buf[n] << (64 - shift); // return result; public boolean testBitZero() { return m_ints.length > 0 && (m_ints[0] & 1L) != 0; } public boolean testBit(int n) { return testBit(m_ints, 0, n); } private static boolean testBit(long[] buf, int off, int n) { // theInt = n / 64 int theInt = n >>> 6; // theBit = n % 64 int theBit = n & 0x3F; long tester = 1L << theBit; return (buf[off + theInt] & tester) != 0; } private static void flipBit(long[] buf, int off, int n) { // theInt = n / 64 int theInt = n >>> 6; // theBit = n % 64 int theBit = n & 0x3F; long flipper = 1L << theBit; buf[off + theInt] ^= flipper; } public void setBit(int n) { setBit(m_ints, 0, n); } private static void setBit(long[] buf, int off, int n) { // theInt = n / 64 int theInt = n >>> 6; // theBit = n % 64 int theBit = n & 0x3F; long setter = 1L << theBit; buf[off + theInt] |= setter; } private static void clearBit(long[] buf, int off, int n) { // theInt = n / 64 int theInt = n >>> 6; // theBit = n % 64 int theBit = n & 0x3F; long setter = 1L << theBit; buf[off + theInt] &= ~setter; } public LongArray modMultiply(LongArray other, int m, int[] ks) { /* * Find out the degree of each argument and handle the zero cases */ int aDeg = degree(); if (aDeg == 0) { return this; } int bDeg = other.degree(); if (bDeg == 0) { return other; } /* * Swap if necessary so that A is the smaller argument */ LongArray A = this, B = other; if (aDeg > bDeg) { A = other; B = this; int tmp = aDeg; aDeg = bDeg; bDeg = tmp; } /* * Establish the word lengths of the arguments and result */ int aLen = (aDeg + 63) >>> 6; int bLen = (bDeg + 63) >>> 6; int cLen = (aDeg + bDeg + 62) >>> 6; if (aLen == 1) { long a = A.m_ints[0]; if (a == 1L) { return B; } /* * Fast path for small A, with performance dependent only on the number of set bits */ long[] b = B.m_ints; long[] c = new long[cLen]; if ((a & 1L) != 0L) { add(c, 0, b, 0, bLen); } int k = 1; while ((a >>>= 1) != 0) { if ((a & 1L) != 0L) { long carry = addShiftedByBits(c, 0, b, 0, bLen, k); if (carry != 0) { c[bLen] ^= carry; } } ++k; } /* * Reduce the raw answer against the reduction coefficients */ return reduceResult(c, 0, cLen, m, ks); } /* * Determine the parameters of the interleaved window algorithm: the 'width' in bits to * process together, the number of evaluation 'positions' implied by that width, and the * 'top' position at which the regular window algorithm stops. */ int width, positions, top; // NOTE: These work, but require too many shifts to be competitive // width = 1; positions = 64; top = 64; // width = 2; positions = 32; top = 64; // width = 3; positions = 21; top = 63; if (aLen <= 16) { width = 4; positions = 16; top = 64; } else if (aLen <= 32) { width = 5; positions = 13; top = 65; } else if (aLen <= 128) { width = 7; positions = 9; top = 63; } else { width = 8; positions = 8; top = 64; } /* * Determine if B will get bigger during shifting */ int shifts = positions; if (top >= 64) { --shifts; } int bMax = bLen; if ((B.m_ints[bLen - 1] >>> (64 - shifts)) != 0L) { ++bMax; } /* * Create a single temporary buffer, with an offset table to find the positions of things in it */ int[] ci = new int[1 << width]; // ci[0] = 0; int total = bMax + aLen; ci[1] = total; for (int i = 2; i < ci.length; ++i) { total += cLen; ci[i] = total; } long[] c = new long[total + cLen]; // Make a working copy of B, since we will be shifting it System.arraycopy(B.m_ints, 0, c, 0, bLen); // Prepare A in interleaved form, according to the chosen width interleave(A.m_ints, 0, c, bMax, aLen, width); /* * The main loop analyzes the interleaved windows in A, and for each non-zero window * a single word-array XOR is performed to a carefully selected slice of 'c'. The loop is * breadth-first, checking the lowest window in each word, then looping again for the * next higher window position. */ int MASK = (1 << width) - 1; int k = 0; for (;;) { for (int aPos = 0; aPos < aLen; ++aPos) { int index = (int)(c[bMax + aPos] >>> k) & MASK; if (index != 0) { /* * Add to a 'c' buffer based on the bit-pattern of 'index'. Since A is in * interleaved form, the bits represent the current B shifted by 0, 'positions', * 'positions' * 2, ..., 'positions' * ('width' - 1) */ add(c, ci[index] + aPos, c, 0, bLen); } } if ((k += width) >= top) { if (k >= 64) { break; } /* * Adjustment for window setups with top == 63, the final bit (if any) is processed * as the top-bit of a window */ k = 64 - width; MASK &= MASK << (top - k); } /* * After each window position has been checked in all words of A, B is shifted to the * left 1 place and expanded if necessary. */ long carry = shiftLeft(c, bLen); if (carry != 0) { c[bLen++] = carry; } } int ciPos = ci.length, pow2 = ciPos >>> 1; int offset = top; while (--ciPos > 1) { if (ciPos == pow2) { /* * For powers of 2, we finally shift things back to the correct position and add to * the final result */ offset -= positions; addShiftedByBits(c, ci[1], c, ci[pow2], cLen, offset); pow2 >>>= 1; } else { /* * Non-powers of 2 are dealt with by 'distributing' down to the next-lowest power of * 2 and to the remainder (which will eventually distribute to the lower powers) */ distribute(c, ci[pow2], ci[ciPos - pow2], ci[ciPos], cLen); } } /* * Finally the raw answer is collected, reduce it against the reduction coefficients */ return reduceResult(c, ci[1], cLen, m, ks); } private static LongArray reduceResult(long[] buf, int off, int len, int m, int[] ks) { int rLen = reduceInPlace(buf, off, len, m, ks); return new LongArray(buf, off, rLen); } // private static void deInterleave(long[] x, int xOff, long[] z, int zOff, int count, int rounds) // for (int i = 0; i < count; ++i) // z[zOff + i] = deInterleave(x[zOff + i], rounds); // private static long deInterleave(long x, int rounds) // while (--rounds >= 0) // x = deInterleave32(x & DEINTERLEAVE_MASK) | (deInterleave32((x >>> 1) & DEINTERLEAVE_MASK) << 32); // return x; // private static long deInterleave32(long x) // x = (x | (x >>> 1)) & 0x3333333333333333L; // x = (x | (x >>> 2)) & 0x0F0F0F0F0F0F0F0FL; // x = (x | (x >>> 4)) & 0x00FF00FF00FF00FFL; // x = (x | (x >>> 8)) & 0x0000FFFF0000FFFFL; // x = (x | (x >>> 16)) & 0x00000000FFFFFFFFL; // return x; private static int reduceInPlace(long[] buf, int off, int len, int m, int[] ks) { int mLen = (m + 63) >>> 6; if (len < mLen) { return len; } int kMax = ks[ks.length - 1]; int wordWiseLimit = Math.max(m, kMax + 64); int numBits = len << 6; if (numBits > wordWiseLimit) { reduceWordWise(buf, off, len, wordWiseLimit, m, ks); numBits = wordWiseLimit; } if (numBits > m) { reduceBitWise(buf, off, numBits, m, ks); } return mLen; } private static void reduceBitWise(long[] buf, int off, int bitlength, int m, int[] ks) { while (--bitlength >= m) { if (testBit(buf, off, bitlength)) { clearBit(buf, off, bitlength); int bit = bitlength - m; flipBit(buf, off, bit); int j = ks.length; while (--j >= 0) { flipBit(buf, off, ks[j] + bit); } } } } private static void reduceWordWise(long[] buf, int off, int len, int toBit, int m, int[] ks) { int toPos = toBit >>> 6; while (--len > toPos) { long word = buf[off + len]; if (word != 0) { buf[off + len] = 0; reduceWord(buf, off, (len << 6), word, m, ks); } } int partial = toBit & 0x3F; long word = buf[off + toPos] >>> partial; if (word != 0) { buf[off + toPos] ^= word << partial; reduceWord(buf, off, toBit, word, m, ks); } } private static void reduceWord(long[] buf, int off, int bit, long word, int m, int[] ks) { int offset = bit - m; flipWord(buf, off, offset, word); int j = ks.length; while (--j >= 0) { flipWord(buf, off, offset + ks[j], word); } } public LongArray modSquare(int m, int[] ks) { int len = getUsedLength(); if (len == 0) { return this; } int _2len = len << 1; long[] r = new long[_2len]; int pos = 0; while (pos < _2len) { long mi = m_ints[pos >>> 1]; r[pos++] = interleave2_32to64((int)mi); r[pos++] = interleave2_32to64((int)(mi >>> 32)); } return new LongArray(r, 0, reduceInPlace(r, 0, r.length, m, ks)); } private static void interleave(long[] x, int xOff, long[] z, int zOff, int count, int width) { switch (width) { case 3: interleave3(x, xOff, z, zOff, count); break; case 5: interleave5(x, xOff, z, zOff, count); break; case 7: interleave7(x, xOff, z, zOff, count); break; default: interleave2_n(x, xOff, z, zOff, count, bitLengths[width] - 1); break; } } private static void interleave3(long[] x, int xOff, long[] z, int zOff, int count) { for (int i = 0; i < count; ++i) { z[zOff + i] = interleave3(x[xOff + i]); } } private static long interleave3(long x) { long z = x & (1L << 63); return z | interleave3_21to63((int)x & 0x1FFFFF) | interleave3_21to63((int)(x >>> 21) & 0x1FFFFF) << 1 | interleave3_21to63((int)(x >>> 42) & 0x1FFFFF) << 2; // int zPos = 0, wPos = 0, xPos = 0; // for (;;) // z |= ((x >>> xPos) & 1L) << zPos; // if (++zPos == 63) // String sz2 = Long.toBinaryString(z); // return z; // if ((xPos += 21) >= 63) // xPos = ++wPos; } private static long interleave3_21to63(int x) { int r00 = INTERLEAVE3_TABLE[x & 0x7F]; int r21 = INTERLEAVE3_TABLE[(x >>> 7) & 0x7F]; int r42 = INTERLEAVE3_TABLE[x >>> 14]; return (r42 & 0xFFFFFFFFL) << 42 | (r21 & 0xFFFFFFFFL) << 21 | (r00 & 0xFFFFFFFFL); } private static void interleave5(long[] x, int xOff, long[] z, int zOff, int count) { for (int i = 0; i < count; ++i) { z[zOff + i] = interleave5(x[xOff + i]); } } private static long interleave5(long x) { return interleave3_13to65((int)x & 0x1FFF) | interleave3_13to65((int)(x >>> 13) & 0x1FFF) << 1 | interleave3_13to65((int)(x >>> 26) & 0x1FFF) << 2 | interleave3_13to65((int)(x >>> 39) & 0x1FFF) << 3 | interleave3_13to65((int)(x >>> 52) & 0x1FFF) << 4; // long z = 0; // int zPos = 0, wPos = 0, xPos = 0; // for (;;) // z |= ((x >>> xPos) & 1L) << zPos; // if (++zPos == 64) // return z; // if ((xPos += 13) >= 64) // xPos = ++wPos; } private static long interleave3_13to65(int x) { int r00 = INTERLEAVE5_TABLE[x & 0x7F]; int r35 = INTERLEAVE5_TABLE[x >>> 7]; return (r35 & 0xFFFFFFFFL) << 35 | (r00 & 0xFFFFFFFFL); } private static void interleave7(long[] x, int xOff, long[] z, int zOff, int count) { for (int i = 0; i < count; ++i) { z[zOff + i] = interleave7(x[xOff + i]); } } private static long interleave7(long x) { long z = x & (1L << 63); return z | INTERLEAVE7_TABLE[(int)x & 0x1FF] | INTERLEAVE7_TABLE[(int)(x >>> 9) & 0x1FF] << 1 | INTERLEAVE7_TABLE[(int)(x >>> 18) & 0x1FF] << 2 | INTERLEAVE7_TABLE[(int)(x >>> 27) & 0x1FF] << 3 | INTERLEAVE7_TABLE[(int)(x >>> 36) & 0x1FF] << 4 | INTERLEAVE7_TABLE[(int)(x >>> 45) & 0x1FF] << 5 | INTERLEAVE7_TABLE[(int)(x >>> 54) & 0x1FF] << 6; // int zPos = 0, wPos = 0, xPos = 0; // for (;;) // z |= ((x >>> xPos) & 1L) << zPos; // if (++zPos == 63) // return z; // if ((xPos += 9) >= 63) // xPos = ++wPos; } private static void interleave2_n(long[] x, int xOff, long[] z, int zOff, int count, int rounds) { for (int i = 0; i < count; ++i) { z[zOff + i] = interleave2_n(x[xOff + i], rounds); } } private static long interleave2_n(long x, int rounds) { while (rounds > 1) { rounds -= 2; x = interleave4_16to64((int)x & 0xFFFF) | interleave4_16to64((int)(x >>> 16) & 0xFFFF) << 1 | interleave4_16to64((int)(x >>> 32) & 0xFFFF) << 2 | interleave4_16to64((int)(x >>> 48) & 0xFFFF) << 3; } if (rounds > 0) { x = interleave2_32to64((int)x) | interleave2_32to64((int)(x >>> 32)) << 1; } return x; } private static long interleave4_16to64(int x) { int r00 = INTERLEAVE4_TABLE[x & 0xFF]; int r32 = INTERLEAVE4_TABLE[x >>> 8]; return (r32 & 0xFFFFFFFFL) << 32 | (r00 & 0xFFFFFFFFL); } private static long interleave2_32to64(int x) { int r00 = INTERLEAVE2_TABLE[x & 0xFF] | INTERLEAVE2_TABLE[(x >>> 8) & 0xFF] << 16; int r32 = INTERLEAVE2_TABLE[(x >>> 16) & 0xFF] | INTERLEAVE2_TABLE[x >>> 24] << 16; return (r32 & 0xFFFFFFFFL) << 32 | (r00 & 0xFFFFFFFFL); } public LongArray modInverse(int m, int[] ks) { // Inversion in F2m using the extended Euclidean algorithm // Input: A nonzero polynomial a(z) of degree at most m-1 // Output: a(z)^(-1) mod f(z) int uzDegree = degree(); if (uzDegree == 1) { return this; } // u(z) := a(z) LongArray uz = (LongArray)clone(); int t = (m + 63) >>> 6; // v(z) := f(z) LongArray vz = new LongArray(t); vz.setBit(m); vz.setBit(0); vz.setBit(ks[0]); if (ks.length > 1) { vz.setBit(ks[1]); vz.setBit(ks[2]); } // g1(z) := 1, g2(z) := 0 LongArray g1z = new LongArray(t); g1z.setBit(0); LongArray g2z = new LongArray(t); while (uzDegree != 0) { // j := deg(u(z)) - deg(v(z)) int j = uzDegree - vz.degree(); // If j < 0 then: u(z) <-> v(z), g1(z) <-> g2(z), j := -j if (j < 0) { final LongArray uzCopy = uz; uz = vz; vz = uzCopy; final LongArray g1zCopy = g1z; g1z = g2z; g2z = g1zCopy; j = -j; } // u(z) := u(z) + z^j * v(z) // Note, that no reduction modulo f(z) is required, because // deg(u(z) + z^j * v(z)) <= max(deg(u(z)), j + deg(v(z))) // = max(deg(u(z)), deg(u(z)) - deg(v(z)) + deg(v(z)) // = deg(u(z)) // uz = uz.xor(vz.shiftLeft(j)); uz.addShiftedByBits(vz, j); uzDegree = uz.degree(); // g1(z) := g1(z) + z^j * g2(z) // g1z = g1z.xor(g2z.shiftLeft(j)); if (uzDegree != 0) { g1z.addShiftedByBits(g2z, j); } } return g2z; } public boolean equals(Object o) { if (!(o instanceof LongArray)) { return false; } LongArray other = (LongArray) o; int usedLen = getUsedLength(); if (other.getUsedLength() != usedLen) { return false; } for (int i = 0; i < usedLen; i++) { if (m_ints[i] != other.m_ints[i]) { return false; } } return true; } public int hashCode() { int usedLen = getUsedLength(); int hash = 1; for (int i = 0; i < usedLen; i++) { long mi = m_ints[i]; hash *= 31; hash ^= (int)mi; hash *= 31; hash ^= (int)(mi >>> 32); } return hash; } public Object clone() { return new LongArray(Arrays.clone(m_ints)); } public String toString() { int i = getUsedLength(); if (i == 0) { return "0"; } StringBuffer sb = new StringBuffer(Long.toBinaryString(m_ints[--i])); while (--i >= 0) { String s = Long.toBinaryString(m_ints[i]); // Add leading zeroes, except for highest significant word int len = s.length(); if (len < 64) { sb.append(ZEROES.substring(len)); } sb.append(s); } return sb.toString(); } }
package com.opengamma.analytics.financial.riskfactor; import com.opengamma.analytics.financial.commodity.derivative.AgricultureFutureOption; import com.opengamma.analytics.financial.commodity.derivative.EnergyFutureOption; import com.opengamma.analytics.financial.commodity.derivative.MetalFutureOption; import com.opengamma.analytics.financial.equity.StaticReplicationDataBundle; import com.opengamma.analytics.financial.equity.option.EquityIndexFutureOption; import com.opengamma.analytics.financial.equity.option.EquityIndexOption; import com.opengamma.analytics.financial.equity.option.EquityOption; import com.opengamma.analytics.financial.interestrate.InstrumentDerivative; import com.opengamma.analytics.financial.interestrate.InstrumentDerivativeVisitorAdapter; import com.opengamma.util.ArgumentChecker; /** * Calculates the value (or dollar) gamma of an option given market data and the gamma. The value gamma is defined as the * option gamma multiplied by half of the spot squared and shares per option. */ public final class ValueGammaCalculator implements ValueGreekCalculator { /** Static instance */ private static final ValueGammaCalculator s_instance = new ValueGammaCalculator(); /** Calculates the multiplier for converting delta to value delta */ private static final MultiplierCalculator s_multiplierCalculator = new MultiplierCalculator(); /** * Gets an instance of this calculator * @return The (singleton) instance */ public static ValueGammaCalculator getInstance() { return s_instance; } private ValueGammaCalculator() { } @Override public double valueGreek(final InstrumentDerivative derivative, final StaticReplicationDataBundle market, final double gamma) { ArgumentChecker.notNull(derivative, "derivative"); ArgumentChecker.notNull(market, "market"); return gamma * derivative.accept(s_multiplierCalculator, market); } /** * Calculates the multiplier for value gamma - spot * spot * shares per option / 2 */ private static final class MultiplierCalculator extends InstrumentDerivativeVisitorAdapter<StaticReplicationDataBundle, Double> { /* package */MultiplierCalculator() { } @Override public Double visitEquityIndexOption(final EquityIndexOption option, final StaticReplicationDataBundle market) { final double spot = market.getForwardCurve().getSpot(); return option.getUnitAmount() * spot * spot / 20000.; } @Override public Double visitEquityIndexFutureOption(final EquityIndexFutureOption option, final StaticReplicationDataBundle market) { final double spot = market.getForwardCurve().getSpot(); return option.getPointValue() * spot * spot / 2; } @Override public Double visitEquityOption(final EquityOption option, final StaticReplicationDataBundle market) { final double spot = market.getForwardCurve().getSpot(); return option.getUnitAmount() * spot * spot / 20000.; } @Override public Double visitAgricultureFutureOption(final AgricultureFutureOption option, final StaticReplicationDataBundle market) { final double spot = market.getForwardCurve().getSpot(); return option.getUnderlying().getUnitAmount() * spot * spot / 2; } @Override public Double visitEnergyFutureOption(final EnergyFutureOption option, final StaticReplicationDataBundle market) { final double spot = market.getForwardCurve().getSpot(); return option.getUnderlying().getUnitAmount() * spot * spot / 2; } @Override public Double visitMetalFutureOption(final MetalFutureOption option, final StaticReplicationDataBundle market) { final double spot = market.getForwardCurve().getSpot(); return option.getUnderlying().getUnitAmount() * spot * spot / 2; } } }
package com.sematext.solr.handler.component.relaxer.heuristics; import org.apache.lucene.analysis.Analyzer; import org.apache.solr.common.params.HighlightParams; import org.apache.solr.common.params.SolrParams; import org.apache.solr.request.SolrQueryRequest; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import com.sematext.solr.handler.component.relaxer.MMRelaxerSuggestion; import com.sematext.solr.handler.component.relaxer.QueryRelaxerHeuristic; import com.sematext.solr.handler.component.relaxer.QueryRelaxerSuggestion; import com.sematext.solr.handler.component.relaxer.RelaxerSuggestion; import com.sematext.solr.handler.component.relaxer.heuristics.regular.RemoveOneTerm; import com.sematext.solr.handler.component.relaxer.query.Clause; import com.sematext.solr.handler.component.relaxer.query.EdismaxQueryConverter; import com.sematext.solr.handler.component.relaxer.query.QueryConverter; import com.sematext.solr.handler.component.relaxer.query.RegexExtractor; import com.sematext.solr.handler.component.relaxer.query.RelaxerParams; import com.sematext.solr.handler.component.relaxer.query.UserQueryExtractor; public class RemoveOneClauseHeuristic extends QueryRelaxerHeuristic { private QueryConverter queryConverter = new EdismaxQueryConverter(); private UserQueryExtractor userQueryExtractor = new RegexExtractor(); @Override public Set<RelaxerSuggestion> createSuggestions(SolrQueryRequest req) { SolrParams params = req.getParams(); int longQueryLength = params.getInt(RelaxerParams.QUERY_RELAXER_LONG_QUERY_TERMS, 5); String userQuery = userQueryExtractor.extract(params); String highlightQuery = params.get(HighlightParams.Q); List<Clause> clauses = queryConverter.convert(userQuery, req); int clauseLength = clauseLength(clauses); if (clauseLength <= 1) { return null; } else if (clauseLength >= longQueryLength) { Set<RelaxerSuggestion> suggestions = new LinkedHashSet<RelaxerSuggestion>(); String relaxedMM = req.getParams().get(RelaxerParams.QUERY_RELAXER_LONG_QUERY_MM); if(relaxedMM != null) { MMRelaxerSuggestion suggestion = new MMRelaxerSuggestion(relaxedMM); String relaxedQuery = userQueryExtractor.relaxMM(params, relaxedMM); suggestion.setRelaxedQuery(relaxedQuery); suggestions.add(suggestion); } return suggestions; } else { Set<RelaxerSuggestion> suggestions = new LinkedHashSet<RelaxerSuggestion>(); for (int i = 0; i < clauses.size(); i++) { Clause clauseToRemove = clauses.get(i); boolean multipleTokenClause = clauseToRemove.getTokens() != null && clauseToRemove.getTokens().length > 1; String text = clauseToRemove.getRaw(); if ("NOT".equals(text) || "AND".equals(text) || "OR".equals(text)) { continue; } StringBuilder before = new StringBuilder(); StringBuilder after = new StringBuilder(); for (int j = 0; j < i - 1; j++) { before.append(clauses.get(j).getRaw()); before.append(" "); } if (i >= 1) { String raw = clauses.get(i - 1).getRaw(); if (multipleTokenClause || (!"NOT".equals(raw) && !"AND".equals(raw) && !"OR".equals(raw))) { before.append(raw); before.append(" "); } } if (i < clauses.size() - 1) { String raw = clauses.get(i + 1).getRaw(); if (multipleTokenClause || (!"AND".equals(raw) && !"OR".equals(raw))) { after.append(raw); after.append(" "); } } for (int j = i + 2; j < clauses.size(); j++) { after.append(clauses.get(j).getRaw()); after.append(" "); } if (multipleTokenClause) { for (int k = 0; k < clauseToRemove.getTokens().length; k++ ) { StringBuilder sug = new StringBuilder(before.toString()); if (clauseToRemove.getMust() == '+' || clauseToRemove.getMust() == '-') { sug.append(clauseToRemove.getMust()); } if (clauseToRemove.getField() != null) { sug.append(clauseToRemove.getField()); sug.append(":"); } for (int t = 0; t < clauseToRemove.getTokens().length; t++) { if (t != k) { sug.append(clauseToRemove.getTokens()[t]); } } sug.append(" "); sug.append(after.toString()); String relaxedUserQuery = sug.toString().trim(); String relaxedQuery = userQueryExtractor.relaxQuery(params, userQuery, relaxedUserQuery); QueryRelaxerSuggestion suggestion = new QueryRelaxerSuggestion(relaxedQuery, userQuery, relaxedUserQuery); if (highlightQuery != null) { String relaxedHighlightQuery = userQueryExtractor.relaxHighlightQuery(highlightQuery, params, highlightQuery, relaxedUserQuery); suggestion.setRelaxedHighlightQuery(relaxedHighlightQuery); } suggestions.add(suggestion); } } else { String relaxedUserQuery = before.append(after.toString()).toString().trim(); String relaxedQuery = userQueryExtractor.relaxQuery(params, userQuery, relaxedUserQuery); QueryRelaxerSuggestion suggestion = new QueryRelaxerSuggestion(relaxedQuery, userQuery, relaxedUserQuery); if (highlightQuery != null) { String relaxedHighlightQuery = userQueryExtractor.relaxHighlightQuery(highlightQuery, params, highlightQuery, relaxedUserQuery); suggestion.setRelaxedHighlightQuery(relaxedHighlightQuery); } suggestions.add(suggestion); } } return suggestions; } } private int clauseLength(List<Clause> clauses) { int length = 0; for(Clause clause : clauses) { if (clause.getTokens() == null || clause.isPhrase() ) { length++; } else { length += clause.getTokens().length; } } return length; } @Override public void setFieldAnalyzerMaps(Map<Pattern, Analyzer> fieldAnalyzerMaps) { super.setFieldAnalyzerMaps(fieldAnalyzerMaps); this.queryConverter.setFieldAnalyzerMaps(fieldAnalyzerMaps); } }
package org.kohsuke.stapler; import junit.framework.TestCase; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import javax.servlet.ServletException; import java.util.Collections; import java.util.List; /** * Tests the instantiation of nested objects. * * @author Kohsuke Kawaguchi */ public class NestedJsonTest extends TestCase { public static final class Foo { public Bar bar; // we test this with manual .stapler file // @DataBoundConstructor public Foo(Bar bar) { this.bar = bar; } } public static interface Bar {} public static final class BarImpl implements Bar { public final int i; // we test this with manual .stapler file // @DataBoundConstructor public BarImpl(int i) { this.i = i; } } public void testCreateObject() throws Exception { Foo o = createRequest().bindJSON(Foo.class, createDataSet()); assertNotNull(o); assertTrue(o.bar instanceof BarImpl); assertEquals(123, ((BarImpl)o.bar).i); } public void testInstanceFill() throws Exception { Foo o = new Foo(null); createRequest().bindJSON(o, createDataSet()); assertTrue(o.bar instanceof BarImpl); assertEquals(123, ((BarImpl)o.bar).i); } public void testCreateList() throws Exception { // Just one List<Foo> list = createRequest().bindJSONToList(Foo.class, createDataSet()); assertNotNull(list); assertEquals(1, list.size()); assertTrue(list.get(0).bar instanceof BarImpl); assertEquals(123, ((BarImpl)list.get(0).bar).i); // Longer list JSONArray data = new JSONArray(); data.add(createDataSet()); data.add(createDataSet()); data.add(createDataSet()); list = createRequest().bindJSONToList(Foo.class, data); assertNotNull(list); assertEquals(3, list.size()); assertEquals(123, ((BarImpl)list.get(2).bar).i); } private RequestImpl createRequest() throws Exception { return new RequestImpl(createStapler(), new MockRequest(), Collections.EMPTY_LIST,null); } private JSONObject createDataSet() { JSONObject bar = new JSONObject(); bar.put("i",123); JSONObject foo = new JSONObject(); foo.put("bar",bar); foo.getJSONObject("bar").put("stapler-class", BarImpl.class.getName()); return foo; } private Stapler createStapler() throws ServletException { Stapler stapler = new Stapler(); stapler.init(new ServletConfigImpl()); return stapler; } }
package org.sbolstandard.core2; import static org.sbolstandard.core.datatree.Datatree.NamedProperties; import static org.sbolstandard.core.datatree.Datatree.NamedProperty; import static org.sbolstandard.core.datatree.Datatree.NestedDocument; import java.net.URI; import java.util.ArrayList; import java.util.List; import javax.xml.namespace.QName; import org.sbolstandard.core.datatree.Literal.BooleanLiteral; import org.sbolstandard.core.datatree.Literal.DoubleLiteral; import org.sbolstandard.core.datatree.Literal.IntegerLiteral; import org.sbolstandard.core.datatree.Literal.StringLiteral; import org.sbolstandard.core.datatree.Literal.UriLiteral; import org.sbolstandard.core.datatree.NamedProperty; import org.sbolstandard.core.datatree.NestedDocument; /** * Represents an Annotation object in the cSBOL data model. * * @author Zhen Zhang * @author Matthew Pocock * @author Goksel Misirli * @author Chris Myers * @version 2.1 */ public class Annotation implements Comparable<Annotation> { //private NamedProperty<QName> value; private String namespaceURI = null; private String localPart = null; private String prefix = null; private String type = null; private Boolean boolValue = null; private Double doubleValue = null; private Integer intValue = null; private String stringValue = null; private URI URIValue = null; private String nestedNamespaceURI = null; private String nestedLocalPart = null; private String nestedPrefix = null; private URI nestedURI = null; private List<Annotation> nestedAnnotations = null; /** * Constructs an annotation using the given qName and the string type literal. * * @param qName the QName of this annotation * @param literal a string type value * @throws SBOLValidationException if any of the following SBOL validation rules was violated: * 12201, 12203 */ public Annotation(QName qName, String literal) throws SBOLValidationException { setQName(qName); setStringValue(literal); } /** * Constructs an annotation using the given qName and the integer type literal. * * @param qName the QName of this annotation * @param literal an integer type value * @throws SBOLValidationException if any of the following SBOL validation rules was violated: * 12201, 12203 */ public Annotation(QName qName, int literal) throws SBOLValidationException { setQName(qName); setIntegerValue(literal); } /** * Constructs an annotation using the given qName and the double type literal. * * @param qName the QName of this annotation * @param literal a double type value * @throws SBOLValidationException if any of the following SBOL validation rules was violated: * 12201, 12203 */ public Annotation(QName qName, double literal) throws SBOLValidationException { setQName(qName); setDoubleValue(literal); } /** * Constructs an annotation using the given qName and the boolean type literal. * * @param qName the QName of this annotation * @param literal a boolean type value * @throws SBOLValidationException if any of the following SBOL validation rules was violated: * 12201, 12203 */ public Annotation(QName qName, boolean literal) throws SBOLValidationException { setQName(qName); setBooleanValue(literal); } /** * Constructs an annotation using the given qName and the {@code URI} type literal. * * @param qName the QName of this annotation * @param literal a URI type value * @throws SBOLValidationException if any of the following SBOL validation rules was violated: * 12201, 12203 */ public Annotation(QName qName, URI literal) throws SBOLValidationException { setQName(qName); setURIValue(literal); } /** * Constructs a nested annotation using the given qName, nested qName, * nested URI, and list of annotations. * * @param qName the QName of this annotation * @param nestedQName the QName of the nested annotation * @param nestedURI the identity URI for the nested annotation * @param annotations the list of annotations to construct the nested annotation * @throws SBOLValidationException if any of the following SBOL validation rules was violated: * 12201, 12203, 12204, 12205, 12206 */ Annotation(QName qName, QName nestedQName, URI nestedURI, List<Annotation> annotations) throws SBOLValidationException { setQName(qName); setNestedQName(nestedQName); setNestedIdentity(nestedURI); setAnnotations(annotations); } /** * Creates an annotation with nested annotations using the given arguments, and then adds to this instance's list of annotations. * * @param qName the QName of the annotation to be created * @param nestedQName the QName of the nested annotation * @param nestedId the id for the nested annotation * @param annotations the list of annotations used to construct the nested annotation * @return the created annotation * @throws SBOLValidationException if any of the following SBOL validation rules was violated: * 10401, 10501, 10701, 10801, 10901, 11101, 11201, 11301, 11401, 11501, 11601, 11701, 11801, 11901, 12001, 12101, 12301. */ public Annotation createAnnotation(QName qName,QName nestedQName, String nestedId, List<Annotation> annotations) throws SBOLValidationException { if (isNestedAnnotations() && nestedURI != null) { URI nestednestedURI = URIcompliance.createCompliantURI(URIcompliance.extractPersistentId(nestedURI), TopLevel.ANNOTATION, nestedId, URIcompliance.extractVersion(nestedURI), false); Annotation annotation = new Annotation(qName, nestedQName, nestednestedURI, annotations); nestedAnnotations.add(annotation); return annotation; } else { // TODO: perhaps not the best error message throw new SBOLValidationException("sbol-12205"); } } Annotation(NamedProperty<QName> value) throws SBOLValidationException { if (value.getName().getNamespaceURI().equals(Sbol2Terms.sbol2.getNamespaceURI()) || value.getName().getNamespaceURI().equals(Sbol1Terms.sbol1.getNamespaceURI())) { if (value.getName().equals(Sbol2Terms.Identified.timeStamp)) { System.err.println("Warning: sbol:timeStamp is deprecated"); } } setQName(value.getName()); if ((value.getValue() instanceof BooleanLiteral<?>)) { setBooleanValue(((BooleanLiteral<QName>) value.getValue()).getValue()); } else if ((value.getValue() instanceof DoubleLiteral<?>)) { setDoubleValue(((DoubleLiteral<QName>) value.getValue()).getValue()); } else if ((value.getValue() instanceof IntegerLiteral<?>)) { setIntegerValue(((IntegerLiteral<QName>) value.getValue()).getValue()); } else if ((value.getValue() instanceof StringLiteral<?>)) { setStringValue(((StringLiteral<QName>) value.getValue()).getValue()); } else if ((value.getValue() instanceof UriLiteral<?>)) { setURIValue(((UriLiteral<QName>) value.getValue()).getValue()); } else if (value.getValue() instanceof NestedDocument<?>) { setNestedQName(((NestedDocument<QName>) value.getValue()).getType()); setNestedIdentity(((NestedDocument<QName>) value.getValue()).getIdentity()); List<Annotation> annotations = new ArrayList<>(); for (NamedProperty<QName> namedProperty : ((NestedDocument<QName>) value.getValue()).getProperties()) { annotations.add(new Annotation(namedProperty)); } setAnnotations(annotations); } else { throw new SBOLValidationException("sbol-12203"); } } private Annotation(Annotation annotation) throws SBOLValidationException { setQName(annotation.getQName()); if (annotation.isBooleanValue()) { setBooleanValue(annotation.getBooleanValue()); } else if (annotation.isDoubleValue()) { setDoubleValue(annotation.getDoubleValue()); } else if (annotation.isIntegerValue()) { setIntegerValue(annotation.getIntegerValue()); } else if (annotation.isStringValue()) { setStringValue(annotation.getStringValue()); } else if (annotation.isURIValue()) { setURIValue(annotation.getURIValue()); } else if (annotation.isNestedAnnotations()) { setNestedQName(annotation.getNestedQName()); setNestedIdentity(annotation.getNestedIdentity()); setAnnotations(annotation.getAnnotations()); } else { throw new SBOLValidationException("sbol-12203"); } } @Override public int compareTo(Annotation annotation) { int result = this.getQName().getNamespaceURI().compareTo(annotation.getQName().getNamespaceURI()); if (result==0) { result = this.getQName().getLocalPart().compareTo(annotation.getQName().getLocalPart()); } if (result==0) { result = this.hashCode() - annotation.hashCode(); } return result; } /** * Returns the QName of this Annotation instance. * * @return the QName of this Annotation instance */ public QName getQName() { return new QName(namespaceURI, localPart, prefix); } /** * Sets the QName of this annotation. * @param qName the QName for this annotation. * @throws SBOLValidationException if any of the following SBOL validation rules was violated: * 12201 */ public void setQName(QName qName) throws SBOLValidationException { if (qName==null) { throw new SBOLValidationException("sbol-12201"); } namespaceURI = qName.getNamespaceURI(); localPart = qName.getLocalPart(); prefix = qName.getPrefix(); } /** * Sets the boolean representation of the value property. * @param literal the boolean representation of the value property */ public void setBooleanValue(boolean literal) { type = "Boolean"; boolValue = literal; } /** * Checks if the annotation has a boolean value property. * * @return {@code true} if the value property is a boolean, {@code false} otherwise. */ public boolean isBooleanValue() { if (type.equals("Boolean")) { return true; } return false; } /** * Returns a Boolean representation of the value property. * * @return a Boolean representation of the value property if its * value is a Boolean, {@code null} otherwise. */ public Boolean getBooleanValue() { if (isBooleanValue()) { return boolValue; } return null; } /** * Sets the double representation of the value property. * @param literal the double representation of the value property */ public void setDoubleValue(double literal) { type = "Double"; doubleValue = literal; } /** * Checks if the annotation has a double value property. * * @return true if the value property is a double integer, {@code false} otherwise */ public boolean isDoubleValue() { if (type.equals("Double")) { return true; } return false; } /** * Returns a Double representation of the value property. * * @return a Double integer representation of the value property if its * value is a Double integer, {@code null} otherwise. */ public Double getDoubleValue() { if (isDoubleValue()) { return doubleValue; } return null; } /** * Sets the integer representation of the value property. * @param literal the integer representation of the value property */ public void setIntegerValue(int literal) { type = "Integer"; intValue = literal; } /** * Checks if the annotation has an integer value property. * * @return {@code true} if the value property is an integer, {@code false} otherwise */ public boolean isIntegerValue() { if (type.equals("Integer")) { return true; } return false; } /** * Returns an Integer representation of the value property. * * @return an Integer representation of the value property if its * value is an Integer, {@code null} otherwise. */ public Integer getIntegerValue() { if (isIntegerValue()) { return intValue; } return null; } /** * Sets the string representation of the value property. * @param literal the string representation of the value property * @throws SBOLValidationException if any of the following SBOL validation rules was violated: * 12203 */ public void setStringValue(String literal) throws SBOLValidationException { if (literal==null) { throw new SBOLValidationException("sbol-12203"); } type = "String"; stringValue = literal; } /** * Checks if the annotation has a string value property. * * @return true if the value property is string type, {@code false} otherwise */ public boolean isStringValue() { if (type.equals("String")) { return true; } return false; } /** * Returns a string representation of the value property. * * @return a string representation of the value property if it is a string, * {@code null} otherwise. */ public String getStringValue() { if (isStringValue()) { return stringValue; } return null; } /** * Sets the string representation of the value property. * @param literal the URI representation of the value property * @throws SBOLValidationException if any of the following SBOL validation rules was violated: * 12203 */ public void setURIValue(URI literal) throws SBOLValidationException { if (literal==null) { throw new SBOLValidationException("sbol-12203"); } type = "URI"; URIValue = literal; } /** * Checks if the annotation is a URI {@code value} property. * * @return true if the annotation is a URI {@code value} property. */ public boolean isURIValue() { if (type.equals("URI")) { return true; } return false; } /** * Returns a URI representation of the value property. * * @return a URI representation of the value property if it is a URI, * {@code null} otherwise. */ public URI getURIValue() { if (isURIValue()) { return URIValue; } return null; } /** * Sets the nested QName for this annotation. * * @param qName the nested QName for this annotation. * @throws SBOLValidationException if any of the following SBOL validation rules was violated: * 12204 */ public void setNestedQName(QName qName) throws SBOLValidationException { if (qName==null) { throw new SBOLValidationException("sbol-12204"); } nestedNamespaceURI = qName.getNamespaceURI(); nestedLocalPart = qName.getLocalPart(); nestedPrefix = qName.getPrefix(); } /** * Returns the nested QName of the nested Annotation. * * @return the nested QName if its value is nested Annotations, {@code null} otherwise. */ public QName getNestedQName() { if (isNestedAnnotations()) { return new QName(nestedNamespaceURI,nestedLocalPart,nestedPrefix); } return null; } /** * Returns the nested identity URI of the nested Annotation. * * @return the nested identity URI of the nested nested Annotations if its value is nested Annotations, {@code null} otherwise. */ public URI getNestedIdentity() { if (isNestedAnnotations()) { return nestedURI; } return null; } /** * Sets the nested URI for this annotation. * * @param uri the nested uri for this annotation. * @throws SBOLValidationException if any of the following SBOL validation rules was violated: * 12205 */ public void setNestedIdentity(URI uri) throws SBOLValidationException { if (uri==null) { throw new SBOLValidationException("sbol-12205"); } nestedURI = uri; } /** * Checks if the annotation has a nested value property. * * @return true if the value property is nested Annotations, {@code false} otherwise */ public boolean isNestedAnnotations() { if (type.equals("NestedAnnotation")) { return true; } return false; } /** * Sets the list of Annotations of the nested value property. * * @param annotations the list of Annotations for the nested value property. * @throws SBOLValidationException if any of the following SBOL validation rules was violated: * 12206 */ public void setAnnotations(List<Annotation> annotations) throws SBOLValidationException { if (annotations==null) { throw new SBOLValidationException("sbol-12206"); } type = "NestedAnnotation"; nestedAnnotations = new ArrayList<>(); for(Annotation a : annotations) { nestedAnnotations.add(a); } } /** * Returns the list of Annotations of the nested value property. * * @return the list of Annotations if its value is nested Annotations, {@code null} otherwise. */ public List<Annotation> getAnnotations() { if (isNestedAnnotations()) { return nestedAnnotations; } return null; } /** * Returns the value of this Annotation instance. * * @return the value of this Annotation instance. */ NamedProperty<QName> getValue() { if (isBooleanValue()) { return NamedProperty(getQName(),getBooleanValue()); } else if (isDoubleValue()) { return NamedProperty(getQName(),getDoubleValue()); } else if (isIntegerValue()) { return NamedProperty(getQName(),getIntegerValue()); } else if (isStringValue()) { return NamedProperty(getQName(),getStringValue()); } else if (isURIValue()) { return NamedProperty(getQName(),getURIValue()); } else if (isNestedAnnotations()) { List<NamedProperty<QName>> list = new ArrayList<>(); for(Annotation a : getAnnotations()) { list.add(a.getValue()); } return NamedProperty(getQName(), NestedDocument(getNestedQName(), getNestedIdentity(), NamedProperties(list))); } return null; } /** * Makes a deep copy of this Annotation instance. * @return an Annotation instance that is the exact copy of this instance. * @throws SBOLValidationException if any of the following SBOL validation rules was violated: * 12201, 12203, 12204, 12205, 12206 */ private Annotation deepCopy() throws SBOLValidationException { return new Annotation(this); } /** * Makes a deep copy of this Annotation instance. * @return an Annotation instance that is the exact copy of this instance. * @throws SBOLValidationException if any of the following SBOL validation rules was violated: * 12201, 12203, 12204, 12205, 12206 */ Annotation copy() throws SBOLValidationException { return this.deepCopy(); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((URIValue == null) ? 0 : URIValue.hashCode()); result = prime * result + ((boolValue == null) ? 0 : boolValue.hashCode()); result = prime * result + ((doubleValue == null) ? 0 : doubleValue.hashCode()); result = prime * result + ((intValue == null) ? 0 : intValue.hashCode()); result = prime * result + ((stringValue == null) ? 0 : stringValue.hashCode()); result = prime * result + ((localPart == null) ? 0 : localPart.hashCode()); result = prime * result + ((namespaceURI == null) ? 0 : namespaceURI.hashCode()); result = prime * result + ((nestedAnnotations == null) ? 0 : nestedAnnotations.hashCode()); result = prime * result + ((nestedLocalPart == null) ? 0 : nestedLocalPart.hashCode()); result = prime * result + ((nestedNamespaceURI == null) ? 0 : nestedNamespaceURI.hashCode()); // TODO: removed, not needed to be equal //result = prime * result + ((nestedPrefix == null) ? 0 : nestedPrefix.hashCode()); result = prime * result + ((nestedURI == null) ? 0 : nestedURI.hashCode()); // TODO: removed, not needed to be equal //result = prime * result + ((prefix == null) ? 0 : prefix.hashCode()); result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Annotation other = (Annotation) obj; if (URIValue == null) { if (other.URIValue != null) return false; } else if (!URIValue.equals(other.URIValue)) return false; if (boolValue == null) { if (other.boolValue != null) return false; } else if (!boolValue.equals(other.boolValue)) return false; if (doubleValue == null) { if (other.doubleValue != null) return false; } else if (!doubleValue.equals(other.doubleValue)) return false; if (intValue == null) { if (other.intValue != null) return false; } else if (!intValue.equals(other.intValue)) return false; if (localPart == null) { if (other.localPart != null) return false; } else if (!localPart.equals(other.localPart)) return false; if (namespaceURI == null) { if (other.namespaceURI != null) return false; } else if (!namespaceURI.equals(other.namespaceURI)) return false; if (nestedAnnotations == null) { if (other.nestedAnnotations != null) return false; } else if (!nestedAnnotations.containsAll(other.nestedAnnotations)) return false; if (nestedLocalPart == null) { if (other.nestedLocalPart != null) return false; } else if (!nestedLocalPart.equals(other.nestedLocalPart)) return false; if (nestedNamespaceURI == null) { if (other.nestedNamespaceURI != null) return false; } else if (!nestedNamespaceURI.equals(other.nestedNamespaceURI)) return false; // TODO: removed since do not need to be equal /* if (nestedPrefix == null) { if (other.nestedPrefix != null) return false; } else if (!nestedPrefix.equals(other.nestedPrefix)) return false; */ if (nestedURI == null) { if (other.nestedURI != null) return false; } else if (!nestedURI.equals(other.nestedURI)) return false; // TODO: removed since do not need to be equal /* if (prefix == null) { if (other.prefix != null) return false; } else if (!prefix.equals(other.prefix)) return false; */ if (stringValue == null) { if (other.stringValue != null) return false; } else if (!stringValue.equals(other.stringValue)) return false; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; return true; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "Annotation [(" + prefix + ":" + namespaceURI + ":" + localPart + ")" + ", type=" + type + ", value=" + (isBooleanValue()?boolValue:"") + (isDoubleValue()?doubleValue:"") + (isIntegerValue()?intValue:"") + (isStringValue()?stringValue:"") + (isURIValue()?URIValue:"") + (isNestedAnnotations()?("("+nestedPrefix+":"+nestedNamespaceURI+":"+nestedLocalPart+":"+ nestedURI + ")" + nestedAnnotations.toString()):"") + "]"; } }
package com.commercetools.pspadapter.payone.mapping; import com.commercetools.pspadapter.payone.config.PayoneConfig; import com.commercetools.pspadapter.payone.domain.ctp.PaymentWithCartLike; import com.commercetools.pspadapter.payone.domain.payone.model.common.CaptureRequest; import com.commercetools.pspadapter.payone.domain.payone.model.common.RequestType; import com.commercetools.pspadapter.payone.domain.payone.model.paymentinadvance.BankTransferInAdvanceCaptureRequest; import com.commercetools.pspadapter.payone.domain.payone.model.paymentinadvance.BankTransferInAdvanceRequest; import com.commercetools.pspadapter.tenant.TenantConfig; import com.google.common.base.Preconditions; import io.sphere.sdk.payments.Payment; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; import java.util.Optional; import java.util.function.BiFunction; import static com.commercetools.pspadapter.payone.domain.ctp.paymentmethods.PaymentMethod.BANK_TRANSFER_ADVANCE; import static org.javamoney.moneta.function.MonetaryQueries.convertMinorPart; /** * @author mht@dotsource.de */ public class BankTransferInAdvanceRequestFactory extends PayoneRequestFactory { private Logger LOG = LoggerFactory.getLogger(BankTransferInAdvanceRequestFactory.class); public BankTransferInAdvanceRequestFactory(@Nonnull final TenantConfig tenantConfig) { super(tenantConfig); } @Nonnull @Override public BankTransferInAdvanceRequest createPreauthorizationRequest(@Nonnull PaymentWithCartLike paymentWithCartLike) { return createRequestInternal(RequestType.PREAUTHORIZATION, paymentWithCartLike, BankTransferInAdvanceRequest::new); } /** * <b>NOTE:</b> this is a potentially dangerous transaction type for this payment method. See more in * {@link com.commercetools.pspadapter.payone.transaction.paymentinadvance.BankTransferInAdvanceChargeTransactionExecutor BankTransferInAdvanceChargeTransactionExecutor} * @see com.commercetools.pspadapter.payone.transaction.paymentinadvance.BankTransferInAdvanceChargeTransactionExecutor */ @Nonnull @Override public BankTransferInAdvanceRequest createAuthorizationRequest(@Nonnull PaymentWithCartLike paymentWithCartLike) { LOG.warn("Unsupported transaction type \"{}\" for payment method \"\".\n" + "\t\tNote: this payment/transaction type officially isn't supported by Payone " + "and thus the behavior of such transaction handling is undefined.\n" + "Either change the transaction type or update the service if the Payone API has changed.", RequestType.AUTHORIZATION, BANK_TRANSFER_ADVANCE.getKey()); return createRequestInternal(RequestType.AUTHORIZATION, paymentWithCartLike, BankTransferInAdvanceRequest::new); } @Nonnull public BankTransferInAdvanceRequest createRequestInternal( @Nonnull final RequestType requestType, @Nonnull final PaymentWithCartLike paymentWithCartLike, @Nonnull final BiFunction<RequestType, PayoneConfig, BankTransferInAdvanceRequest> requestConstructor) { final Payment ctPayment = paymentWithCartLike.getPayment(); Preconditions.checkArgument(ctPayment.getCustom() != null, "Missing custom fields on payment!"); BankTransferInAdvanceRequest request = requestConstructor.apply(requestType, getPayoneConfig()); mapFormPaymentWithCartLike(request, paymentWithCartLike); return request; } @Override public CaptureRequest createCaptureRequest(final PaymentWithCartLike paymentWithCartLike, final int sequenceNumber) { final Payment ctPayment = paymentWithCartLike.getPayment(); CaptureRequest request = new BankTransferInAdvanceCaptureRequest(getPayoneConfig()); request.setTxid(ctPayment.getInterfaceId()); request.setSequencenumber(sequenceNumber); Optional.ofNullable(ctPayment.getAmountPlanned()) .ifPresent(amount -> { request.setCurrency(amount.getCurrency().getCurrencyCode()); request.setAmount(convertMinorPart() .queryFrom(amount) .intValue()); }); return request; } }
package org.sagebionetworks.file.worker; import java.sql.Timestamp; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.stream.Collectors; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.Trigger; import org.quartz.TriggerKey; import org.sagebionetworks.StackConfiguration; import org.sagebionetworks.aws.SynapseS3Client; import org.sagebionetworks.repo.manager.UserManager; import org.sagebionetworks.repo.model.AccessRequirementDAO; import org.sagebionetworks.repo.model.AuthorizationConstants.BOOTSTRAP_PRINCIPAL; import org.sagebionetworks.repo.model.ManagedACTAccessRequirement; import org.sagebionetworks.repo.model.UserInfo; import org.sagebionetworks.repo.model.athena.AthenaQueryResult; import org.sagebionetworks.repo.model.athena.AthenaSupport; import org.sagebionetworks.repo.model.dao.FileHandleStatus; import org.sagebionetworks.repo.model.dbo.FileMetadataUtils; import org.sagebionetworks.repo.model.dbo.dao.TestUtils; import org.sagebionetworks.repo.model.dbo.dao.files.FilesScannerStatusDao; import org.sagebionetworks.repo.model.dbo.file.FileHandleDao; import org.sagebionetworks.repo.model.dbo.persistence.DBOFileHandle; import org.sagebionetworks.repo.model.file.FileHandle; import org.sagebionetworks.repo.model.helper.DaoObjectHelper; import org.sagebionetworks.util.Pair; import org.sagebionetworks.util.TimeUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import com.amazonaws.services.glue.model.Database; import com.amazonaws.services.glue.model.Table; import com.amazonaws.services.s3.model.DeleteObjectsRequest; import com.amazonaws.services.s3.model.DeleteObjectsRequest.KeyVersion; import com.amazonaws.services.s3.model.ListObjectsRequest; import com.amazonaws.services.s3.model.ObjectListing; import com.amazonaws.services.stepfunctions.AWSStepFunctions; import com.amazonaws.services.stepfunctions.model.DescribeExecutionRequest; import com.amazonaws.services.stepfunctions.model.ExecutionStatus; import com.amazonaws.services.stepfunctions.model.ListStateMachinesRequest; import com.amazonaws.services.stepfunctions.model.ListStateMachinesResult; import com.amazonaws.services.stepfunctions.model.StartExecutionRequest; import com.amazonaws.services.stepfunctions.model.StateMachineListItem; @ExtendWith(SpringExtension.class) @ContextConfiguration(locations = { "classpath:test-context.xml" }) public class FileHandleUnlinkedQueryIntegrationTest { private static final Logger LOG = LogManager.getLogger(FileHandleUnlinkedQueryIntegrationTest.class); private static final long TIMEOUT = 3 * 60 * 1000; @Autowired private FilesScannerStatusDao scannerDao; @Autowired private FileHandleDao fileHandleDao; @Autowired private UserManager userManager; @Autowired private DaoObjectHelper<ManagedACTAccessRequirement> managedHelper; @Autowired private AccessRequirementDAO arDao; @Autowired private Scheduler scheduler; @Autowired private AWSStepFunctions stepFunctionsClient; @Autowired private StackConfiguration config; @Autowired private AthenaSupport athenaSupport; @Autowired private SynapseS3Client s3Client; private UserInfo user; private Trigger dispatcherTrigger; private String stack; private String instance; @BeforeEach public void before() throws SchedulerException { user = userManager.getUserInfo(BOOTSTRAP_PRINCIPAL.THE_ADMIN_USER.getPrincipalId()); arDao.clear(); fileHandleDao.truncateTable(); scannerDao.truncateAll(); dispatcherTrigger = scheduler.getTrigger(new TriggerKey("fileHandleAssociationScanDispatcherWorkerTrigger")); stack = config.getStack(); instance = config.getStackInstance(); cleanOldData("fileHandleData/"); cleanOldData("fileHandleAssociations/"); } @AfterEach public void afterEach() { arDao.clear(); fileHandleDao.truncateTable(); scannerDao.truncateAll(); } private void cleanOldData(String prefix) { ObjectListing list; String marker = null; String bucketName = config.getStack() + ".filehandles.sagebase.org"; Date recent = Date.from(Instant.now().minus(10, ChronoUnit.HOURS)); do { ListObjectsRequest request = new ListObjectsRequest() .withBucketName(bucketName) .withPrefix(prefix) .withMarker(marker); list = s3Client.listObjects(request); List<KeyVersion> keys = list.getObjectSummaries().stream().filter(obj -> obj.getLastModified().before(recent)).map( obj -> new KeyVersion(obj.getKey())).collect(Collectors.toList()); if (!keys.isEmpty()) { s3Client.deleteObjects(new DeleteObjectsRequest(bucketName).withKeys(keys)); } marker = list.getNextMarker(); } while(list.isTruncated()); } @Test public void testRoundTrip() throws Exception { // Makes sure to create "old" file handles Timestamp createdOn = Timestamp.from(Instant.now().minus(60, ChronoUnit.DAYS)); // Generate an high random number to avoid issues with different users Long startId = 1_000_000L + config.getStackInstanceNumber() + new Random().nextInt(100_000); DBOFileHandle linkedHandle = FileMetadataUtils.createDBOFromDTO(TestUtils.createS3FileHandle(user.getId().toString(), (++startId).toString())); DBOFileHandle unlinkedHandle = FileMetadataUtils.createDBOFromDTO(TestUtils.createS3FileHandle(user.getId().toString(), (++startId).toString())); linkedHandle.setCreatedOn(createdOn); linkedHandle.setUpdatedOn(createdOn); unlinkedHandle.setCreatedOn(createdOn); unlinkedHandle.setUpdatedOn(createdOn); fileHandleDao.createBatchDbo(Arrays.asList(linkedHandle, unlinkedHandle)); // We create at least one association so that we are sure one job need to run at least managedHelper.create(ar-> { ar.setCreatedBy(user.getId().toString()); ar.setSubjectIds(Collections.emptyList()); ar.setDucTemplateFileHandleId(linkedHandle.getId().toString()); }); // Manually trigger the job for the scanner since the start time is very long scheduler.triggerJob(dispatcherTrigger.getJobKey(), dispatcherTrigger.getJobDataMap()); // We wait for the ids to end up in the right glue tables, using athena itself to check waitForKinesisData(Arrays.asList(linkedHandle.getId(), unlinkedHandle.getId()), "fileHandleDataRecords", "id"); waitForKinesisData(Arrays.asList(linkedHandle.getId()), "fileHandleAssociationsRecords", "filehandleid"); String stateMachineArn = findStateMachineArn("UnlinkedFileHandles"); String executionArn = stepFunctionsClient.startExecution(new StartExecutionRequest().withStateMachineArn(stateMachineArn)).getExecutionArn(); TimeUtils.waitFor(TIMEOUT, 1000L, () -> { ExecutionStatus status = ExecutionStatus.valueOf(stepFunctionsClient.describeExecution(new DescribeExecutionRequest().withExecutionArn(executionArn)).getStatus()); switch (status) { case FAILED: case ABORTED: case TIMED_OUT: throw new IllegalStateException("The execution " + executionArn + " failed: " + status); case RUNNING: return new Pair<>(false, null); default: break; } List<FileHandle> linked = fileHandleDao.getFileHandlesBatchByStatus(Arrays.asList(linkedHandle.getId()), FileHandleStatus.AVAILABLE); List<FileHandle> unlinked = fileHandleDao.getFileHandlesBatchByStatus(Arrays.asList(unlinkedHandle.getId()), FileHandleStatus.UNLINKED); return new Pair<>(linked.size() == 1 && unlinked.size() == 1, null); }); } private void waitForKinesisData(List<Long> ids, String tableName, String idColumn) throws Exception { Database dataBase = athenaSupport.getDatabase("firehoseLogs"); Table fileHandleDataTable = athenaSupport.getTable(dataBase, tableName); String query = "SELECT COUNT(*) FROM " + fileHandleDataTable.getName() + " WHERE " + idColumn + " IN (" + String.join(",", ids.stream().map(id -> id.toString()).collect(Collectors.toList())) + ")"; LOG.info("Executing query {}...", query); TimeUtils.waitFor(TIMEOUT, 5000L, () -> { AthenaQueryResult<Long> q = athenaSupport.executeQuery(dataBase, query, (row) -> { return Long.valueOf(row.getData().get(0).getVarCharValue()); }); Iterator<Long> it = q.getQueryResultsIterator(); Long count = 0L; if (it.hasNext()) { count = q.getQueryResultsIterator().next(); } else { throw new IllegalStateException("No results from Athena, expected 1"); } LOG.info("Executing query {}...DONE (Count: {})", query, count); return new Pair<>(count >= ids.size(), null); }); } private String findStateMachineArn(String name) { ListStateMachinesResult result; String nextPageToken = null; do { result = stepFunctionsClient.listStateMachines(new ListStateMachinesRequest().withMaxResults(10).withNextToken(nextPageToken)); for (StateMachineListItem stateMachine : result.getStateMachines()) { if (stateMachine.getName().toLowerCase().contains((stack + instance + name).toLowerCase())) { LOG.info("Found state machine with name: {} , ARN: {}", stateMachine.getName(), stateMachine.getStateMachineArn()); return stateMachine.getStateMachineArn(); } } nextPageToken = result.getNextToken(); } while (nextPageToken != null); throw new IllegalArgumentException("The state machine named " + name + " could not be found"); } }
package org.sagebionetworks.table.worker; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.LinkedList; import java.util.List; import java.util.UUID; import org.junit.After; import org.junit.Assume; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.sagebionetworks.StackConfiguration; import org.sagebionetworks.ids.IdGenerator; import org.sagebionetworks.ids.IdGenerator.TYPE; import org.sagebionetworks.repo.manager.EntityManager; import org.sagebionetworks.repo.manager.SemaphoreManager; import org.sagebionetworks.repo.manager.UserManager; import org.sagebionetworks.repo.manager.asynch.AsynchJobStatusManager; import org.sagebionetworks.repo.manager.table.ColumnModelManager; import org.sagebionetworks.repo.manager.table.TableEntityManager; import org.sagebionetworks.repo.model.AuthorizationConstants.BOOTSTRAP_PRINCIPAL; import org.sagebionetworks.repo.model.DatastoreException; import org.sagebionetworks.repo.model.InvalidModelException; import org.sagebionetworks.repo.model.Project; import org.sagebionetworks.repo.model.UnauthorizedException; import org.sagebionetworks.repo.model.UserInfo; import org.sagebionetworks.repo.model.asynch.AsynchJobState; import org.sagebionetworks.repo.model.asynch.AsynchronousJobStatus; import org.sagebionetworks.repo.model.dao.FileHandleDao; import org.sagebionetworks.repo.model.file.S3FileHandle; import org.sagebionetworks.repo.model.table.ColumnModel; import org.sagebionetworks.repo.model.table.ColumnType; import org.sagebionetworks.repo.model.table.CsvTableDescriptor; import org.sagebionetworks.repo.model.table.DownloadFromTableRequest; import org.sagebionetworks.repo.model.table.DownloadFromTableResult; import org.sagebionetworks.repo.model.table.RowReferenceSet; import org.sagebionetworks.repo.model.table.TableEntity; import org.sagebionetworks.repo.model.table.TableRowChange; import org.sagebionetworks.repo.model.table.TableUpdateRequest; import org.sagebionetworks.repo.model.table.TableUpdateTransactionRequest; import org.sagebionetworks.repo.model.table.TableUpdateTransactionResponse; import org.sagebionetworks.repo.model.table.UploadToTableRequest; import org.sagebionetworks.repo.model.table.UploadToTableResult; import org.sagebionetworks.repo.web.NotFoundException; import org.sagebionetworks.table.cluster.utils.TableModelUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.model.GetObjectRequest; import com.google.common.collect.Lists; import au.com.bytecode.opencsv.CSVReader; import au.com.bytecode.opencsv.CSVWriter; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:test-context.xml" }) public class TableCSVAppenderWorkerIntegrationTest { public static final int MAX_WAIT_MS = 1000 * 60; @Autowired AsynchJobStatusManager asynchJobStatusManager; @Autowired StackConfiguration config; @Autowired FileHandleDao fileHandleDao; @Autowired EntityManager entityManager; @Autowired TableEntityManager tableEntityManager; @Autowired ColumnModelManager columnManager; @Autowired UserManager userManager; @Autowired AmazonS3Client s3Client; @Autowired SemaphoreManager semphoreManager; @Autowired private IdGenerator idGenerator; private UserInfo adminUserInfo; RowReferenceSet referenceSet; List<ColumnModel> schema; List<String> headers; private String tableId; private List<String> toDelete = Lists.newArrayList(); private List<File> tempFiles = Lists.newArrayList(); private List<S3FileHandle> fileHandles = Lists.newArrayList(); @Before public void before() throws NotFoundException { // Only run this test if the table feature is enabled. Assume.assumeTrue(config.getTableEnabled()); semphoreManager.releaseAllLocksAsAdmin(new UserInfo(true)); // Start with an empty queue. asynchJobStatusManager.emptyAllQueues(); // Get the admin user adminUserInfo = userManager.getUserInfo(BOOTSTRAP_PRINCIPAL.THE_ADMIN_USER.getPrincipalId()); } @After public void after() { if (config.getTableEnabled()) { if (adminUserInfo != null) { for (String id : toDelete) { try { entityManager.deleteEntity(adminUserInfo, id); } catch (Exception e) { } } } for (File tempFile : tempFiles) tempFile.delete(); } for (S3FileHandle fileHandle : fileHandles) { s3Client.deleteObject(fileHandle.getBucketName(), fileHandle.getKey()); fileHandleDao.delete(fileHandle.getId()); } } @Test public void testRoundTripWithCSVHeaders() throws DatastoreException, InvalidModelException, UnauthorizedException, NotFoundException, IOException, InterruptedException { doTestRoundTrip(true); } @Test public void testRoundTripWithColumnIds() throws DatastoreException, InvalidModelException, UnauthorizedException, NotFoundException, IOException, InterruptedException { doTestRoundTrip(false); } private void doTestRoundTrip(boolean useCSVHeader) throws DatastoreException, InvalidModelException, UnauthorizedException, NotFoundException, IOException, InterruptedException { this.schema = new LinkedList<ColumnModel>(); // Create a project Project project = new Project(); project.setName(UUID.randomUUID().toString()); String id = entityManager.createEntity(adminUserInfo, project, null); project = entityManager.getEntity(adminUserInfo, id, Project.class); toDelete.add(project.getId()); // Create a few columns // String ColumnModel cm = new ColumnModel(); cm.setColumnType(ColumnType.STRING); cm.setName("somestrings"); cm = columnManager.createColumnModel(adminUserInfo, cm); this.schema.add(cm); // integer cm = new ColumnModel(); cm.setColumnType(ColumnType.INTEGER); cm.setName("someinteger"); cm = columnManager.createColumnModel(adminUserInfo, cm); schema.add(cm); headers = TableModelUtils.getIds(schema); // Create the table TableEntity table = new TableEntity(); table.setParentId(project.getId()); table.setColumnIds(headers); table.setName(UUID.randomUUID().toString()); tableId = entityManager.createEntity(adminUserInfo, table, null); // Bind the columns. This is normally done at the service layer but the workers cannot depend on that layer. tableEntityManager.setTableSchema(adminUserInfo, headers, tableId); // Create a CSV file to upload File tempFile = File.createTempFile("TableCSVAppenderWorkerIntegrationTest", ".csv"); tempFiles.add(tempFile); CSVWriter csv = new CSVWriter(new FileWriter(tempFile)); int rowCount = 100; try { if (useCSVHeader) { // Write the header csv.writeNext(new String[] { schema.get(1).getName(), schema.get(0).getName() }); } // Write some rows for (int i = 0; i < rowCount; i++) { csv.writeNext(new String[] { "" + i, "stringdata" + i }); } } finally { csv.close(); } S3FileHandle fileHandle = new S3FileHandle(); fileHandle.setBucketName(StackConfiguration.getS3Bucket()); fileHandle.setKey(UUID.randomUUID() + ".csv"); fileHandle.setContentType("text/csv"); fileHandle.setCreatedBy("" + adminUserInfo.getId()); fileHandle.setFileName("ToAppendToTable.csv"); fileHandle.setId(idGenerator.generateNewId(TYPE.FILE_IDS).toString()); fileHandle.setEtag(UUID.randomUUID().toString()); fileHandle.setPreviewId(fileHandle.getId()); // Upload the File to S3 fileHandle = (S3FileHandle) fileHandleDao.createFile(fileHandle); fileHandles.add(fileHandle); // Upload the file to S3. s3Client.putObject(fileHandle.getBucketName(), fileHandle.getKey(), tempFile); // We are now ready to start the job UploadToTableRequest body = new UploadToTableRequest(); body.setTableId(tableId); body.setUploadFileHandleId(fileHandle.getId()); body.setEntityId(tableId); CsvTableDescriptor csvTableDescriptor = new CsvTableDescriptor(); csvTableDescriptor.setIsFirstLineHeader(useCSVHeader); body.setCsvTableDescriptor(csvTableDescriptor); if (!useCSVHeader) { body.setColumnIds(Lists.newArrayList(schema.get(1).getId(), schema.get(0).getId())); } TableUpdateTransactionRequest txRequest = TableModelUtils.wrapInTransactionRequest(body); AsynchronousJobStatus status = asynchJobStatusManager.startJob(adminUserInfo, txRequest); // Wait for the job to complete. status = waitForStatus(adminUserInfo, status); assertNotNull(status); UploadToTableResult response = TableModelUtils.extractResponseFromTransaction(status.getResponseBody(), UploadToTableResult.class); assertNotNull(response.getEtag()); assertEquals(new Long(rowCount), response.getRowsProcessed()); // There should be one change set applied to the table List<TableRowChange> changes = this.tableEntityManager.listRowSetsKeysForTable(tableId); assertNotNull(changes); assertEquals(1, changes.size()); TableRowChange change = changes.get(0); assertEquals(new Long(rowCount), change.getRowCount()); // the etag of the change should match what the job returned. assertEquals(change.getEtag(), response.getEtag()); } @Test public void testUpdateRoundTrip() throws DatastoreException, InvalidModelException, UnauthorizedException, NotFoundException, IOException, InterruptedException { this.schema = new LinkedList<ColumnModel>(); // Create a project Project project = new Project(); project.setName(UUID.randomUUID().toString()); String id = entityManager.createEntity(adminUserInfo, project, null); project = entityManager.getEntity(adminUserInfo, id, Project.class); toDelete.add(project.getId()); // Create a few columns // String ColumnModel cm = new ColumnModel(); cm.setColumnType(ColumnType.STRING); cm.setName("somestrings"); cm = columnManager.createColumnModel(adminUserInfo, cm); this.schema.add(cm); // integer cm = new ColumnModel(); cm.setColumnType(ColumnType.INTEGER); cm.setName("someinteger"); cm = columnManager.createColumnModel(adminUserInfo, cm); schema.add(cm); List<String> ids = TableModelUtils.getIds(schema); headers = ids; // Create the table TableEntity table = new TableEntity(); table.setParentId(project.getId()); table.setColumnIds(headers); table.setName(UUID.randomUUID().toString()); tableId = entityManager.createEntity(adminUserInfo, table, null); // Bind the columns. This is normally done at the service layer but the workers cannot depend on that layer. tableEntityManager.setTableSchema(adminUserInfo, headers, tableId); // Create a CSV file to upload File tempFile = File.createTempFile("TableCSVAppenderWorkerIntegrationTest", ".csv"); tempFiles.add(tempFile); CSVWriter csv = new CSVWriter(new FileWriter(tempFile)); int rowCount = 100; try { // Write the header csv.writeNext(new String[] { schema.get(1).getName(), schema.get(0).getName() }); // Write some rows for (int i = 0; i < rowCount; i++) { csv.writeNext(new String[] { "" + i, "stringdata" + i }); } } finally { csv.close(); } S3FileHandle fileHandle = new S3FileHandle(); fileHandle.setBucketName(StackConfiguration.getS3Bucket()); fileHandle.setKey(UUID.randomUUID() + ".csv"); fileHandle.setContentType("text/csv"); fileHandle.setCreatedBy("" + adminUserInfo.getId()); fileHandle.setFileName("ToAppendToTable.csv"); fileHandle.setId(idGenerator.generateNewId(TYPE.FILE_IDS).toString()); fileHandle.setEtag(UUID.randomUUID().toString()); fileHandle.setPreviewId(fileHandle.getId()); // Upload the File to S3 fileHandle = (S3FileHandle) fileHandleDao.createFile(fileHandle); fileHandles.add(fileHandle); // Upload the file to S3. s3Client.putObject(fileHandle.getBucketName(), fileHandle.getKey(), tempFile); // We are now ready to start the job UploadToTableRequest body = new UploadToTableRequest(); body.setTableId(tableId); body.setEntityId(tableId); body.setUploadFileHandleId(fileHandle.getId()); System.out.println("Inserting"); TableUpdateTransactionRequest txRequest = TableModelUtils.wrapInTransactionRequest(body); AsynchronousJobStatus status = asynchJobStatusManager.startJob(adminUserInfo, txRequest); // Wait for the job to complete. status = waitForStatus(adminUserInfo, status); // download the csv DownloadFromTableRequest download = new DownloadFromTableRequest(); download.setSql("select somestrings, someinteger from " + tableId); download.setIncludeRowIdAndRowVersion(true); download.setCsvTableDescriptor(new CsvTableDescriptor()); download.getCsvTableDescriptor().setIsFirstLineHeader(true); System.out.println("Downloading"); status = asynchJobStatusManager.startJob(adminUserInfo, download); status = waitForStatus(adminUserInfo, status); DownloadFromTableResult downloadResult = (DownloadFromTableResult) status.getResponseBody(); S3FileHandle resultFile = (S3FileHandle) fileHandleDao.get(downloadResult.getResultsFileHandleId()); fileHandles.add(resultFile); tempFile = File.createTempFile("DownloadCSV", ".csv"); tempFiles.add(tempFile); s3Client.getObject(new GetObjectRequest(resultFile.getBucketName(), resultFile.getKey()), tempFile); // Load the CSV data CSVReader csvReader = new CSVReader(new FileReader(tempFile)); List<String[]> results = csvReader.readAll(); csvReader.close(); // modify it int i = 3000; for (String[] row : results.subList(1, results.size())) { assertEquals(4, row.length); row[2] += "-changed" + i++; } tempFile = File.createTempFile("TableCSVAppenderWorkerIntegrationTest2", ".csv"); tempFiles.add(tempFile); csv = new CSVWriter(new FileWriter(tempFile)); for (String[] row : results) { csv.writeNext(row); } csv.close(); fileHandle = new S3FileHandle(); fileHandle.setBucketName(StackConfiguration.getS3Bucket()); fileHandle.setKey(UUID.randomUUID() + ".csv"); fileHandle.setContentType("text/csv"); fileHandle.setCreatedBy("" + adminUserInfo.getId()); fileHandle.setFileName("ToAppendToTable2.csv"); fileHandle.setId(idGenerator.generateNewId(TYPE.FILE_IDS).toString()); fileHandle.setEtag(UUID.randomUUID().toString()); fileHandle.setPreviewId(fileHandle.getId()); // Upload the File to S3 fileHandle = (S3FileHandle) fileHandleDao.createFile(fileHandle); fileHandles.add(fileHandle); // Upload the file to S3. s3Client.putObject(fileHandle.getBucketName(), fileHandle.getKey(), tempFile); // We are now ready to start the job body = new UploadToTableRequest(); body.setTableId(tableId); body.setEntityId(tableId); body.setUploadFileHandleId(fileHandle.getId()); System.out.println("Appending"); txRequest = TableModelUtils.wrapInTransactionRequest(body); status = asynchJobStatusManager.startJob(adminUserInfo, txRequest); // Wait for the job to complete. status = waitForStatus(adminUserInfo, status); // There should be two change sets applied to the table List<TableRowChange> changes = this.tableEntityManager.listRowSetsKeysForTable(tableId); assertNotNull(changes); assertEquals(2, changes.size()); } private AsynchronousJobStatus waitForStatus(UserInfo user, AsynchronousJobStatus status) throws InterruptedException, DatastoreException, NotFoundException { long start = System.currentTimeMillis(); while (!AsynchJobState.COMPLETE.equals(status.getJobState())) { assertFalse("Job Failed: " + status.getErrorDetails(), AsynchJobState.FAILED.equals(status.getJobState())); assertTrue("Timed out waiting for table status", (System.currentTimeMillis() - start) < MAX_WAIT_MS); Thread.sleep(1000); // Get the status again status = this.asynchJobStatusManager.getJobStatus(user, status.getJobId()); } return status; } }
package gov.nih.nci.caarray.web.plugins; import java.util.HashMap; import java.util.Map; import com.atlassian.plugin.spring.SpringAwarePackageScannerConfiguration; /** * Configuration for the Atlassian package scanner that defines what packages from the host system to make available to * plugins. * * @author dkokotov */ public class CaArrayPackageScannerConfiguration extends SpringAwarePackageScannerConfiguration { /** * Constructor - adds in packages to those defined in the base class and Spring. */ public CaArrayPackageScannerConfiguration() { super(); getPackageIncludes().add("com.google*"); getPackageIncludes().add("com.ctc*"); getPackageIncludes().add("org.codehaus*"); getPackageIncludes().add("com.fiveamsolutions*"); getPackageIncludes().add("gov.nih.nci.caarray*"); getPackageIncludes().add("org.hibernate*"); getPackageIncludes().add("com.opensymphony.xwork2*"); getPackageIncludes().add("org.slf4j*"); getPackageIncludes().add("affymetrix.*"); getPackageExcludes().add("org.apache.commons.logging*"); final Map<String, String> pkgVersions = new HashMap<String, String>(); pkgVersions.put("gov.nih.nci.caarray*", "2.4.0"); setPackageVersions(pkgVersions); } }
package org.flymine.metadata; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import org.flymine.util.StringUtil; import org.flymine.util.Util; import org.apache.log4j.Logger; /** * Describe a business model class. Gives access to attribute, reference and collection * descriptors. Includes primary key information. * * @author Richard Smith */ public class ClassDescriptor { protected static final Logger LOG = Logger.getLogger(ClassDescriptor.class); private final String name; // name of this class private final String superclassName; private ClassDescriptor superclassDescriptor; private final String interfaces; private final Set interfaceNames = new LinkedHashSet(); private final Set interfaceDescriptors = new LinkedHashSet(); private ClassDescriptor ultimateSuperclassDesc; private boolean ultimateSuperSet = false; private final boolean isInterface; private final Set attDescriptors; private final Set refDescriptors; private final Set colDescriptors; private final Map fieldDescriptors = new HashMap(); private final Set pkFields = new LinkedHashSet(); private Model model; // set when ClassDescriptor added to DescriptorRespository private boolean modelSet = false; private Set subclassDescriptors; private boolean subSet = false; private Set implementorDescriptors; private boolean implSet = false; public ClassDescriptor(String name, String superclassName, String interfaces, boolean isInterface, Set atts, Set refs, Set cols) throws IllegalArgumentException { if (name == null || name.equals("")) { throw new IllegalArgumentException("'name' parameter must be a valid String"); } this.name = name; if (superclassName != null && superclassName.equals("")) { throw new IllegalArgumentException("'superclassName' parameter must be null" + " or a valid class name"); } this.superclassName = superclassName; if (interfaces != null && interfaces.equals("")) { throw new IllegalArgumentException("'interfaces' parameter must be null" + " or a valid list of interface names"); } this.interfaces = interfaces; if (interfaces != null) { interfaceNames.addAll(StringUtil.tokenize(interfaces)); } this.isInterface = isInterface; attDescriptors = new LinkedHashSet(atts); refDescriptors = new LinkedHashSet(refs); colDescriptors = new LinkedHashSet(cols); // build maps of names to FieldDescriptors and populate pkFields set Set fieldDescriptorSet = new LinkedHashSet(); fieldDescriptorSet.addAll(atts); fieldDescriptorSet.addAll(refs); fieldDescriptorSet.addAll(cols); Iterator fieldDescriptorIter = fieldDescriptorSet.iterator(); while (fieldDescriptorIter.hasNext()) { FieldDescriptor fieldDescriptor = (FieldDescriptor) fieldDescriptorIter.next(); try { fieldDescriptor.setClassDescriptor(this); } catch (IllegalStateException e) { throw new IllegalArgumentException("FieldDescriptor '" + fieldDescriptor.getName() + "' has already had ClassDescriptor set"); } fieldDescriptors.put(fieldDescriptor.getName(), fieldDescriptor); if (fieldDescriptor.isPrimaryKey()) { pkFields.add(fieldDescriptor); } } } /** * Returns the fully qualified class name described by this ClassDescriptor. * @return name of the described Class */ public String getClassName() { return name; } public Set getPkFieldDescriptors() { checkModel(); Set allPkFields = new LinkedHashSet(pkFields); if (superclassDescriptor != null) { allPkFields.addAll(superclassDescriptor.getPkFieldDescriptors()); } return allPkFields; } // public Set getFieldDescriptors() { // return new HashSet(fieldDescriptors.values()); // public Set getAllFieldDescriptors() { // if (superclassDescriptor == null) { // return getFieldDescriptors(); // } else { // Set set = new LinkedHashSet(getFieldDescriptors()); // set.addAll(superclassDescriptor.getAllFieldDescriptors()); // return set; /** * Retrieve a FieldDescriptor by name * @param name the name * @return the FieldDescriptor */ public FieldDescriptor getFieldDescriptorByName(String name) { if (name == null) { throw new NullPointerException("Argument 'name' cannot be null"); } FieldDescriptor fd = (FieldDescriptor) fieldDescriptors.get(name); if (fd == null) { if (superclassDescriptor != null) { return superclassDescriptor.getFieldDescriptorByName(name); } else { throw new NullPointerException("ClassDescriptor '" + getClassName() + "' has no field named '" + name + "'"); } } return fd; } /** * Gets AttributeDescriptors for this class - i.e. fields that are not references or * collections. * @return set of attributes for this Class */ public Set getAttributeDescriptors() { return attDescriptors; } /** * Gets all AttributeDescriptors for this class - i.e. fields that are not references or * collections. * @return set of attributes for this Class */ public Set getAllAttributeDescriptors() { if (superclassDescriptor == null) { return getAttributeDescriptors(); } else { Set set = new LinkedHashSet(getAttributeDescriptors()); set.addAll(superclassDescriptor.getAllAttributeDescriptors()); return set; } } /** * Gets an AttributeDescriptor for a field of the given name. Returns null if * not found. * @param name the name of an AttributeDescriptor to find * @return an AttributeDescriptor */ public AttributeDescriptor getAttributeDescriptorByName(String name) { if (name == null) { throw new NullPointerException("Argument 'name' cannot be null"); } if (fieldDescriptors.containsKey(name) && fieldDescriptors.get(name) instanceof AttributeDescriptor) { return (AttributeDescriptor) fieldDescriptors.get(name); } return null; } /** * Gets the descriptors for the external object references in this class. * @return set ReferenceDescriptors for this Class */ public Set getReferenceDescriptors() { return refDescriptors; } /** * Gets a ReferenceDescriptor for a field of the given name. Returns null if * not found. * @param name the name of a ReferenceDescriptor to find * @return a ReferenceDescriptor */ public ReferenceDescriptor getReferenceDescriptorByName(String name) { if (name == null) { throw new NullPointerException("Argument 'name' cannot be null"); } if (fieldDescriptors.containsKey(name) && fieldDescriptors.get(name) instanceof ReferenceDescriptor) { return (ReferenceDescriptor) fieldDescriptors.get(name); } else { return null; } } private void configureReferenceDescriptors() throws MetaDataException { // ReferenceDescriptors need to find a ClassDescriptor for their referenced class Iterator refIter = refDescriptors.iterator(); while (refIter.hasNext()) { ReferenceDescriptor rfd = (ReferenceDescriptor) refIter.next(); rfd.findReferencedDescriptor(); } // ReferenceDescriptors need to find a ClassDescriptor for their referenced class Iterator colIter = colDescriptors.iterator(); while (colIter.hasNext()) { CollectionDescriptor cod = (CollectionDescriptor) colIter.next(); cod.findReferencedDescriptor(); } } /** * Gets all CollectionDescriptors for this class. * @return set of CollectionDescriptors for this Class */ public Set getCollectionDescriptors() { return colDescriptors; } /** * Gets a CollectionDescriptor for a collection of the given name. Returns null if * not found. * @param name the name of a CollectionDescriptor to find * @return a CollectionDescriptor */ public CollectionDescriptor getCollectionDescriptorByName(String name) { if (name == null) { throw new NullPointerException("Argument 'name' cannot be null"); } if (fieldDescriptors.containsKey(name) && fieldDescriptors.get(name) instanceof CollectionDescriptor) { return (CollectionDescriptor) fieldDescriptors.get(name); } else { return null; } } public ClassDescriptor getSuperclassDescriptor() { checkModel(); return superclassDescriptor; } private void findSuperclassDescriptor() throws MetaDataException { // descriptor for super class if (superclassName != null) { superclassDescriptor = model.getClassDescriptorByName(superclassName); if (superclassDescriptor == null) { throw new MetaDataException("No ClassDescriptor for super class: " + superclassName + " found in model."); } if (isInterface() != superclassDescriptor.isInterface()) { throw new MetaDataException("This class (" + getClassName() + (isInterface() ? ") is " : ") is not ") + "an interface but superclass (" + superclassDescriptor.getClassName() + (superclassDescriptor.isInterface() ? ") is." : ") is not.")); } } } public Set getInterfaceDescriptors() { checkModel(); return interfaceDescriptors; } /** * True if this class is an interface. * @return true if an interface */ public boolean isInterface() { return isInterface; } private void findInterfaceDescriptors() throws MetaDataException { // descriptors for interfaces if (interfaceNames.size() > 0) { Iterator iter = interfaceNames.iterator(); while (iter.hasNext()) { String iName = (String) iter.next(); if (!model.hasClassDescriptor(iName)) { throw new MetaDataException("No ClassDescriptor for interface ( " + iName + ") found in model."); } ClassDescriptor iDescriptor = model.getClassDescriptorByName(iName); if (!iDescriptor.isInterface()) { throw new MetaDataException("ClassDescriptor for ( " + iName + ") does not describe and interface."); } interfaceDescriptors.add(iDescriptor); } } } protected void setSubclassDescriptors(Set sub) { if (subSet) { throw new IllegalStateException("subclasses have already been set for this " + "ClassDescriptor (" + name + ")."); } subclassDescriptors = new LinkedHashSet(sub); subSet = true; } public Set getSubclassDescriptors() throws IllegalStateException { if (!subSet) { throw new IllegalStateException("This ClassDescriptor has not yet had subclass" + "Descriptors set."); } return subclassDescriptors; } protected void setImplementorDescriptors(Set impl) { if (implSet) { throw new IllegalStateException("implementors have already been set for this " + "ClassDescriptor (" + name + ")."); } if (isInterface()) { implementorDescriptors = impl; } implSet = true; } public Set getImplementorDescriptors() throws IllegalStateException { if (!implSet) { throw new IllegalStateException("This ClassDescriptor (" + getClassName() + ") has not yet had implementor Descriptors set."); } return implementorDescriptors; } protected void setModel(Model model) throws IllegalStateException, MetaDataException { if (modelSet) { throw new IllegalStateException("Model has already been set and " + "may not be changed."); } this.model = model; findSuperclassDescriptor(); findInterfaceDescriptors(); configureReferenceDescriptors(); modelSet = true; } /** * Return the model this class is a part of * @return the parent Model */ public Model getModel() { return model; } private void checkModel() { if (!modelSet) { throw new IllegalArgumentException("ClassDescriptor '" + getClassName() + "' has not been added to a Model"); } } /** * @see Object#equals */ public boolean equals(Object obj) { if (obj instanceof ClassDescriptor) { ClassDescriptor cld = (ClassDescriptor) obj; return name.equals(cld.name) && Util.equals(superclassName, cld.superclassName) && interfaceNames.equals(cld.interfaceNames) && isInterface == cld.isInterface && fieldDescriptors.equals(cld.fieldDescriptors); } return false; } /** * @see Object#hashCode */ public int hashCode() { return 3 * name.hashCode() + 5 * Util.hashCode(superclassName) + 7 * interfaceNames.hashCode() + 11 * (isInterface ? 1 : 0) + 13 * fieldDescriptors.hashCode(); } /** * @see Object#toString */ public String toString() { StringBuffer sb = new StringBuffer(); sb.append("<class name=\"" + name + "\"") .append(superclassName != null ? " extends=\"" + superclassName + "\"" : "") .append(interfaces != null ? " implements=\"" + interfaces + "\"" : "") .append(" is-interface=\"" + isInterface + "\">"); Set l = new LinkedHashSet(); l.addAll(getAttributeDescriptors()); l.addAll(getReferenceDescriptors()); l.addAll(getCollectionDescriptors()); for (Iterator iter = l.iterator(); iter.hasNext();) { sb.append(iter.next().toString()); } sb.append("</class>"); return sb.toString(); } }
package io.grpc.stub; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.NANOSECONDS; import static java.util.concurrent.TimeUnit.SECONDS; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.same; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import io.grpc.CallOptions; import io.grpc.Channel; import io.grpc.ClientCall; import io.grpc.Deadline; import io.grpc.MethodDescriptor; import io.grpc.testing.integration.Messages.SimpleRequest; import io.grpc.testing.integration.Messages.SimpleResponse; import io.grpc.testing.integration.TestServiceGrpc; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; /** * Tests for stub reconfiguration. */ @RunWith(JUnit4.class) public class StubConfigTest { @Mock private Channel channel; @Mock private StreamObserver<SimpleResponse> responseObserver; @Mock private ClientCall<SimpleRequest, SimpleResponse> call; /** * Sets up mocks. */ @Before public void setUp() { MockitoAnnotations.initMocks(this); when(channel.newCall( Mockito.<MethodDescriptor<SimpleRequest, SimpleResponse>>any(), any(CallOptions.class))) .thenReturn(call); } @Test public void testConfigureDeadline() { Deadline deadline = Deadline.after(2, NANOSECONDS); // Create a default stub TestServiceGrpc.TestServiceBlockingStub stub = TestServiceGrpc.newBlockingStub(channel); assertNull(stub.getCallOptions().getDeadline()); // Reconfigure it TestServiceGrpc.TestServiceBlockingStub reconfiguredStub = stub.withDeadline(deadline); // New altered config assertEquals(deadline, reconfiguredStub.getCallOptions().getDeadline()); // Default config unchanged assertNull(stub.getCallOptions().getDeadline()); } @Test @Deprecated public void testConfigureDeadlineNanoTime() { long deadline = System.nanoTime() + SECONDS.toNanos(1); // Create a default stub TestServiceGrpc.TestServiceBlockingStub stub = TestServiceGrpc.newBlockingStub(channel); assertNull(stub.getCallOptions().getDeadlineNanoTime()); // Warm up JVM stub.withDeadlineNanoTime(deadline); // Reconfigure it TestServiceGrpc.TestServiceBlockingStub reconfiguredStub = stub.withDeadlineNanoTime(deadline); // New altered config assertNotNull(reconfiguredStub.getCallOptions().getDeadlineNanoTime()); long maxDelta = MILLISECONDS.toNanos(10); long actualDelta = Math.abs(reconfiguredStub.getCallOptions().getDeadlineNanoTime() - deadline); assertTrue(maxDelta + " < " + actualDelta, maxDelta >= actualDelta); // Default config unchanged assertNull(stub.getCallOptions().getDeadlineNanoTime()); } @Test public void testStubCallOptionsPopulatedToNewCall() { TestServiceGrpc.TestServiceStub stub = TestServiceGrpc.newStub(channel); CallOptions options1 = stub.getCallOptions(); SimpleRequest request = SimpleRequest.getDefaultInstance(); stub.unaryCall(request, responseObserver); verify(channel).newCall(same(TestServiceGrpc.METHOD_UNARY_CALL), same(options1)); stub = stub.withDeadlineAfter(2, NANOSECONDS); CallOptions options2 = stub.getCallOptions(); assertNotSame(options1, options2); stub.unaryCall(request, responseObserver); verify(channel).newCall(same(TestServiceGrpc.METHOD_UNARY_CALL), same(options2)); } }
package cn.zhaiyifan.appinit; import java.util.concurrent.CountDownLatch; public abstract class Task implements Runnable { private static final String TAG = "Task"; private String mTaskName; private CountDownLatch mDoneSignal; private boolean mIsBlocked = true; private long mDelay = 0; private int mStatus = Status.STATUS_PENDING_START; // for asynchronous task chain private Task mParentTask; private Task mChildTask; /** * Constructor * * @param name task name */ public Task(String name) { mTaskName = name; } /** * Constructor * * @param name task name * @param delay task delay */ public Task(String name, long delay) { mTaskName = name; mDelay = delay; } /** * Constructor * * @param name task name * @param isBlocked if task is blocked */ public Task(String name, boolean isBlocked) { mTaskName = name; mIsBlocked = isBlocked; } /** * Constructor * * @param name task name * @param isBlocked if task is blocked * @param delay task delay */ public Task(String name, boolean isBlocked, long delay) { mTaskName = name; mIsBlocked = isBlocked; mDelay = delay; } /** * Normally should not override it */ @Override public void run() { if (mDelay > 0) { try { Thread.sleep(mDelay); } catch (InterruptedException e) { LogImpl.w(TAG, getName() + ": " + e.getMessage()); } } if (mParentTask != null) { synchronized (this) { try { wait(); } catch (InterruptedException e) { LogImpl.w(TAG, getName() + ": " + e.getMessage()); } } } mStatus = Status.STATUS_EXECUTING; long startTime = System.currentTimeMillis(); start(); long endTime = System.currentTimeMillis(); LogImpl.i(TAG, getName() + " runs " + (endTime - startTime)); if (mDoneSignal != null) { mDoneSignal.countDown(); } if (mChildTask != null) { synchronized (mChildTask) { mChildTask.notify(); } } mStatus = Status.STATUS_DONE; } /** * Run task. */ protected abstract void start(); /** * Returns true if the task is blocked, by default returns true. */ public boolean isBlocked() { return mIsBlocked; } /** * Set done signal. * * @param doneSignal CountDownLatch signal */ public void setDoneSignal(CountDownLatch doneSignal) { this.mDoneSignal = doneSignal; } /** * Set parent task which blocks this task until it finished. * * @param task parent task */ public void setParentTask(Task task) { mParentTask = task; task.setChildTask(this); } void setChildTask(Task task) { mChildTask = task; } /** * Returns delay of the task in milliseconds, by default returns 0. */ public long getDelay() { return mDelay; } /** * Get task status * * @return status */ public int getStatus() { return mStatus; } /** * Determine task's process, by default returns true, which means run on all processes. * * @param processName process name * @return whether given processName should run the task. */ public boolean runOnProcess(String processName) { return true; } /** * Get name of task. * * @return Task's name */ public String getName() { return mTaskName; } }
package javaschtasks.batchjob; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import org.apache.log4j.Logger; public class wintask { private static Logger logger = Logger.getLogger(wintask.class.getName()); public static void main(String args[]) throws IOException, InterruptedException { StringBuffer sb = wintask.getrunoncexml(); String myxml = sb.toString(); ReadXMLFile.readxmlString(myxml, null); System.out.println(myxml); } public static StringBuffer stoutErrors(Process p) { BufferedReader br = null; try{ // stdout StringBuffer ret = new StringBuffer(); InputStream is = p.getInputStream(); InputStreamReader isr = new InputStreamReader(is); br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { logger.debug(line); ret.append(line); } //stderr is = p.getErrorStream(); isr = new InputStreamReader(is); br = new BufferedReader(isr); while ((line = br.readLine()) != null) { logger.debug(line); ret.append(line); } return ret; } catch (IOException e) { e.printStackTrace(); } finally { try { if (br != null)br.close(); } catch (IOException ex) { ex.printStackTrace(); } } return null; } public static StringBuffer runawinho() { List<String> commands = new ArrayList<String>(); commands.add("schtasks.exe"); commands.add("/run"); commands.add("/S"); commands.add(JobSubmitGui.defaultserverip); commands.add("/U"); commands.add(JobSubmitGui.defaultuser); commands.add("/P"); commands.add(JobSubmitGui.defaultpass); commands.add("/TN"); commands.add("FOLDERJOBS\\Testing777"); logger.debug("Running shell command: " + commands); ProcessBuilder builder = new ProcessBuilder(commands); Process p; try { p = builder.start(); StringBuffer sb = wintask.stoutErrors(p); p.waitFor(); System.out.println(p.exitValue()); return sb; } catch (IOException | InterruptedException e) { e.printStackTrace(); } return null; } public static StringBuffer deltask1(Taskobj task) { List<String> commands = new ArrayList<String>(); String taskname = wintask.getGoodTaskName(task); commands.add("schtasks.exe"); commands.add("/delete"); commands.add("/S"); commands.add(JobSubmitGui.defaultserverip); commands.add("/U"); commands.add(JobSubmitGui.defaultuser); commands.add("/P"); commands.add(JobSubmitGui.defaultpass); commands.add("/TN"); commands.add("FOLDERJOBS\\" + taskname); commands.add("/F"); logger.debug("Running shell command: " + commands); ProcessBuilder builder = new ProcessBuilder(commands); Process p; try { p = builder.start(); StringBuffer sb = wintask.stoutErrors(p); p.waitFor(); System.out.println(p.exitValue()); return sb; } catch (IOException | InterruptedException e) { e.printStackTrace(); } return null; } public static StringBuffer linuxfortune(Taskobj task) { List<String> commands = new ArrayList<String>(); commands.add("/bin/bash"); commands.add("-c"); commands.add("sleep 5"); commands.add(";"); commands.add("fortune"); logger.debug("Running shell command: " + commands); ProcessBuilder builder = new ProcessBuilder(commands); Process p; try { p = builder.start(); StringBuffer sb = wintask.stoutErrors(p); p.waitFor(); System.out.println(p.exitValue()); return sb; } catch (IOException | InterruptedException e) { e.printStackTrace(); } return null; } public static StringBuffer runataskl(Taskobj task) { List<String> commands = new ArrayList<String>(); String taskname = wintask.getGoodTaskName(task); commands.add("schtasks.exe"); commands.add("/Create"); commands.add("/S"); commands.add(JobSubmitGui.defaultserverip); commands.add("/U"); commands.add(JobSubmitGui.defaultuser); commands.add("/P"); commands.add(JobSubmitGui.defaultpass); commands.add("/XML"); commands.add(task.getFilename()); commands.add("/TN"); commands.add("FOLDERJOBS\\" + taskname); commands.add("/F"); //commands.add("/RU"); //commands.add(JobSubmitGui.defaultservername + "\\" + JobSubmitGui.defaultuser); //commands.add("/RP"); //commands.add(JobSubmitGui.defaultpass); logger.debug("Running shell command: " + commands); ProcessBuilder builder = new ProcessBuilder(commands); Process p; try { p = builder.start(); StringBuffer sb = wintask.stoutErrors(p); p.waitFor(); logger.debug(p.exitValue()); return sb; } catch (IOException | InterruptedException e) { e.printStackTrace(); } return null; } private static String getGoodTaskName(Taskobj task) { File afile = new File(task.getFilename()); String filenameshort = afile.getName(); Calendar ca1 = Calendar.getInstance(); int DAY_OF_YEAR = ca1.get(Calendar.DAY_OF_YEAR); String newtask = DAY_OF_YEAR + filenameshort; return newtask; } public static StringBuffer getrunoncexml() { List<String> commands = new ArrayList<String>(); commands.add("schtasks.exe"); commands.add("/query"); commands.add("/S"); commands.add(JobSubmitGui.defaultserverip); commands.add("/U"); commands.add(JobSubmitGui.defaultuser); commands.add("/P"); commands.add(JobSubmitGui.defaultpass); commands.add("/TN"); commands.add("FOLDERJOBS\\"); commands.add("/XML"); logger.debug("Running shell command: " + commands); ProcessBuilder builder = new ProcessBuilder(commands); Process p; try { p = builder.start(); StringBuffer sb = wintask.stoutErrors(p); p.waitFor(); System.out.println(p.exitValue()); return sb; } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } return null; } }
package edu.umd.cs.findbugs; import java.io.IOException; import java.io.InputStream; import java.util.Iterator; import java.util.LinkedList; import java.util.jar.Attributes; import java.util.jar.Manifest; import org.apache.bcel.classfile.JavaClass; import edu.umd.cs.findbugs.ba.JavaClassAndMethod; import edu.umd.cs.findbugs.classfile.IClassFactory; import edu.umd.cs.findbugs.classfile.IClassPath; import edu.umd.cs.findbugs.classfile.ICodeBase; import edu.umd.cs.findbugs.classfile.ICodeBaseEntry; import edu.umd.cs.findbugs.classfile.ICodeBaseIterator; import edu.umd.cs.findbugs.classfile.ICodeBaseLocator; import edu.umd.cs.findbugs.classfile.IScannableCodeBase; import edu.umd.cs.findbugs.classfile.ResourceNotFoundException; import edu.umd.cs.findbugs.classfile.impl.ClassFactory; import edu.umd.cs.findbugs.io.IO; import edu.umd.cs.findbugs.util.Archive; /** * FindBugs driver class. * Experimental version to use the new bytecode-framework-neutral * codebase/classpath/classfile infrastructure. * Don't expect this class to do anything useful for a while. * * @author David Hovemeyer */ public class FindBugs2 { private static final boolean DEBUG = Boolean.getBoolean("findbugs2.debug"); private BugReporter bugReporter; private Project project; private IClassFactory classFactory; private IClassPath classPath; public FindBugs2(BugReporter bugReporter, Project project) { this.bugReporter = bugReporter; this.project = project; } public void execute() throws IOException, InterruptedException, ResourceNotFoundException { // Get the class factory for creating classpath/codebase/etc. classFactory = ClassFactory.instance(); // The class path object // FIXME: this should be in the analysis context eventually classPath = classFactory.createClassPath(); try { buildClassPath(); // TODO: the execution plan, analysis, etc. } finally { // Make sure the codebases on the classpath are closed classPath.close(); } } /** * Worklist item. * Represents one codebase to be processed during the * classpath construction algorithm. */ static class WorkListItem { private ICodeBaseLocator codeBaseLocator; private boolean isAppCodeBase; WorkListItem(ICodeBaseLocator codeBaseLocator, boolean isApplication) { this.codeBaseLocator = codeBaseLocator; this.isAppCodeBase = isApplication; } public ICodeBaseLocator getCodeBaseLocator() { return codeBaseLocator; } public boolean isAppCodeBase() { return isAppCodeBase; } } /** * Build the classpath by scanning the application and aux classpath entries * specified in the project. We will attempt to find all nested archives and * Class-Path entries specified in Jar manifests. This should give us * as good an idea as possible of all of the classes available (and * which are part of the application). * * @throws InterruptedException if the analysis thread is interrupted * @throws IOException if an I/O error occurs * @throws ResourceNotFoundException */ private void buildClassPath() throws InterruptedException, IOException, ResourceNotFoundException { // Seed worklist with app codebases and aux codebases. LinkedList<WorkListItem> workList = new LinkedList<WorkListItem>(); for (String path : project.getFileArray()) { workList.add(new WorkListItem(classFactory.createFilesystemCodeBaseLocator(path), true)); } for (String path : project.getAuxClasspathEntryList()) { workList.add(new WorkListItem(classFactory.createFilesystemCodeBaseLocator(path), false)); } // Build the classpath, scanning codebases for nested archives // and referenced codebases. while (!workList.isEmpty()) { WorkListItem item = workList.removeFirst(); // If we are working on an application codebase, // then failing to open/scan it is a fatal error. // We issue warnings about problems with aux codebases, // but continue anyway. boolean isAppCodeBase = item.isAppCodeBase(); try { // Open the codebase and add it to the classpath ICodeBase codeBase = item.getCodeBaseLocator().openCodeBase(); codeBase.setApplicationCodeBase(isAppCodeBase); classPath.addCodeBase(codeBase); // If it is a scannable codebase, check it for nested archives. if (codeBase instanceof IScannableCodeBase) { checkForNestedArchives(workList, (IScannableCodeBase) codeBase); } // Check for a Jar manifest for additional aux classpath entries. scanJarManifestForClassPathEntries(workList, codeBase); } catch (IOException e) { if (isAppCodeBase) { throw e; } else { // TODO: log warning } } catch (ResourceNotFoundException e) { if (isAppCodeBase) { throw e; } else { // TODO: log warning } } } if (DEBUG) { System.out.println("Classpath:"); dumpCodeBaseList(classPath.appCodeBaseIterator(), "Application codebases"); dumpCodeBaseList(classPath.auxCodeBaseIterator(), "Auxiliary codebases"); } } private void dumpCodeBaseList(Iterator<? extends ICodeBase> i, String desc) throws InterruptedException { System.out.println(" " + desc + ":"); while (i.hasNext()) { ICodeBase codeBase = i.next(); System.out.println(" " + codeBase.getCodeBaseLocator().toString()); if (codeBase.containsSourceFiles()) { System.out.println(" * contains source files"); } } } /** * Check a codebase for nested archives. * Add any found to the worklist. * * @param workList the worklist * @param codeBase the codebase to scan * @throws InterruptedException */ private void checkForNestedArchives(LinkedList<WorkListItem> workList, IScannableCodeBase codeBase) throws InterruptedException { if (DEBUG) { System.out.println("Checking " + codeBase.getCodeBaseLocator() + " for nested codebases"); } ICodeBaseIterator i = codeBase.iterator(); while (i.hasNext()) { ICodeBaseEntry entry = i.next(); if (DEBUG) { System.out.println("Entry: " + entry.getResourceName()); } if (Archive.isArchiveFileName(entry.getResourceName())) { if (DEBUG) { System.out.println("Entry is an archive!"); } ICodeBaseLocator nestedArchiveLocator = classFactory.createNestedArchiveCodeBaseLocator(codeBase, entry.getResourceName()); workList.add(new WorkListItem(nestedArchiveLocator, codeBase.isApplicationCodeBase())); } } } /** * Check a codebase for a Jar manifest to examine for Class-Path entries. * * @param workList the worklist * @param codeBase the codebase for examine for a Jar manifest * @throws IOException */ private void scanJarManifestForClassPathEntries(LinkedList<WorkListItem> workList, ICodeBase codeBase) throws IOException { try { // See if this codebase has a jar manifest ICodeBaseEntry manifestEntry = codeBase.lookupResource("META-INF/MANIFEST.MF"); // Try to read the manifest InputStream in = null; try { in = manifestEntry.openResource(); Manifest manifest = new Manifest(in); Attributes mainAttrs = manifest.getMainAttributes(); String classPath = mainAttrs.getValue("Class-Path"); if (classPath != null) { String[] pathList = classPath.split("\\s+"); for (String path : pathList) { // Create a codebase locator for the classpath entry // relative to the codebase in which we discovered the Jar // manifest ICodeBaseLocator relativeCodeBaseLocator = codeBase.getCodeBaseLocator().createRelativeCodeBaseLocator(path); // Codebases found in Class-Path entries are always // added to the aux classpath, not the application. workList.add(new WorkListItem(relativeCodeBaseLocator, false)); } } } finally { if (in != null) { IO.close(in); } } } catch (ResourceNotFoundException e) { // Do nothing - no Jar manifest found } } public static void main(String[] args) throws Exception { if (args.length != 1) { System.err.println("Usage: " + FindBugs2.class.getName() + " <project>"); System.exit(1); } BugReporter bugReporter = new PrintingBugReporter(); Project project = new Project(); project.read(args[0]); FindBugs2 findBugs = new FindBugs2(bugReporter, project); findBugs.execute(); } }
package com.yahoo.vespa.flags; import com.yahoo.component.Vtag; import com.yahoo.vespa.defaults.Defaults; import java.time.Instant; import java.time.LocalDate; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.List; import java.util.Optional; import java.util.TreeMap; import java.util.function.Predicate; import static com.yahoo.vespa.flags.FetchVector.Dimension.APPLICATION_ID; import static com.yahoo.vespa.flags.FetchVector.Dimension.CONSOLE_USER_EMAIL; import static com.yahoo.vespa.flags.FetchVector.Dimension.HOSTNAME; import static com.yahoo.vespa.flags.FetchVector.Dimension.NODE_TYPE; import static com.yahoo.vespa.flags.FetchVector.Dimension.TENANT_ID; import static com.yahoo.vespa.flags.FetchVector.Dimension.VESPA_VERSION; import static com.yahoo.vespa.flags.FetchVector.Dimension.ZONE_ID; /** * Definitions of feature flags. * * <p>To use feature flags, define the flag in this class as an "unbound" flag, e.g. {@link UnboundBooleanFlag} * or {@link UnboundStringFlag}. At the location you want to get the value of the flag, you need the following:</p> * * <ol> * <li>The unbound flag</li> * <li>A {@link FlagSource}. The flag source is typically available as an injectable component. Binding * an unbound flag to a flag source produces a (bound) flag, e.g. {@link BooleanFlag} and {@link StringFlag}.</li> * <li>If you would like your flag value to be dependent on e.g. the application ID, then 1. you should * declare this in the unbound flag definition in this file (referring to * {@link FetchVector.Dimension#APPLICATION_ID}), and 2. specify the application ID when retrieving the value, e.g. * {@link BooleanFlag#with(FetchVector.Dimension, String)}. See {@link FetchVector} for more info.</li> * </ol> * * <p>Once the code is in place, you can override the flag value. This depends on the flag source, but typically * there is a REST API for updating the flags in the config server, which is the root of all flag sources in the zone.</p> * * @author hakonhall */ public class Flags { private static volatile TreeMap<FlagId, FlagDefinition> flags = new TreeMap<>(); public static final UnboundBooleanFlag ROOT_CHAIN_GRAPH = defineFeatureFlag( "root-chain-graph", true, List.of("hakonhall"), "2022-10-05", "2022-11-04", "Whether to run all tasks in the root task chain up to the one failing to converge (false), or " + "run all tasks in the root task chain whose dependencies have converged (true). And when suspending, " + "whether to run the tasks in sequence (false) or in reverse sequence (true).", "On first tick of the root chain after (re)start of host admin.", ZONE_ID, NODE_TYPE, HOSTNAME); public static final UnboundDoubleFlag DEFAULT_TERM_WISE_LIMIT = defineDoubleFlag( "default-term-wise-limit", 1.0, List.of("baldersheim"), "2020-12-02", "2023-01-01", "Default limit for when to apply termwise query evaluation", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag QUERY_DISPATCH_POLICY = defineStringFlag( "query-dispatch-policy", "adaptive", List.of("baldersheim"), "2022-08-20", "2023-01-01", "Select query dispatch policy, valid values are adaptive, round-robin, best-of-random-2," + " latency-amortized-over-requests, latency-amortized-over-time", "Takes effect at redeployment (requires restart)", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag FEED_SEQUENCER_TYPE = defineStringFlag( "feed-sequencer-type", "THROUGHPUT", List.of("baldersheim"), "2020-12-02", "2023-01-01", "Selects type of sequenced executor used for feeding in proton, valid values are LATENCY, ADAPTIVE, THROUGHPUT", "Takes effect at redeployment (requires restart)", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag KEEP_STORAGE_NODE_UP = defineFeatureFlag( "keep-storage-node-up", true, List.of("hakonhall"), "2022-07-07", "2022-11-07", "Whether to leave the storage node (with wanted state) UP while the node is permanently down.", "Takes effect immediately for nodes transitioning to permanently down.", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MAX_UNCOMMITTED_MEMORY = defineIntFlag( "max-uncommitted-memory", 130000, List.of("geirst, baldersheim"), "2021-10-21", "2023-01-01", "Max amount of memory holding updates to an attribute before we do a commit.", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag RESPONSE_SEQUENCER_TYPE = defineStringFlag( "response-sequencer-type", "ADAPTIVE", List.of("baldersheim"), "2020-12-02", "2023-01-01", "Selects type of sequenced executor used for mbus responses, valid values are LATENCY, ADAPTIVE, THROUGHPUT", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag RESPONSE_NUM_THREADS = defineIntFlag( "response-num-threads", 2, List.of("baldersheim"), "2020-12-02", "2023-01-01", "Number of threads used for mbus responses, default is 2, negative number = numcores/4", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SKIP_COMMUNICATIONMANAGER_THREAD = defineFeatureFlag( "skip-communicationmanager-thread", false, List.of("baldersheim"), "2020-12-02", "2023-01-01", "Should we skip the communicationmanager thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SKIP_MBUS_REQUEST_THREAD = defineFeatureFlag( "skip-mbus-request-thread", false, List.of("baldersheim"), "2020-12-02", "2023-01-01", "Should we skip the mbus request thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SKIP_MBUS_REPLY_THREAD = defineFeatureFlag( "skip-mbus-reply-thread", false, List.of("baldersheim"), "2020-12-02", "2023-01-01", "Should we skip the mbus reply thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_ASYNC_MESSAGE_HANDLING_ON_SCHEDULE = defineFeatureFlag( "async-message-handling-on-schedule", false, List.of("baldersheim"), "2020-12-02", "2023-01-01", "Optionally deliver async messages in own thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag FEED_CONCURRENCY = defineDoubleFlag( "feed-concurrency", 0.5, List.of("baldersheim"), "2020-12-02", "2023-01-01", "How much concurrency should be allowed for feed", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag FEED_NICENESS = defineDoubleFlag( "feed-niceness", 0.0, List.of("baldersheim"), "2022-06-24", "2023-01-01", "How nice feeding shall be", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MBUS_JAVA_NUM_TARGETS = defineIntFlag( "mbus-java-num-targets", 1, List.of("baldersheim"), "2022-07-05", "2023-01-01", "Number of rpc targets per service", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MBUS_CPP_NUM_TARGETS = defineIntFlag( "mbus-cpp-num-targets", 1, List.of("baldersheim"), "2022-07-05", "2023-01-01", "Number of rpc targets per service", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag RPC_NUM_TARGETS = defineIntFlag( "rpc-num-targets", 1, List.of("baldersheim"), "2022-07-05", "2023-01-01", "Number of rpc targets per content node", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MBUS_JAVA_EVENTS_BEFORE_WAKEUP = defineIntFlag( "mbus-java-events-before-wakeup", 1, List.of("baldersheim"), "2022-07-05", "2023-01-01", "Number write events before waking up transport thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MBUS_CPP_EVENTS_BEFORE_WAKEUP = defineIntFlag( "mbus-cpp-events-before-wakeup", 1, List.of("baldersheim"), "2022-07-05", "2023-01-01", "Number write events before waking up transport thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag RPC_EVENTS_BEFORE_WAKEUP = defineIntFlag( "rpc-events-before-wakeup", 1, List.of("baldersheim"), "2022-07-05", "2023-01-01", "Number write events before waking up transport thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MBUS_NUM_NETWORK_THREADS = defineIntFlag( "mbus-num-network-threads", 1, List.of("baldersheim"), "2022-07-01", "2023-01-01", "Number of threads used for mbus network", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SHARED_STRING_REPO_NO_RECLAIM = defineFeatureFlag( "shared-string-repo-no-reclaim", false, List.of("baldersheim"), "2022-06-14", "2023-01-01", "Controls whether we do track usage and reclaim unused enum values in shared string repo", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag CONTAINER_DUMP_HEAP_ON_SHUTDOWN_TIMEOUT = defineFeatureFlag( "container-dump-heap-on-shutdown-timeout", false, List.of("baldersheim"), "2021-09-25", "2023-01-01", "Will trigger a heap dump during if container shutdown times out", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag LOAD_CODE_AS_HUGEPAGES = defineFeatureFlag( "load-code-as-hugepages", false, List.of("baldersheim"), "2022-05-13", "2023-01-01", "Will try to map the code segment with huge (2M) pages", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag CONTAINER_SHUTDOWN_TIMEOUT = defineDoubleFlag( "container-shutdown-timeout", 50.0, List.of("baldersheim"), "2021-09-25", "2023-05-01", "Timeout for shutdown of a jdisc container", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundListFlag<String> ALLOWED_ATHENZ_PROXY_IDENTITIES = defineListFlag( "allowed-athenz-proxy-identities", List.of(), String.class, List.of("bjorncs", "tokle"), "2021-02-10", "2022-11-01", "Allowed Athenz proxy identities", "takes effect at redeployment"); public static final UnboundIntFlag MAX_ACTIVATION_INHIBITED_OUT_OF_SYNC_GROUPS = defineIntFlag( "max-activation-inhibited-out-of-sync-groups", 0, List.of("vekterli"), "2021-02-19", "2022-12-01", "Allows replicas in up to N content groups to not be activated " + "for query visibility if they are out of sync with a majority of other replicas", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MAX_CONCURRENT_MERGES_PER_NODE = defineIntFlag( "max-concurrent-merges-per-node", 16, List.of("balder", "vekterli"), "2021-06-06", "2022-12-01", "Specifies max concurrent merges per content node.", "Takes effect at redeploy", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MAX_MERGE_QUEUE_SIZE = defineIntFlag( "max-merge-queue-size", 100, List.of("balder", "vekterli"), "2021-06-06", "2022-12-01", "Specifies max size of merge queue.", "Takes effect at redeploy", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag MIN_NODE_RATIO_PER_GROUP = defineDoubleFlag( "min-node-ratio-per-group", 0.0, List.of("geirst", "vekterli"), "2021-07-16", "2022-11-01", "Minimum ratio of nodes that have to be available (i.e. not Down) in any hierarchic content cluster group for the group to be Up", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag ENABLED_HORIZON_DASHBOARD = defineFeatureFlag( "enabled-horizon-dashboard", false, List.of("olaa"), "2021-09-13", "2023-01-01", "Enable Horizon dashboard", "Takes effect immediately", TENANT_ID, CONSOLE_USER_EMAIL ); public static final UnboundBooleanFlag IGNORE_THREAD_STACK_SIZES = defineFeatureFlag( "ignore-thread-stack-sizes", false, List.of("arnej"), "2021-11-12", "2022-12-01", "Whether C++ thread creation should ignore any requested stack size", "Triggers restart, takes effect immediately", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_V8_GEO_POSITIONS = defineFeatureFlag( "use-v8-geo-positions", true, List.of("arnej"), "2021-11-15", "2022-12-31", "Use Vespa 8 types and formats for geographical positions", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MAX_COMPACT_BUFFERS = defineIntFlag( "max-compact-buffers", 1, List.of("baldersheim", "geirst", "toregge"), "2021-12-15", "2023-01-01", "Upper limit of buffers to compact in a data store at the same time for each reason (memory usage, address space usage)", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_QRSERVER_SERVICE_NAME = defineFeatureFlag( "use-qrserver-service-name", false, List.of("arnej"), "2022-01-18", "2022-12-31", "Use backwards-compatible 'qrserver' service name for containers with only 'search' API", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag AVOID_RENAMING_SUMMARY_FEATURES = defineFeatureFlag( "avoid-renaming-summary-features", true, List.of("arnej"), "2022-01-15", "2023-12-31", "Tell backend about the original name of summary-features that were wrapped in a rankingExpression feature", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag NOTIFICATION_DISPATCH_FLAG = defineFeatureFlag( "dispatch-notifications", false, List.of("enygaard"), "2022-05-02", "2022-12-30", "Whether we should send notification for a given tenant", "Takes effect immediately", TENANT_ID); public static final UnboundBooleanFlag ENABLE_PROXY_PROTOCOL_MIXED_MODE = defineFeatureFlag( "enable-proxy-protocol-mixed-mode", true, List.of("tokle"), "2022-05-09", "2022-11-01", "Enable or disable proxy protocol mixed mode", "Takes effect on redeployment", APPLICATION_ID); public static final UnboundListFlag<String> FILE_DISTRIBUTION_ACCEPTED_COMPRESSION_TYPES = defineListFlag( "file-distribution-accepted-compression-types", List.of("gzip", "lz4"), String.class, List.of("hmusum"), "2022-07-05", "2022-11-01", "´List of accepted compression types used when asking for a file reference. Valid values: gzip, lz4", "Takes effect on restart of service", APPLICATION_ID); public static final UnboundListFlag<String> FILE_DISTRIBUTION_COMPRESSION_TYPES_TO_SERVE = defineListFlag( "file-distribution-compression-types-to-use", List.of("lz4", "gzip"), String.class, List.of("hmusum"), "2022-07-05", "2022-11-01", "List of compression types to use (in preferred order), matched with accepted compression types when serving file references. Valid values: gzip, lz4", "Takes effect on restart of service", APPLICATION_ID); public static final UnboundBooleanFlag USE_YUM_PROXY_V2 = defineFeatureFlag( "use-yumproxy-v2", false, List.of("tokle"), "2022-05-05", "2022-11-01", "Use yumproxy-v2", "Takes effect on host admin restart", HOSTNAME); public static final UnboundStringFlag LOG_FILE_COMPRESSION_ALGORITHM = defineStringFlag( "log-file-compression-algorithm", "", List.of("arnej"), "2022-06-14", "2024-12-31", "Which algorithm to use for compressing log files. Valid values: empty string (default), gzip, zstd", "Takes effect immediately", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SEPARATE_METRIC_CHECK_CONFIG = defineFeatureFlag( "separate-metric-check-config", false, List.of("olaa"), "2022-07-04", "2022-11-01", "Determines whether one metrics config check should be written per Vespa node", "Takes effect on next tick", HOSTNAME); public static final UnboundStringFlag TLS_CAPABILITIES_ENFORCEMENT_MODE = defineStringFlag( "tls-capabilities-enforcement-mode", "disable", List.of("bjorncs", "vekterli"), "2022-07-21", "2024-01-01", "Configure Vespa TLS capability enforcement mode", "Takes effect on restart of Docker container", APPLICATION_ID,HOSTNAME,NODE_TYPE,TENANT_ID,VESPA_VERSION ); public static final UnboundBooleanFlag CLEANUP_TENANT_ROLES = defineFeatureFlag( "cleanup-tenant-roles", false, List.of("olaa"), "2022-08-10", "2023-01-01", "Determines whether old tenant roles should be deleted", "Takes effect next maintenance run" ); public static final UnboundBooleanFlag USE_TWO_PHASE_DOCUMENT_GC = defineFeatureFlag( "use-two-phase-document-gc", false, List.of("vekterli"), "2022-08-24", "2022-11-01", "Use two-phase document GC in content clusters", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag RESTRICT_DATA_PLANE_BINDINGS = defineFeatureFlag( "restrict-data-plane-bindings", false, List.of("mortent"), "2022-09-08", "2022-11-01", "Use restricted data plane bindings", "Takes effect at redeployment", APPLICATION_ID); public static final UnboundStringFlag CSRF_MODE = defineStringFlag( "csrf-mode", "disabled", List.of("bjorncs", "tokle"), "2022-09-22", "2023-06-01", "Set mode for CSRF filter ('disabled', 'log_only', 'enabled')", "Takes effect on controller restart/redeployment"); public static final UnboundBooleanFlag SOFT_REBUILD = defineFeatureFlag( "soft-rebuild", false, List.of("mpolden"), "2022-09-27", "2022-12-01", "Whether soft rebuild can be used to rebuild hosts with remote disk", "Takes effect on next run of OsUpgradeActivator" ); public static final UnboundListFlag<String> CSRF_USERS = defineListFlag( "csrf-users", List.of(), String.class, List.of("bjorncs", "tokle"), "2022-09-22", "2023-06-01", "List of users to enable CSRF filter for. Use empty list for everyone.", "Takes effect on controller restart/redeployment"); public static final UnboundBooleanFlag ENABLE_OTELCOL = defineFeatureFlag( "enable-otel-collector", false, List.of("olaa"), "2022-09-23", "2023-01-01", "Whether an OpenTelemetry collector should be enabled", "Takes effect at next tick", APPLICATION_ID); public static final UnboundBooleanFlag CONSOLE_CSRF = defineFeatureFlag( "console-csrf", false, List.of("bjorncs", "tokle"), "2022-09-26", "2023-06-01", "Enable CSRF token in console", "Takes effect immediately", CONSOLE_USER_EMAIL); public static final UnboundBooleanFlag USE_WIREGUARD_ON_CONFIGSERVERS = defineFeatureFlag( "use-wireguard-on-configservers", false, List.of("andreer", "gjoranv"), "2022-09-28", "2023-04-01", "Set up a WireGuard endpoint on config servers", "Takes effect on configserver restart", ZONE_ID, NODE_TYPE); public static final UnboundBooleanFlag USE_WIREGUARD_ON_TENANT_HOSTS = defineFeatureFlag( "use-wireguard-on-tenant-hosts", false, List.of("andreer", "gjoranv"), "2022-09-28", "2023-04-01", "Set up a WireGuard endpoint on tenant hosts", "Takes effect on host admin restart", HOSTNAME); /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundBooleanFlag defineFeatureFlag(String flagId, boolean defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundBooleanFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundStringFlag defineStringFlag(String flagId, String defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return defineStringFlag(flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, value -> true, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundStringFlag defineStringFlag(String flagId, String defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, Predicate<String> validator, FetchVector.Dimension... dimensions) { return define((i, d, v) -> new UnboundStringFlag(i, d, v, validator), flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundIntFlag defineIntFlag(String flagId, int defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundIntFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundLongFlag defineLongFlag(String flagId, long defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundLongFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundDoubleFlag defineDoubleFlag(String flagId, double defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundDoubleFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static <T> UnboundJacksonFlag<T> defineJacksonFlag(String flagId, T defaultValue, Class<T> jacksonClass, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define((id2, defaultValue2, vector2) -> new UnboundJacksonFlag<>(id2, defaultValue2, vector2, jacksonClass), flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static <T> UnboundListFlag<T> defineListFlag(String flagId, List<T> defaultValue, Class<T> elementClass, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define((fid, dval, fvec) -> new UnboundListFlag<>(fid, dval, elementClass, fvec), flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } @FunctionalInterface private interface TypedUnboundFlagFactory<T, U extends UnboundFlag<?, ?, ?>> { U create(FlagId id, T defaultValue, FetchVector defaultFetchVector); } /** * Defines a Flag. * * @param factory Factory for creating unbound flag of type U * @param flagId The globally unique FlagId. * @param defaultValue The default value if none is present after resolution. * @param description Description of how the flag is used. * @param modificationEffect What is required for the flag to take effect? A restart of process? immediately? etc. * @param dimensions What dimensions will be set in the {@link FetchVector} when fetching * the flag value in * {@link FlagSource#fetch(FlagId, FetchVector) FlagSource::fetch}. * For instance, if APPLICATION is one of the dimensions here, you should make sure * APPLICATION is set to the ApplicationId in the fetch vector when fetching the RawFlag * from the FlagSource. * @param <T> The boxed type of the flag value, e.g. Boolean for flags guarding features. * @param <U> The type of the unbound flag, e.g. UnboundBooleanFlag. * @return An unbound flag with {@link FetchVector.Dimension#HOSTNAME HOSTNAME} and * {@link FetchVector.Dimension#VESPA_VERSION VESPA_VERSION} already set. The ZONE environment * is typically implicit. */ private static <T, U extends UnboundFlag<?, ?, ?>> U define(TypedUnboundFlagFactory<T, U> factory, String flagId, T defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension[] dimensions) { FlagId id = new FlagId(flagId); FetchVector vector = new FetchVector() .with(HOSTNAME, Defaults.getDefaults().vespaHostname()) // Warning: In unit tests and outside official Vespa releases, the currentVersion is e.g. 7.0.0 // (determined by the current major version). Consider not setting VESPA_VERSION if minor = micro = 0. .with(VESPA_VERSION, Vtag.currentVersion.toFullString()); U unboundFlag = factory.create(id, defaultValue, vector); FlagDefinition definition = new FlagDefinition( unboundFlag, owners, parseDate(createdAt), parseDate(expiresAt), description, modificationEffect, dimensions); flags.put(id, definition); return unboundFlag; } private static Instant parseDate(String rawDate) { return DateTimeFormatter.ISO_DATE.parse(rawDate, LocalDate::from).atStartOfDay().toInstant(ZoneOffset.UTC); } public static List<FlagDefinition> getAllFlags() { return List.copyOf(flags.values()); } public static Optional<FlagDefinition> getFlag(FlagId flagId) { return Optional.ofNullable(flags.get(flagId)); } /** * Allows the statically defined flags to be controlled in a test. * * <p>Returns a Replacer instance to be used with e.g. a try-with-resources block. Within the block, * the flags starts out as cleared. Flags can be defined, etc. When leaving the block, the flags from * before the block is reinserted. * * <p>NOT thread-safe. Tests using this cannot run in parallel. */ public static Replacer clearFlagsForTesting(FlagId... flagsToKeep) { return new Replacer(flagsToKeep); } public static class Replacer implements AutoCloseable { private static volatile boolean flagsCleared = false; private final TreeMap<FlagId, FlagDefinition> savedFlags; private Replacer(FlagId... flagsToKeep) { verifyAndSetFlagsCleared(true); this.savedFlags = Flags.flags; Flags.flags = new TreeMap<>(); List.of(flagsToKeep).forEach(id -> Flags.flags.put(id, savedFlags.get(id))); } @Override public void close() { verifyAndSetFlagsCleared(false); Flags.flags = savedFlags; } /** * Used to implement a simple verification that Replacer is not used by multiple threads. * For instance two different tests running in parallel cannot both use Replacer. */ private static void verifyAndSetFlagsCleared(boolean newValue) { if (flagsCleared == newValue) { throw new IllegalStateException("clearFlagsForTesting called while already cleared - running tests in parallell!?"); } flagsCleared = newValue; } } }
package com.yahoo.vespa.flags; import com.yahoo.component.Vtag; import com.yahoo.vespa.defaults.Defaults; import com.yahoo.vespa.flags.custom.PreprovisionCapacity; import java.util.List; import java.util.Optional; import java.util.TreeMap; import static com.yahoo.vespa.flags.FetchVector.Dimension.APPLICATION_ID; import static com.yahoo.vespa.flags.FetchVector.Dimension.HOSTNAME; import static com.yahoo.vespa.flags.FetchVector.Dimension.NODE_TYPE; import static com.yahoo.vespa.flags.FetchVector.Dimension.VESPA_VERSION; import static com.yahoo.vespa.flags.FetchVector.Dimension.ZONE_ID; /** * Definitions of feature flags. * * <p>To use feature flags, define the flag in this class as an "unbound" flag, e.g. {@link UnboundBooleanFlag} * or {@link UnboundStringFlag}. At the location you want to get the value of the flag, you need the following:</p> * * <ol> * <li>The unbound flag</li> * <li>A {@link FlagSource}. The flag source is typically available as an injectable component. Binding * an unbound flag to a flag source produces a (bound) flag, e.g. {@link BooleanFlag} and {@link StringFlag}.</li> * <li>If you would like your flag value to be dependent on e.g. the application ID, then 1. you should * declare this in the unbound flag definition in this file (referring to * {@link FetchVector.Dimension#APPLICATION_ID}), and 2. specify the application ID when retrieving the value, e.g. * {@link BooleanFlag#with(FetchVector.Dimension, String)}. See {@link FetchVector} for more info.</li> * </ol> * * <p>Once the code is in place, you can override the flag value. This depends on the flag source, but typically * there is a REST API for updating the flags in the config server, which is the root of all flag sources in the zone.</p> * * @author hakonhall */ public class Flags { private static volatile TreeMap<FlagId, FlagDefinition> flags = new TreeMap<>(); public static final UnboundIntFlag DROP_CACHES = defineIntFlag( "drop-caches", 3, "The int value to write into /proc/sys/vm/drop_caches for each tick. " + "1 is page cache, 2 is dentries inodes, 3 is both page cache and dentries inodes, etc.", "Takes effect on next tick.", HOSTNAME); public static final UnboundBooleanFlag ENABLE_CROWDSTRIKE = defineFeatureFlag( "enable-crowdstrike", true, "Whether to enable CrowdStrike.", "Takes effect on next host admin tick", HOSTNAME); public static final UnboundBooleanFlag ENABLE_NESSUS = defineFeatureFlag( "enable-nessus", true, "Whether to enable Nessus.", "Takes effect on next host admin tick", HOSTNAME); public static final UnboundBooleanFlag ENABLE_FLEET_SSHD_CONFIG = defineFeatureFlag( "enable-fleet-sshd-config", true, "Whether fleet should manage the /etc/ssh/sshd_config file.", "Takes effect on next host admin tick.", HOSTNAME); public static final UnboundBooleanFlag FLEET_CANARY = defineFeatureFlag( "fleet-canary", false, "Whether the host is a fleet canary.", "Takes effect on next host admin tick.", HOSTNAME); public static final UnboundBooleanFlag USE_NEW_VESPA_RPMS = defineFeatureFlag( "use-new-vespa-rpms", false, "Whether to use the new vespa-rpms YUM repo when upgrading/downgrading. The vespa-version " + "when fetching the flag value is the wanted version of the host.", "Takes effect when upgrading or downgrading host admin to a different version.", HOSTNAME, NODE_TYPE, VESPA_VERSION); public static final UnboundListFlag<String> DISABLED_HOST_ADMIN_TASKS = defineListFlag( "disabled-host-admin-tasks", List.of(), String.class, "List of host-admin task names (as they appear in the log, e.g. root>main>UpgradeTask) that should be skipped", "Takes effect on next host admin tick", HOSTNAME, NODE_TYPE); public static final UnboundStringFlag DOCKER_VERSION = defineStringFlag( "docker-version", "1.13.1-102.git7f2769b", "The version of the docker to use of the format VERSION-REL: The YUM package to be installed will be " + "2:docker-VERSION-REL.el7.centos.x86_64 in AWS (and without '.centos' otherwise). " + "If docker-version is not of this format, it must be parseable by YumPackageName::fromString.", "Takes effect on next tick.", HOSTNAME); public static final UnboundLongFlag THIN_POOL_GB = defineLongFlag( "thin-pool-gb", -1, "The size of the disk reserved for the thin pool with dynamic provisioning in AWS, in base-2 GB. " + "If <0, the default is used (which may depend on the zone and node type).", "Takes effect immediately (but used only during provisioning).", NODE_TYPE); public static final UnboundDoubleFlag CONTAINER_CPU_CAP = defineDoubleFlag( "container-cpu-cap", 0, "Hard limit on how many CPUs a container may use. This value is multiplied by CPU allocated to node, so " + "to cap CPU at 200%, set this to 2, etc.", "Takes effect on next node agent tick. Change is orchestrated, but does NOT require container restart", HOSTNAME, APPLICATION_ID); public static final UnboundStringFlag TLS_INSECURE_AUTHORIZATION_MODE = defineStringFlag( "tls-insecure-authorization-mode", "log_only", "TLS insecure authorization mode. Allowed values: ['disable', 'log_only', 'enforce']", "Takes effect on restart of Docker container", NODE_TYPE, APPLICATION_ID, HOSTNAME); public static final UnboundBooleanFlag USE_ADAPTIVE_DISPATCH = defineFeatureFlag( "use-adaptive-dispatch", false, "Should adaptive dispatch be used over round robin", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag REBOOT_INTERVAL_IN_DAYS = defineIntFlag( "reboot-interval-in-days", 30, "No reboots are scheduled 0x-1x reboot intervals after the previous reboot, while reboot is " + "scheduled evenly distributed in the 1x-2x range (and naturally guaranteed at the 2x boundary).", "Takes effect on next run of NodeRebooter"); public static final UnboundBooleanFlag RETIRE_WITH_PERMANENTLY_DOWN = defineFeatureFlag( "retire-with-permanently-down", false, "If enabled, retirement will end with setting the host status to PERMANENTLY_DOWN, " + "instead of ALLOWED_TO_BE_DOWN (old behavior).", "Takes effect on the next run of RetiredExpirer.", HOSTNAME); public static final UnboundListFlag<PreprovisionCapacity> PREPROVISION_CAPACITY = defineListFlag( "preprovision-capacity", List.of(), PreprovisionCapacity.class, "List of node resources and their count that should be present in zone to receive new deployments. When a " + "preprovisioned is taken, new will be provisioned within next iteration of maintainer.", "Takes effect on next iteration of HostProvisionMaintainer."); public static final UnboundDoubleFlag DEFAULT_TERM_WISE_LIMIT = defineDoubleFlag( "default-term-wise-limit", 1.0, "Default limit for when to apply termwise query evaluation", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag DEFAULT_SOFT_START_SECONDS = defineDoubleFlag( "default-soft-start-seconds", 0.0, "Default number of seconds that a soft start shall use", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag DEFAULT_THREADPOOL_SIZE_FACTOR = defineDoubleFlag( "default-threadpool-size-factor", 0.0, "Default multiplication factor when computing maxthreads for main container threadpool based on available cores", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag DEFAULT_QUEUE_SIZE_FACTOR = defineDoubleFlag( "default-queue-size-factor", 0.0, "Default multiplication factor when computing queuesize for burst handling", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag DEFAULT_TOP_K_PROBABILITY = defineDoubleFlag( "default-top-k-probability", 1.0, "Default probability that you will get the globally top K documents when merging many partitions.", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag DEFAULT_NUM_RESPONSE_THREADS = defineIntFlag( "default-num-response-threads", 0, "Default number of threads used for processing put/update/remove responses.", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_DISTRIBUTOR_BTREE_DB = defineFeatureFlag( "use-distributor-btree-db", false, "Whether to use the new B-tree bucket database in the distributors.", "Takes effect at restart of distributor process", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_THREE_PHASE_UPDATES = defineFeatureFlag( "use-three-phase-updates", false, "Whether to enable the use of three-phase updates when bucket replicas are out of sync.", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag HOST_HARDENING = defineFeatureFlag( "host-hardening", false, "Whether to enable host hardening Linux baseline.", "Takes effect on next tick or on host-admin restart (may vary where used).", HOSTNAME); public static final UnboundBooleanFlag TCP_ABORT_ON_OVERFLOW = defineFeatureFlag( "tcp-abort-on-overflow", false, "Whether to set /proc/sys/net/ipv4/tcp_abort_on_overflow to 0 (false) or 1 (true)", "Takes effect on next host-admin tick.", HOSTNAME); public static final UnboundStringFlag ZOOKEEPER_SERVER_MAJOR_MINOR_VERSION = defineStringFlag( "zookeeper-server-version", "3.5", "The version of ZooKeeper server to use (major.minor, not full version)", "Takes effect on restart of Docker container", NODE_TYPE, APPLICATION_ID, HOSTNAME); public static final UnboundStringFlag TLS_FOR_ZOOKEEPER_QUORUM_COMMUNICATION = defineStringFlag( "tls-for-zookeeper-quorum-communication", "TLS_WITH_PORT_UNIFICATION", "How to setup TLS for ZooKeeper quorum communication. Valid values are OFF, PORT_UNIFICATION, TLS_WITH_PORT_UNIFICATION, TLS_ONLY", "Takes effect on restart of config server", NODE_TYPE, HOSTNAME); public static final UnboundStringFlag TLS_FOR_ZOOKEEPER_CLIENT_SERVER_COMMUNICATION = defineStringFlag( "tls-for-zookeeper-client-server-communication", "OFF", "How to setup TLS for ZooKeeper client/server communication. Valid values are OFF, PORT_UNIFICATION, TLS_WITH_PORT_UNIFICATION, TLS_ONLY", "Takes effect on restart of config server", NODE_TYPE, HOSTNAME); public static final UnboundBooleanFlag USE_TLS_FOR_ZOOKEEPER_CLIENT = defineFeatureFlag( "use-tls-for-zookeeper-client", false, "Whether to use TLS for ZooKeeper clients", "Takes effect on restart of process", NODE_TYPE, HOSTNAME); public static final UnboundBooleanFlag ENABLE_DISK_WRITE_TEST = defineFeatureFlag( "enable-disk-write-test", true, "Regularly issue a small write to disk and fail the host if it is not successful", "Takes effect on next node agent tick (but does not clear existing failure reports)", HOSTNAME); public static final UnboundBooleanFlag USE_REFRESHED_ENDPOINT_CERTIFICATE = defineFeatureFlag( "use-refreshed-endpoint-certificate", false, "Whether an application should start using a newer certificate/key pair if available", "Takes effect on the next deployment of the application", APPLICATION_ID); public static final UnboundBooleanFlag VALIDATE_ENDPOINT_CERTIFICATES = defineFeatureFlag( "validate-endpoint-certificates", false, "Whether endpoint certificates should be validated before use", "Takes effect on the next deployment of the application"); public static final UnboundStringFlag ENDPOINT_CERTIFICATE_BACKFILL = defineStringFlag( "endpoint-certificate-backfill", "disable", "Whether the endpoint certificate maintainer should backfill missing certificate data from cameo", "Takes effect on next scheduled run of maintainer - set to \"disable\", \"dryrun\" or \"enable\""); public static final UnboundStringFlag DOCKER_IMAGE_REPO = defineStringFlag( "docker-image-repo", "", "Override default docker image repo. Docker image version will be Vespa version.", "Takes effect on next deployment from controller", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag ENDPOINT_CERT_IN_SHARED_ROUTING = defineFeatureFlag( "endpoint-cert-in-shared-routing", false, "Whether to provision and use endpoint certs for apps in shared routing zones", "Takes effect on next deployment of the application", APPLICATION_ID); public static final UnboundBooleanFlag PHRASE_SEGMENTING = defineFeatureFlag( "phrase-segmenting", false, "Should 'implicit phrases' in queries we parsed to a phrase or and?", "Takes effect on redeploy", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag ALLOW_DIRECT_ROUTING = defineFeatureFlag( "publish-direct-routing-endpoint", false, "Whether an application should receive a directly routed endpoint in its endpoint list", "Takes effect immediately", APPLICATION_ID); public static final UnboundBooleanFlag NLB_PROXY_PROTOCOL = defineFeatureFlag( "nlb-proxy-protocol", false, "Configure NLB to use proxy protocol", "Takes effect on next application redeploy", APPLICATION_ID); public static final UnboundLongFlag CONFIGSERVER_SESSIONS_EXPIRY_INTERVAL_IN_DAYS = defineLongFlag( "configserver-sessions-expiry-interval-in-days", 28, "Expiry time for unused sessions in config server", "Takes effect on next run of config server maintainer SessionsMaintainer"); public static final UnboundBooleanFlag USE_CLOUD_INIT_FORMAT = defineFeatureFlag( "use-cloud-init", false, "Use the cloud-init format when provisioning hosts", "Takes effect immediately", ZONE_ID); public static final UnboundBooleanFlag CONFIGSERVER_DISTRIBUTE_APPLICATION_PACKAGE = defineFeatureFlag( "configserver-distribute-application-package", false, "Whether the application package should be distributed to other config servers during a deployment", "Takes effect immediately"); public static final UnboundBooleanFlag CONFIGSERVER_UNSET_ENDPOINTS = defineFeatureFlag( "configserver-unset-endpoints", false, "Whether the configserver allows removal of existing endpoints when an empty list of container endpoints is request", "Takes effect on next external deployment", APPLICATION_ID ); /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundBooleanFlag defineFeatureFlag(String flagId, boolean defaultValue, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundBooleanFlag::new, flagId, defaultValue, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundStringFlag defineStringFlag(String flagId, String defaultValue, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundStringFlag::new, flagId, defaultValue, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundIntFlag defineIntFlag(String flagId, int defaultValue, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundIntFlag::new, flagId, defaultValue, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundLongFlag defineLongFlag(String flagId, long defaultValue, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundLongFlag::new, flagId, defaultValue, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundDoubleFlag defineDoubleFlag(String flagId, double defaultValue, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundDoubleFlag::new, flagId, defaultValue, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static <T> UnboundJacksonFlag<T> defineJacksonFlag(String flagId, T defaultValue, Class<T> jacksonClass, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define((id2, defaultValue2, vector2) -> new UnboundJacksonFlag<>(id2, defaultValue2, vector2, jacksonClass), flagId, defaultValue, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static <T> UnboundListFlag<T> defineListFlag(String flagId, List<T> defaultValue, Class<T> elementClass, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define((fid, dval, fvec) -> new UnboundListFlag<>(fid, dval, elementClass, fvec), flagId, defaultValue, description, modificationEffect, dimensions); } @FunctionalInterface private interface TypedUnboundFlagFactory<T, U extends UnboundFlag<?, ?, ?>> { U create(FlagId id, T defaultVale, FetchVector defaultFetchVector); } /** * Defines a Flag. * * @param factory Factory for creating unbound flag of type U * @param flagId The globally unique FlagId. * @param defaultValue The default value if none is present after resolution. * @param description Description of how the flag is used. * @param modificationEffect What is required for the flag to take effect? A restart of process? immediately? etc. * @param dimensions What dimensions will be set in the {@link FetchVector} when fetching * the flag value in * {@link FlagSource#fetch(FlagId, FetchVector) FlagSource::fetch}. * For instance, if APPLICATION is one of the dimensions here, you should make sure * APPLICATION is set to the ApplicationId in the fetch vector when fetching the RawFlag * from the FlagSource. * @param <T> The boxed type of the flag value, e.g. Boolean for flags guarding features. * @param <U> The type of the unbound flag, e.g. UnboundBooleanFlag. * @return An unbound flag with {@link FetchVector.Dimension#HOSTNAME HOSTNAME} and * {@link FetchVector.Dimension#VESPA_VERSION VESPA_VERSION} already set. The ZONE environment * is typically implicit. */ private static <T, U extends UnboundFlag<?, ?, ?>> U define(TypedUnboundFlagFactory<T, U> factory, String flagId, T defaultValue, String description, String modificationEffect, FetchVector.Dimension[] dimensions) { FlagId id = new FlagId(flagId); FetchVector vector = new FetchVector() .with(HOSTNAME, Defaults.getDefaults().vespaHostname()) // Warning: In unit tests and outside official Vespa releases, the currentVersion is e.g. 7.0.0 // (determined by the current major version). Consider not setting VESPA_VERSION if minor = micro = 0. .with(VESPA_VERSION, Vtag.currentVersion.toFullString()); U unboundFlag = factory.create(id, defaultValue, vector); FlagDefinition definition = new FlagDefinition(unboundFlag, description, modificationEffect, dimensions); flags.put(id, definition); return unboundFlag; } public static List<FlagDefinition> getAllFlags() { return List.copyOf(flags.values()); } public static Optional<FlagDefinition> getFlag(FlagId flagId) { return Optional.ofNullable(flags.get(flagId)); } /** * Allows the statically defined flags to be controlled in a test. * * <p>Returns a Replacer instance to be used with e.g. a try-with-resources block. Within the block, * the flags starts out as cleared. Flags can be defined, etc. When leaving the block, the flags from * before the block is reinserted. * * <p>NOT thread-safe. Tests using this cannot run in parallel. */ public static Replacer clearFlagsForTesting() { return new Replacer(); } public static class Replacer implements AutoCloseable { private static volatile boolean flagsCleared = false; private final TreeMap<FlagId, FlagDefinition> savedFlags; private Replacer() { verifyAndSetFlagsCleared(true); this.savedFlags = Flags.flags; Flags.flags = new TreeMap<>(); } @Override public void close() { verifyAndSetFlagsCleared(false); Flags.flags = savedFlags; } /** * Used to implement a simple verification that Replacer is not used by multiple threads. * For instance two different tests running in parallel cannot both use Replacer. */ private static void verifyAndSetFlagsCleared(boolean newValue) { if (flagsCleared == newValue) { throw new IllegalStateException("clearFlagsForTesting called while already cleared - running tests in parallell!?"); } flagsCleared = newValue; } } }
package com.yahoo.vespa.flags; import com.yahoo.component.Vtag; import com.yahoo.vespa.defaults.Defaults; import com.yahoo.vespa.flags.custom.PreprovisionCapacity; import java.util.List; import java.util.Optional; import java.util.TreeMap; import static com.yahoo.vespa.flags.FetchVector.Dimension.APPLICATION_ID; import static com.yahoo.vespa.flags.FetchVector.Dimension.HOSTNAME; import static com.yahoo.vespa.flags.FetchVector.Dimension.NODE_TYPE; import static com.yahoo.vespa.flags.FetchVector.Dimension.VESPA_VERSION; import static com.yahoo.vespa.flags.FetchVector.Dimension.ZONE_ID; /** * Definitions of feature flags. * * <p>To use feature flags, define the flag in this class as an "unbound" flag, e.g. {@link UnboundBooleanFlag} * or {@link UnboundStringFlag}. At the location you want to get the value of the flag, you need the following:</p> * * <ol> * <li>The unbound flag</li> * <li>A {@link FlagSource}. The flag source is typically available as an injectable component. Binding * an unbound flag to a flag source produces a (bound) flag, e.g. {@link BooleanFlag} and {@link StringFlag}.</li> * <li>If you would like your flag value to be dependent on e.g. the application ID, then 1. you should * declare this in the unbound flag definition in this file (referring to * {@link FetchVector.Dimension#APPLICATION_ID}), and 2. specify the application ID when retrieving the value, e.g. * {@link BooleanFlag#with(FetchVector.Dimension, String)}. See {@link FetchVector} for more info.</li> * </ol> * * <p>Once the code is in place, you can override the flag value. This depends on the flag source, but typically * there is a REST API for updating the flags in the config server, which is the root of all flag sources in the zone.</p> * * @author hakonhall */ public class Flags { private static volatile TreeMap<FlagId, FlagDefinition> flags = new TreeMap<>(); public static final UnboundIntFlag DROP_CACHES = defineIntFlag( "drop-caches", 3, "The int value to write into /proc/sys/vm/drop_caches for each tick. " + "1 is page cache, 2 is dentries inodes, 3 is both page cache and dentries inodes, etc.", "Takes effect on next tick.", HOSTNAME); public static final UnboundBooleanFlag ENABLE_CROWDSTRIKE = defineFeatureFlag( "enable-crowdstrike", true, "Whether to enable CrowdStrike.", "Takes effect on next host admin tick", HOSTNAME); public static final UnboundBooleanFlag ENABLE_NESSUS = defineFeatureFlag( "enable-nessus", true, "Whether to enable Nessus.", "Takes effect on next host admin tick", HOSTNAME); public static final UnboundBooleanFlag ENABLE_FLEET_SSHD_CONFIG = defineFeatureFlag( "enable-fleet-sshd-config", true, "Whether fleet should manage the /etc/ssh/sshd_config file.", "Takes effect on next host admin tick.", HOSTNAME); public static final UnboundBooleanFlag FLEET_CANARY = defineFeatureFlag( "fleet-canary", false, "Whether the host is a fleet canary.", "Takes effect on next host admin tick.", HOSTNAME); public static final UnboundBooleanFlag USE_NEW_VESPA_RPMS = defineFeatureFlag( "use-new-vespa-rpms", false, "Whether to use the new vespa-rpms YUM repo when upgrading/downgrading. The vespa-version " + "when fetching the flag value is the wanted version of the host.", "Takes effect when upgrading or downgrading host admin to a different version.", HOSTNAME, NODE_TYPE, VESPA_VERSION); public static final UnboundListFlag<String> DISABLED_HOST_ADMIN_TASKS = defineListFlag( "disabled-host-admin-tasks", List.of(), String.class, "List of host-admin task names (as they appear in the log, e.g. root>main>UpgradeTask) that should be skipped", "Takes effect on next host admin tick", HOSTNAME, NODE_TYPE); public static final UnboundStringFlag DOCKER_VERSION = defineStringFlag( "docker-version", "1.13.1-102.git7f2769b", "The version of the docker to use of the format VERSION-REL: The YUM package to be installed will be " + "2:docker-VERSION-REL.el7.centos.x86_64 in AWS (and without '.centos' otherwise). " + "If docker-version is not of this format, it must be parseable by YumPackageName::fromString.", "Takes effect on next tick.", HOSTNAME); public static final UnboundLongFlag THIN_POOL_GB = defineLongFlag( "thin-pool-gb", -1, "The size of the disk reserved for the thin pool with dynamic provisioning in AWS, in base-2 GB. " + "If <0, the default is used (which may depend on the zone and node type).", "Takes effect immediately (but used only during provisioning).", NODE_TYPE); public static final UnboundDoubleFlag CONTAINER_CPU_CAP = defineDoubleFlag( "container-cpu-cap", 0, "Hard limit on how many CPUs a container may use. This value is multiplied by CPU allocated to node, so " + "to cap CPU at 200%, set this to 2, etc.", "Takes effect on next node agent tick. Change is orchestrated, but does NOT require container restart", HOSTNAME, APPLICATION_ID); public static final UnboundStringFlag TLS_INSECURE_AUTHORIZATION_MODE = defineStringFlag( "tls-insecure-authorization-mode", "log_only", "TLS insecure authorization mode. Allowed values: ['disable', 'log_only', 'enforce']", "Takes effect on restart of Docker container", NODE_TYPE, APPLICATION_ID, HOSTNAME); public static final UnboundIntFlag REBOOT_INTERVAL_IN_DAYS = defineIntFlag( "reboot-interval-in-days", 30, "No reboots are scheduled 0x-1x reboot intervals after the previous reboot, while reboot is " + "scheduled evenly distributed in the 1x-2x range (and naturally guaranteed at the 2x boundary).", "Takes effect on next run of NodeRebooter"); public static final UnboundBooleanFlag RETIRE_WITH_PERMANENTLY_DOWN = defineFeatureFlag( "retire-with-permanently-down", false, "If enabled, retirement will end with setting the host status to PERMANENTLY_DOWN, " + "instead of ALLOWED_TO_BE_DOWN (old behavior).", "Takes effect on the next run of RetiredExpirer.", HOSTNAME); public static final UnboundListFlag<PreprovisionCapacity> PREPROVISION_CAPACITY = defineListFlag( "preprovision-capacity", List.of(), PreprovisionCapacity.class, "List of node resources and their count that should be present in zone to receive new deployments. When a " + "preprovisioned is taken, new will be provisioned within next iteration of maintainer.", "Takes effect on next iteration of HostProvisionMaintainer."); public static final UnboundDoubleFlag DEFAULT_TERM_WISE_LIMIT = defineDoubleFlag( "default-term-wise-limit", 1.0, "Default limit for when to apply termwise query evaluation", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag DEFAULT_SOFT_START_SECONDS = defineDoubleFlag( "default-soft-start-seconds", 0.0, "Default number of seconds that a soft start shall use", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag DEFAULT_THREADPOOL_SIZE_FACTOR = defineDoubleFlag( "default-threadpool-size-factor", 0.0, "Default multiplication factor when computing maxthreads for main container threadpool based on available cores", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag DEFAULT_QUEUE_SIZE_FACTOR = defineDoubleFlag( "default-queue-size-factor", 0.0, "Default multiplication factor when computing queuesize for burst handling", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag DEFAULT_TOP_K_PROBABILITY = defineDoubleFlag( "default-top-k-probability", 1.0, "Default probability that you will get the globally top K documents when merging many partitions.", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_DISTRIBUTOR_BTREE_DB = defineFeatureFlag( "use-distributor-btree-db", false, "Whether to use the new B-tree bucket database in the distributors.", "Takes effect at restart of distributor process", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_THREE_PHASE_UPDATES = defineFeatureFlag( "use-three-phase-updates", false, "Whether to enable the use of three-phase updates when bucket replicas are out of sync.", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag HOST_HARDENING = defineFeatureFlag( "host-hardening", false, "Whether to enable host hardening Linux baseline.", "Takes effect on next tick or on host-admin restart (may vary where used).", HOSTNAME); public static final UnboundBooleanFlag TCP_ABORT_ON_OVERFLOW = defineFeatureFlag( "tcp-abort-on-overflow", false, "Whether to set /proc/sys/net/ipv4/tcp_abort_on_overflow to 0 (false) or 1 (true)", "Takes effect on next host-admin tick.", HOSTNAME); public static final UnboundStringFlag ZOOKEEPER_SERVER_VERSION = defineStringFlag( "zookeeper-server-version", "3.5.6", "ZooKeeper server version, a jar file zookeeper-server-<ZOOKEEPER_SERVER_VERSION>-jar-with-dependencies.jar must exist", "Takes effect on restart of Docker container", NODE_TYPE, APPLICATION_ID, HOSTNAME); public static final UnboundStringFlag TLS_FOR_ZOOKEEPER_CLIENT_SERVER_COMMUNICATION = defineStringFlag( "tls-for-zookeeper-client-server-communication", "OFF", "How to setup TLS for ZooKeeper client/server communication. Valid values are OFF, PORT_UNIFICATION, TLS_WITH_PORT_UNIFICATION, TLS_ONLY", "Takes effect on restart of config server", NODE_TYPE, HOSTNAME); public static final UnboundBooleanFlag USE_TLS_FOR_ZOOKEEPER_CLIENT = defineFeatureFlag( "use-tls-for-zookeeper-client", false, "Whether to use TLS for ZooKeeper clients", "Takes effect on restart of process", NODE_TYPE, HOSTNAME); public static final UnboundBooleanFlag ENABLE_DISK_WRITE_TEST = defineFeatureFlag( "enable-disk-write-test", true, "Regularly issue a small write to disk and fail the host if it is not successful", "Takes effect on next node agent tick (but does not clear existing failure reports)", HOSTNAME); public static final UnboundBooleanFlag USE_REFRESHED_ENDPOINT_CERTIFICATE = defineFeatureFlag( "use-refreshed-endpoint-certificate", false, "Whether an application should start using a newer certificate/key pair if available", "Takes effect on the next deployment of the application", APPLICATION_ID); public static final UnboundBooleanFlag VALIDATE_ENDPOINT_CERTIFICATES = defineFeatureFlag( "validate-endpoint-certificates", false, "Whether endpoint certificates should be validated before use", "Takes effect on the next deployment of the application"); public static final UnboundStringFlag ENDPOINT_CERTIFICATE_BACKFILL = defineStringFlag( "endpoint-certificate-backfill", "disable", "Whether the endpoint certificate maintainer should backfill missing certificate data from cameo", "Takes effect on next scheduled run of maintainer - set to \"disable\", \"dryrun\" or \"enable\""); public static final UnboundStringFlag DOCKER_IMAGE_REPO = defineStringFlag( "docker-image-repo", "", "Override default docker image repo. Docker image version will be Vespa version.", "Takes effect on next deployment from controller", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag ENDPOINT_CERT_IN_SHARED_ROUTING = defineFeatureFlag( "endpoint-cert-in-shared-routing", false, "Whether to provision and use endpoint certs for apps in shared routing zones", "Takes effect on next deployment of the application", APPLICATION_ID); public static final UnboundBooleanFlag PHRASE_SEGMENTING = defineFeatureFlag( "phrase-segmenting", false, "Should 'implicit phrases' in queries we parsed to a phrase or and?", "Takes effect on redeploy", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag ALLOW_DIRECT_ROUTING = defineFeatureFlag( "publish-direct-routing-endpoint", false, "Whether an application should receive a directly routed endpoint in its endpoint list", "Takes effect immediately", APPLICATION_ID); public static final UnboundBooleanFlag NLB_PROXY_PROTOCOL = defineFeatureFlag( "nlb-proxy-protocol", false, "Configure NLB to use proxy protocol", "Takes effect on next application redeploy", APPLICATION_ID); public static final UnboundLongFlag CONFIGSERVER_SESSIONS_EXPIRY_INTERVAL_IN_DAYS = defineLongFlag( "configserver-sessions-expiry-interval-in-days", 28, "Expiry time for unused sessions in config server", "Takes effect on next run of config server maintainer SessionsMaintainer"); public static final UnboundBooleanFlag USE_CLOUD_INIT_FORMAT = defineFeatureFlag( "use-cloud-init", false, "Use the cloud-init format when provisioning hosts", "Takes effect immediately", ZONE_ID); public static final UnboundBooleanFlag CONFIGSERVER_DISTRIBUTE_APPLICATION_PACKAGE = defineFeatureFlag( "configserver-distribute-application-package", false, "Whether the application package should be distributed to other config servers during a deployment", "Takes effect immediately"); public static final UnboundBooleanFlag PROVISION_APPLICATION_ROLES = defineFeatureFlag( "provision-application-roles", false, "Whether application roles should be provisioned", "Takes effect on next deployment (controller)", ZONE_ID); public static final UnboundBooleanFlag CONFIGSERVER_UNSET_ENDPOINTS = defineFeatureFlag( "configserver-unset-endpoints", false, "Whether the configserver allows removal of existing endpoints when an empty list of container endpoints is request", "Takes effect on next external deployment", APPLICATION_ID ); public static final UnboundIntFlag JDISC_HEALTH_CHECK_PROXY_CLIENT_TIMEOUT = defineIntFlag( "jdisc-health-check-proxy-client-timeout", 1000, "Temporary flag to rollout reduced timeout for JDisc's health check proxy client. Timeout in milliseconds", "Takes effect on next internal redeployment", APPLICATION_ID); public static final UnboundBooleanFlag APPLICATION_IAM_ROLE = defineFeatureFlag( "application-iam-roles", false, "Allow separate iam roles when provisioning/assigning hosts", "Takes effect immediately on new hosts, on next redeploy for applications", APPLICATION_ID); /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundBooleanFlag defineFeatureFlag(String flagId, boolean defaultValue, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundBooleanFlag::new, flagId, defaultValue, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundStringFlag defineStringFlag(String flagId, String defaultValue, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundStringFlag::new, flagId, defaultValue, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundIntFlag defineIntFlag(String flagId, int defaultValue, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundIntFlag::new, flagId, defaultValue, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundLongFlag defineLongFlag(String flagId, long defaultValue, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundLongFlag::new, flagId, defaultValue, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundDoubleFlag defineDoubleFlag(String flagId, double defaultValue, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundDoubleFlag::new, flagId, defaultValue, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static <T> UnboundJacksonFlag<T> defineJacksonFlag(String flagId, T defaultValue, Class<T> jacksonClass, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define((id2, defaultValue2, vector2) -> new UnboundJacksonFlag<>(id2, defaultValue2, vector2, jacksonClass), flagId, defaultValue, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static <T> UnboundListFlag<T> defineListFlag(String flagId, List<T> defaultValue, Class<T> elementClass, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define((fid, dval, fvec) -> new UnboundListFlag<>(fid, dval, elementClass, fvec), flagId, defaultValue, description, modificationEffect, dimensions); } @FunctionalInterface private interface TypedUnboundFlagFactory<T, U extends UnboundFlag<?, ?, ?>> { U create(FlagId id, T defaultVale, FetchVector defaultFetchVector); } /** * Defines a Flag. * * @param factory Factory for creating unbound flag of type U * @param flagId The globally unique FlagId. * @param defaultValue The default value if none is present after resolution. * @param description Description of how the flag is used. * @param modificationEffect What is required for the flag to take effect? A restart of process? immediately? etc. * @param dimensions What dimensions will be set in the {@link FetchVector} when fetching * the flag value in * {@link FlagSource#fetch(FlagId, FetchVector) FlagSource::fetch}. * For instance, if APPLICATION is one of the dimensions here, you should make sure * APPLICATION is set to the ApplicationId in the fetch vector when fetching the RawFlag * from the FlagSource. * @param <T> The boxed type of the flag value, e.g. Boolean for flags guarding features. * @param <U> The type of the unbound flag, e.g. UnboundBooleanFlag. * @return An unbound flag with {@link FetchVector.Dimension#HOSTNAME HOSTNAME} and * {@link FetchVector.Dimension#VESPA_VERSION VESPA_VERSION} already set. The ZONE environment * is typically implicit. */ private static <T, U extends UnboundFlag<?, ?, ?>> U define(TypedUnboundFlagFactory<T, U> factory, String flagId, T defaultValue, String description, String modificationEffect, FetchVector.Dimension[] dimensions) { FlagId id = new FlagId(flagId); FetchVector vector = new FetchVector() .with(HOSTNAME, Defaults.getDefaults().vespaHostname()) // Warning: In unit tests and outside official Vespa releases, the currentVersion is e.g. 7.0.0 // (determined by the current major version). Consider not setting VESPA_VERSION if minor = micro = 0. .with(VESPA_VERSION, Vtag.currentVersion.toFullString()); U unboundFlag = factory.create(id, defaultValue, vector); FlagDefinition definition = new FlagDefinition(unboundFlag, description, modificationEffect, dimensions); flags.put(id, definition); return unboundFlag; } public static List<FlagDefinition> getAllFlags() { return List.copyOf(flags.values()); } public static Optional<FlagDefinition> getFlag(FlagId flagId) { return Optional.ofNullable(flags.get(flagId)); } /** * Allows the statically defined flags to be controlled in a test. * * <p>Returns a Replacer instance to be used with e.g. a try-with-resources block. Within the block, * the flags starts out as cleared. Flags can be defined, etc. When leaving the block, the flags from * before the block is reinserted. * * <p>NOT thread-safe. Tests using this cannot run in parallel. */ public static Replacer clearFlagsForTesting() { return new Replacer(); } public static class Replacer implements AutoCloseable { private static volatile boolean flagsCleared = false; private final TreeMap<FlagId, FlagDefinition> savedFlags; private Replacer() { verifyAndSetFlagsCleared(true); this.savedFlags = Flags.flags; Flags.flags = new TreeMap<>(); } @Override public void close() { verifyAndSetFlagsCleared(false); Flags.flags = savedFlags; } /** * Used to implement a simple verification that Replacer is not used by multiple threads. * For instance two different tests running in parallel cannot both use Replacer. */ private static void verifyAndSetFlagsCleared(boolean newValue) { if (flagsCleared == newValue) { throw new IllegalStateException("clearFlagsForTesting called while already cleared - running tests in parallell!?"); } flagsCleared = newValue; } } }
package com.yahoo.vespa.flags; import com.yahoo.component.Vtag; import com.yahoo.vespa.defaults.Defaults; import java.time.Instant; import java.time.LocalDate; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.List; import java.util.Optional; import java.util.TreeMap; import static com.yahoo.vespa.flags.FetchVector.Dimension.APPLICATION_ID; import static com.yahoo.vespa.flags.FetchVector.Dimension.CONSOLE_USER_EMAIL; import static com.yahoo.vespa.flags.FetchVector.Dimension.HOSTNAME; import static com.yahoo.vespa.flags.FetchVector.Dimension.NODE_TYPE; import static com.yahoo.vespa.flags.FetchVector.Dimension.TENANT_ID; import static com.yahoo.vespa.flags.FetchVector.Dimension.VESPA_VERSION; import static com.yahoo.vespa.flags.FetchVector.Dimension.ZONE_ID; /** * Definitions of feature flags. * * <p>To use feature flags, define the flag in this class as an "unbound" flag, e.g. {@link UnboundBooleanFlag} * or {@link UnboundStringFlag}. At the location you want to get the value of the flag, you need the following:</p> * * <ol> * <li>The unbound flag</li> * <li>A {@link FlagSource}. The flag source is typically available as an injectable component. Binding * an unbound flag to a flag source produces a (bound) flag, e.g. {@link BooleanFlag} and {@link StringFlag}.</li> * <li>If you would like your flag value to be dependent on e.g. the application ID, then 1. you should * declare this in the unbound flag definition in this file (referring to * {@link FetchVector.Dimension#APPLICATION_ID}), and 2. specify the application ID when retrieving the value, e.g. * {@link BooleanFlag#with(FetchVector.Dimension, String)}. See {@link FetchVector} for more info.</li> * </ol> * * <p>Once the code is in place, you can override the flag value. This depends on the flag source, but typically * there is a REST API for updating the flags in the config server, which is the root of all flag sources in the zone.</p> * * @author hakonhall */ public class Flags { private static volatile TreeMap<FlagId, FlagDefinition> flags = new TreeMap<>(); public static final UnboundDoubleFlag DEFAULT_TERM_WISE_LIMIT = defineDoubleFlag( "default-term-wise-limit", 1.0, List.of("baldersheim"), "2020-12-02", "2022-06-01", "Default limit for when to apply termwise query evaluation", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag FEED_SEQUENCER_TYPE = defineStringFlag( "feed-sequencer-type", "THROUGHPUT", List.of("baldersheim"), "2020-12-02", "2022-06-01", "Selects type of sequenced executor used for feeding in proton, valid values are LATENCY, ADAPTIVE, THROUGHPUT", "Takes effect at redeployment (requires restart)", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag FEED_TASK_LIMIT = defineIntFlag( "feed-task-limit", 1000, List.of("geirst, baldersheim"), "2021-10-14", "2022-06-01", "The task limit used by the executors handling feed in proton", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag FEED_MASTER_TASK_LIMIT = defineIntFlag( "feed-master-task-limit", 1000, List.of("geirst, baldersheim"), "2021-11-18", "2022-06-01", "The task limit used by the master thread in each document db in proton. Ignored when set to 0.", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag SHARED_FIELD_WRITER_EXECUTOR = defineStringFlag( "shared-field-writer-executor", "NONE", List.of("geirst, baldersheim"), "2021-11-05", "2022-06-01", "Whether to use a shared field writer executor for the document database(s) in proton. " + "Valid values: NONE, INDEX, INDEX_AND_ATTRIBUTE, DOCUMENT_DB", "Takes effect at redeployment (requires restart)", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MAX_UNCOMMITTED_MEMORY = defineIntFlag( "max-uncommitted-memory", 130000, List.of("geirst, baldersheim"), "2021-10-21", "2022-06-01", "Max amount of memory holding updates to an attribute before we do a commit.", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag RESPONSE_SEQUENCER_TYPE = defineStringFlag( "response-sequencer-type", "ADAPTIVE", List.of("baldersheim"), "2020-12-02", "2022-06-01", "Selects type of sequenced executor used for mbus responses, valid values are LATENCY, ADAPTIVE, THROUGHPUT", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag RESPONSE_NUM_THREADS = defineIntFlag( "response-num-threads", 2, List.of("baldersheim"), "2020-12-02", "2022-06-01", "Number of threads used for mbus responses, default is 2, negative number = numcores/4", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SKIP_COMMUNICATIONMANAGER_THREAD = defineFeatureFlag( "skip-communicationmanager-thread", false, List.of("baldersheim"), "2020-12-02", "2022-06-01", "Should we skip the communicationmanager thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SKIP_MBUS_REQUEST_THREAD = defineFeatureFlag( "skip-mbus-request-thread", false, List.of("baldersheim"), "2020-12-02", "2022-06-01", "Should we skip the mbus request thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SKIP_MBUS_REPLY_THREAD = defineFeatureFlag( "skip-mbus-reply-thread", false, List.of("baldersheim"), "2020-12-02", "2022-06-01", "Should we skip the mbus reply thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_THREE_PHASE_UPDATES = defineFeatureFlag( "use-three-phase-updates", false, List.of("vekterli"), "2020-12-02", "2022-05-01", "Whether to enable the use of three-phase updates when bucket replicas are out of sync.", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_ASYNC_MESSAGE_HANDLING_ON_SCHEDULE = defineFeatureFlag( "async-message-handling-on-schedule", false, List.of("baldersheim"), "2020-12-02", "2022-06-01", "Optionally deliver async messages in own thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag FEED_CONCURRENCY = defineDoubleFlag( "feed-concurrency", 0.5, List.of("baldersheim"), "2020-12-02", "2022-06-01", "How much concurrency should be allowed for feed", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag CONTAINER_DUMP_HEAP_ON_SHUTDOWN_TIMEOUT = defineFeatureFlag( "container-dump-heap-on-shutdown-timeout", false, List.of("baldersheim"), "2021-09-25", "2022-06-01", "Will trigger a heap dump during if container shutdown times out", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag CONTAINER_SHUTDOWN_TIMEOUT = defineDoubleFlag( "container-shutdown-timeout", 50.0, List.of("baldersheim"), "2021-09-25", "2022-06-01", "Timeout for shutdown of a jdisc container", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundListFlag<String> ALLOWED_ATHENZ_PROXY_IDENTITIES = defineListFlag( "allowed-athenz-proxy-identities", List.of(), String.class, List.of("bjorncs", "tokle"), "2021-02-10", "2022-06-01", "Allowed Athenz proxy identities", "takes effect at redeployment"); public static final UnboundIntFlag MAX_ACTIVATION_INHIBITED_OUT_OF_SYNC_GROUPS = defineIntFlag( "max-activation-inhibited-out-of-sync-groups", 0, List.of("vekterli"), "2021-02-19", "2022-05-01", "Allows replicas in up to N content groups to not be activated " + "for query visibility if they are out of sync with a majority of other replicas", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MAX_CONCURRENT_MERGES_PER_NODE = defineIntFlag( "max-concurrent-merges-per-node", 16, List.of("balder", "vekterli"), "2021-06-06", "2022-05-01", "Specifies max concurrent merges per content node.", "Takes effect at redeploy", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MAX_MERGE_QUEUE_SIZE = defineIntFlag( "max-merge-queue-size", 100, List.of("balder", "vekterli"), "2021-06-06", "2022-05-01", "Specifies max size of merge queue.", "Takes effect at redeploy", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag MIN_NODE_RATIO_PER_GROUP = defineDoubleFlag( "min-node-ratio-per-group", 0.0, List.of("geirst", "vekterli"), "2021-07-16", "2022-06-01", "Minimum ratio of nodes that have to be available (i.e. not Down) in any hierarchic content cluster group for the group to be Up", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag METRICSPROXY_NUM_THREADS = defineIntFlag( "metricsproxy-num-threads", 2, List.of("balder"), "2021-09-01", "2022-06-01", "Number of threads for metrics proxy", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag AVAILABLE_PROCESSORS = defineIntFlag( "available-processors", 2, List.of("balder"), "2022-01-18", "2022-07-01", "Number of processors the jvm sees in non-application clusters", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag ENABLED_HORIZON_DASHBOARD = defineFeatureFlag( "enabled-horizon-dashboard", false, List.of("olaa"), "2021-09-13", "2022-07-01", "Enable Horizon dashboard", "Takes effect immediately", TENANT_ID, CONSOLE_USER_EMAIL ); public static final UnboundBooleanFlag UNORDERED_MERGE_CHAINING = defineFeatureFlag( "unordered-merge-chaining", true, List.of("vekterli", "geirst"), "2021-11-15", "2022-06-01", "Enables the use of unordered merge chains for data merge operations", "Takes effect at redeploy", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag JDK_VERSION = defineStringFlag( "jdk-version", "11", List.of("hmusum"), "2021-10-25", "2022-05-01", "JDK version to use on host and inside containers. Note application-id dimension only applies for container, " + "while hostname and node type applies for host.", "Takes effect on restart for Docker container and on next host-admin tick for host", APPLICATION_ID, TENANT_ID, HOSTNAME, NODE_TYPE); public static final UnboundBooleanFlag IGNORE_THREAD_STACK_SIZES = defineFeatureFlag( "ignore-thread-stack-sizes", false, List.of("arnej"), "2021-11-12", "2022-06-01", "Whether C++ thread creation should ignore any requested stack size", "Triggers restart, takes effect immediately", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_V8_GEO_POSITIONS = defineFeatureFlag( "use-v8-geo-positions", false, List.of("arnej"), "2021-11-15", "2022-12-31", "Use Vespa 8 types and formats for geographical positions", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_V8_DOC_MANAGER_CFG = defineFeatureFlag( "use-v8-doc-manager-cfg", true, List.of("arnej", "baldersheim"), "2021-12-09", "2022-12-31", "Use new (preparing for Vespa 8) section in documentmanager.def", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MAX_COMPACT_BUFFERS = defineIntFlag( "max-compact-buffers", 1, List.of("baldersheim", "geirst", "toregge"), "2021-12-15", "2022-06-01", "Upper limit of buffers to compact in a data store at the same time for each reason (memory usage, address space usage)", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag FAIL_DEPLOYMENT_WITH_INVALID_JVM_OPTIONS = defineFeatureFlag( "fail-deployment-with-invalid-jvm-options", false, List.of("hmusum"), "2021-12-20", "2022-05-01", "Whether to fail deployments with invalid JVM options in services.xml", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag ENABLE_SERVER_OCSP_STAPLING = defineFeatureFlag( "enable-server-ocsp-stapling", false, List.of("bjorncs"), "2021-12-17", "2022-06-01", "Enable server OCSP stapling for jdisc containers", "Takes effect on redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag ENABLE_DATA_HIGHWAY_IN_AWS = defineFeatureFlag( "enable-data-highway-in-aws", false, List.of("hmusum"), "2022-01-06", "2022-06-01", "Enable Data Highway in AWS", "Takes effect on restart of Docker container", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag PERSISTENCE_ASYNC_THROTTLING = defineStringFlag( "persistence-async-throttling", "UNLIMITED", List.of("vekterli"), "2022-01-12", "2022-05-01", "Sets the throttling policy used for async persistence operations on the content nodes. " + "Valid values: UNLIMITED, DYNAMIC", "Triggers restart, takes effect immediately", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag MERGE_THROTTLING_POLICY = defineStringFlag( "merge-throttling-policy", "STATIC", List.of("vekterli"), "2022-01-25", "2022-05-01", "Sets the policy used for merge throttling on the content nodes. " + "Valid values: STATIC, DYNAMIC", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag PERSISTENCE_THROTTLING_WS_DECREMENT_FACTOR = defineDoubleFlag( "persistence-throttling-ws-decrement-factor", 1.2, List.of("vekterli"), "2022-01-27", "2022-05-01", "Sets the dynamic throttle policy window size decrement factor for persistence " + "async throttling. Only applies if DYNAMIC policy is used.", "Takes effect on redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag PERSISTENCE_THROTTLING_WS_BACKOFF = defineDoubleFlag( "persistence-throttling-ws-backoff", 0.95, List.of("vekterli"), "2022-01-27", "2022-05-01", "Sets the dynamic throttle policy window size backoff for persistence " + "async throttling. Only applies if DYNAMIC policy is used. Valid range [0, 1]", "Takes effect on redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag PERSISTENCE_THROTTLING_WINDOW_SIZE = defineIntFlag( "persistence-throttling-window-size", -1, List.of("vekterli"), "2022-02-23", "2022-06-01", "If greater than zero, sets both min and max window size to the given number, effectively " + "turning dynamic throttling into a static throttling policy. " + "Only applies if DYNAMIC policy is used.", "Takes effect on redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag PERSISTENCE_THROTTLING_WS_RESIZE_RATE = defineDoubleFlag( "persistence-throttling-ws-resize-rate", 3.0, List.of("vekterli"), "2022-02-23", "2022-06-01", "Sets the dynamic throttle policy resize rate. Only applies if DYNAMIC policy is used.", "Takes effect on redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag PERSISTENCE_THROTTLING_OF_MERGE_FEED_OPS = defineFeatureFlag( "persistence-throttling-of-merge-feed-ops", true, List.of("vekterli"), "2022-02-24", "2022-06-01", "If true, each put/remove contained within a merge is individually throttled as if it " + "were a put/remove from a client. If false, merges are throttled at a persistence thread " + "level, i.e. per ApplyBucketDiff message, regardless of how many document operations " + "are contained within. Only applies if DYNAMIC policy is used.", "Takes effect on redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag INHIBIT_DEFAULT_MERGES_WHEN_GLOBAL_MERGES_PENDING = defineFeatureFlag( "inhibit-default-merges-when-global-merges-pending", false, List.of("geirst", "vekterli"), "2022-02-11", "2022-06-01", "Inhibits all merges to buckets in the default bucket space if the current " + "cluster state bundle indicates that global merges are pending in the cluster", "Takes effect on redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_QRSERVER_SERVICE_NAME = defineFeatureFlag( "use-qrserver-service-name", true, List.of("arnej"), "2022-01-18", "2022-12-31", "Use backwards-compatible 'qrserver' service name for containers with only 'search' API", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag ENABLE_JDISC_PRESHUTDOWN_COMMAND = defineFeatureFlag( "enable-jdisc-preshutdown-command", false, List.of("bjorncs", "baldersheim"), "2022-01-31", "2022-05-31", "Enable pre-shutdown command for jdisc", "Takes effect at redeployment", APPLICATION_ID, HOSTNAME, TENANT_ID); public static final UnboundBooleanFlag AVOID_RENAMING_SUMMARY_FEATURES = defineFeatureFlag( "avoid-renaming-summary-features", false, List.of("arnej"), "2022-01-15", "2023-12-31", "Tell backend about the original name of summary-features that were wrapped in a rankingExpression feature", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag REUSE_NODE_INDEXES = defineFeatureFlag( "reuse-node-indexes", true, List.of("bratseth"), "2022-02-25", "2022-04-25", "Whether we should reuse earlier indexes when allocating new nodes", "Takes effect immediately", ZONE_ID); public static final UnboundBooleanFlag ALLOW_NO_TESTS = defineFeatureFlag( "allow-no-tests", false, List.of("jonmv"), "2022-02-28", "2022-06-25", "Whether test jobs without any tests run are acceptable", "Takes effect immediately", TENANT_ID); public static final UnboundBooleanFlag MERGE_GROUPING_RESULT_IN_SEARCH_INVOKER = defineFeatureFlag( "merge-grouping-result-in-search-invoker", false, List.of("bjorncs", "baldersheim"), "2022-02-23", "2022-08-01", "Merge grouping results incrementally in interleaved search invoker", "Takes effect at redeployment", APPLICATION_ID); public static final UnboundBooleanFlag EXPERIMENTAL_SD_PARSING = defineFeatureFlag( "experimental-sd-parsing", false, List.of("arnej"), "2022-03-04", "2022-12-31", "Parsed schema files via intermediate format", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_NEW_CONTROLLER_LOCKS = defineFeatureFlag( "transition-to-new-controller-locks", false, List.of("hmusum"), "2022-04-07", "2022-05-07", "Use two locks in transition period to new lock schema for application-related controller locks", "Takes effect immediately", ZONE_ID); /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundBooleanFlag defineFeatureFlag(String flagId, boolean defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundBooleanFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundStringFlag defineStringFlag(String flagId, String defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundStringFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundIntFlag defineIntFlag(String flagId, int defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundIntFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundLongFlag defineLongFlag(String flagId, long defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundLongFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundDoubleFlag defineDoubleFlag(String flagId, double defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundDoubleFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static <T> UnboundJacksonFlag<T> defineJacksonFlag(String flagId, T defaultValue, Class<T> jacksonClass, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define((id2, defaultValue2, vector2) -> new UnboundJacksonFlag<>(id2, defaultValue2, vector2, jacksonClass), flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static <T> UnboundListFlag<T> defineListFlag(String flagId, List<T> defaultValue, Class<T> elementClass, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define((fid, dval, fvec) -> new UnboundListFlag<>(fid, dval, elementClass, fvec), flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } @FunctionalInterface private interface TypedUnboundFlagFactory<T, U extends UnboundFlag<?, ?, ?>> { U create(FlagId id, T defaultVale, FetchVector defaultFetchVector); } /** * Defines a Flag. * * @param factory Factory for creating unbound flag of type U * @param flagId The globally unique FlagId. * @param defaultValue The default value if none is present after resolution. * @param description Description of how the flag is used. * @param modificationEffect What is required for the flag to take effect? A restart of process? immediately? etc. * @param dimensions What dimensions will be set in the {@link FetchVector} when fetching * the flag value in * {@link FlagSource#fetch(FlagId, FetchVector) FlagSource::fetch}. * For instance, if APPLICATION is one of the dimensions here, you should make sure * APPLICATION is set to the ApplicationId in the fetch vector when fetching the RawFlag * from the FlagSource. * @param <T> The boxed type of the flag value, e.g. Boolean for flags guarding features. * @param <U> The type of the unbound flag, e.g. UnboundBooleanFlag. * @return An unbound flag with {@link FetchVector.Dimension#HOSTNAME HOSTNAME} and * {@link FetchVector.Dimension#VESPA_VERSION VESPA_VERSION} already set. The ZONE environment * is typically implicit. */ private static <T, U extends UnboundFlag<?, ?, ?>> U define(TypedUnboundFlagFactory<T, U> factory, String flagId, T defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension[] dimensions) { FlagId id = new FlagId(flagId); FetchVector vector = new FetchVector() .with(HOSTNAME, Defaults.getDefaults().vespaHostname()) // Warning: In unit tests and outside official Vespa releases, the currentVersion is e.g. 7.0.0 // (determined by the current major version). Consider not setting VESPA_VERSION if minor = micro = 0. .with(VESPA_VERSION, Vtag.currentVersion.toFullString()); U unboundFlag = factory.create(id, defaultValue, vector); FlagDefinition definition = new FlagDefinition( unboundFlag, owners, parseDate(createdAt), parseDate(expiresAt), description, modificationEffect, dimensions); flags.put(id, definition); return unboundFlag; } private static Instant parseDate(String rawDate) { return DateTimeFormatter.ISO_DATE.parse(rawDate, LocalDate::from).atStartOfDay().toInstant(ZoneOffset.UTC); } public static List<FlagDefinition> getAllFlags() { return List.copyOf(flags.values()); } public static Optional<FlagDefinition> getFlag(FlagId flagId) { return Optional.ofNullable(flags.get(flagId)); } /** * Allows the statically defined flags to be controlled in a test. * * <p>Returns a Replacer instance to be used with e.g. a try-with-resources block. Within the block, * the flags starts out as cleared. Flags can be defined, etc. When leaving the block, the flags from * before the block is reinserted. * * <p>NOT thread-safe. Tests using this cannot run in parallel. */ public static Replacer clearFlagsForTesting(FlagId... flagsToKeep) { return new Replacer(flagsToKeep); } public static class Replacer implements AutoCloseable { private static volatile boolean flagsCleared = false; private final TreeMap<FlagId, FlagDefinition> savedFlags; private Replacer(FlagId... flagsToKeep) { verifyAndSetFlagsCleared(true); this.savedFlags = Flags.flags; Flags.flags = new TreeMap<>(); List.of(flagsToKeep).forEach(id -> Flags.flags.put(id, savedFlags.get(id))); } @Override public void close() { verifyAndSetFlagsCleared(false); Flags.flags = savedFlags; } /** * Used to implement a simple verification that Replacer is not used by multiple threads. * For instance two different tests running in parallel cannot both use Replacer. */ private static void verifyAndSetFlagsCleared(boolean newValue) { if (flagsCleared == newValue) { throw new IllegalStateException("clearFlagsForTesting called while already cleared - running tests in parallell!?"); } flagsCleared = newValue; } } }
package com.yahoo.vespa.flags; import com.yahoo.component.Vtag; import com.yahoo.vespa.defaults.Defaults; import java.time.Instant; import java.time.LocalDate; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.List; import java.util.Optional; import java.util.TreeMap; import static com.yahoo.vespa.flags.FetchVector.Dimension.APPLICATION_ID; import static com.yahoo.vespa.flags.FetchVector.Dimension.CONSOLE_USER_EMAIL; import static com.yahoo.vespa.flags.FetchVector.Dimension.HOSTNAME; import static com.yahoo.vespa.flags.FetchVector.Dimension.NODE_TYPE; import static com.yahoo.vespa.flags.FetchVector.Dimension.TENANT_ID; import static com.yahoo.vespa.flags.FetchVector.Dimension.VESPA_VERSION; import static com.yahoo.vespa.flags.FetchVector.Dimension.ZONE_ID; /** * Definitions of feature flags. * * <p>To use feature flags, define the flag in this class as an "unbound" flag, e.g. {@link UnboundBooleanFlag} * or {@link UnboundStringFlag}. At the location you want to get the value of the flag, you need the following:</p> * * <ol> * <li>The unbound flag</li> * <li>A {@link FlagSource}. The flag source is typically available as an injectable component. Binding * an unbound flag to a flag source produces a (bound) flag, e.g. {@link BooleanFlag} and {@link StringFlag}.</li> * <li>If you would like your flag value to be dependent on e.g. the application ID, then 1. you should * declare this in the unbound flag definition in this file (referring to * {@link FetchVector.Dimension#APPLICATION_ID}), and 2. specify the application ID when retrieving the value, e.g. * {@link BooleanFlag#with(FetchVector.Dimension, String)}. See {@link FetchVector} for more info.</li> * </ol> * * <p>Once the code is in place, you can override the flag value. This depends on the flag source, but typically * there is a REST API for updating the flags in the config server, which is the root of all flag sources in the zone.</p> * * @author hakonhall */ public class Flags { private static volatile TreeMap<FlagId, FlagDefinition> flags = new TreeMap<>(); public static final UnboundDoubleFlag DEFAULT_TERM_WISE_LIMIT = defineDoubleFlag( "default-term-wise-limit", 1.0, List.of("baldersheim"), "2020-12-02", "2022-01-01", "Default limit for when to apply termwise query evaluation", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag FEED_SEQUENCER_TYPE = defineStringFlag( "feed-sequencer-type", "LATENCY", List.of("baldersheim"), "2020-12-02", "2022-01-01", "Selects type of sequenced executor used for feeding in proton, valid values are LATENCY, ADAPTIVE, THROUGHPUT", "Takes effect at redeployment (requires restart)", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag FEED_TASK_LIMIT = defineIntFlag( "feed-task-limit", 1000, List.of("geirst, baldersheim"), "2021-10-14", "2022-01-01", "The task limit used by the executors handling feed in proton", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag FEED_MASTER_TASK_LIMIT = defineIntFlag( "feed-master-task-limit", 0, List.of("geirst, baldersheim"), "2021-11-18", "2022-02-01", "The task limit used by the master thread in each document db in proton. Ignored when set to 0.", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag SHARED_FIELD_WRITER_EXECUTOR = defineStringFlag( "shared-field-writer-executor", "NONE", List.of("geirst, baldersheim"), "2021-11-05", "2022-02-01", "Whether to use a shared field writer executor for the document database(s) in proton. " + "Valid values: NONE, INDEX, INDEX_AND_ATTRIBUTE, DOCUMENT_DB", "Takes effect at redeployment (requires restart)", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MAX_UNCOMMITTED_MEMORY = defineIntFlag( "max-uncommitted-memory", 130000, List.of("geirst, baldersheim"), "2021-10-21", "2022-01-01", "Max amount of memory holding updates to an attribute before we do a commit.", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag RESPONSE_SEQUENCER_TYPE = defineStringFlag( "response-sequencer-type", "ADAPTIVE", List.of("baldersheim"), "2020-12-02", "2022-01-01", "Selects type of sequenced executor used for mbus responses, valid values are LATENCY, ADAPTIVE, THROUGHPUT", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag RESPONSE_NUM_THREADS = defineIntFlag( "response-num-threads", 2, List.of("baldersheim"), "2020-12-02", "2022-01-01", "Number of threads used for mbus responses, default is 2, negative number = numcores/4", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SKIP_COMMUNICATIONMANAGER_THREAD = defineFeatureFlag( "skip-communicationmanager-thread", false, List.of("baldersheim"), "2020-12-02", "2022-01-01", "Should we skip the communicationmanager thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SKIP_MBUS_REQUEST_THREAD = defineFeatureFlag( "skip-mbus-request-thread", false, List.of("baldersheim"), "2020-12-02", "2022-01-01", "Should we skip the mbus request thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SKIP_MBUS_REPLY_THREAD = defineFeatureFlag( "skip-mbus-reply-thread", false, List.of("baldersheim"), "2020-12-02", "2022-01-01", "Should we skip the mbus reply thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_THREE_PHASE_UPDATES = defineFeatureFlag( "use-three-phase-updates", false, List.of("vekterli"), "2020-12-02", "2022-01-01", "Whether to enable the use of three-phase updates when bucket replicas are out of sync.", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag HIDE_SHARED_ROUTING_ENDPOINT = defineFeatureFlag( "hide-shared-routing-endpoint", false, List.of("tokle", "bjormel"), "2020-12-02", "2022-01-01", "Whether the controller should hide shared routing layer endpoint", "Takes effect immediately", APPLICATION_ID ); public static final UnboundBooleanFlag USE_ASYNC_MESSAGE_HANDLING_ON_SCHEDULE = defineFeatureFlag( "async-message-handling-on-schedule", false, List.of("baldersheim"), "2020-12-02", "2022-01-01", "Optionally deliver async messages in own thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag FEED_CONCURRENCY = defineDoubleFlag( "feed-concurrency", 0.5, List.of("baldersheim"), "2020-12-02", "2022-01-01", "How much concurrency should be allowed for feed", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag DISK_BLOAT_FACTOR = defineDoubleFlag( "disk-bloat-factor", 0.2, List.of("baldersheim"), "2021-10-08", "2022-01-01", "Amount of bloat allowed before compacting file", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag DOCSTORE_COMPRESSION_LEVEL = defineIntFlag( "docstore-compression-level", 3, List.of("baldersheim"), "2021-10-08", "2022-01-01", "Default compression level used for document store", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag NUM_DEPLOY_HELPER_THREADS = defineIntFlag( "num-model-builder-threads", -1, List.of("balder"), "2021-09-09", "2022-01-01", "Number of threads used for speeding up building of models.", "Takes effect on first (re)start of config server"); public static final UnboundBooleanFlag ENABLE_FEED_BLOCK_IN_DISTRIBUTOR = defineFeatureFlag( "enable-feed-block-in-distributor", true, List.of("geirst"), "2021-01-27", "2022-01-31", "Enables blocking of feed in the distributor if resource usage is above limit on at least one content node", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag CONTAINER_DUMP_HEAP_ON_SHUTDOWN_TIMEOUT = defineFeatureFlag( "container-dump-heap-on-shutdown-timeout", false, List.of("baldersheim"), "2021-09-25", "2022-01-01", "Will trigger a heap dump during if container shutdown times out", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag CONTAINER_SHUTDOWN_TIMEOUT = defineDoubleFlag( "container-shutdown-timeout", 50.0, List.of("baldersheim"), "2021-09-25", "2022-01-01", "Timeout for shutdown of a jdisc container", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundListFlag<String> ALLOWED_ATHENZ_PROXY_IDENTITIES = defineListFlag( "allowed-athenz-proxy-identities", List.of(), String.class, List.of("bjorncs", "tokle"), "2021-02-10", "2022-02-01", "Allowed Athenz proxy identities", "takes effect at redeployment"); public static final UnboundBooleanFlag GENERATE_NON_MTLS_ENDPOINT = defineFeatureFlag( "generate-non-mtls-endpoint", true, List.of("tokle"), "2021-02-18", "2022-02-01", "Whether to generate the non-mtls endpoint", "Takes effect on next internal redeployment", APPLICATION_ID); public static final UnboundIntFlag MAX_ACTIVATION_INHIBITED_OUT_OF_SYNC_GROUPS = defineIntFlag( "max-activation-inhibited-out-of-sync-groups", 0, List.of("vekterli"), "2021-02-19", "2022-02-01", "Allows replicas in up to N content groups to not be activated " + "for query visibility if they are out of sync with a majority of other replicas", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MAX_CONCURRENT_MERGES_PER_NODE = defineIntFlag( "max-concurrent-merges-per-node", 128, List.of("balder", "vekterli"), "2021-06-06", "2022-01-01", "Specifies max concurrent merges per content node.", "Takes effect at redeploy", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MAX_MERGE_QUEUE_SIZE = defineIntFlag( "max-merge-queue-size", 1024, List.of("balder", "vekterli"), "2021-06-06", "2022-01-01", "Specifies max size of merge queue.", "Takes effect at redeploy", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag IGNORE_MERGE_QUEUE_LIMIT = defineFeatureFlag( "ignore-merge-queue-limit", false, List.of("vekterli", "geirst"), "2021-10-06", "2022-03-01", "Specifies if merges that are forwarded (chained) from another content node are always " + "allowed to be enqueued even if the queue is otherwise full.", "Takes effect at redeploy", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag LARGE_RANK_EXPRESSION_LIMIT = defineIntFlag( "large-rank-expression-limit", 8192, List.of("baldersheim"), "2021-06-09", "2022-01-01", "Limit for size of rank expressions distributed by filedistribution", "Takes effect on next internal redeployment", APPLICATION_ID); public static final UnboundDoubleFlag MIN_NODE_RATIO_PER_GROUP = defineDoubleFlag( "min-node-ratio-per-group", 0.0, List.of("geirst", "vekterli"), "2021-07-16", "2022-03-01", "Minimum ratio of nodes that have to be available (i.e. not Down) in any hierarchic content cluster group for the group to be Up", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SEPARATE_TENANT_IAM_ROLES = defineFeatureFlag( "separate-tenant-iam-roles", false, List.of("mortent"), "2021-08-12", "2022-01-01", "Create separate iam roles for tenant", "Takes effect on redeploy", TENANT_ID); public static final UnboundIntFlag METRICSPROXY_NUM_THREADS = defineIntFlag( "metricsproxy-num-threads", 2, List.of("balder"), "2021-09-01", "2022-01-01", "Number of threads for metrics proxy", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag ENABLED_HORIZON_DASHBOARD = defineFeatureFlag( "enabled-horizon-dashboard", false, List.of("olaa"), "2021-09-13", "2021-12-31", "Enable Horizon dashboard", "Takes effect immediately", TENANT_ID, CONSOLE_USER_EMAIL ); public static final UnboundBooleanFlag ENABLE_ONPREM_TENANT_S3_ARCHIVE = defineFeatureFlag( "enable-onprem-tenant-s3-archive", false, List.of("bjorncs"), "2021-09-14", "2021-12-31", "Enable tenant S3 buckets in cd/main. Must be set on controller cluster only.", "Takes effect immediately", ZONE_ID, TENANT_ID ); public static final UnboundBooleanFlag DELETE_UNMAINTAINED_CERTIFICATES = defineFeatureFlag( "delete-unmaintained-certificates", false, List.of("andreer"), "2021-09-23", "2021-12-21", "Whether to delete certificates that are known by provider but not by controller", "Takes effect on next run of EndpointCertificateMaintainer" ); public static final UnboundBooleanFlag USE_NEW_ENDPOINT_CERTIFICATE_PROVIDER_URL = defineFeatureFlag( "use-new-endpoint-certificate-provider-url", false, List.of("andreer"), "2021-12-14", "2022-01-14", "Use the new URL for the endpoint certificate provider API", "Takes effect immediately" ); public static final UnboundBooleanFlag ENABLE_TENANT_DEVELOPER_ROLE = defineFeatureFlag( "enable-tenant-developer-role", false, List.of("bjorncs"), "2021-09-23", "2021-12-31", "Enable tenant developer Athenz role in cd/main. Must be set on controller cluster only.", "Takes effect immediately", TENANT_ID ); public static final UnboundBooleanFlag ENABLE_ROUTING_REUSE_PORT = defineFeatureFlag( "enable-routing-reuse-port", false, List.of("mortent"), "2021-09-29", "2021-12-31", "Enable reuse port in routing configuration", "Takes effect on container restart", HOSTNAME ); public static final UnboundBooleanFlag ENABLE_TENANT_OPERATOR_ROLE = defineFeatureFlag( "enable-tenant-operator-role", false, List.of("bjorncs"), "2021-09-29", "2021-12-31", "Enable tenant specific operator roles in public systems. For controllers only.", "Takes effect on subsequent maintainer invocation", TENANT_ID ); public static final UnboundIntFlag DISTRIBUTOR_MERGE_BUSY_WAIT = defineIntFlag( "distributor-merge-busy-wait", 10, List.of("geirst", "vekterli"), "2021-10-04", "2022-03-01", "Number of seconds that scheduling of new merge operations in the distributor should be inhibited " + "towards a content node that has indicated merge busy", "Takes effect at redeploy", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag DISTRIBUTOR_ENHANCED_MAINTENANCE_SCHEDULING = defineFeatureFlag( "distributor-enhanced-maintenance-scheduling", false, List.of("vekterli", "geirst"), "2021-10-14", "2022-01-31", "Enable enhanced maintenance operation scheduling semantics on the distributor", "Takes effect at redeploy", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag ASYNC_APPLY_BUCKET_DIFF = defineFeatureFlag( "async-apply-bucket-diff", false, List.of("geirst", "vekterli"), "2021-10-22", "2022-01-31", "Whether portions of apply bucket diff handling will be performed asynchronously", "Takes effect at redeploy", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag UNORDERED_MERGE_CHAINING = defineFeatureFlag( "unordered-merge-chaining", false, List.of("vekterli", "geirst"), "2021-11-15", "2022-03-01", "Enables the use of unordered merge chains for data merge operations", "Takes effect at redeploy", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag JDK_VERSION = defineStringFlag( "jdk-version", "11", List.of("hmusum"), "2021-10-25", "2022-03-01", "JDK version to use on host and inside containers. Note application-id dimension only applies for container, " + "while hostname and node type applies for host.", "Takes effect on restart for Docker container and on next host-admin tick for host", APPLICATION_ID, TENANT_ID, HOSTNAME, NODE_TYPE); public static final UnboundBooleanFlag IGNORE_THREAD_STACK_SIZES = defineFeatureFlag( "ignore-thread-stack-sizes", false, List.of("arnej"), "2021-11-12", "2022-01-31", "Whether C++ thread creation should ignore any requested stack size", "Triggers restart, takes effect immediately", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_V8_GEO_POSITIONS = defineFeatureFlag( "use-v8-geo-positions", false, List.of("arnej"), "2021-11-15", "2022-12-31", "Use Vespa 8 types and formats for geographical positions", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_LEGACY_LB_SERVICES = defineFeatureFlag( "use-legacy-lb-services", false, List.of("tokle"), "2021-11-22", "2021-12-31", "Whether to generate routing table based on legacy lb-services config", "Takes effect on container reboot", ZONE_ID, HOSTNAME); public static final UnboundBooleanFlag USE_V8_DOC_MANAGER_CFG = defineFeatureFlag( "use-v8-doc-manager-cfg", false, List.of("arnej", "baldersheim"), "2021-12-09", "2022-12-31", "Use new (preparing for Vespa 8) section in documentmanager.def", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundBooleanFlag defineFeatureFlag(String flagId, boolean defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundBooleanFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundStringFlag defineStringFlag(String flagId, String defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundStringFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundIntFlag defineIntFlag(String flagId, int defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundIntFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundLongFlag defineLongFlag(String flagId, long defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundLongFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundDoubleFlag defineDoubleFlag(String flagId, double defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundDoubleFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static <T> UnboundJacksonFlag<T> defineJacksonFlag(String flagId, T defaultValue, Class<T> jacksonClass, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define((id2, defaultValue2, vector2) -> new UnboundJacksonFlag<>(id2, defaultValue2, vector2, jacksonClass), flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static <T> UnboundListFlag<T> defineListFlag(String flagId, List<T> defaultValue, Class<T> elementClass, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define((fid, dval, fvec) -> new UnboundListFlag<>(fid, dval, elementClass, fvec), flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } @FunctionalInterface private interface TypedUnboundFlagFactory<T, U extends UnboundFlag<?, ?, ?>> { U create(FlagId id, T defaultVale, FetchVector defaultFetchVector); } /** * Defines a Flag. * * @param factory Factory for creating unbound flag of type U * @param flagId The globally unique FlagId. * @param defaultValue The default value if none is present after resolution. * @param description Description of how the flag is used. * @param modificationEffect What is required for the flag to take effect? A restart of process? immediately? etc. * @param dimensions What dimensions will be set in the {@link FetchVector} when fetching * the flag value in * {@link FlagSource#fetch(FlagId, FetchVector) FlagSource::fetch}. * For instance, if APPLICATION is one of the dimensions here, you should make sure * APPLICATION is set to the ApplicationId in the fetch vector when fetching the RawFlag * from the FlagSource. * @param <T> The boxed type of the flag value, e.g. Boolean for flags guarding features. * @param <U> The type of the unbound flag, e.g. UnboundBooleanFlag. * @return An unbound flag with {@link FetchVector.Dimension#HOSTNAME HOSTNAME} and * {@link FetchVector.Dimension#VESPA_VERSION VESPA_VERSION} already set. The ZONE environment * is typically implicit. */ private static <T, U extends UnboundFlag<?, ?, ?>> U define(TypedUnboundFlagFactory<T, U> factory, String flagId, T defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension[] dimensions) { FlagId id = new FlagId(flagId); FetchVector vector = new FetchVector() .with(HOSTNAME, Defaults.getDefaults().vespaHostname()) // Warning: In unit tests and outside official Vespa releases, the currentVersion is e.g. 7.0.0 // (determined by the current major version). Consider not setting VESPA_VERSION if minor = micro = 0. .with(VESPA_VERSION, Vtag.currentVersion.toFullString()); U unboundFlag = factory.create(id, defaultValue, vector); FlagDefinition definition = new FlagDefinition( unboundFlag, owners, parseDate(createdAt), parseDate(expiresAt), description, modificationEffect, dimensions); flags.put(id, definition); return unboundFlag; } private static Instant parseDate(String rawDate) { return DateTimeFormatter.ISO_DATE.parse(rawDate, LocalDate::from).atStartOfDay().toInstant(ZoneOffset.UTC); } public static List<FlagDefinition> getAllFlags() { return List.copyOf(flags.values()); } public static Optional<FlagDefinition> getFlag(FlagId flagId) { return Optional.ofNullable(flags.get(flagId)); } /** * Allows the statically defined flags to be controlled in a test. * * <p>Returns a Replacer instance to be used with e.g. a try-with-resources block. Within the block, * the flags starts out as cleared. Flags can be defined, etc. When leaving the block, the flags from * before the block is reinserted. * * <p>NOT thread-safe. Tests using this cannot run in parallel. */ public static Replacer clearFlagsForTesting(FlagId... flagsToKeep) { return new Replacer(flagsToKeep); } public static class Replacer implements AutoCloseable { private static volatile boolean flagsCleared = false; private final TreeMap<FlagId, FlagDefinition> savedFlags; private Replacer(FlagId... flagsToKeep) { verifyAndSetFlagsCleared(true); this.savedFlags = Flags.flags; Flags.flags = new TreeMap<>(); List.of(flagsToKeep).forEach(id -> Flags.flags.put(id, savedFlags.get(id))); } @Override public void close() { verifyAndSetFlagsCleared(false); Flags.flags = savedFlags; } /** * Used to implement a simple verification that Replacer is not used by multiple threads. * For instance two different tests running in parallel cannot both use Replacer. */ private static void verifyAndSetFlagsCleared(boolean newValue) { if (flagsCleared == newValue) { throw new IllegalStateException("clearFlagsForTesting called while already cleared - running tests in parallell!?"); } flagsCleared = newValue; } } }
package com.yahoo.vespa.flags; import com.yahoo.component.Vtag; import com.yahoo.vespa.defaults.Defaults; import java.time.Instant; import java.time.LocalDate; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.List; import java.util.Optional; import java.util.TreeMap; import static com.yahoo.vespa.flags.FetchVector.Dimension.APPLICATION_ID; import static com.yahoo.vespa.flags.FetchVector.Dimension.CONSOLE_USER_EMAIL; import static com.yahoo.vespa.flags.FetchVector.Dimension.HOSTNAME; import static com.yahoo.vespa.flags.FetchVector.Dimension.NODE_TYPE; import static com.yahoo.vespa.flags.FetchVector.Dimension.TENANT_ID; import static com.yahoo.vespa.flags.FetchVector.Dimension.VESPA_VERSION; import static com.yahoo.vespa.flags.FetchVector.Dimension.ZONE_ID; /** * Definitions of feature flags. * * <p>To use feature flags, define the flag in this class as an "unbound" flag, e.g. {@link UnboundBooleanFlag} * or {@link UnboundStringFlag}. At the location you want to get the value of the flag, you need the following:</p> * * <ol> * <li>The unbound flag</li> * <li>A {@link FlagSource}. The flag source is typically available as an injectable component. Binding * an unbound flag to a flag source produces a (bound) flag, e.g. {@link BooleanFlag} and {@link StringFlag}.</li> * <li>If you would like your flag value to be dependent on e.g. the application ID, then 1. you should * declare this in the unbound flag definition in this file (referring to * {@link FetchVector.Dimension#APPLICATION_ID}), and 2. specify the application ID when retrieving the value, e.g. * {@link BooleanFlag#with(FetchVector.Dimension, String)}. See {@link FetchVector} for more info.</li> * </ol> * * <p>Once the code is in place, you can override the flag value. This depends on the flag source, but typically * there is a REST API for updating the flags in the config server, which is the root of all flag sources in the zone.</p> * * @author hakonhall */ public class Flags { private static volatile TreeMap<FlagId, FlagDefinition> flags = new TreeMap<>(); public static final UnboundBooleanFlag MAIN_CHAIN_GRAPH = defineFeatureFlag( "main-chain-graph", false, List.of("hakonhall"), "2022-07-06", "2022-09-05", "Whether to run all tasks in the main task chain up to the one failing to converge (false), or " + "run all tasks in the main task chain whose dependencies have converged (true). And when suspending, " + "whether to run the tasks in sequence (false) or in reverse sequence (true).", "On first tick of the main chain after (re)start of host admin.", ZONE_ID, NODE_TYPE, HOSTNAME); public static final UnboundDoubleFlag DEFAULT_TERM_WISE_LIMIT = defineDoubleFlag( "default-term-wise-limit", 1.0, List.of("baldersheim"), "2020-12-02", "2023-01-01", "Default limit for when to apply termwise query evaluation", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag FEED_SEQUENCER_TYPE = defineStringFlag( "feed-sequencer-type", "THROUGHPUT", List.of("baldersheim"), "2020-12-02", "2023-01-01", "Selects type of sequenced executor used for feeding in proton, valid values are LATENCY, ADAPTIVE, THROUGHPUT", "Takes effect at redeployment (requires restart)", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag KEEP_STORAGE_NODE_UP = defineFeatureFlag( "keep-storage-node-up", true, List.of("hakonhall"), "2022-07-07", "2022-08-07", "Whether to leave the storage node (with wanted state) UP while the node is permanently down.", "Takes effect immediately for nodes transitioning to permanently down.", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MAX_UNCOMMITTED_MEMORY = defineIntFlag( "max-uncommitted-memory", 130000, List.of("geirst, baldersheim"), "2021-10-21", "2023-01-01", "Max amount of memory holding updates to an attribute before we do a commit.", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag RESPONSE_SEQUENCER_TYPE = defineStringFlag( "response-sequencer-type", "ADAPTIVE", List.of("baldersheim"), "2020-12-02", "2023-01-01", "Selects type of sequenced executor used for mbus responses, valid values are LATENCY, ADAPTIVE, THROUGHPUT", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag RESPONSE_NUM_THREADS = defineIntFlag( "response-num-threads", 2, List.of("baldersheim"), "2020-12-02", "2023-01-01", "Number of threads used for mbus responses, default is 2, negative number = numcores/4", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SKIP_COMMUNICATIONMANAGER_THREAD = defineFeatureFlag( "skip-communicationmanager-thread", false, List.of("baldersheim"), "2020-12-02", "2023-01-01", "Should we skip the communicationmanager thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SKIP_MBUS_REQUEST_THREAD = defineFeatureFlag( "skip-mbus-request-thread", false, List.of("baldersheim"), "2020-12-02", "2023-01-01", "Should we skip the mbus request thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SKIP_MBUS_REPLY_THREAD = defineFeatureFlag( "skip-mbus-reply-thread", false, List.of("baldersheim"), "2020-12-02", "2023-01-01", "Should we skip the mbus reply thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_THREE_PHASE_UPDATES = defineFeatureFlag( "use-three-phase-updates", false, List.of("vekterli"), "2020-12-02", "2022-08-01", "Whether to enable the use of three-phase updates when bucket replicas are out of sync.", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_ASYNC_MESSAGE_HANDLING_ON_SCHEDULE = defineFeatureFlag( "async-message-handling-on-schedule", false, List.of("baldersheim"), "2020-12-02", "2023-01-01", "Optionally deliver async messages in own thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag FEED_CONCURRENCY = defineDoubleFlag( "feed-concurrency", 0.5, List.of("baldersheim"), "2020-12-02", "2023-01-01", "How much concurrency should be allowed for feed", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag FEED_NICENESS = defineDoubleFlag( "feed-niceness", 0.0, List.of("baldersheim"), "2022-06-24", "2023-01-01", "How nice feeding shall be", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag MBUS_DISPATCH_ON_ENCODE = defineFeatureFlag( "mbus-dispatch-on-encode", true, List.of("baldersheim"), "2022-07-01", "2023-01-01", "Should we use mbus threadpool on encode", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag MBUS_DISPATCH_ON_DECODE = defineFeatureFlag( "mbus-dispatch-on-decode", true, List.of("baldersheim"), "2022-07-01", "2023-01-01", "Should we use mbus threadpool on decode", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MBUS_JAVA_NUM_TARGETS = defineIntFlag( "mbus-java-num-targets", 1, List.of("baldersheim"), "2022-07-05", "2023-01-01", "Number of rpc targets per service", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MBUS_CPP_NUM_TARGETS = defineIntFlag( "mbus-cpp-num-targets", 1, List.of("baldersheim"), "2022-07-05", "2023-01-01", "Number of rpc targets per service", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag RPC_NUM_TARGETS = defineIntFlag( "rpc-num-targets", 1, List.of("baldersheim"), "2022-07-05", "2023-01-01", "Number of rpc targets per content node", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MBUS_JAVA_EVENTS_BEFORE_WAKEUP = defineIntFlag( "mbus-java-events-before-wakeup", 1, List.of("baldersheim"), "2022-07-05", "2023-01-01", "Number write events before waking up transport thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MBUS_CPP_EVENTS_BEFORE_WAKEUP = defineIntFlag( "mbus-cpp-events-before-wakeup", 1, List.of("baldersheim"), "2022-07-05", "2023-01-01", "Number write events before waking up transport thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag RPC_EVENTS_BEFORE_WAKEUP = defineIntFlag( "rpc-events-before-wakeup", 1, List.of("baldersheim"), "2022-07-05", "2023-01-01", "Number write events before waking up transport thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MBUS_NUM_THREADS = defineIntFlag( "mbus-num-threads", 4, List.of("baldersheim"), "2022-07-01", "2023-01-01", "Number of threads used for mbus threadpool", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MBUS_NUM_NETWORK_THREADS = defineIntFlag( "mbus-num-network-threads", 1, List.of("baldersheim"), "2022-07-01", "2023-01-01", "Number of threads used for mbus network", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SHARED_STRING_REPO_NO_RECLAIM = defineFeatureFlag( "shared-string-repo-no-reclaim", false, List.of("baldersheim"), "2022-06-14", "2023-01-01", "Controls whether we do track usage and reclaim unused enum values in shared string repo", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag CONTAINER_DUMP_HEAP_ON_SHUTDOWN_TIMEOUT = defineFeatureFlag( "container-dump-heap-on-shutdown-timeout", false, List.of("baldersheim"), "2021-09-25", "2023-01-01", "Will trigger a heap dump during if container shutdown times out", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag LOAD_CODE_AS_HUGEPAGES = defineFeatureFlag( "load-code-as-hugepages", false, List.of("baldersheim"), "2022-05-13", "2023-01-01", "Will try to map the code segment with huge (2M) pages", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag CONTAINER_SHUTDOWN_TIMEOUT = defineDoubleFlag( "container-shutdown-timeout", 50.0, List.of("baldersheim"), "2021-09-25", "2023-05-01", "Timeout for shutdown of a jdisc container", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundListFlag<String> ALLOWED_ATHENZ_PROXY_IDENTITIES = defineListFlag( "allowed-athenz-proxy-identities", List.of(), String.class, List.of("bjorncs", "tokle"), "2021-02-10", "2022-09-01", "Allowed Athenz proxy identities", "takes effect at redeployment"); public static final UnboundIntFlag MAX_ACTIVATION_INHIBITED_OUT_OF_SYNC_GROUPS = defineIntFlag( "max-activation-inhibited-out-of-sync-groups", 0, List.of("vekterli"), "2021-02-19", "2022-08-01", "Allows replicas in up to N content groups to not be activated " + "for query visibility if they are out of sync with a majority of other replicas", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MAX_CONCURRENT_MERGES_PER_NODE = defineIntFlag( "max-concurrent-merges-per-node", 16, List.of("balder", "vekterli"), "2021-06-06", "2022-08-01", "Specifies max concurrent merges per content node.", "Takes effect at redeploy", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MAX_MERGE_QUEUE_SIZE = defineIntFlag( "max-merge-queue-size", 100, List.of("balder", "vekterli"), "2021-06-06", "2022-08-01", "Specifies max size of merge queue.", "Takes effect at redeploy", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag MIN_NODE_RATIO_PER_GROUP = defineDoubleFlag( "min-node-ratio-per-group", 0.0, List.of("geirst", "vekterli"), "2021-07-16", "2022-09-01", "Minimum ratio of nodes that have to be available (i.e. not Down) in any hierarchic content cluster group for the group to be Up", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag METRICSPROXY_NUM_THREADS = defineIntFlag( "metricsproxy-num-threads", 2, List.of("balder"), "2021-09-01", "2023-01-01", "Number of threads for metrics proxy", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag AVAILABLE_PROCESSORS = defineIntFlag( "available-processors", 2, List.of("balder"), "2022-01-18", "2023-01-01", "Number of processors the jvm sees in non-application clusters", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag ENABLED_HORIZON_DASHBOARD = defineFeatureFlag( "enabled-horizon-dashboard", false, List.of("olaa"), "2021-09-13", "2022-10-01", "Enable Horizon dashboard", "Takes effect immediately", TENANT_ID, CONSOLE_USER_EMAIL ); public static final UnboundBooleanFlag UNORDERED_MERGE_CHAINING = defineFeatureFlag( "unordered-merge-chaining", true, List.of("vekterli", "geirst"), "2021-11-15", "2022-09-01", "Enables the use of unordered merge chains for data merge operations", "Takes effect at redeploy", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag IGNORE_THREAD_STACK_SIZES = defineFeatureFlag( "ignore-thread-stack-sizes", false, List.of("arnej"), "2021-11-12", "2022-12-01", "Whether C++ thread creation should ignore any requested stack size", "Triggers restart, takes effect immediately", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_V8_GEO_POSITIONS = defineFeatureFlag( "use-v8-geo-positions", true, List.of("arnej"), "2021-11-15", "2022-12-31", "Use Vespa 8 types and formats for geographical positions", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MAX_COMPACT_BUFFERS = defineIntFlag( "max-compact-buffers", 1, List.of("baldersheim", "geirst", "toregge"), "2021-12-15", "2023-01-01", "Upper limit of buffers to compact in a data store at the same time for each reason (memory usage, address space usage)", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag ENABLE_SERVER_OCSP_STAPLING = defineFeatureFlag( "enable-server-ocsp-stapling", false, List.of("bjorncs"), "2021-12-17", "2022-09-01", "Enable server OCSP stapling for jdisc containers", "Takes effect on redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag ENABLE_DATA_HIGHWAY_IN_AWS = defineFeatureFlag( "enable-data-highway-in-aws", false, List.of("hmusum"), "2022-01-06", "2022-08-01", "Enable Data Highway in AWS", "Takes effect on restart of Docker container", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag MERGE_THROTTLING_POLICY = defineStringFlag( "merge-throttling-policy", "STATIC", List.of("vekterli"), "2022-01-25", "2022-08-01", "Sets the policy used for merge throttling on the content nodes. " + "Valid values: STATIC, DYNAMIC", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag PERSISTENCE_THROTTLING_WS_DECREMENT_FACTOR = defineDoubleFlag( "persistence-throttling-ws-decrement-factor", 1.2, List.of("vekterli"), "2022-01-27", "2022-08-01", "Sets the dynamic throttle policy window size decrement factor for persistence " + "async throttling. Only applies if DYNAMIC policy is used.", "Takes effect on redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag PERSISTENCE_THROTTLING_WS_BACKOFF = defineDoubleFlag( "persistence-throttling-ws-backoff", 0.95, List.of("vekterli"), "2022-01-27", "2022-08-01", "Sets the dynamic throttle policy window size backoff for persistence " + "async throttling. Only applies if DYNAMIC policy is used. Valid range [0, 1]", "Takes effect on redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag PERSISTENCE_THROTTLING_WINDOW_SIZE = defineIntFlag( "persistence-throttling-window-size", -1, List.of("vekterli"), "2022-02-23", "2022-09-01", "If greater than zero, sets both min and max window size to the given number, effectively " + "turning dynamic throttling into a static throttling policy. " + "Only applies if DYNAMIC policy is used.", "Takes effect on redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag PERSISTENCE_THROTTLING_WS_RESIZE_RATE = defineDoubleFlag( "persistence-throttling-ws-resize-rate", 3.0, List.of("vekterli"), "2022-02-23", "2022-09-01", "Sets the dynamic throttle policy resize rate. Only applies if DYNAMIC policy is used.", "Takes effect on redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag PERSISTENCE_THROTTLING_OF_MERGE_FEED_OPS = defineFeatureFlag( "persistence-throttling-of-merge-feed-ops", true, List.of("vekterli"), "2022-02-24", "2022-09-01", "If true, each put/remove contained within a merge is individually throttled as if it " + "were a put/remove from a client. If false, merges are throttled at a persistence thread " + "level, i.e. per ApplyBucketDiff message, regardless of how many document operations " + "are contained within. Only applies if DYNAMIC policy is used.", "Takes effect on redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_QRSERVER_SERVICE_NAME = defineFeatureFlag( "use-qrserver-service-name", false, List.of("arnej"), "2022-01-18", "2022-12-31", "Use backwards-compatible 'qrserver' service name for containers with only 'search' API", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag AVOID_RENAMING_SUMMARY_FEATURES = defineFeatureFlag( "avoid-renaming-summary-features", true, List.of("arnej"), "2022-01-15", "2023-12-31", "Tell backend about the original name of summary-features that were wrapped in a rankingExpression feature", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag ENABLE_BIT_VECTORS = defineFeatureFlag( "enable-bit-vectors", false, List.of("baldersheim"), "2022-05-03", "2022-12-31", "Enables bit vector by default for fast-search attributes", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag APPLICATION_FILES_WITH_UNKNOWN_EXTENSION = defineStringFlag( "fail-deployment-for-files-with-unknown-extension", "LOG", List.of("hmusum"), "2022-04-27", "2022-07-27", "Whether to log, fail or do nothing for deployments when app has a file with unknown extension (valid values LOG, FAIL, NOOP)", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag NOTIFICATION_DISPATCH_FLAG = defineFeatureFlag( "dispatch-notifications", false, List.of("enygaard"), "2022-05-02", "2022-09-30", "Whether we should send notification for a given tenant", "Takes effect immediately", TENANT_ID); public static final UnboundBooleanFlag ENABLE_PROXY_PROTOCOL_MIXED_MODE = defineFeatureFlag( "enable-proxy-protocol-mixed-mode", true, List.of("tokle"), "2022-05-09", "2022-09-01", "Enable or disable proxy protocol mixed mode", "Takes effect on redeployment", APPLICATION_ID); public static final UnboundListFlag<String> FILE_DISTRIBUTION_ACCEPTED_COMPRESSION_TYPES = defineListFlag( "file-distribution-accepted-compression-types", List.of("gzip", "lz4"), String.class, List.of("hmusum"), "2022-07-05", "2022-09-05", "´List of accepted compression types used when asking for a file reference. Valid values: gzip, lz4", "Takes effect on restart of service", APPLICATION_ID); public static final UnboundListFlag<String> FILE_DISTRIBUTION_COMPRESSION_TYPES_TO_SERVE = defineListFlag( "file-distribution-compression-types-to-use", List.of("lz4", "gzip"), String.class, List.of("hmusum"), "2022-07-05", "2022-09-05", "List of compression types to use (in preferred order), matched with accepted compression types when serving file references. Valid values: gzip, lz4", "Takes effect on restart of service", APPLICATION_ID); public static final UnboundBooleanFlag USE_YUM_PROXY_V2 = defineFeatureFlag( "use-yumproxy-v2", false, List.of("tokle"), "2022-05-05", "2022-09-01", "Use yumproxy-v2", "Takes effect on host admin restart", HOSTNAME); public static final UnboundStringFlag LOG_FILE_COMPRESSION_ALGORITHM = defineStringFlag( "log-file-compression-algorithm", "", List.of("arnej"), "2022-06-14", "2024-12-31", "Which algorithm to use for compressing log files. Valid values: empty string (default), gzip, zstd", "Takes effect immediately", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag FIX_IPV6_GATEWAY = defineFeatureFlag( "fix-ipv6-gateway", true, List.of("mpolden"), "2022-07-04", "2022-09-01", "Fix a misconfigured IPv6 gateway automatically", "Takes effect on first host admin resume", HOSTNAME); public static final UnboundBooleanFlag SEPARATE_METRIC_CHECK_CONFIG = defineFeatureFlag( "separate-metric-check-config", false, List.of("olaa"), "2022-07-04", "2022-09-01", "Determines whether one metrics config check should be written per Vespa node", "Takes effect on next tick", HOSTNAME); /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundBooleanFlag defineFeatureFlag(String flagId, boolean defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundBooleanFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundStringFlag defineStringFlag(String flagId, String defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundStringFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundIntFlag defineIntFlag(String flagId, int defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundIntFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundLongFlag defineLongFlag(String flagId, long defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundLongFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundDoubleFlag defineDoubleFlag(String flagId, double defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundDoubleFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static <T> UnboundJacksonFlag<T> defineJacksonFlag(String flagId, T defaultValue, Class<T> jacksonClass, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define((id2, defaultValue2, vector2) -> new UnboundJacksonFlag<>(id2, defaultValue2, vector2, jacksonClass), flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static <T> UnboundListFlag<T> defineListFlag(String flagId, List<T> defaultValue, Class<T> elementClass, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define((fid, dval, fvec) -> new UnboundListFlag<>(fid, dval, elementClass, fvec), flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } @FunctionalInterface private interface TypedUnboundFlagFactory<T, U extends UnboundFlag<?, ?, ?>> { U create(FlagId id, T defaultVale, FetchVector defaultFetchVector); } /** * Defines a Flag. * * @param factory Factory for creating unbound flag of type U * @param flagId The globally unique FlagId. * @param defaultValue The default value if none is present after resolution. * @param description Description of how the flag is used. * @param modificationEffect What is required for the flag to take effect? A restart of process? immediately? etc. * @param dimensions What dimensions will be set in the {@link FetchVector} when fetching * the flag value in * {@link FlagSource#fetch(FlagId, FetchVector) FlagSource::fetch}. * For instance, if APPLICATION is one of the dimensions here, you should make sure * APPLICATION is set to the ApplicationId in the fetch vector when fetching the RawFlag * from the FlagSource. * @param <T> The boxed type of the flag value, e.g. Boolean for flags guarding features. * @param <U> The type of the unbound flag, e.g. UnboundBooleanFlag. * @return An unbound flag with {@link FetchVector.Dimension#HOSTNAME HOSTNAME} and * {@link FetchVector.Dimension#VESPA_VERSION VESPA_VERSION} already set. The ZONE environment * is typically implicit. */ private static <T, U extends UnboundFlag<?, ?, ?>> U define(TypedUnboundFlagFactory<T, U> factory, String flagId, T defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension[] dimensions) { FlagId id = new FlagId(flagId); FetchVector vector = new FetchVector() .with(HOSTNAME, Defaults.getDefaults().vespaHostname()) // Warning: In unit tests and outside official Vespa releases, the currentVersion is e.g. 7.0.0 // (determined by the current major version). Consider not setting VESPA_VERSION if minor = micro = 0. .with(VESPA_VERSION, Vtag.currentVersion.toFullString()); U unboundFlag = factory.create(id, defaultValue, vector); FlagDefinition definition = new FlagDefinition( unboundFlag, owners, parseDate(createdAt), parseDate(expiresAt), description, modificationEffect, dimensions); flags.put(id, definition); return unboundFlag; } private static Instant parseDate(String rawDate) { return DateTimeFormatter.ISO_DATE.parse(rawDate, LocalDate::from).atStartOfDay().toInstant(ZoneOffset.UTC); } public static List<FlagDefinition> getAllFlags() { return List.copyOf(flags.values()); } public static Optional<FlagDefinition> getFlag(FlagId flagId) { return Optional.ofNullable(flags.get(flagId)); } /** * Allows the statically defined flags to be controlled in a test. * * <p>Returns a Replacer instance to be used with e.g. a try-with-resources block. Within the block, * the flags starts out as cleared. Flags can be defined, etc. When leaving the block, the flags from * before the block is reinserted. * * <p>NOT thread-safe. Tests using this cannot run in parallel. */ public static Replacer clearFlagsForTesting(FlagId... flagsToKeep) { return new Replacer(flagsToKeep); } public static class Replacer implements AutoCloseable { private static volatile boolean flagsCleared = false; private final TreeMap<FlagId, FlagDefinition> savedFlags; private Replacer(FlagId... flagsToKeep) { verifyAndSetFlagsCleared(true); this.savedFlags = Flags.flags; Flags.flags = new TreeMap<>(); List.of(flagsToKeep).forEach(id -> Flags.flags.put(id, savedFlags.get(id))); } @Override public void close() { verifyAndSetFlagsCleared(false); Flags.flags = savedFlags; } /** * Used to implement a simple verification that Replacer is not used by multiple threads. * For instance two different tests running in parallel cannot both use Replacer. */ private static void verifyAndSetFlagsCleared(boolean newValue) { if (flagsCleared == newValue) { throw new IllegalStateException("clearFlagsForTesting called while already cleared - running tests in parallell!?"); } flagsCleared = newValue; } } }
package com.yahoo.vespa.flags; import com.yahoo.vespa.defaults.Defaults; import java.util.List; import java.util.Optional; import java.util.TreeMap; import static com.yahoo.vespa.flags.FetchVector.Dimension.APPLICATION_ID; import static com.yahoo.vespa.flags.FetchVector.Dimension.HOSTNAME; import static com.yahoo.vespa.flags.FetchVector.Dimension.NODE_TYPE; /** * Definitions of feature flags. * * <p>To use feature flags, define the flag in this class as an "unbound" flag, e.g. {@link UnboundBooleanFlag} * or {@link UnboundStringFlag}. At the location you want to get the value of the flag, you need the following:</p> * * <ol> * <li>The unbound flag</li> * <li>A {@link FlagSource}. The flag source is typically available as an injectible component. Binding * an unbound flag to a flag source produces a (bound) flag, e.g. {@link BooleanFlag} and {@link StringFlag}.</li> * <li>If you would like your flag value to be dependent on e.g. the application ID, then 1. you should * declare this in the unbound flag definition in this file (referring to * {@link FetchVector.Dimension#APPLICATION_ID}), and 2. specify the application ID when retrieving the value, e.g. * {@link BooleanFlag#with(FetchVector.Dimension, String)}. See {@link FetchVector} for more info.</li> * </ol> * * <p>Once the code is in place, you can override the flag value. This depends on the flag source, but typically * there is a REST API for updating the flags in the config server, which is the root of all flag sources in the zone.</p> * * @author hakonhall */ public class Flags { private static volatile TreeMap<FlagId, FlagDefinition> flags = new TreeMap<>(); public static final UnboundIntFlag DROP_CACHES = defineIntFlag("drop-caches", 3, "The int value to write into /proc/sys/vm/drop_caches for each tick. " + "1 is page cache, 2 is dentries inodes, 3 is both page cache and dentries inodes, etc.", "Takes effect on next tick.", HOSTNAME); public static final UnboundBooleanFlag ENABLE_CROWDSTRIKE = defineFeatureFlag( "enable-crowdstrike", true, "Whether to enable CrowdStrike.", "Takes effect on next host admin tick", HOSTNAME); public static final UnboundBooleanFlag ENABLE_NESSUS = defineFeatureFlag( "enable-nessus", true, "Whether to enable Nessus.", "Takes effect on next host admin tick", HOSTNAME); public static final UnboundListFlag<String> DISABLED_HOST_ADMIN_TASKS = defineListFlag( "disabled-host-admin-tasks", List.of(), "List of host-admin task names (as they appear in the log, e.g. root>main>UpgradeTask) that should be skipped", "Takes effect on next host admin tick", HOSTNAME, NODE_TYPE); public static final UnboundBooleanFlag USE_DEDICATED_NODE_FOR_LOGSERVER = defineFeatureFlag( "use-dedicated-node-for-logserver", true, "Whether to use a dedicated node for the logserver.", "Takes effect at redeployment", APPLICATION_ID); public static final UnboundDoubleFlag CONTAINER_CPU_CAP = defineDoubleFlag( "container-cpu-cap", 0, "Hard limit on how many CPUs a container may use. This value is multiplied by CPU allocated to node, so " + "to cap CPU at 200%, set this to 2, etc.", "Takes effect on next node agent tick. Change is orchestrated, but does NOT require container restart", HOSTNAME, APPLICATION_ID); public static final UnboundStringFlag TLS_INSECURE_MIXED_MODE = defineStringFlag( "tls-insecure-mixed-mode", "tls_client_mixed_server", "TLS insecure mixed mode. Allowed values: ['plaintext_client_mixed_server', 'tls_client_mixed_server', 'tls_client_tls_server']", "Takes effect on restart of Docker container", NODE_TYPE, APPLICATION_ID, HOSTNAME); public static final UnboundStringFlag TLS_INSECURE_AUTHORIZATION_MODE = defineStringFlag( "tls-insecure-authorization-mode", "log_only", "TLS insecure authorization mode. Allowed values: ['disable', 'log_only', 'enforce']", "Takes effect on restart of Docker container", NODE_TYPE, APPLICATION_ID, HOSTNAME); public static final UnboundBooleanFlag USE_FDISPATCH_BY_DEFAULT = defineFeatureFlag( "use-fdispatch-by-default", true, "Should fdispatch be used as the default instead of the java dispatcher", "Takes effect at redeployment", APPLICATION_ID); public static final UnboundBooleanFlag USE_ADAPTIVE_DISPATCH = defineFeatureFlag( "use-adaptive-dispatch", false, "Should adaptive dispatch be used over round robin", "Takes effect at redeployment", APPLICATION_ID); public static final UnboundBooleanFlag DISPATCH_WITH_PROTOBUF = defineFeatureFlag( "dispatch-with-protobuf", false, "Should the java dispatcher use protobuf/jrt as the default", "Takes effect at redeployment", APPLICATION_ID); public static final UnboundBooleanFlag ENABLE_DYNAMIC_PROVISIONING = defineFeatureFlag( "enable-dynamic-provisioning", false, "Provision a new docker host when we otherwise can't allocate a docker node", "Takes effect on next deployment", APPLICATION_ID); public static final UnboundListFlag<String> DISABLED_DYNAMIC_PROVISIONING_FLAVORS = defineListFlag( "disabled-dynamic-provisioning-flavors", List.of(), "List of disabled Vespa flavor names that cannot be used for dynamic provisioning", "Takes effect on next provisioning"); public static final UnboundBooleanFlag ENABLE_DISK_WRITE_TEST = defineFeatureFlag( "enable-disk-write-test", false, "Regularly issue a small write to disk and fail the host if it is not successful", "Takes effect on next node agent tick (but does not clear existing failure reports)", HOSTNAME); public static final UnboundBooleanFlag ENABLE_METRICS_PROXY_CONTAINER = defineFeatureFlag( "enable-metrics-proxy-container", false, "Start a container for metrics-proxy on every vespa node", "Takes effect at redeployment", APPLICATION_ID); public static final UnboundBooleanFlag USE_HTTPS_LOAD_BALANCER_UPSTREAM = defineFeatureFlag( "use-https-load-balancer-upstream", false, "Use https between load balancer and upstream containers", "Takes effect at redeployment", APPLICATION_ID); public static final UnboundBooleanFlag REDIRECT_LEGACY_DNS_NAMES = defineFeatureFlag( "redirect-legacy-dns", false, "Redirect legacy DNS names to the main DNS name", "Takes effect on deployment through controller", APPLICATION_ID); public static final UnboundBooleanFlag CONFIG_SERVER_FAIL_IF_ACTIVE_SESSION_CANNOT_BE_LOADED = defineFeatureFlag( "config-server-fail-if-active-session-cannot-be-loaded", false, "Whether to fail or just log if loading an active session fails at startup of config server", "Takes effect only at bootstrap of config server/controller", HOSTNAME); public static final UnboundStringFlag CONFIGSERVER_RPC_AUTHORIZER = defineStringFlag( "configserver-rpc-authorizer", "log-only", "Configserver RPC authorizer. Allowed values: ['disable', 'log-only', 'enforce']", "Takes effect on restart of configserver"); public static final UnboundBooleanFlag PROVISION_APPLICATION_CERTIFICATE = defineFeatureFlag( "provision-application-certificate", false, "Privision certificate from CA and include reference in deployment", "Takes effect on deployment through controller", APPLICATION_ID); public static final UnboundBooleanFlag MULTIPLE_GLOBAL_ENDPOINTS = defineFeatureFlag( "multiple-global-endpoints", false, "Allow applications to use new endpoints syntax in deployment.xml", "Takes effect on deployment through controller", APPLICATION_ID); public static final UnboundBooleanFlag DISABLE_CHEF = defineFeatureFlag( "disable-chef", false, "Stops and disables chef-client", "Takes effect on next host-admin tick", HOSTNAME, NODE_TYPE); /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundBooleanFlag defineFeatureFlag(String flagId, boolean defaultValue, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundBooleanFlag::new, flagId, defaultValue, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundStringFlag defineStringFlag(String flagId, String defaultValue, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundStringFlag::new, flagId, defaultValue, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundIntFlag defineIntFlag(String flagId, int defaultValue, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundIntFlag::new, flagId, defaultValue, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundLongFlag defineLongFlag(String flagId, long defaultValue, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundLongFlag::new, flagId, defaultValue, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundDoubleFlag defineDoubleFlag(String flagId, double defaultValue, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundDoubleFlag::new, flagId, defaultValue, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static <T> UnboundJacksonFlag<T> defineJacksonFlag(String flagId, T defaultValue, Class<T> jacksonClass, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define((id2, defaultValue2, vector2) -> new UnboundJacksonFlag<>(id2, defaultValue2, vector2, jacksonClass), flagId, defaultValue, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static <T> UnboundListFlag<T> defineListFlag(String flagId, List<T> defaultValue, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundListFlag::new, flagId, defaultValue, description, modificationEffect, dimensions); } @FunctionalInterface private interface TypedUnboundFlagFactory<T, U extends UnboundFlag<?, ?, ?>> { U create(FlagId id, T defaultVale, FetchVector defaultFetchVector); } /** * Defines a Flag. * * @param factory Factory for creating unbound flag of type U * @param flagId The globally unique FlagId. * @param defaultValue The default value if none is present after resolution. * @param description Description of how the flag is used. * @param modificationEffect What is required for the flag to take effect? A restart of process? immediately? etc. * @param dimensions What dimensions will be set in the {@link FetchVector} when fetching * the flag value in * {@link FlagSource#fetch(FlagId, FetchVector) FlagSource::fetch}. * For instance, if APPLICATION is one of the dimensions here, you should make sure * APPLICATION is set to the ApplicationId in the fetch vector when fetching the RawFlag * from the FlagSource. * @param <T> The boxed type of the flag value, e.g. Boolean for flags guarding features. * @param <U> The type of the unbound flag, e.g. UnboundBooleanFlag. * @return An unbound flag with {@link FetchVector.Dimension#HOSTNAME HOSTNAME} environment. The ZONE environment * is typically implicit. */ private static <T, U extends UnboundFlag<?, ?, ?>> U define(TypedUnboundFlagFactory<T, U> factory, String flagId, T defaultValue, String description, String modificationEffect, FetchVector.Dimension[] dimensions) { FlagId id = new FlagId(flagId); FetchVector vector = new FetchVector().with(HOSTNAME, Defaults.getDefaults().vespaHostname()); U unboundFlag = factory.create(id, defaultValue, vector); FlagDefinition definition = new FlagDefinition(unboundFlag, description, modificationEffect, dimensions); flags.put(id, definition); return unboundFlag; } public static List<FlagDefinition> getAllFlags() { return List.copyOf(flags.values()); } public static Optional<FlagDefinition> getFlag(FlagId flagId) { return Optional.ofNullable(flags.get(flagId)); } /** * Allows the statically defined flags to be controlled in a test. * * <p>Returns a Replacer instance to be used with e.g. a try-with-resources block. Within the block, * the flags starts out as cleared. Flags can be defined, etc. When leaving the block, the flags from * before the block is reinserted. * * <p>NOT thread-safe. Tests using this cannot run in parallel. */ public static Replacer clearFlagsForTesting() { return new Replacer(); } public static class Replacer implements AutoCloseable { private static volatile boolean flagsCleared = false; private final TreeMap<FlagId, FlagDefinition> savedFlags; private Replacer() { verifyAndSetFlagsCleared(true); this.savedFlags = Flags.flags; Flags.flags = new TreeMap<>(); } @Override public void close() { verifyAndSetFlagsCleared(false); Flags.flags = savedFlags; } /** * Used to implement a simple verification that Replacer is not used by multiple threads. * For instance two different tests running in parallel cannot both use Replacer. */ private static void verifyAndSetFlagsCleared(boolean newValue) { if (flagsCleared == newValue) { throw new IllegalStateException("clearFlagsForTesting called while already cleared - running tests in parallell!?"); } flagsCleared = newValue; } } }
package com.yahoo.vespa.flags; import com.yahoo.component.Vtag; import com.yahoo.vespa.defaults.Defaults; import java.time.Instant; import java.time.LocalDate; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.List; import java.util.Optional; import java.util.TreeMap; import java.util.function.Predicate; import static com.yahoo.vespa.flags.FetchVector.Dimension.APPLICATION_ID; import static com.yahoo.vespa.flags.FetchVector.Dimension.CONSOLE_USER_EMAIL; import static com.yahoo.vespa.flags.FetchVector.Dimension.HOSTNAME; import static com.yahoo.vespa.flags.FetchVector.Dimension.NODE_TYPE; import static com.yahoo.vespa.flags.FetchVector.Dimension.TENANT_ID; import static com.yahoo.vespa.flags.FetchVector.Dimension.VESPA_VERSION; import static com.yahoo.vespa.flags.FetchVector.Dimension.ZONE_ID; /** * Definitions of feature flags. * * <p>To use feature flags, define the flag in this class as an "unbound" flag, e.g. {@link UnboundBooleanFlag} * or {@link UnboundStringFlag}. At the location you want to get the value of the flag, you need the following:</p> * * <ol> * <li>The unbound flag</li> * <li>A {@link FlagSource}. The flag source is typically available as an injectable component. Binding * an unbound flag to a flag source produces a (bound) flag, e.g. {@link BooleanFlag} and {@link StringFlag}.</li> * <li>If you would like your flag value to be dependent on e.g. the application ID, then 1. you should * declare this in the unbound flag definition in this file (referring to * {@link FetchVector.Dimension#APPLICATION_ID}), and 2. specify the application ID when retrieving the value, e.g. * {@link BooleanFlag#with(FetchVector.Dimension, String)}. See {@link FetchVector} for more info.</li> * </ol> * * <p>Once the code is in place, you can override the flag value. This depends on the flag source, but typically * there is a REST API for updating the flags in the config server, which is the root of all flag sources in the zone.</p> * * @author hakonhall */ public class Flags { private static volatile TreeMap<FlagId, FlagDefinition> flags = new TreeMap<>(); public static final UnboundBooleanFlag MAIN_CHAIN_GRAPH = defineFeatureFlag( "main-chain-graph", true, List.of("hakonhall"), "2022-07-06", "2022-10-05", "Whether to run all tasks in the main task chain up to the one failing to converge (false), or " + "run all tasks in the main task chain whose dependencies have converged (true). And when suspending, " + "whether to run the tasks in sequence (false) or in reverse sequence (true).", "On first tick of the main chain after (re)start of host admin.", ZONE_ID, NODE_TYPE, HOSTNAME); public static final UnboundDoubleFlag DEFAULT_TERM_WISE_LIMIT = defineDoubleFlag( "default-term-wise-limit", 1.0, List.of("baldersheim"), "2020-12-02", "2023-01-01", "Default limit for when to apply termwise query evaluation", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag QUERY_DISPATCH_POLICY = defineStringFlag( "query-dispatch-policy", "adaptive", List.of("baldersheim"), "2022-08-20", "2023-01-01", "Select query dispatch policy, valid values are adaptive, round-robin, best-of-random-2," + " latency-amortized-over-requests, latency-amortized-over-time", "Takes effect at redeployment (requires restart)", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag FEED_SEQUENCER_TYPE = defineStringFlag( "feed-sequencer-type", "THROUGHPUT", List.of("baldersheim"), "2020-12-02", "2023-01-01", "Selects type of sequenced executor used for feeding in proton, valid values are LATENCY, ADAPTIVE, THROUGHPUT", "Takes effect at redeployment (requires restart)", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag KEEP_STORAGE_NODE_UP = defineFeatureFlag( "keep-storage-node-up", true, List.of("hakonhall"), "2022-07-07", "2022-09-07", "Whether to leave the storage node (with wanted state) UP while the node is permanently down.", "Takes effect immediately for nodes transitioning to permanently down.", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MAX_UNCOMMITTED_MEMORY = defineIntFlag( "max-uncommitted-memory", 130000, List.of("geirst, baldersheim"), "2021-10-21", "2023-01-01", "Max amount of memory holding updates to an attribute before we do a commit.", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag RESPONSE_SEQUENCER_TYPE = defineStringFlag( "response-sequencer-type", "ADAPTIVE", List.of("baldersheim"), "2020-12-02", "2023-01-01", "Selects type of sequenced executor used for mbus responses, valid values are LATENCY, ADAPTIVE, THROUGHPUT", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag RESPONSE_NUM_THREADS = defineIntFlag( "response-num-threads", 2, List.of("baldersheim"), "2020-12-02", "2023-01-01", "Number of threads used for mbus responses, default is 2, negative number = numcores/4", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SKIP_COMMUNICATIONMANAGER_THREAD = defineFeatureFlag( "skip-communicationmanager-thread", false, List.of("baldersheim"), "2020-12-02", "2023-01-01", "Should we skip the communicationmanager thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SKIP_MBUS_REQUEST_THREAD = defineFeatureFlag( "skip-mbus-request-thread", false, List.of("baldersheim"), "2020-12-02", "2023-01-01", "Should we skip the mbus request thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SKIP_MBUS_REPLY_THREAD = defineFeatureFlag( "skip-mbus-reply-thread", false, List.of("baldersheim"), "2020-12-02", "2023-01-01", "Should we skip the mbus reply thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_THREE_PHASE_UPDATES = defineFeatureFlag( "use-three-phase-updates", false, List.of("vekterli"), "2020-12-02", "2022-10-01", "Whether to enable the use of three-phase updates when bucket replicas are out of sync.", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_ASYNC_MESSAGE_HANDLING_ON_SCHEDULE = defineFeatureFlag( "async-message-handling-on-schedule", false, List.of("baldersheim"), "2020-12-02", "2023-01-01", "Optionally deliver async messages in own thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag FEED_CONCURRENCY = defineDoubleFlag( "feed-concurrency", 0.5, List.of("baldersheim"), "2020-12-02", "2023-01-01", "How much concurrency should be allowed for feed", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag FEED_NICENESS = defineDoubleFlag( "feed-niceness", 0.0, List.of("baldersheim"), "2022-06-24", "2023-01-01", "How nice feeding shall be", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag MBUS_DISPATCH_ON_ENCODE = defineFeatureFlag( "mbus-dispatch-on-encode", true, List.of("baldersheim"), "2022-07-01", "2023-01-01", "Should we use mbus threadpool on encode", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag MBUS_DISPATCH_ON_DECODE = defineFeatureFlag( "mbus-dispatch-on-decode", true, List.of("baldersheim"), "2022-07-01", "2023-01-01", "Should we use mbus threadpool on decode", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MBUS_JAVA_NUM_TARGETS = defineIntFlag( "mbus-java-num-targets", 1, List.of("baldersheim"), "2022-07-05", "2023-01-01", "Number of rpc targets per service", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MBUS_CPP_NUM_TARGETS = defineIntFlag( "mbus-cpp-num-targets", 1, List.of("baldersheim"), "2022-07-05", "2023-01-01", "Number of rpc targets per service", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag RPC_NUM_TARGETS = defineIntFlag( "rpc-num-targets", 1, List.of("baldersheim"), "2022-07-05", "2023-01-01", "Number of rpc targets per content node", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MBUS_JAVA_EVENTS_BEFORE_WAKEUP = defineIntFlag( "mbus-java-events-before-wakeup", 1, List.of("baldersheim"), "2022-07-05", "2023-01-01", "Number write events before waking up transport thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MBUS_CPP_EVENTS_BEFORE_WAKEUP = defineIntFlag( "mbus-cpp-events-before-wakeup", 1, List.of("baldersheim"), "2022-07-05", "2023-01-01", "Number write events before waking up transport thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag RPC_EVENTS_BEFORE_WAKEUP = defineIntFlag( "rpc-events-before-wakeup", 1, List.of("baldersheim"), "2022-07-05", "2023-01-01", "Number write events before waking up transport thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MBUS_NUM_THREADS = defineIntFlag( "mbus-num-threads", 4, List.of("baldersheim"), "2022-07-01", "2023-01-01", "Number of threads used for mbus threadpool", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MBUS_NUM_NETWORK_THREADS = defineIntFlag( "mbus-num-network-threads", 1, List.of("baldersheim"), "2022-07-01", "2023-01-01", "Number of threads used for mbus network", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SHARED_STRING_REPO_NO_RECLAIM = defineFeatureFlag( "shared-string-repo-no-reclaim", false, List.of("baldersheim"), "2022-06-14", "2023-01-01", "Controls whether we do track usage and reclaim unused enum values in shared string repo", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag CONTAINER_DUMP_HEAP_ON_SHUTDOWN_TIMEOUT = defineFeatureFlag( "container-dump-heap-on-shutdown-timeout", false, List.of("baldersheim"), "2021-09-25", "2023-01-01", "Will trigger a heap dump during if container shutdown times out", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag LOAD_CODE_AS_HUGEPAGES = defineFeatureFlag( "load-code-as-hugepages", false, List.of("baldersheim"), "2022-05-13", "2023-01-01", "Will try to map the code segment with huge (2M) pages", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag CONTAINER_SHUTDOWN_TIMEOUT = defineDoubleFlag( "container-shutdown-timeout", 50.0, List.of("baldersheim"), "2021-09-25", "2023-05-01", "Timeout for shutdown of a jdisc container", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundListFlag<String> ALLOWED_ATHENZ_PROXY_IDENTITIES = defineListFlag( "allowed-athenz-proxy-identities", List.of(), String.class, List.of("bjorncs", "tokle"), "2021-02-10", "2022-09-01", "Allowed Athenz proxy identities", "takes effect at redeployment"); public static final UnboundIntFlag MAX_ACTIVATION_INHIBITED_OUT_OF_SYNC_GROUPS = defineIntFlag( "max-activation-inhibited-out-of-sync-groups", 0, List.of("vekterli"), "2021-02-19", "2022-10-01", "Allows replicas in up to N content groups to not be activated " + "for query visibility if they are out of sync with a majority of other replicas", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MAX_CONCURRENT_MERGES_PER_NODE = defineIntFlag( "max-concurrent-merges-per-node", 16, List.of("balder", "vekterli"), "2021-06-06", "2022-10-01", "Specifies max concurrent merges per content node.", "Takes effect at redeploy", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MAX_MERGE_QUEUE_SIZE = defineIntFlag( "max-merge-queue-size", 100, List.of("balder", "vekterli"), "2021-06-06", "2022-10-01", "Specifies max size of merge queue.", "Takes effect at redeploy", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag MIN_NODE_RATIO_PER_GROUP = defineDoubleFlag( "min-node-ratio-per-group", 0.0, List.of("geirst", "vekterli"), "2021-07-16", "2022-09-01", "Minimum ratio of nodes that have to be available (i.e. not Down) in any hierarchic content cluster group for the group to be Up", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag METRICSPROXY_NUM_THREADS = defineIntFlag( "metricsproxy-num-threads", 2, List.of("balder"), "2021-09-01", "2023-01-01", "Number of threads for metrics proxy", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag AVAILABLE_PROCESSORS = defineIntFlag( "available-processors", 2, List.of("balder"), "2022-01-18", "2023-01-01", "Number of processors the jvm sees in non-application clusters", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag ENABLED_HORIZON_DASHBOARD = defineFeatureFlag( "enabled-horizon-dashboard", false, List.of("olaa"), "2021-09-13", "2022-10-01", "Enable Horizon dashboard", "Takes effect immediately", TENANT_ID, CONSOLE_USER_EMAIL ); public static final UnboundBooleanFlag UNORDERED_MERGE_CHAINING = defineFeatureFlag( "unordered-merge-chaining", true, List.of("vekterli", "geirst"), "2021-11-15", "2022-09-01", "Enables the use of unordered merge chains for data merge operations", "Takes effect at redeploy", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag IGNORE_THREAD_STACK_SIZES = defineFeatureFlag( "ignore-thread-stack-sizes", false, List.of("arnej"), "2021-11-12", "2022-12-01", "Whether C++ thread creation should ignore any requested stack size", "Triggers restart, takes effect immediately", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_V8_GEO_POSITIONS = defineFeatureFlag( "use-v8-geo-positions", true, List.of("arnej"), "2021-11-15", "2022-12-31", "Use Vespa 8 types and formats for geographical positions", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MAX_COMPACT_BUFFERS = defineIntFlag( "max-compact-buffers", 1, List.of("baldersheim", "geirst", "toregge"), "2021-12-15", "2023-01-01", "Upper limit of buffers to compact in a data store at the same time for each reason (memory usage, address space usage)", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag ENABLE_SERVER_OCSP_STAPLING = defineFeatureFlag( "enable-server-ocsp-stapling", false, List.of("bjorncs"), "2021-12-17", "2022-09-01", "Enable server OCSP stapling for jdisc containers", "Takes effect on redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag ENABLE_DATA_HIGHWAY_IN_AWS = defineFeatureFlag( "enable-data-highway-in-aws", false, List.of("hmusum"), "2022-01-06", "2022-10-01", "Enable Data Highway in AWS", "Takes effect on restart of Docker container", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag MERGE_THROTTLING_POLICY = defineStringFlag( "merge-throttling-policy", "STATIC", List.of("vekterli"), "2022-01-25", "2022-10-01", "Sets the policy used for merge throttling on the content nodes. " + "Valid values: STATIC, DYNAMIC", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag PERSISTENCE_THROTTLING_WS_DECREMENT_FACTOR = defineDoubleFlag( "persistence-throttling-ws-decrement-factor", 1.2, List.of("vekterli"), "2022-01-27", "2022-10-01", "Sets the dynamic throttle policy window size decrement factor for persistence " + "async throttling. Only applies if DYNAMIC policy is used.", "Takes effect on redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag PERSISTENCE_THROTTLING_WS_BACKOFF = defineDoubleFlag( "persistence-throttling-ws-backoff", 0.95, List.of("vekterli"), "2022-01-27", "2022-10-01", "Sets the dynamic throttle policy window size backoff for persistence " + "async throttling. Only applies if DYNAMIC policy is used. Valid range [0, 1]", "Takes effect on redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag PERSISTENCE_THROTTLING_WINDOW_SIZE = defineIntFlag( "persistence-throttling-window-size", -1, List.of("vekterli"), "2022-02-23", "2022-09-01", "If greater than zero, sets both min and max window size to the given number, effectively " + "turning dynamic throttling into a static throttling policy. " + "Only applies if DYNAMIC policy is used.", "Takes effect on redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag PERSISTENCE_THROTTLING_WS_RESIZE_RATE = defineDoubleFlag( "persistence-throttling-ws-resize-rate", 3.0, List.of("vekterli"), "2022-02-23", "2022-09-01", "Sets the dynamic throttle policy resize rate. Only applies if DYNAMIC policy is used.", "Takes effect on redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag PERSISTENCE_THROTTLING_OF_MERGE_FEED_OPS = defineFeatureFlag( "persistence-throttling-of-merge-feed-ops", true, List.of("vekterli"), "2022-02-24", "2022-09-01", "If true, each put/remove contained within a merge is individually throttled as if it " + "were a put/remove from a client. If false, merges are throttled at a persistence thread " + "level, i.e. per ApplyBucketDiff message, regardless of how many document operations " + "are contained within. Only applies if DYNAMIC policy is used.", "Takes effect on redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_QRSERVER_SERVICE_NAME = defineFeatureFlag( "use-qrserver-service-name", false, List.of("arnej"), "2022-01-18", "2022-12-31", "Use backwards-compatible 'qrserver' service name for containers with only 'search' API", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag AVOID_RENAMING_SUMMARY_FEATURES = defineFeatureFlag( "avoid-renaming-summary-features", true, List.of("arnej"), "2022-01-15", "2023-12-31", "Tell backend about the original name of summary-features that were wrapped in a rankingExpression feature", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag ENABLE_BIT_VECTORS = defineFeatureFlag( "enable-bit-vectors", false, List.of("baldersheim"), "2022-05-03", "2022-12-31", "Enables bit vector by default for fast-search attributes", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag APPLICATION_FILES_WITH_UNKNOWN_EXTENSION = defineStringFlag( "fail-deployment-for-files-with-unknown-extension", "FAIL", List.of("hmusum"), "2022-04-27", "2022-10-01", "Whether to log or fail for deployments when app has a file with unknown extension (valid values: LOG, FAIL)", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag NOTIFICATION_DISPATCH_FLAG = defineFeatureFlag( "dispatch-notifications", false, List.of("enygaard"), "2022-05-02", "2022-09-30", "Whether we should send notification for a given tenant", "Takes effect immediately", TENANT_ID); public static final UnboundBooleanFlag ENABLE_PROXY_PROTOCOL_MIXED_MODE = defineFeatureFlag( "enable-proxy-protocol-mixed-mode", true, List.of("tokle"), "2022-05-09", "2022-09-01", "Enable or disable proxy protocol mixed mode", "Takes effect on redeployment", APPLICATION_ID); public static final UnboundListFlag<String> FILE_DISTRIBUTION_ACCEPTED_COMPRESSION_TYPES = defineListFlag( "file-distribution-accepted-compression-types", List.of("gzip", "lz4"), String.class, List.of("hmusum"), "2022-07-05", "2022-10-01", "´List of accepted compression types used when asking for a file reference. Valid values: gzip, lz4", "Takes effect on restart of service", APPLICATION_ID); public static final UnboundListFlag<String> FILE_DISTRIBUTION_COMPRESSION_TYPES_TO_SERVE = defineListFlag( "file-distribution-compression-types-to-use", List.of("lz4", "gzip"), String.class, List.of("hmusum"), "2022-07-05", "2022-10-01", "List of compression types to use (in preferred order), matched with accepted compression types when serving file references. Valid values: gzip, lz4", "Takes effect on restart of service", APPLICATION_ID); public static final UnboundBooleanFlag USE_YUM_PROXY_V2 = defineFeatureFlag( "use-yumproxy-v2", false, List.of("tokle"), "2022-05-05", "2022-09-01", "Use yumproxy-v2", "Takes effect on host admin restart", HOSTNAME); public static final UnboundStringFlag LOG_FILE_COMPRESSION_ALGORITHM = defineStringFlag( "log-file-compression-algorithm", "", List.of("arnej"), "2022-06-14", "2024-12-31", "Which algorithm to use for compressing log files. Valid values: empty string (default), gzip, zstd", "Takes effect immediately", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SEPARATE_METRIC_CHECK_CONFIG = defineFeatureFlag( "separate-metric-check-config", false, List.of("olaa"), "2022-07-04", "2022-09-01", "Determines whether one metrics config check should be written per Vespa node", "Takes effect on next tick", HOSTNAME); public static final UnboundStringFlag TLS_CAPABILITIES_ENFORCEMENT_MODE = defineStringFlag( "tls-capabilities-enforcement-mode", "disable", List.of("bjorncs", "vekterli"), "2022-07-21", "2024-01-01", "Configure Vespa TLS capability enforcement mode", "Takes effect on restart of Docker container", APPLICATION_ID,HOSTNAME,NODE_TYPE,TENANT_ID,VESPA_VERSION ); public static final UnboundBooleanFlag CLEANUP_TENANT_ROLES = defineFeatureFlag( "cleanup-tenant-roles", false, List.of("olaa"), "2022-08-10", "2022-10-01", "Determines whether old tenant roles should be deleted", "Takes effect next maintenance run" ); /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundBooleanFlag defineFeatureFlag(String flagId, boolean defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundBooleanFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundStringFlag defineStringFlag(String flagId, String defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return defineStringFlag(flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, value -> true, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundStringFlag defineStringFlag(String flagId, String defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, Predicate<String> validator, FetchVector.Dimension... dimensions) { return define((i, d, v) -> new UnboundStringFlag(i, d, v, validator), flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundIntFlag defineIntFlag(String flagId, int defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundIntFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundLongFlag defineLongFlag(String flagId, long defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundLongFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundDoubleFlag defineDoubleFlag(String flagId, double defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundDoubleFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static <T> UnboundJacksonFlag<T> defineJacksonFlag(String flagId, T defaultValue, Class<T> jacksonClass, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define((id2, defaultValue2, vector2) -> new UnboundJacksonFlag<>(id2, defaultValue2, vector2, jacksonClass), flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static <T> UnboundListFlag<T> defineListFlag(String flagId, List<T> defaultValue, Class<T> elementClass, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define((fid, dval, fvec) -> new UnboundListFlag<>(fid, dval, elementClass, fvec), flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } @FunctionalInterface private interface TypedUnboundFlagFactory<T, U extends UnboundFlag<?, ?, ?>> { U create(FlagId id, T defaultValue, FetchVector defaultFetchVector); } /** * Defines a Flag. * * @param factory Factory for creating unbound flag of type U * @param flagId The globally unique FlagId. * @param defaultValue The default value if none is present after resolution. * @param description Description of how the flag is used. * @param modificationEffect What is required for the flag to take effect? A restart of process? immediately? etc. * @param dimensions What dimensions will be set in the {@link FetchVector} when fetching * the flag value in * {@link FlagSource#fetch(FlagId, FetchVector) FlagSource::fetch}. * For instance, if APPLICATION is one of the dimensions here, you should make sure * APPLICATION is set to the ApplicationId in the fetch vector when fetching the RawFlag * from the FlagSource. * @param <T> The boxed type of the flag value, e.g. Boolean for flags guarding features. * @param <U> The type of the unbound flag, e.g. UnboundBooleanFlag. * @return An unbound flag with {@link FetchVector.Dimension#HOSTNAME HOSTNAME} and * {@link FetchVector.Dimension#VESPA_VERSION VESPA_VERSION} already set. The ZONE environment * is typically implicit. */ private static <T, U extends UnboundFlag<?, ?, ?>> U define(TypedUnboundFlagFactory<T, U> factory, String flagId, T defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension[] dimensions) { FlagId id = new FlagId(flagId); FetchVector vector = new FetchVector() .with(HOSTNAME, Defaults.getDefaults().vespaHostname()) // Warning: In unit tests and outside official Vespa releases, the currentVersion is e.g. 7.0.0 // (determined by the current major version). Consider not setting VESPA_VERSION if minor = micro = 0. .with(VESPA_VERSION, Vtag.currentVersion.toFullString()); U unboundFlag = factory.create(id, defaultValue, vector); FlagDefinition definition = new FlagDefinition( unboundFlag, owners, parseDate(createdAt), parseDate(expiresAt), description, modificationEffect, dimensions); flags.put(id, definition); return unboundFlag; } private static Instant parseDate(String rawDate) { return DateTimeFormatter.ISO_DATE.parse(rawDate, LocalDate::from).atStartOfDay().toInstant(ZoneOffset.UTC); } public static List<FlagDefinition> getAllFlags() { return List.copyOf(flags.values()); } public static Optional<FlagDefinition> getFlag(FlagId flagId) { return Optional.ofNullable(flags.get(flagId)); } /** * Allows the statically defined flags to be controlled in a test. * * <p>Returns a Replacer instance to be used with e.g. a try-with-resources block. Within the block, * the flags starts out as cleared. Flags can be defined, etc. When leaving the block, the flags from * before the block is reinserted. * * <p>NOT thread-safe. Tests using this cannot run in parallel. */ public static Replacer clearFlagsForTesting(FlagId... flagsToKeep) { return new Replacer(flagsToKeep); } public static class Replacer implements AutoCloseable { private static volatile boolean flagsCleared = false; private final TreeMap<FlagId, FlagDefinition> savedFlags; private Replacer(FlagId... flagsToKeep) { verifyAndSetFlagsCleared(true); this.savedFlags = Flags.flags; Flags.flags = new TreeMap<>(); List.of(flagsToKeep).forEach(id -> Flags.flags.put(id, savedFlags.get(id))); } @Override public void close() { verifyAndSetFlagsCleared(false); Flags.flags = savedFlags; } /** * Used to implement a simple verification that Replacer is not used by multiple threads. * For instance two different tests running in parallel cannot both use Replacer. */ private static void verifyAndSetFlagsCleared(boolean newValue) { if (flagsCleared == newValue) { throw new IllegalStateException("clearFlagsForTesting called while already cleared - running tests in parallell!?"); } flagsCleared = newValue; } } }
package tv.floe.metronome.deeplearning.neuralnetwork.core; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutput; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.math3.distribution.RealDistribution; import org.apache.commons.math3.random.MersenneTwister; import org.apache.commons.math3.random.RandomGenerator; import org.apache.mahout.math.Matrix; import org.apache.mahout.math.MatrixWritable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import tv.floe.metronome.deeplearning.math.transforms.MatrixTransform; import tv.floe.metronome.deeplearning.neuralnetwork.activation.ActivationFunction; import tv.floe.metronome.deeplearning.neuralnetwork.layer.HiddenLayer; import tv.floe.metronome.deeplearning.neuralnetwork.optimize.MultiLayerNetworkOptimizer; import tv.floe.metronome.deeplearning.neuralnetwork.serde.Persistable; import tv.floe.metronome.math.MatrixUtils; import tv.floe.metronome.types.Pair; public abstract class BaseMultiLayerNeuralNetworkVectorized implements Serializable,Persistable { private static final long serialVersionUID = 4066891298715416874L; private static Logger log = LoggerFactory.getLogger( BaseMultiLayerNeuralNetworkVectorized.class ); public int inputNeuronCount; public int outputNeuronCount; //the hidden layer sizes at each layer public int[] hiddenLayerSizes; public int numberLayers; //the hidden layers public HiddenLayer[] hiddenLayers; public LogisticRegression logisticRegressionLayer; // DA / RBM Layers public NeuralNetworkVectorized[] preTrainingLayers; public RandomGenerator randomGenerator; public RealDistribution distribution; // how was it handled with the OOP-MLPN version? public Matrix inputTrainingData = null; public Matrix outputTrainingLabels = null; public double learningRateUpdate = 0.95; public boolean useRegularization = true; public double l2 = 0.01; private double momentum = 0.1; //don't use sparsity by default private double sparsity = 0; public MultiLayerNetworkOptimizer optimizer; protected Map<Integer,MatrixTransform> weightTransforms = new HashMap<Integer,MatrixTransform>(); //hidden bias transforms; for initialization private Map<Integer,MatrixTransform> hiddenBiasTransforms = new HashMap<Integer,MatrixTransform>(); //visible bias transforms for initialization private Map<Integer,MatrixTransform> visibleBiasTransforms = new HashMap<Integer,MatrixTransform>(); /** * CTOR * */ public BaseMultiLayerNeuralNetworkVectorized() { } public BaseMultiLayerNeuralNetworkVectorized(int n_ins, int[] hidden_layer_sizes, int n_outs, int n_layers, RandomGenerator rng) { this(n_ins,hidden_layer_sizes,n_outs,n_layers,rng,null,null); } public BaseMultiLayerNeuralNetworkVectorized(int n_ins, int[] hidden_layer_sizes, int n_outs, int n_layers, RandomGenerator rng, Matrix input, Matrix labels) { this.inputNeuronCount = n_ins; this.hiddenLayerSizes = hidden_layer_sizes; this.inputTrainingData = input; this.outputTrainingLabels = labels; if(hidden_layer_sizes.length != n_layers) { throw new IllegalArgumentException("The number of hidden layer sizes must be equivalent to the nLayers argument which is a value of " + n_layers); } this.outputNeuronCount = n_outs; this.numberLayers = n_layers; this.hiddenLayers = new HiddenLayer[n_layers]; this.preTrainingLayers = createNetworkLayers( this.numberLayers ); if (rng == null) { this.randomGenerator = new MersenneTwister(123); } else { this.randomGenerator = rng; } if (input != null) { initializeLayers(input); } } /** * Base class for initializing the layers based on the input. * This is meant for capturing numbers such as input columns or other things. * * This method sets up two types of layers: * - normal ML-NN layers * - RBM / DA layers * * @param input the input matrix for training */ protected void initializeLayers(Matrix input) { Matrix layer_input = input; int input_size; System.out.println("initializeLayers // construct multi-layer for (int i = 0; i < this.numberLayers; i++) { if (i == 0) { //input_size = this.nIns; input_size = this.inputNeuronCount; // construct sigmoid_layer //this.sigmoidLayers[i] = new HiddenLayer(input_size, this.hiddenLayerSizes[i], null, null, rng,layer_input); this.hiddenLayers[ i ] = new HiddenLayer(input_size, this.hiddenLayerSizes[i], this.randomGenerator ); this.hiddenLayers[ i ].setInput( layer_input ); } else { input_size = this.hiddenLayerSizes[ i - 1 ]; //layer_input = sigmoidLayers[i - 1].sample_h_given_v(); layer_input = this.hiddenLayers[i - 1].sampleHiddenGivenLastVisible(); // construct sigmoid_layer //this.sigmoidLayers[i] = new HiddenLayer(input_size, this.hiddenLayerSizes[i], null, null, rng,layer_input); this.hiddenLayers[ i ] = new HiddenLayer(input_size, this.hiddenLayerSizes[i], this.randomGenerator); this.hiddenLayers[ i ].setInput( layer_input ); } System.out.println("Layer [" + i + "] " ); System.out.println("\tCreated Hidden Layer [" + i + "]: Neuron Count: " + this.hiddenLayerSizes[i] ); System.out.println("\tCreated RBM PreTrain Layer [" + i + "]: Num Visible: " + input_size + ", Num Hidden: " + this.hiddenLayerSizes[i] ); // construct DL appropriate class for pre training layer this.preTrainingLayers[ i ] = createPreTrainingLayer( layer_input,input_size, this.hiddenLayerSizes[i], this.hiddenLayers[i].connectionWeights, this.hiddenLayers[i].biasTerms, null, this.randomGenerator, i ); } System.out.println("Logistic Output Layer: Inputs: " + this.hiddenLayerSizes[this.numberLayers-1] + ", Output Classes: " + this.outputNeuronCount ); this.logisticRegressionLayer = new LogisticRegression(layer_input, this.hiddenLayerSizes[this.numberLayers-1], this.outputNeuronCount ); System.out.println( "Finished layer init System.out.println( "DBN Network Stats:\n" + this.generateNetworkSizeReport() ); } public synchronized Map<Integer, MatrixTransform> getHiddenBiasTransforms() { return hiddenBiasTransforms; } public synchronized Map<Integer, MatrixTransform> getVisibleBiasTransforms() { return visibleBiasTransforms; } public List<Matrix> feedForward() { if (this.inputTrainingData == null) { throw new IllegalStateException("Unable to perform feed forward; no input found"); } List<Matrix> activations = new ArrayList<Matrix>(); Matrix input = this.inputTrainingData; activations.add(input); for (int i = 0; i < this.numberLayers; i++) { HiddenLayer layer = this.hiddenLayers[ i ]; //layers[i].setInput(input); this.preTrainingLayers[i].setInput(input); input = layer.computeOutputActivation(input); activations.add(input); } activations.add( this.logisticRegressionLayer.predict(input) ); return activations; } /** * TODO: make sure our concept of an activation function can deliver functionality * * @param activations * @param deltaRet */ private void computeDeltas(List<Matrix> activations,List<Pair<Matrix,Matrix>> deltaRet) { Matrix[] gradients = new Matrix[ this.numberLayers + 2 ]; Matrix[] deltas = new Matrix[ this.numberLayers + 2 ]; ActivationFunction derivative = this.hiddenLayers[ 0 ].activationFunction; //- y - h Matrix delta = null; /* * Precompute activations and z's (pre activation network outputs) */ List<Matrix> weights = new ArrayList<Matrix>(); /* for (int j = 0; j < layers.length; j++) { weights.add(layers[j].getW()); } */ for (int j = 0; j < this.preTrainingLayers.length; j++) { weights.add( this.preTrainingLayers[j].getConnectionWeights() ); } weights.add( this.logisticRegressionLayer.connectionWeights ); List<Matrix> zs = new ArrayList<Matrix>(); zs.add( this.inputTrainingData ); for (int i = 0; i < this.preTrainingLayers.length; i++) { if (this.preTrainingLayers[i].getInput() == null && i == 0) { this.preTrainingLayers[i].setInput( this.inputTrainingData ); } else if (this.preTrainingLayers[i].getInput() == null) { this.feedForward(); } //zs.add(MatrixUtil.sigmoid(layers[i].getInput().mmul(weights.get(i)).addRowVector(layers[i].gethBias()))); //zs.add(MatrixUtils.sigmoid( this.preTrainingLayers[ i ].getInput().times( weights.get( i ) ).addRowVector( this.preTrainingLayers[i].getHiddenBias() ))); zs.add(MatrixUtils.sigmoid( MatrixUtils.addRowVector( this.preTrainingLayers[ i ].getInput().times( weights.get( i ) ), this.preTrainingLayers[i].getHiddenBias().viewRow(0) ))); } //zs.add(logLayer.input.mmul(logLayer.W).addRowVector(logLayer.b)); //zs.add( this.logisticRegressionLayer.input.times( this.logisticRegressionLayer.connectionWeights ).addRowVector( this.logisticRegressionLayer.biasTerms )); zs.add( MatrixUtils.addRowVector( this.logisticRegressionLayer.input.times( this.logisticRegressionLayer.connectionWeights ), this.logisticRegressionLayer.biasTerms.viewRow(0) ) ); //errors for (int i = this.numberLayers + 1; i >= 0; i if (i >= this.numberLayers + 1) { Matrix z = zs.get(i); //- y - h //delta = labels.sub(activations.get(i)).neg(); delta = MatrixUtils.neg( this.outputTrainingLabels.minus( activations.get( i ) ) ); //(- y - h) .* f'(z^l) where l is the output layer //Matrix initialDelta = delta.times( derivative.applyDerivative( z ) ); Matrix initialDelta = MatrixUtils.elementWiseMultiplication( delta, derivative.applyDerivative( z ) ); deltas[ i ] = initialDelta; } else { delta = deltas[ i + 1 ]; Matrix w = weights.get( i ).transpose(); Matrix z = zs.get( i ); Matrix a = activations.get( i + 1 ); //W^t * error^l + 1 Matrix error = delta.times( w ); deltas[ i ] = error; // MatrixUtils.debug_print_matrix_stats(error, "error matrix"); // MatrixUtils.debug_print_matrix_stats(z, "z matrix"); //error = error.times(derivative.applyDerivative(z)); error = MatrixUtils.elementWiseMultiplication( error, derivative.applyDerivative(z) ); deltas[ i ] = error; // gradients[ i ] = a.transpose().times(error).transpose().div( this.inputTrainingData.numRows() ); gradients[ i ] = a.transpose().times(error).transpose().divide( this.inputTrainingData.numRows() ); } } for (int i = 0; i < gradients.length; i++) { deltaRet.add(new Pair<Matrix, Matrix>(gradients[i],deltas[i])); } } /** * Backpropagation of errors for weights * @param lr the learning rate to use * @param epochs the number of epochs to iterate (this is already called in finetune) */ public void backProp(double lr,int epochs) { for (int i = 0; i < epochs; i++) { List<Matrix> activations = feedForward(); //precompute deltas List<Pair<Matrix,Matrix>> deltas = new ArrayList<Pair<Matrix, Matrix>>(); computeDeltas(activations, deltas); for (int l = 0; l < this.numberLayers; l++) { Matrix add = deltas.get( l ).getFirst().divide( this.inputTrainingData.numRows() ).times( lr ); add = add.divide( this.inputTrainingData.numRows() ); if (useRegularization) { //add = add.times( this.preTrainingLayers[ l ].getConnectionWeights().times( l2 ) ); add = MatrixUtils.elementWiseMultiplication(add, this.preTrainingLayers[ l ].getConnectionWeights().times( l2 )); } this.preTrainingLayers[ l ].setConnectionWeights( this.preTrainingLayers[ l ].getConnectionWeights().minus( add.times( lr ) ) ); this.hiddenLayers[ l ].connectionWeights = this.preTrainingLayers[l].getConnectionWeights(); Matrix deltaColumnSums = MatrixUtils.columnSums( deltas.get( l + 1 ).getSecond() ); // TODO: check this, needs to happen in place? deltaColumnSums = deltaColumnSums.divide( this.inputTrainingData.numRows() ); // TODO: check this, needs to happen in place? //this.preTrainingLayers[ l ].getHiddenBias().subi( deltaColumnSums.times( lr ) ); Matrix hbiasMinus = this.preTrainingLayers[ l ].getHiddenBias().minus( deltaColumnSums.times( lr ) ); this.preTrainingLayers[ l ].sethBias(hbiasMinus); this.hiddenLayers[ l ].biasTerms = this.preTrainingLayers[l].getHiddenBias(); } this.logisticRegressionLayer.connectionWeights = this.logisticRegressionLayer.connectionWeights.plus(deltas.get( this.numberLayers ).getFirst()); } } /** * Creates a layer depending on the index. * The main reason this matters is for continuous variations such as the {@link CDBN} * where the first layer needs to be an {@link CRBM} for continuous inputs * */ public abstract NeuralNetworkVectorized createPreTrainingLayer(Matrix input, int nVisible, int nHidden, Matrix weights, Matrix hbias, Matrix vBias, RandomGenerator rng, int index); public void finetune(double learningRate, int epochs) { finetune( this.outputTrainingLabels, learningRate, epochs ); } /** * Run SGD based on the given output vectors * * * @param labels the labels to use * @param lr the learning rate during training * @param epochs the number of times to iterate */ public void finetune(Matrix outputLabels, double learningRate, int epochs) { if (null != outputLabels) { this.outputTrainingLabels = outputLabels; } optimizer = new MultiLayerNetworkOptimizer(this,learningRate); optimizer.optimize( outputLabels, learningRate, epochs ); //optimizer.optimizeWSGD( outputLabels, learningRate, epochs ); } /** * Label the probabilities of the input * @param x the input to label * @return a vector of probabilities * given each label. * * This is typically of the form: * [0.5, 0.5] or some other probability distribution summing to one * * */ public Matrix predict(Matrix x) { Matrix input = x; for(int i = 0; i < this.numberLayers; i++) { HiddenLayer layer = this.hiddenLayers[i]; input = layer.computeOutputActivation(input); } return this.logisticRegressionLayer.predict(input); } /** * Serializes this to the output stream. * @param os the output stream to write to */ public void write(OutputStream os) { try { // ObjectOutputStream oos = new ObjectOutputStream(os); // oos.writeObject(this); // MatrixWritable.writeMatrix(arg0, arg1)this.hiddenLayers[ 0 ].biasTerms // ByteArrayOutputStream out = new ByteArrayOutputStream(); DataOutput d = new DataOutputStream(os); MatrixWritable.writeMatrix(d, inputTrainingData); // d.writeUTF(src_host); /* //d.writeInt(this.SrcWorkerPassCount); d.writeInt(this.GlobalPassCount); d.writeInt(this.IterationComplete); d.writeInt(this.CurrentIteration); d.writeInt(this.TrainedRecords); //d.writeFloat(this.AvgLogLikelihood); d.writeFloat(this.PercentCorrect); d.writeDouble(this.RMSE); */ //d.write // buf.write // MatrixWritable.writeMatrix(d, this.worker_gradient.getMatrix()); //MatrixWritable.writeMatrix(d, this.parameter_vector); // MatrixWritable. // ObjectOutputStream oos = new ObjectOutputStream(out); } catch (IOException e) { throw new RuntimeException(e); } } public void write( String filename ) throws IOException { File file = new File( filename ); if (!file.exists()) { try { file.getParentFile().mkdirs(); } catch (Exception e) { } file.createNewFile(); } FileOutputStream oFile = new FileOutputStream(filename, false); this.write(oFile); oFile.close(); } /** * Load (using {@link ObjectInputStream} * @param is the input stream to load from (usually a file) */ public void load(InputStream is) { try { ObjectInputStream ois = new ObjectInputStream(is); BaseMultiLayerNeuralNetworkVectorized loaded = (BaseMultiLayerNeuralNetworkVectorized) ois.readObject(); update(loaded); } catch (Exception e) { throw new RuntimeException(e); } } /** * Load (using {@link ObjectInputStream} * @param is the input stream to load from (usually a file) */ public static BaseMultiLayerNeuralNetworkVectorized loadFromFile(InputStream is) { try { ObjectInputStream ois = new ObjectInputStream(is); log.info("Loading network model..."); BaseMultiLayerNeuralNetworkVectorized loaded = (BaseMultiLayerNeuralNetworkVectorized) ois.readObject(); return loaded; } catch (Exception e) { throw new RuntimeException(e); } } /** * Helper method for loading the model file from disk by path name * * @param filename * @return * @throws Exception */ public static BaseMultiLayerNeuralNetworkVectorized loadFromFile(String filename ) throws Exception { BaseMultiLayerNeuralNetworkVectorized nn = null; File file = new File( filename ); if(!file.exists()) { //file.createNewFile(); throw new Exception("Model File Path does not exist!"); } //FileOutputStream oFile = new FileOutputStream(filename, false); try { DataInputStream dis = new DataInputStream( new FileInputStream( filename )); nn = BaseMultiLayerNeuralNetworkVectorized.loadFromFile( dis ); //dataOutputStream.flush(); dis.close(); } catch (IOException e) { log.error("Unable to load model",e); } return nn; } /** * Assigns the parameters of this model to the ones specified by this * network. This is used in loading from input streams, factory methods, etc * @param network the network to get parameters from */ protected void update(BaseMultiLayerNeuralNetworkVectorized network) { this.preTrainingLayers = new NeuralNetworkVectorized[ network.preTrainingLayers.length ]; for (int i = 0; i < preTrainingLayers.length; i++) { this.preTrainingLayers[i] = network.preTrainingLayers[ i ].clone(); } this.hiddenLayerSizes = network.hiddenLayerSizes; this.logisticRegressionLayer = network.logisticRegressionLayer.clone(); this.inputNeuronCount = network.inputNeuronCount; this.numberLayers = network.numberLayers; this.outputNeuronCount = network.outputNeuronCount; this.randomGenerator = network.randomGenerator; this.distribution = network.distribution; this.hiddenLayers = new HiddenLayer[network.hiddenLayers.length]; for (int i = 0; i < hiddenLayers.length; i++) { this.hiddenLayers[ i ] = network.hiddenLayers[ i ].clone(); } this.weightTransforms = network.weightTransforms; this.visibleBiasTransforms = network.visibleBiasTransforms; this.hiddenBiasTransforms = network.hiddenBiasTransforms; } public void initBasedOn(BaseMultiLayerNeuralNetworkVectorized network) { this.update(network); // now clear all connections. for (int i = 0; i < preTrainingLayers.length; i++) { this.preTrainingLayers[i].clearWeights(); } this.logisticRegressionLayer.clearWeights(); for (int i = 0; i < hiddenLayers.length; i++) { this.hiddenLayers[ i ].clearWeights(); } } /** * @return the negative log likelihood of the model */ public double negativeLogLikelihood() { return this.logisticRegressionLayer.negativeLogLikelihood(); } /** * Train the network running some unsupervised * pretraining followed by SGD/finetune * @param input the input to train on * @param labels the labels for the training examples(a matrix of the following format: * [0,1,0] where 0 represents the labels its not and 1 represents labels for the positive outcomes * @param otherParams the other parameters for child classes (algorithm specific parameters such as corruption level for SDA) */ public abstract void trainNetwork(Matrix input,Matrix labels,Object[] otherParams); /** * Creates a layer depending on the index. * The main reason this matters is for continuous variations such as the {@link CDBN} * where the first layer needs to be an {@link CRBM} for continuous inputs * @param input the input to the layer * @param nVisible the number of visible inputs * @param nHidden the number of hidden units * @param W the weight vector * @param hbias the hidden bias * @param vBias the visible bias * @param rng the rng to use (THiS IS IMPORTANT; YOU DO NOT WANT TO HAVE A MIS REFERENCED RNG OTHERWISE NUMBERS WILL BE MEANINGLESS) * @param index the index of the layer * @return a neural network layer such as {@link RBM} */ // public abstract NeuralNetwork createLayer(Matrix input,int nVisible,int nHidden, Matrix W,Matrix hbias,Matrix vBias,RandomGenerator rng,int index); public abstract NeuralNetworkVectorized[] createNetworkLayers(int numLayers); /** * Apply transforms to RBMs before we train * * * */ protected void applyTransforms() { // do we have RBMs at all if(this.preTrainingLayers == null || this.preTrainingLayers.length < 1) { throw new IllegalStateException("Layers not initialized"); } for (int i = 0; i < this.preTrainingLayers.length; i++) { if (weightTransforms.containsKey(i)) { // layers[i].setW(weightTransforms.get(i).apply(layers[i].getW())); this.preTrainingLayers[i].setConnectionWeights( weightTransforms.get(i).apply( this.preTrainingLayers[i].getConnectionWeights() ) ); } if (hiddenBiasTransforms.containsKey(i)) { preTrainingLayers[i].sethBias(getHiddenBiasTransforms().get(i).apply(preTrainingLayers[i].getHiddenBias())); } if (this.visibleBiasTransforms.containsKey(i)) { preTrainingLayers[i].setVisibleBias(getVisibleBiasTransforms().get(i).apply(preTrainingLayers[i].getVisibleBias())); } } } public synchronized double getMomentum() { return momentum; } public synchronized void setMomentum(double momentum) { this.momentum = momentum; } public synchronized Map<Integer, MatrixTransform> getWeightTransforms() { return weightTransforms; } public synchronized void setWeightTransforms( Map<Integer, MatrixTransform> weightTransforms) { this.weightTransforms = weightTransforms; } public synchronized void addWeightTransform( int layer,MatrixTransform transform) { this.weightTransforms.put(layer,transform); } public synchronized double getSparsity() { return sparsity; } public synchronized void setSparsity(double sparsity) { this.sparsity = sparsity; } public String generateNetworkSizeReport() { String out = ""; long hiddenLayerConnectionCount = 0; long preTrainLayerConnectionCount = 0; for ( int x = 0; x < this.numberLayers; x++ ) { hiddenLayerConnectionCount += MatrixUtils.length( this.hiddenLayers[ x ].connectionWeights ); } for ( int x = 0; x < this.numberLayers; x++ ) { preTrainLayerConnectionCount += MatrixUtils.length( this.preTrainingLayers[ x ].getConnectionWeights() ); } out += "Number of Hidden / RBM Layers: " + this.numberLayers + "\n"; out += "Total Hidden Layer Connection Count: " + hiddenLayerConnectionCount + "\n"; out += "Total PreTrain (RBM) Layer Connection Count: " + preTrainLayerConnectionCount + "\n"; return out; } /** * Merges this network with the other one. * This is a weight averaging with the update of: * a += b - a / n * where a is a matrix on the network * b is the incoming matrix and n * is the batch size. * This update is performed across the network layers * as well as hidden layers and logistic layers * * @param network the network to merge with * @param batchSize the batch size (number of training examples) * to average by */ public void merge(BaseMultiLayerNeuralNetworkVectorized network, int batchSize) { if (network.numberLayers != this.numberLayers) { throw new IllegalArgumentException("Unable to merge networks that are not of equal length"); } for (int i = 0; i < this.numberLayers; i++) { // pretrain layers NeuralNetworkVectorized n = this.preTrainingLayers[i]; NeuralNetworkVectorized otherNetwork = network.preTrainingLayers[i]; n.merge(otherNetwork, batchSize); //tied weights: must be updated at the same time //getSigmoidLayers()[i].setB(n.gethBias()); this.hiddenLayers[i].biasTerms = n.getHiddenBias(); //getSigmoidLayers()[i].setW(n.getW()); this.hiddenLayers[i].connectionWeights = n.getConnectionWeights(); } //getLogLayer().merge(network.logLayer, batchSize); this.logisticRegressionLayer.merge(network.logisticRegressionLayer, batchSize); } }
package tv.floe.metronome.deeplearning.neuralnetwork.core; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutput; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.math3.distribution.RealDistribution; import org.apache.commons.math3.random.MersenneTwister; import org.apache.commons.math3.random.RandomGenerator; import org.apache.mahout.math.Matrix; import org.apache.mahout.math.MatrixWritable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import tv.floe.metronome.classification.neuralnetworks.core.NeuralNetwork; import tv.floe.metronome.deeplearning.math.transforms.MatrixTransform; import tv.floe.metronome.deeplearning.neuralnetwork.activation.ActivationFunction; import tv.floe.metronome.deeplearning.neuralnetwork.gradient.LogisticRegressionGradient; import tv.floe.metronome.deeplearning.neuralnetwork.gradient.MultiLayerGradient; import tv.floe.metronome.deeplearning.neuralnetwork.gradient.NeuralNetworkGradient; import tv.floe.metronome.deeplearning.neuralnetwork.layer.HiddenLayer; import tv.floe.metronome.deeplearning.neuralnetwork.optimize.MultiLayerNetworkOptimizer; import tv.floe.metronome.deeplearning.neuralnetwork.serde.Persistable; import tv.floe.metronome.math.MatrixUtils; import tv.floe.metronome.types.Pair; public abstract class BaseMultiLayerNeuralNetworkVectorized implements Serializable,Persistable { private static final long serialVersionUID = 4066891298715416874L; private static Logger log = LoggerFactory.getLogger( BaseMultiLayerNeuralNetworkVectorized.class ); public int inputNeuronCount; public int outputNeuronCount; //the hidden layer sizes at each layer public int[] hiddenLayerSizes; public int numberLayers; //the hidden layers public HiddenLayer[] hiddenLayers; public LogisticRegression logisticRegressionLayer; // DA / RBM Layers public NeuralNetworkVectorized[] preTrainingLayers; public RandomGenerator randomGenerator; public RealDistribution distribution; // how was it handled with the OOP-MLPN version? public Matrix inputTrainingData = null; public Matrix outputTrainingLabels = null; public double learningRateUpdate = 0.95; public boolean useRegularization = true; public double l2 = 0.01; private double momentum = 0.1; //don't use sparsity by default private double sparsity = 0; //optional: used in normalizing input. This is used in saving the model for prediction purposes in normalizing incoming data private Matrix columnSums = null; //subtract input by column means for zero mean private Matrix columnMeans = null; //divide by the std deviation private Matrix columnStds = null; private boolean initCalled = false; public MultiLayerNetworkOptimizer optimizer; protected Map<Integer,MatrixTransform> weightTransforms = new HashMap<Integer,MatrixTransform>(); //hidden bias transforms; for initialization private Map<Integer,MatrixTransform> hiddenBiasTransforms = new HashMap<Integer,MatrixTransform>(); //visible bias transforms for initialization private Map<Integer,MatrixTransform> visibleBiasTransforms = new HashMap<Integer,MatrixTransform>(); private boolean useAdaGrad = false; /** * CTOR * */ public BaseMultiLayerNeuralNetworkVectorized() { } public BaseMultiLayerNeuralNetworkVectorized(int n_ins, int[] hidden_layer_sizes, int n_outs, int n_layers, RandomGenerator rng) { this(n_ins,hidden_layer_sizes,n_outs,n_layers,rng,null,null); } public BaseMultiLayerNeuralNetworkVectorized(int n_ins, int[] hidden_layer_sizes, int n_outs, int n_layers, RandomGenerator rng, Matrix input, Matrix labels) { this.inputNeuronCount = n_ins; this.hiddenLayerSizes = hidden_layer_sizes; this.inputTrainingData = input; this.outputTrainingLabels = labels; if(hidden_layer_sizes.length != n_layers) { throw new IllegalArgumentException("The number of hidden layer sizes must be equivalent to the nLayers argument which is a value of " + n_layers); } this.outputNeuronCount = n_outs; this.numberLayers = n_layers; this.hiddenLayers = new HiddenLayer[n_layers]; this.preTrainingLayers = createNetworkLayers( this.numberLayers ); if (rng == null) { this.randomGenerator = new MersenneTwister(123); } else { this.randomGenerator = rng; } if (input != null) { initializeLayers(input); } } /** * Base class for initializing the layers based on the input. * This is meant for capturing numbers such as input columns or other things. * * This method sets up two types of layers: * - normal ML-NN layers * - RBM / DA layers * * @param input the input matrix for training */ protected void initializeLayers(Matrix input) { Matrix layer_input = input; int input_size; // construct multi-layer for (int i = 0; i < this.numberLayers; i++) { if (i == 0) { //input_size = this.nIns; input_size = this.inputNeuronCount; // construct sigmoid_layer //this.sigmoidLayers[i] = new HiddenLayer(input_size, this.hiddenLayerSizes[i], null, null, rng,layer_input); this.hiddenLayers[ i ] = new HiddenLayer(input_size, this.hiddenLayerSizes[i], this.randomGenerator ); this.hiddenLayers[ i ].setInput( layer_input ); } else { input_size = this.hiddenLayerSizes[ i - 1 ]; layer_input = this.hiddenLayers[i - 1].sampleHiddenGivenLastVisible(); // construct sigmoid_layer this.hiddenLayers[ i ] = new HiddenLayer(input_size, this.hiddenLayerSizes[i], this.randomGenerator); this.hiddenLayers[ i ].setInput( layer_input ); } // System.out.println("Layer [" + i + "] " ); // System.out.println("\tCreated Hidden Layer [" + i + "]: Neuron Count: " + this.hiddenLayerSizes[i] ); // System.out.println("\tCreated RBM PreTrain Layer [" + i + "]: Num Visible: " + input_size + ", Num Hidden: " + this.hiddenLayerSizes[i] ); // construct DL appropriate class for pre training layer this.preTrainingLayers[ i ] = createPreTrainingLayer( layer_input,input_size, this.hiddenLayerSizes[i], this.hiddenLayers[i].connectionWeights, this.hiddenLayers[i].biasTerms, null, this.randomGenerator, i ); } System.out.println("Logistic Output Layer: Inputs: " + this.hiddenLayerSizes[this.numberLayers-1] + ", Output Classes: " + this.outputNeuronCount ); this.logisticRegressionLayer = new LogisticRegression(layer_input, this.hiddenLayerSizes[this.numberLayers-1], this.outputNeuronCount ); // System.out.println( "DBN Network Stats:\n" + this.generateNetworkSizeReport() ); } public synchronized Map<Integer, MatrixTransform> getHiddenBiasTransforms() { return hiddenBiasTransforms; } public synchronized Map<Integer, MatrixTransform> getVisibleBiasTransforms() { return visibleBiasTransforms; } /** * Resets adagrad with the given learning rate. * This is used for switching from the pretrain to finetune phase. * @param lr the new master learning rate to use */ /* public void resetAdaGrad(double lr) { for (int i = 0; i < this.numberLayers; i++) { //layers[i].resetAdaGrad(lr); //this.preTrainingLayers } //logLayer.resetAdaGrad(lr); } */ /** * Returns the -fanIn to fanIn * coefficient used for initializing the * weights. * The default is 1 / nIns * @return the fan in coefficient */ /* public double fanIn() { if(this.in < 0) return 1.0 / nIns; return fanIn; } */ public double getReconstructionCrossEntropy() { double sum = 0; for(int i = 0; i < this.numberLayers; i++) { sum += this.preTrainingLayers[i].getReConstructionCrossEntropy(); } sum /= (double) this.numberLayers; return sum; } /** * Compute Activations * - TODO: considering adding a param to take on inputs * * @return */ public List<Matrix> feedForward() { if (this.inputTrainingData == null) { throw new IllegalStateException("Unable to perform feed forward; no input found"); } List<Matrix> activations = new ArrayList<Matrix>(); Matrix input = this.inputTrainingData; activations.add(input); for (int i = 0; i < this.numberLayers; i++) { HiddenLayer layer = this.hiddenLayers[ i ]; //layers[i].setInput(input); this.preTrainingLayers[i].setInput(input); input = layer.computeOutputActivation(input); activations.add(input); } activations.add( this.logisticRegressionLayer.predict(input) ); return activations; } /** * TODO: make sure our concept of an activation function can deliver functionality * * @param activations * @param deltaRet */ private void computeDeltas(List<Pair<Matrix,Matrix>> deltaRet) { Matrix[] gradients = new Matrix[ this.numberLayers + 2 ]; Matrix[] deltas = new Matrix[ this.numberLayers + 2 ]; ActivationFunction derivative = this.hiddenLayers[ 0 ].activationFunction; //- y - h Matrix delta = null; List<Matrix> activations = this.feedForward(); /* * Precompute activations and z's (pre activation network outputs) */ List<Matrix> weights = new ArrayList<Matrix>(); for (int j = 0; j < this.preTrainingLayers.length; j++) { weights.add( this.preTrainingLayers[j].getConnectionWeights() ); } weights.add( this.logisticRegressionLayer.connectionWeights ); /* List<Matrix> zs = new ArrayList<Matrix>(); zs.add( this.inputTrainingData ); for (int i = 0; i < this.preTrainingLayers.length; i++) { if (this.preTrainingLayers[i].getInput() == null && i == 0) { this.preTrainingLayers[i].setInput( this.inputTrainingData ); } else if (this.preTrainingLayers[i].getInput() == null) { this.feedForward(); } zs.add(MatrixUtils.sigmoid( MatrixUtils.addRowVector( this.preTrainingLayers[ i ].getInput().times( weights.get( i ) ), this.preTrainingLayers[i].getHiddenBias().viewRow(0) ))); } zs.add( MatrixUtils.addRowVector( this.logisticRegressionLayer.input.times( this.logisticRegressionLayer.connectionWeights ), this.logisticRegressionLayer.biasTerms.viewRow(0) ) ); */ Matrix labels = this.outputTrainingLabels; //errors for (int i = this.numberLayers + 1; i >= 0; i // output layer if (i >= this.numberLayers + 1) { Matrix z = activations.get(i); //- y - h delta = MatrixUtils.neg( labels.minus( z ) ); //(- y - h) .* f'(z^l) where l is the output layer Matrix initialDelta = MatrixUtils.elementWiseMultiplication( delta, derivative.applyDerivative( z ) ); deltas[ i ] = initialDelta; } else { //derivative i + 1; aka gradient for bias delta = deltas[ i + 1 ]; Matrix w = weights.get( i ).transpose(); Matrix z = activations.get( i ); //zs.get( i ); Matrix a = activations.get( i ); //W^t * error^l + 1 Matrix error = delta.times( w ); deltas[ i ] = error; error = MatrixUtils.elementWiseMultiplication( error, derivative.applyDerivative(z) ); deltas[ i ] = error; //calculate gradient for layer Matrix lastLayerDelta = deltas[i + 1].transpose(); Matrix newGradient = lastLayerDelta.times(a); //gradients[ i ] = a.transpose().times(error).transpose().divide( this.inputTrainingData.numRows() ); // gradients[i] = newGradient.div(getInput().rows); gradients[ i ] = newGradient.divide( this.inputTrainingData.numRows() ); } } for (int i = 0; i < gradients.length; i++) { deltaRet.add(new Pair<Matrix, Matrix>(gradients[i],deltas[i])); } } /** * Backpropagation of errors for weights * @param lr the learning rate to use * @param epochs the number of epochs to iterate (this is already called in finetune) */ public void backProp(double lr,int epochs) { for (int i = 0; i < epochs; i++) { List<Matrix> activations = feedForward(); //precompute deltas List<Pair<Matrix,Matrix>> deltas = new ArrayList<Pair<Matrix, Matrix>>(); computeDeltas(activations, deltas); for (int l = 0; l < this.numberLayers; l++) { Matrix add = deltas.get( l ).getFirst().divide( this.inputTrainingData.numRows() ).times( lr ); add = add.divide( this.inputTrainingData.numRows() ); if (useRegularization) { //add = add.times( this.preTrainingLayers[ l ].getConnectionWeights().times( l2 ) ); add = MatrixUtils.elementWiseMultiplication(add, this.preTrainingLayers[ l ].getConnectionWeights().times( l2 )); } this.preTrainingLayers[ l ].setConnectionWeights( this.preTrainingLayers[ l ].getConnectionWeights().minus( add.times( lr ) ) ); this.hiddenLayers[ l ].connectionWeights = this.preTrainingLayers[l].getConnectionWeights(); Matrix deltaColumnSums = MatrixUtils.columnSums( deltas.get( l + 1 ).getSecond() ); // TODO: check this, needs to happen in place? deltaColumnSums = deltaColumnSums.divide( this.inputTrainingData.numRows() ); // TODO: check this, needs to happen in place? //this.preTrainingLayers[ l ].getHiddenBias().subi( deltaColumnSums.times( lr ) ); Matrix hbiasMinus = this.preTrainingLayers[ l ].getHiddenBias().minus( deltaColumnSums.times( lr ) ); this.preTrainingLayers[ l ].sethBias(hbiasMinus); this.hiddenLayers[ l ].biasTerms = this.preTrainingLayers[l].getHiddenBias(); } this.logisticRegressionLayer.connectionWeights = this.logisticRegressionLayer.connectionWeights.plus(deltas.get( this.numberLayers ).getFirst()); } } /** * Do a back prop iteration. * This involves computing the activations, tracking the last layers weights * to revert to in case of convergence, the learning rate being used to train * and the current epoch * @param lastEntropy the last error to be had on the previous epoch * @param revert the best network so far * @param lr the learning rate to use for training * @param epoch the epoch to use * @return whether the training should converge or not */ protected void backPropStep(BaseMultiLayerNeuralNetworkVectorized revert, double lr, int epoch) { //feedforward to compute activations //initial error //precompute deltas List<Pair<Matrix,Matrix>> deltas = new ArrayList<Pair<Matrix,Matrix>>(); //compute derivatives and gradients given activations computeDeltas(deltas); for (int l = 0; l < this.numberLayers; l++) { Matrix add = deltas.get(l).getFirst().divide( this.inputTrainingData.numRows() ); //get the gradient if (this.useAdaGrad ) { add = add.times( this.preTrainingLayers[ l ].getAdaGrad().getLearningRates(add) ); } else { //add.muli(lr); add = add.times( lr ); } //add.divi(input.rows); MatrixUtils.divi( add , this.inputTrainingData.numRows() ); if (this.useRegularization) { // add.muli(this.getLayers()[l].getW().mul(l2)); add = add.times( this.preTrainingLayers[ l ].getConnectionWeights().times( l2 ) ); } // this.getLayers()[l].getW().addi(add); MatrixUtils.addi( this.preTrainingLayers[ l ].getConnectionWeights(), add ); // this.getSigmoidLayers()[l].setW(layers[l].getW()); this.hiddenLayers[ l ].setWeights( this.preTrainingLayers[ l ].getConnectionWeights() ); // DoubleMatrix deltaColumnSums = deltas.get(l + 1).getSecond().columnSums(); Matrix deltaColumnSums = MatrixUtils.columnSums( deltas.get( l + 1 ).getSecond() ); // deltaColumnSums.divi(input.rows); MatrixUtils.divi( deltaColumnSums, this.inputTrainingData.numRows() ); // getLayers()[l].gethBias().addi(deltaColumnSums.mul(lr)); MatrixUtils.addi( this.preTrainingLayers[ l ].getHiddenBias(), deltaColumnSums.times( lr ) ); // getSigmoidLayers()[l].setB(getLayers()[l].gethBias()); this.hiddenLayers[ l ].biasTerms = this.preTrainingLayers[ l ].getHiddenBias(); } // getLogLayer().getW().addi(deltas.get(nLayers).getFirst()); MatrixUtils.addi( this.logisticRegressionLayer.connectionWeights, deltas.get( numberLayers ).getFirst() ); } /** * Gets the multi layer gradient for this network. * This includes calculating the gradients for each layer * @param params the params to pass (k, corruption level,...) * @param lr the learning rate to use for logistic regression * @return the multi layer gradient for the whole network */ public MultiLayerGradient getGradient(Object[] params) { List<NeuralNetworkGradient> gradient = new ArrayList<NeuralNetworkGradient>(); for (NeuralNetworkVectorized network : this.preTrainingLayers) { gradient.add( network.getGradient(params) ); } double lr = 0.01; if (params.length >= 2) { lr = (Double) params[1]; } this.feedForward(); LogisticRegressionGradient g2 = this.logisticRegressionLayer.getGradient(lr); MultiLayerGradient ret = new MultiLayerGradient(gradient,g2); /* if(multiLayerGradientListeners != null && !multiLayerGradientListeners.isEmpty()) { for(MultiLayerGradientListener listener : multiLayerGradientListeners) { listener.onMultiLayerGradient(ret); } } */ return ret; } /** * Creates a layer depending on the index. * The main reason this matters is for continuous variations such as the {@link CDBN} * where the first layer needs to be an {@link CRBM} for continuous inputs * */ public abstract NeuralNetworkVectorized createPreTrainingLayer(Matrix input, int nVisible, int nHidden, Matrix weights, Matrix hbias, Matrix vBias, RandomGenerator rng, int index); public void finetune(double learningRate, int epochs) { finetune( this.outputTrainingLabels, learningRate, epochs ); } /** * Run SGD based on the given output vectors * * * @param labels the labels to use * @param lr the learning rate during training * @param epochs the number of times to iterate */ public void finetune(Matrix outputLabels, double learningRate, int epochs) { if (null != outputLabels) { this.outputTrainingLabels = outputLabels; } optimizer = new MultiLayerNetworkOptimizer(this,learningRate); optimizer.optimize( outputLabels, learningRate, epochs ); //optimizer.optimizeWSGD( outputLabels, learningRate, epochs ); } /** * Label the probabilities of the input * @param x the input to label * @return a vector of probabilities * given each label. * * This is typically of the form: * [0.5, 0.5] or some other probability distribution summing to one * * */ public Matrix predict(Matrix x) { Matrix input = x; for(int i = 0; i < this.numberLayers; i++) { HiddenLayer layer = this.hiddenLayers[i]; input = layer.computeOutputActivation(input); } return this.logisticRegressionLayer.predict(input); } /** * Serializes this to the output stream. * @param os the output stream to write to */ public void write(OutputStream os) { try { // ObjectOutputStream oos = new ObjectOutputStream(os); // oos.writeObject(this); // MatrixWritable.writeMatrix(arg0, arg1)this.hiddenLayers[ 0 ].biasTerms // ByteArrayOutputStream out = new ByteArrayOutputStream(); DataOutput d = new DataOutputStream(os); MatrixWritable.writeMatrix(d, inputTrainingData); // d.writeUTF(src_host); /* //d.writeInt(this.SrcWorkerPassCount); d.writeInt(this.GlobalPassCount); d.writeInt(this.IterationComplete); d.writeInt(this.CurrentIteration); d.writeInt(this.TrainedRecords); //d.writeFloat(this.AvgLogLikelihood); d.writeFloat(this.PercentCorrect); d.writeDouble(this.RMSE); */ //d.write // buf.write // MatrixWritable.writeMatrix(d, this.worker_gradient.getMatrix()); //MatrixWritable.writeMatrix(d, this.parameter_vector); // MatrixWritable. // ObjectOutputStream oos = new ObjectOutputStream(out); } catch (IOException e) { throw new RuntimeException(e); } } public void write( String filename ) throws IOException { File file = new File( filename ); if (!file.exists()) { try { file.getParentFile().mkdirs(); } catch (Exception e) { } file.createNewFile(); } FileOutputStream oFile = new FileOutputStream(filename, false); this.write(oFile); oFile.close(); } /** * Load (using {@link ObjectInputStream} * @param is the input stream to load from (usually a file) */ public void load(InputStream is) { try { ObjectInputStream ois = new ObjectInputStream(is); BaseMultiLayerNeuralNetworkVectorized loaded = (BaseMultiLayerNeuralNetworkVectorized) ois.readObject(); update(loaded); } catch (Exception e) { throw new RuntimeException(e); } } /** * Load (using {@link ObjectInputStream} * @param is the input stream to load from (usually a file) */ public static BaseMultiLayerNeuralNetworkVectorized loadFromFile(InputStream is) { try { ObjectInputStream ois = new ObjectInputStream(is); log.info("Loading network model..."); BaseMultiLayerNeuralNetworkVectorized loaded = (BaseMultiLayerNeuralNetworkVectorized) ois.readObject(); return loaded; } catch (Exception e) { throw new RuntimeException(e); } } /** * Helper method for loading the model file from disk by path name * * @param filename * @return * @throws Exception */ public static BaseMultiLayerNeuralNetworkVectorized loadFromFile(String filename ) throws Exception { BaseMultiLayerNeuralNetworkVectorized nn = null; File file = new File( filename ); if(!file.exists()) { //file.createNewFile(); throw new Exception("Model File Path does not exist!"); } //FileOutputStream oFile = new FileOutputStream(filename, false); try { DataInputStream dis = new DataInputStream( new FileInputStream( filename )); nn = BaseMultiLayerNeuralNetworkVectorized.loadFromFile( dis ); //dataOutputStream.flush(); dis.close(); } catch (IOException e) { log.error("Unable to load model",e); } return nn; } /** * Assigns the parameters of this model to the ones specified by this * network. This is used in loading from input streams, factory methods, etc * @param network the network to get parameters from */ protected void update(BaseMultiLayerNeuralNetworkVectorized network) { this.preTrainingLayers = new NeuralNetworkVectorized[ network.preTrainingLayers.length ]; for (int i = 0; i < preTrainingLayers.length; i++) { this.preTrainingLayers[i] = network.preTrainingLayers[ i ].clone(); } this.hiddenLayerSizes = network.hiddenLayerSizes; this.logisticRegressionLayer = network.logisticRegressionLayer.clone(); this.inputNeuronCount = network.inputNeuronCount; this.numberLayers = network.numberLayers; this.outputNeuronCount = network.outputNeuronCount; this.randomGenerator = network.randomGenerator; this.distribution = network.distribution; this.hiddenLayers = new HiddenLayer[network.hiddenLayers.length]; for (int i = 0; i < hiddenLayers.length; i++) { this.hiddenLayers[ i ] = network.hiddenLayers[ i ].clone(); } this.weightTransforms = network.weightTransforms; this.visibleBiasTransforms = network.visibleBiasTransforms; this.hiddenBiasTransforms = network.hiddenBiasTransforms; } public void initBasedOn(BaseMultiLayerNeuralNetworkVectorized network) { this.update(network); // now clear all connections. for (int i = 0; i < preTrainingLayers.length; i++) { this.preTrainingLayers[i].clearWeights(); } this.logisticRegressionLayer.clearWeights(); for (int i = 0; i < hiddenLayers.length; i++) { this.hiddenLayers[ i ].clearWeights(); } } /** * @return the negative log likelihood of the model */ public double negativeLogLikelihood() { return this.logisticRegressionLayer.negativeLogLikelihood(); } /** * Train the network running some unsupervised * pretraining followed by SGD/finetune * @param input the input to train on * @param labels the labels for the training examples(a matrix of the following format: * [0,1,0] where 0 represents the labels its not and 1 represents labels for the positive outcomes * @param otherParams the other parameters for child classes (algorithm specific parameters such as corruption level for SDA) */ public abstract void trainNetwork(Matrix input,Matrix labels,Object[] otherParams); /** * Creates a layer depending on the index. * The main reason this matters is for continuous variations such as the {@link CDBN} * where the first layer needs to be an {@link CRBM} for continuous inputs * @param input the input to the layer * @param nVisible the number of visible inputs * @param nHidden the number of hidden units * @param W the weight vector * @param hbias the hidden bias * @param vBias the visible bias * @param rng the rng to use (THiS IS IMPORTANT; YOU DO NOT WANT TO HAVE A MIS REFERENCED RNG OTHERWISE NUMBERS WILL BE MEANINGLESS) * @param index the index of the layer * @return a neural network layer such as {@link RBM} */ // public abstract NeuralNetwork createLayer(Matrix input,int nVisible,int nHidden, Matrix W,Matrix hbias,Matrix vBias,RandomGenerator rng,int index); public abstract NeuralNetworkVectorized[] createNetworkLayers(int numLayers); /** * Apply transforms to RBMs before we train * * * */ protected void applyTransforms() { // do we have RBMs at all if(this.preTrainingLayers == null || this.preTrainingLayers.length < 1) { throw new IllegalStateException("Layers not initialized"); } for (int i = 0; i < this.preTrainingLayers.length; i++) { if (weightTransforms.containsKey(i)) { // layers[i].setW(weightTransforms.get(i).apply(layers[i].getW())); this.preTrainingLayers[i].setConnectionWeights( weightTransforms.get(i).apply( this.preTrainingLayers[i].getConnectionWeights() ) ); } if (hiddenBiasTransforms.containsKey(i)) { preTrainingLayers[i].sethBias(getHiddenBiasTransforms().get(i).apply(preTrainingLayers[i].getHiddenBias())); } if (this.visibleBiasTransforms.containsKey(i)) { preTrainingLayers[i].setVisibleBias(getVisibleBiasTransforms().get(i).apply(preTrainingLayers[i].getVisibleBias())); } } } public synchronized double getMomentum() { return momentum; } public synchronized void setMomentum(double momentum) { this.momentum = momentum; } public synchronized Map<Integer, MatrixTransform> getWeightTransforms() { return weightTransforms; } public synchronized void setWeightTransforms( Map<Integer, MatrixTransform> weightTransforms) { this.weightTransforms = weightTransforms; } public synchronized void addWeightTransform( int layer,MatrixTransform transform) { this.weightTransforms.put(layer,transform); } public synchronized double getSparsity() { return sparsity; } public synchronized void setSparsity(double sparsity) { this.sparsity = sparsity; } public String generateNetworkSizeReport() { String out = ""; long hiddenLayerConnectionCount = 0; long preTrainLayerConnectionCount = 0; for ( int x = 0; x < this.numberLayers; x++ ) { hiddenLayerConnectionCount += MatrixUtils.length( this.hiddenLayers[ x ].connectionWeights ); } for ( int x = 0; x < this.numberLayers; x++ ) { preTrainLayerConnectionCount += MatrixUtils.length( this.preTrainingLayers[ x ].getConnectionWeights() ); } out += "Number of Hidden / RBM Layers: " + this.numberLayers + "\n"; out += "Total Hidden Layer Connection Count: " + hiddenLayerConnectionCount + "\n"; out += "Total PreTrain (RBM) Layer Connection Count: " + preTrainLayerConnectionCount + "\n"; return out; } public String generateNetworkStateReport() { String out = ""; out += "Number of Hidden / RBM Layers: " + this.numberLayers + "\n"; out += "inputNeuronCount: " + this.inputNeuronCount + "\n"; out += "l2: " + this.l2 + "\n"; out += "learningRateUpdate: " + this.learningRateUpdate + "\n"; out += "momentum: " + this.momentum + "\n"; out += "outputNeuronCount: " + this.outputNeuronCount + "\n"; out += "sparsity: " + this.sparsity + "\n"; out += "this.hiddenLayers.length: " + this.hiddenLayers.length + "\n"; out += "this.logisticRegressionLayer.l2: " + this.logisticRegressionLayer.l2 + "\n"; out += "this.logisticRegressionLayer.nIn: " + this.logisticRegressionLayer.nIn + "\n"; out += "this.logisticRegressionLayer.nOut: " + this.logisticRegressionLayer.nOut + "\n"; out += "this.logisticRegressionLayer.useRegularization: " + this.logisticRegressionLayer.useRegularization + "\n"; out += "this.useRegularization: " + this.useRegularization + "\n"; //out += "this.useRegularization: " + this. + "\n"; return out; } /** * Merges this network with the other one. * This is a weight averaging with the update of: * a += b - a / n * where a is a matrix on the network * b is the incoming matrix and n * is the batch size. * This update is performed across the network layers * as well as hidden layers and logistic layers * * @param network the network to merge with * @param batchSize the batch size (number of training examples) * to average by */ public void merge(BaseMultiLayerNeuralNetworkVectorized network, int batchSize) { if (network.numberLayers != this.numberLayers) { throw new IllegalArgumentException("Unable to merge networks that are not of equal length"); } for (int i = 0; i < this.numberLayers; i++) { // pretrain layers NeuralNetworkVectorized n = this.preTrainingLayers[i]; NeuralNetworkVectorized otherNetwork = network.preTrainingLayers[i]; n.merge(otherNetwork, batchSize); //tied weights: must be updated at the same time //getSigmoidLayers()[i].setB(n.gethBias()); this.hiddenLayers[i].biasTerms = n.getHiddenBias(); //getSigmoidLayers()[i].setW(n.getW()); this.hiddenLayers[i].connectionWeights = n.getConnectionWeights(); } //getLogLayer().merge(network.logLayer, batchSize); this.logisticRegressionLayer.merge(network.logisticRegressionLayer, batchSize); } }
package org.helioviewer.jhv.plugins.swek.sources.hek; public enum HEKEventEnum { ACTIVE_REGION("ActiveRegion", "Active Region", "AR"), CORONAL_MASS_EJECTION("CME", "Coronal Mass Ejection", "CE"), CORONAL_DIMMING( "CoronalDimming", "Coronal Dimming", "CD"), CORONAL_HOLE("CoronalHole", "Coronal Hole", "CH"), CORONAL_WAVE("CoronalWave", "Coronal Wave", "CW"), FILAMENT("Filament", "Filament", "FI"), FILAMENT_ERUPTION("FilamentEruption", "Filament Eruption", "FE"), FLARE( "Flare", "Flare", "FL"), SUNSPOT("Sunspot", "Sunspot", "SS"), EMERGING_FLUX("EmergingFlux", "Emerging Flux", "EF"), ERUPTION( "Eruption", "Eruption", "ER"), UNKNOWN("Unknown", "Unknown", "UK"); /** The abbreviation of the HEKEvent */ private final String eventAbbreviation; /** The name of the SWEK Event */ private final String swekEventName; /** The HEK event name */ private final String hekEventName; /** * Private constructor of the HEKEvent enumeration. * * * @param hekEventName * The hek name of the hek event * @param swekEventName * The swek name of the event * @param eventAbbreviation * The hek abbreviation of the hek event */ private HEKEventEnum(String hekEventName, String swekEventName, String eventAbbreviation) { this.eventAbbreviation = eventAbbreviation; this.swekEventName = swekEventName; this.hekEventName = hekEventName; } /** * Gets the abbreviation of the HEK event type * * @return the abbreviation */ public String getAbbriviation() { return eventAbbreviation; } /** * Gets the event name of the SWEK event name. * * @return the SWEK event name */ public String getSWEKEventName() { return swekEventName; } /** * Gets the HEK event name. * * @return the HEK event name */ public String getHEKEventName() { return hekEventName; } }
package edu.jhu.thrax.hadoop.features; import org.apache.hadoop.io.WritableComparator; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Partitioner; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.filecache.DistributedCache; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.SequenceFile; import edu.jhu.thrax.hadoop.datatypes.TextPair; import edu.jhu.thrax.hadoop.datatypes.RuleWritable; import java.util.HashMap; import java.util.Scanner; import java.io.File; import java.io.IOException; public class LexicalProbabilityFeature extends MapReduceFeature { public LexicalProbabilityFeature() { super("lexprob"); } public Class<? extends Mapper> mapperClass() { return Mapper.class; } public Class<? extends WritableComparator> sortComparatorClass() { return RuleWritable.YieldComparator.class; } public Class<? extends Partitioner<RuleWritable, IntWritable>> partitionerClass() { return RuleWritable.YieldPartitioner.class; } public Class<? extends Reducer<RuleWritable, IntWritable, RuleWritable, IntWritable>> reducerClass() { return Reduce.class; } private static class Reduce extends Reducer<RuleWritable, IntWritable, RuleWritable, IntWritable> { private HashMap<TextPair,Double> f2e; private HashMap<TextPair,Double> e2f; private HashMap<RuleWritable,IntWritable> ruleCounts; private RuleWritable current; private double maxf2e; private double maxe2f; private static final double DEFAULT_PROB = 10e-7; private static final Text SGT_LABEL = new Text("LexprobSourceGivenTarget"); private static final Text TGS_LABEL = new Text("LexprobTargetGivenSource"); protected void setup(Context context) throws IOException, InterruptedException { current = new RuleWritable(); ruleCounts = new HashMap<RuleWritable,IntWritable>(); Configuration conf = context.getConfiguration(); // Path [] localFiles = DistributedCache.getLocalCacheFiles(conf); // if (localFiles != null) { // we are in distributed mode // f2e = readTable("lexprobs.f2e"); // e2f = readTable("lexprobs.e2f"); // else { // in local mode; distributed cache does not work // String localWorkDir = conf.getRaw("thrax_work"); // if (!localWorkDir.endsWith(Path.SEPARATOR)) // localWorkDir += Path.SEPARATOR; // f2e = readTable(localWorkDir + "lexprobs.f2e"); // e2f = readTable(localWorkDir + "lexprobs.e2f"); String workDir = conf.getRaw("thrax.work-dir"); String e2fpath = workDir + "lexprobse2f/part-*"; String f2epath = workDir + "lexprobsf2e/part-*"; FileStatus [] e2ffiles = FileSystem.get(conf).globStatus(new Path(e2fpath)); if (e2ffiles.length == 0) throw new IOException("no files found in e2f word level lexprob glob: " + e2fpath); FileStatus [] f2efiles = FileSystem.get(conf).globStatus(new Path(f2epath)); if (e2ffiles.length == 0) throw new IOException("no files found in f2e word level lexprob glob: " + f2epath); e2f = readWordLexprobTable(e2ffiles, conf); f2e = readWordLexprobTable(f2efiles, conf); } protected void reduce(RuleWritable key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { if (current == null || !key.sameYield(current)) { current.set(key); DoubleWritable tgsWritable = new DoubleWritable(-maxf2e); DoubleWritable sgtWritable = new DoubleWritable(-maxe2f); for (RuleWritable r : ruleCounts.keySet()) { IntWritable cnt = ruleCounts.get(r); r.featureLabel.set(TGS_LABEL); r.featureScore.set(-maxf2e); context.write(r, cnt); RuleWritable r2 = new RuleWritable(r); r2.featureLabel.set(SGT_LABEL); r2.featureScore.set(-maxe2f); context.write(r2, cnt); } ruleCounts.clear(); maxe2f = sourceGivenTarget(key); maxf2e = targetGivenSource(key); int count = 0; for (IntWritable x : values) count += x.get(); ruleCounts.put(new RuleWritable(key), new IntWritable(count)); return; } double sgt = sourceGivenTarget(key); double tgs = targetGivenSource(key); if (sgt > maxe2f) maxe2f = sgt; if (tgs > maxf2e) maxf2e = tgs; int count = 0; for (IntWritable x : values) count += x.get(); ruleCounts.put(new RuleWritable(key), new IntWritable(count)); } protected void cleanup(Context context) throws IOException, InterruptedException { DoubleWritable tgsWritable = new DoubleWritable(-maxf2e); DoubleWritable sgtWritable = new DoubleWritable(-maxe2f); for (RuleWritable r : ruleCounts.keySet()) { IntWritable cnt = ruleCounts.get(r); r.featureLabel.set(TGS_LABEL); r.featureScore.set(-maxf2e); context.write(r, cnt); RuleWritable r2 = new RuleWritable(r); r2.featureLabel.set(SGT_LABEL); r2.featureScore.set(-maxe2f); context.write(r2, cnt); } } private double sourceGivenTarget(RuleWritable r) { double result = 0; for (Text [] pairs : r.e2f.get()) { double len = Math.log(pairs.length - 1); result -= len; double prob = 0; Text tgt = pairs[0]; TextPair tp = new TextPair(tgt, new Text()); for (int j = 1; j < pairs.length; j++) { tp.snd.set(pairs[j]); Double currP = e2f.get(tp); if (currP == null) { System.err.println("WARNING: could not read word-level lexprob for pair ``" + tp + "''"); System.err.println(String.format("Assuming prob is %f", DEFAULT_PROB)); prob += DEFAULT_PROB; } else { prob += currP; } } result += Math.log(prob); } return result; } private double targetGivenSource(RuleWritable r) { double result = 0; for (Text [] pairs : r.f2e.get()) { double len = Math.log(pairs.length - 1); result -= len; double prob = 0; Text src = pairs[0]; TextPair tp = new TextPair(src, new Text()); for (int j = 1; j < pairs.length; j++) { tp.snd.set(pairs[j]); Double currP = f2e.get(tp); if (currP == null) { System.err.println("WARNING: could not read word-level lexprob for pair ``" + tp + "''"); System.err.println(String.format("Assuming prob is %f", DEFAULT_PROB)); prob += DEFAULT_PROB; } else { prob += currP; } } result += Math.log(prob); } return result; } private HashMap<TextPair,Double> readTable(String filename) throws IOException { HashMap<TextPair,Double> result = new HashMap<TextPair,Double>(); Scanner scanner = new Scanner(new File(filename), "UTF-8"); while (scanner.hasNextLine()) { String [] tokens = scanner.nextLine().split("\\s+"); if (tokens.length != 3) continue; TextPair tp = new TextPair(new Text(tokens[0]), new Text(tokens[1])); double score = Double.parseDouble(tokens[2]); result.put(tp, score); } return result; } private HashMap<TextPair,Double> readWordLexprobTable(FileStatus [] files, Configuration conf) throws IOException { HashMap<TextPair,Double> result = new HashMap<TextPair,Double>(); for (FileStatus stat : files) { SequenceFile.Reader reader = new SequenceFile.Reader(FileSystem.get(conf), stat.getPath(), conf); TextPair tp = new TextPair(); DoubleWritable d = new DoubleWritable(0.0); while (reader.next(tp, d)) { Text car = new Text(tp.fst); Text cdr = new Text(tp.snd); result.put(new TextPair(car, cdr), d.get()); } } return result; } } }
package ca.corefacility.bioinformatics.irida.ria.integration.pages.projects; import java.util.List; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.support.ui.WebDriverWait; /** * Represents page found at url: /projects/{projectId}/linelist */ public class ProjectLineListPage extends ProjectPageBase { private static final String RELATIVE_URL = "/projects/{projectId}/linelist"; @FindBy(css = ".dataTables_scrollHeadInner th") private List<WebElement> tableHeaders; @FindBy(css = "tbody tr") private List<WebElement> tableRows; @FindBy(id = "col-vis-btn") private WebElement metadataColVisBtn; @FindBy(css = ".metadata-open .modal-content") private WebElement metadataColVisAside; @FindBy(id = "close-aside-btn") private WebElement closeAsideBtn; @FindBy(className = "bootstrap-switch-label") private List<WebElement> colVisBtns; @FindBy(id = "template-select") private WebElement templateSelect; @FindBy(id = "save-btn") private WebElement saveBtn; @FindBy(id = "template-name") private WebElement templateNameInput; @FindBy(id = "complete-save") private WebElement completeSaveBtn; public ProjectLineListPage(WebDriver driver) { super(driver); } public static ProjectLineListPage goToPage(WebDriver driver, int projectId) { get(driver, RELATIVE_URL.replace("{projectId}", String.valueOf(projectId))); return PageFactory.initElements(driver, ProjectLineListPage.class); } public int getNumberSamplesWithMetadata() { return tableRows.size(); } public int getNumberTableColumns() { return tableHeaders.size(); } public void openColumnVisibilityPanel() { WebDriverWait wait = new WebDriverWait(driver, 10); metadataColVisBtn.click(); wait.until(ExpectedConditions.visibilityOf(metadataColVisAside)); } public void closeColumnVisibilityPanel() { closeAsideBtn.click(); waitForTime(300); // Wait for animation to end. } public void toggleColumn(String buttonLabel) { for (WebElement btn : colVisBtns) { if (btn.getText().equalsIgnoreCase(buttonLabel)) { btn.click(); break; } } } public void selectTemplate(String templateName) { Select select = new Select(templateSelect); select.selectByVisibleText(templateName); waitForTime(500); } public void saveTemplate(String templateName) { saveBtn.click(); WebDriverWait wait = new WebDriverWait(driver, 10); wait.until(ExpectedConditions.visibilityOf(templateNameInput)); templateNameInput.sendKeys(templateName); wait.until(ExpectedConditions.elementToBeClickable(completeSaveBtn)); completeSaveBtn.click(); waitForTime(500); } }