answer
stringlengths
17
10.2M
package com.palsulich.nyubustracker.activities; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.CompoundButton; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.model.PolylineOptions; import com.palsulich.nyubustracker.R; import com.palsulich.nyubustracker.adapters.StopAdapter; import com.palsulich.nyubustracker.adapters.TimeAdapter; import com.palsulich.nyubustracker.helpers.BusManager; import com.palsulich.nyubustracker.helpers.FileGrabber; import com.palsulich.nyubustracker.models.Bus; import com.palsulich.nyubustracker.models.Route; import com.palsulich.nyubustracker.models.Stop; import com.palsulich.nyubustracker.models.Time; import org.json.JSONException; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.HashMap; import java.util.Timer; import java.util.TimerTask; import se.emilsjolander.stickylistheaders.StickyListHeadersListView; public class MainActivity extends Activity{ Stop startStop; // Stop object to keep track of the start location of the desired route. Stop endStop; // Keep track of the desired end location. ArrayList<Route> routesBetweenStartAndEnd; // List of all routes between start and end. ArrayList<Time> timesBetweenStartAndEnd; // List of all times between start and end. HashMap<String, Boolean> clickableMapMarkers; // Hash of all markers which are clickable (so we don't zoom in on buses). ArrayList<Marker> busesOnMap = new ArrayList<Marker>(); Time nextBusTime; // mFileGrabber helps to manage cached files/pull new files from the network. FileGrabber mFileGrabber; Timer timeUntilTimer; // Timer used to refresh the "time until next bus" every minute, on the minute. Timer busRefreshTimer; // Timer used to refresh the bus locations every few seconds. private GoogleMap mMap; // Map to display all stops, segments, and buses. private boolean haveAMap = false; // Flag to see if the device can display a map. private void setUpMapIfNeeded() { // Do a null check to confirm that we have not already instantiated the map. if (mMap == null) { MapFragment mFrag = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)); if (mFrag != null) mMap = mFrag.getMap(); // Check if we were successful in obtaining the map. if (mMap != null) { // The Map is verified. It is now safe to manipulate the map. mMap.getUiSettings().setRotateGesturesEnabled(false); mMap.getUiSettings().setZoomControlsEnabled(false); haveAMap = true; } else haveAMap = false; } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Log.v("General Debugging", "onCreate!"); setContentView(R.layout.activity_main); mFileGrabber = new FileGrabber(getCacheDir()); renewTimeUntilTimer(); // Creates and starts the timer to refresh time until next bus. setUpMapIfNeeded(); // Instantiates mMap, if it needs to be. if (haveAMap) mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() { @Override public boolean onMarkerClick(Marker marker) { return !clickableMapMarkers.get(marker.getId()); // Return true to consume the event. } }); // List just for development use to display all //final ListView listView = (ListView) findViewById(R.id.mainActivityList); // Singleton BusManager to keep track of all stops, routes, etc. final BusManager sharedManager = BusManager.getBusManager(); // Only parse stops, routes, buses, times, and segments if we don't have them. Could be more robust. if (!sharedManager.hasStops() && !sharedManager.hasRoutes()) { try { // The Class being created from the parsing *does* the parsing. // mFileGrabber.get*JSON() returns a JSONObject. ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); Stop.parseJSON(mFileGrabber.getStopJSON(networkInfo)); Route.parseJSON(mFileGrabber.getRouteJSON(networkInfo)); BusManager.parseTimes(mFileGrabber.getVersionJSON(networkInfo), mFileGrabber, networkInfo); // Ensure we start the app with predefined favorite stops. BusManager.syncFavoriteStops(getSharedPreferences(Stop.FAVORITES_PREF, MODE_PRIVATE)); if (haveAMap) Bus.parseJSON(mFileGrabber.getVehicleJSON(networkInfo)); if (haveAMap) BusManager.parseSegments(mFileGrabber.getSegmentsJSON(networkInfo)); if (networkInfo == null || !networkInfo.isConnected()){ Context context = getApplicationContext(); CharSequence text = "Unable to connect to the network."; int duration = Toast.LENGTH_SHORT; if (context != null){ Toast toast = Toast.makeText(context, text, duration); toast.show(); } } } catch (JSONException e) { e.printStackTrace(); } } // Initialize start and end stops. By default, they are Lafayette and Broadway. setStartStop(sharedManager.getStopByName(mFileGrabber.getStartStopFile())); setEndStop(sharedManager.getStopByName(mFileGrabber.getEndStopFile())); // Update the map to show the corresponding stops, buses, and segments. if (routesBetweenStartAndEnd != null) updateMapWithNewStartOrEnd(); // Get the location of the buses every 10 sec. renewBusRefreshTimer(); } /* renewTimeUntilTimer() creates a new timer that calls setNextBusTime() every minute on the minute. */ private void renewTimeUntilTimer() { Calendar rightNow = Calendar.getInstance(); if (timeUntilTimer != null) timeUntilTimer.cancel(); timeUntilTimer = new Timer(); timeUntilTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { if(startStop != null && endStop != null) setNextBusTime(); } }); } }, (60 - rightNow.get(Calendar.SECOND)) * 1000, 60000); } private void renewBusRefreshTimer(){ if(haveAMap){ if (busRefreshTimer != null) busRefreshTimer.cancel(); busRefreshTimer = new Timer(); busRefreshTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { try{ if (routesBetweenStartAndEnd != null){ ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); if (networkInfo == null || !networkInfo.isConnected()){ Context context = getApplicationContext(); CharSequence text = "Unable to connect to the network."; int duration = Toast.LENGTH_SHORT; if (context != null){ Toast toast = Toast.makeText(context, text, duration); toast.show(); } } else{ Bus.parseJSON(mFileGrabber.getVehicleJSON(networkInfo)); updateMapWithNewBusLocations(); } } } catch (JSONException e){ e.printStackTrace(); } } }); } }, 0, 10000); } } @Override public void onDestroy() { super.onDestroy(); //Log.v("General Debugging", "onDestroy!"); cacheToAndStartStop(); // Remember user's preferences across lifetimes. timeUntilTimer.cancel(); busRefreshTimer.cancel(); } @Override public void onPause() { super.onPause(); //Log.v("General Debugging", "onPause!"); cacheToAndStartStop(); if (timeUntilTimer != null) timeUntilTimer.cancel(); if (busRefreshTimer != null) busRefreshTimer.cancel(); } @Override public void onResume() { super.onResume(); //Log.v("General Debugging", "onResume!"); setNextBusTime(); renewTimeUntilTimer(); renewBusRefreshTimer(); setUpMapIfNeeded(); } public void cacheToAndStartStop() { FileGrabber mFileGrabber = new FileGrabber(getCacheDir()); if (endStop != null) mFileGrabber.setEndStop(endStop.getName()); // Creates or updates cache file. if (startStop != null) mFileGrabber.setStartStop(startStop.getName()); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } public static Bitmap rotateBitmap(Bitmap source, float angle) { Matrix matrix = new Matrix(); matrix.postRotate(angle); return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true); } // Clear the map of all buses and put them all back on in their new locations. private void updateMapWithNewBusLocations(){ if (haveAMap){ BusManager sharedManager = BusManager.getBusManager(); for (Marker m : busesOnMap){ m.remove(); } busesOnMap = new ArrayList<Marker>(); if (clickableMapMarkers == null) clickableMapMarkers = new HashMap<String, Boolean>(); // New set of buses means new set of clickable markers! for (Route r: routesBetweenStartAndEnd){ for (Bus b : sharedManager.getBuses()){ //Log.v("BusLocations", "bus id: " + b.getID() + ", bus route: " + b.getRoute() + " vs route: " + r.getID()); if (b.getRoute().equals(r.getID())){ Marker mMarker = mMap.addMarker(new MarkerOptions() .position(b.getLocation()) .icon(BitmapDescriptorFactory .fromBitmap( rotateBitmap( BitmapFactory.decodeResource( this.getResources(), R.drawable.ic_bus_arrow), b.getHeading()) )) .anchor(0.5f, 0.5f)); clickableMapMarkers.put(mMarker.getId(), false); // Unable to click on buses. busesOnMap.add(mMarker); } } } } } // Clear the map, because we may have just changed what route we wish to display. Then, add everything back onto the map. private void updateMapWithNewStartOrEnd(){ if (haveAMap){ setUpMapIfNeeded(); mMap.clear(); clickableMapMarkers = new HashMap<String, Boolean>(); LatLngBounds.Builder builder = new LatLngBounds.Builder(); boolean validBuilder = false; for (Route r : routesBetweenStartAndEnd){ //Log.v("MapDebugging", "Updating map with route: " + r.getLongName()); for (Stop s : r.getStops()){ Marker mMarker = mMap.addMarker(new MarkerOptions() // Adds a balloon for every stop to the map. .position(s.getLocation()) .title(s.getName()) .anchor(0.5f, 0.5f) .icon(BitmapDescriptorFactory .fromBitmap( BitmapFactory.decodeResource( this.getResources(), R.drawable.ic_map_stop)))); clickableMapMarkers.put(mMarker.getId(), true); } updateMapWithNewBusLocations(); // Adds the segments of every Route to the map. for (PolylineOptions p : r.getSegments()){ //Log.v("MapDebugging", "Trying to add a segment to the map."); if (p != null){ for (LatLng loc : p.getPoints()){ validBuilder = true; builder.include(loc); } p.color(getResources().getColor(R.color.purple)); mMap.addPolyline(p); } //else Log.v("MapDebugging", "Segment was null for " + r.getID()); } } if (validBuilder){ LatLngBounds bounds = builder.build(); try{ mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 30)); } catch(IllegalStateException e) { // In case the view is not done being created. e.printStackTrace(); mMap.moveCamera( CameraUpdateFactory .newLatLngBounds( bounds, this.getResources().getDisplayMetrics().widthPixels, this.getResources().getDisplayMetrics().heightPixels, 100)); } } } } private void setEndStop(Stop stop) { if (stop != null) { // Make sure we actually have a stop! // Check there is a route between these stops. endStop = stop; ((Button) findViewById(R.id.to_button)).setText(stop.getName()); if (startStop != null){ setNextBusTime(); // Don't set the next bus if we don't have a valid route. if (routesBetweenStartAndEnd != null && haveAMap) updateMapWithNewStartOrEnd(); } } } private void setStartStop(Stop stop) { if (endStop != null && endStop == stop) { // We have an end stop and its name is the same as stopName. // Swap the start and end stops. Stop temp = startStop; startStop = endStop; ((Button) findViewById(R.id.from_button)).setText(startStop.getName()); endStop = temp; ((Button) findViewById(R.id.to_button)).setText(endStop.getName()); setNextBusTime(); updateMapWithNewStartOrEnd(); } else { //Log.v("Debugging", "setStartStop not swapping"); // We have a new start. So, we must ensure the end is actually connected. if (stop != null){ // Don't set Start to an invalid stop. Should never happen. startStop = stop; //Log.v("Debugging", "New start stop: " + startStop.getName()); ((Button) findViewById(R.id.from_button)).setText(stop.getName()); if (endStop != null){ // Loop through all connected Routes. for (Route r : startStop.getRoutes()){ // If the current endStop is connected, we don't have to change endStop. if (r.hasStop(endStop.getName())){ //Log.v("Debugging", "Found a connected end stop: " + endStop.getName() + " through " + r.getLongName()); setNextBusTime(); updateMapWithNewStartOrEnd(); return; } } ArrayList<Stop> connectedStops = startStop.getRoutes().get(0).getStops(); //Log.v("Debugging", "setStartStop picking default endStop: " + connectedStops.get(connectedStops.indexOf(startStop) + 1).getName()); // If we did not return above, the current endStop is not connected to the new // startStop. So, by default pick the first connected stop. setEndStop(connectedStops.get(connectedStops.indexOf(startStop) - 1)); } } } } private void setNextBusTime() { if (timeUntilTimer != null) timeUntilTimer.cancel(); // Don't want to be interrupted in the middle of this. if (busRefreshTimer != null) busRefreshTimer.cancel(); Calendar rightNow = Calendar.getInstance(); ArrayList<Route> fromRoutes = startStop.getRoutes(); // All the routes leaving the start stop. ArrayList<Route> routes = new ArrayList<Route>(); // All the routes connecting the two. for (Route r : fromRoutes) { if (r.hasStop(endStop.getName()) && endStop.getTimesOfRoute(r.getLongName()).size() != 0) { Log.v("Route Debugging", "Adding a route between " + startStop.getName() + " and " + endStop.getName() + ": " + r.getLongName()); routes.add(r); } } if (routes.size() > 0) { ArrayList<Time> tempTimesBetweenStartAndEnd = new ArrayList<Time>(); for (Route r : routes) { // Get the Times at this stop for this route. ArrayList<Time> times; if ((times = startStop.getTimesOfRoute(r.getLongName())) != null){ tempTimesBetweenStartAndEnd.addAll(times); } } if (tempTimesBetweenStartAndEnd.size() > 0){ // We actually found times. timesBetweenStartAndEnd = new ArrayList<Time>(tempTimesBetweenStartAndEnd); routesBetweenStartAndEnd = routes; Time currentTime = new Time(rightNow.get(Calendar.HOUR_OF_DAY), rightNow.get(Calendar.MINUTE)); Collections.sort(tempTimesBetweenStartAndEnd, Time.compare); nextBusTime = tempTimesBetweenStartAndEnd.get(tempTimesBetweenStartAndEnd.indexOf(currentTime) + 1); String timeOfNextBus = nextBusTime.toString(); String timeUntilNextBus = currentTime.getTimeAsStringUntil(nextBusTime); ((TextView) findViewById(R.id.times_button)).setText(timeOfNextBus); ((TextView) findViewById(R.id.next_bus)).setText(timeUntilNextBus); } else{ Context context = getApplicationContext(); CharSequence text = "No available times."; int duration = Toast.LENGTH_LONG; if (context != null){ Toast toast = Toast.makeText(context, text, duration); toast.show(); } } } else { if (busRefreshTimer != null) busRefreshTimer.cancel(); if (timeUntilTimer != null) timeUntilTimer.cancel(); Context context = getApplicationContext(); CharSequence text = "No routes available!"; int duration = Toast.LENGTH_LONG; if (context != null){ Toast toast = Toast.makeText(context, text, duration); toast.show(); } } renewBusRefreshTimer(); renewTimeUntilTimer(); } CompoundButton.OnCheckedChangeListener cbListener = new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { Stop s = (Stop) buttonView.getTag(); s.setFavorite(isChecked); getSharedPreferences(Stop.FAVORITES_PREF, MODE_PRIVATE) .edit().putBoolean(s.getID(), isChecked) .commit(); Log.v("Dialog", "Checkbox is " + isChecked); } }; public void createEndDialog(View view) { // Get all stops connected to the start stop. final ArrayList<Stop> connectedStops = BusManager.getBusManager().getConnectedStops(startStop); ListView listView = new ListView(this); // ListView to populate the dialog. AlertDialog.Builder builder = new AlertDialog.Builder(this); // Used to build the dialog with the list of connected Stops. builder.setView(listView); final Dialog dialog = builder.create(); // An adapter takes some data, then adapts it to fit into a view. The adapter supplies the individual view elements of // the list view. So, in this case, we supply the StopAdapter with a list of stops, and it gives us back the nice // views with a heart button to signify favorites and a TextView with the name of the stop. // We provide the onClickListeners to the adapter, which then attaches them to the respective views. StopAdapter adapter = new StopAdapter(getApplicationContext(), connectedStops, dialog, new View.OnClickListener() { @Override public void onClick(View view) { // Clicked on a Stop. So, make it the end and dismiss the dialog. Stop s = (Stop) view.getTag(); setEndStop(s); // Actually set the end stop. dialog.dismiss(); } }, cbListener); listView.setAdapter(adapter); dialog.setCanceledOnTouchOutside(true); dialog.show(); // Dismissed when a stop is clicked. } public void createStartDialog(View view) { final ArrayList<Stop> stops = BusManager.getBusManager().getStops(); // Show every stop as an option to start. ListView listView = new ListView(this); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setView(listView); final Dialog dialog = builder.create(); StopAdapter adapter = new StopAdapter(getApplicationContext(), stops, dialog, new View.OnClickListener() { @Override public void onClick(View view) { Stop s = (Stop) view.getTag(); setStartStop(s); // Actually set the start stop. dialog.dismiss(); } }, cbListener); listView.setAdapter(adapter); dialog.setCanceledOnTouchOutside(true); dialog.show(); } public void createTimesDialog(View view) { // Library provided ListView with headers that (gasp) stick to the top. StickyListHeadersListView listView = new StickyListHeadersListView(this); AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); TimeAdapter adapter = new TimeAdapter(getApplicationContext(), timesBetweenStartAndEnd); listView.setAdapter(adapter); // listView.setSelection(timesBetweenStartAndEnd.indexOf(nextBusTime)); builder.setView(listView); Dialog dialog = builder.create(); dialog.setCanceledOnTouchOutside(true); dialog.show(); } }
package beginner; import com.sandwich.koan.Koan; import java.util.*; import java.text.MessageFormat; import static com.sandwich.koan.constant.KoanConstants.*; import static com.sandwich.util.Assert.*; public class AboutStrings { @Koan public void implicitStrings() { assertEquals("just a plain ole string".getClass(),String.class); } @Koan public void newString() { // very rarely if ever should Strings be created via new String() in // practice - generally it is redundant, and done repetitively can be slow String string = new String(); String empty = ""; assertEquals(string.equals(empty), true); } @Koan public void newStringIsRedundant() { String stringInstance = "zero"; String stringReference = new String(stringInstance); assertEquals(stringInstance.equals(stringReference), true); } @Koan public void newStringIsNotIdentical() { String stringInstance = "zero"; String stringReference = new String(stringInstance); assertEquals(stringInstance == stringReference, false); } @Koan public void stringConcatenation() { String one = "one"; String space = " "; String two = "two"; assertEquals(one + space + two, "one two"); } @Koan public void stringBuilderCanActAsAMutableString() { // StringBuilder concatenation looks uglier, but is useful when you need a // mutable String like object. It used to be more efficient than using + // to concatenate numerous strings, however this is optimized in the compiler now. // Usually + concatenation is more appropriate than StringBuilder. assertEquals(new StringBuilder("one").append(" ").append("two").toString(), "one two"); } @Koan public void readableStringFormattingWithStringFormat() { assertEquals(String.format("%s %s %s", "a", "b", "a"), "a b a" ); } @Koan public void extraArgumentsToStringFormatGetIgnored() { assertEquals(String.format("%s %s %s", "a", "b", "c", "d"), "a b c"); } @Koan public void insufficientArgumentsToStringFormatCausesAnError() { try { String.format("%s %s %s", "a", "b"); fail("No Exception was thrown!"); } catch (Exception e) { assertEquals(e.getClass(), MissingFormatArgumentException.class); assertEquals(e.getMessage(),"Format specifier '%s'" ); } } @Koan public void readableStringFormattingWithMessageFormat() { assertEquals(MessageFormat.format("{0} {1} {0}", "a", "b"), "a b a"); } @Koan public void extraArgumentsToMessageFormatGetIgnored() { assertEquals(MessageFormat.format("{0} {1} {0}", "a", "b", "c"), "a b a"); } @Koan public void insufficientArgumentsToMessageFormatDoesNotReplaceTheToken() { assertEquals(MessageFormat.format("{0} {1} {0}", "a"), "a {1} a"); } }
package com.facebook.react.bridge; import static com.facebook.infer.annotation.ThreadConfined.ANY; import android.app.Activity; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.facebook.common.logging.FLog; import com.facebook.infer.annotation.Assertions; import com.facebook.infer.annotation.ThreadConfined; import com.facebook.react.common.build.ReactBuildConfig; /** * Base class for Catalyst native modules that require access to the {@link ReactContext} instance. */ public abstract class ReactContextBaseJavaModule extends BaseJavaModule { private final @Nullable ReactApplicationContext mReactApplicationContext; public ReactContextBaseJavaModule() { mReactApplicationContext = null; } public ReactContextBaseJavaModule(@NonNull ReactApplicationContext reactContext) { mReactApplicationContext = reactContext; } /** Subclasses can use this method to access catalyst context passed as a constructor. */ protected final ReactApplicationContext getReactApplicationContext() { return Assertions.assertNotNull( mReactApplicationContext, "Tried to get ReactApplicationContext even though NativeModule wasn't instantiated with one"); } /** * Subclasses can use this method to access catalyst context passed as a constructor. Use this * version to check that the underlying CatalystInstance is active before returning, and * automatically have SoftExceptions or debug information logged for you. Consider using this * whenever calling ReactApplicationContext methods that require the Catalyst instance be alive. * * <p>This can return null at any time, but especially during teardown methods it's * possible/likely. * * <p>Threading implications have not been analyzed fully yet, so assume this method is not * thread-safe. */ @ThreadConfined(ANY) protected @Nullable final ReactApplicationContext getReactApplicationContextIfActiveOrWarn() { if (mReactApplicationContext.hasActiveCatalystInstance()) { return mReactApplicationContext; } // We want to collect data about how often this happens, but SoftExceptions will cause a crash // in debug mode, which isn't usually desirable. String msg = "Catalyst Instance has already disappeared: requested by " + this.getName(); String tag = "ReactContextBaseJavaModule"; if (ReactBuildConfig.DEBUG) { FLog.w(tag, msg); } else { ReactSoftException.logSoftException(tag, new RuntimeException(msg)); } return null; } /** * Get the activity to which this context is currently attached, or {@code null} if not attached. * * <p>DO NOT HOLD LONG-LIVED REFERENCES TO THE OBJECT RETURNED BY THIS METHOD, AS THIS WILL CAUSE * MEMORY LEAKS. * * <p>For example, never store the value returned by this method in a member variable. Instead, * call this method whenever you actually need the Activity and make sure to check for {@code * null}. */ protected @Nullable final Activity getCurrentActivity() { return mReactApplicationContext.getCurrentActivity(); } }
package com.gravity.gameplay; public class Location { private final float x; private final float y; public Location(float x, float y) { this.x = x; this.y = y; } public float getX() { return x; } public float getY() { return y; } @Override public String toString() { return "Location [x=" + x + ", y=" + y + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Float.floatToIntBits(x); result = prime * result + Float.floatToIntBits(y); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Location other = (Location) obj; if (Float.floatToIntBits(x) != Float.floatToIntBits(other.x)) return false; if (Float.floatToIntBits(y) != Float.floatToIntBits(other.y)) return false; return true; } }
package com.hubspot.singularity; import com.hubspot.mesos.Resources; import java.util.List; import java.util.Map; public class SingularityRequestBuilder { private String id; private String name; private String version; private Long timestamp; private Map<String, String> metadata; private String executor; private Resources resources; private String schedule; private Integer instances; private Boolean rackSensitive; private Boolean daemon; private String command; private Map<String, String> env; private List<String> uris; private Object executorData; private List<String> owners; private Integer numRetriesOnFailure; private Integer maxFailuresBeforePausing; public SingularityRequest build() { return new SingularityRequest(command, name, executor, resources, schedule, instances, daemon, env, uris, metadata, executorData, rackSensitive, id, version, timestamp, owners, numRetriesOnFailure, maxFailuresBeforePausing); } public int getMaxFailuresBeforePausing() { return maxFailuresBeforePausing; } public SingularityRequestBuilder setMaxFailuresBeforePausing(int maxFailuresBeforePausing) { this.maxFailuresBeforePausing = maxFailuresBeforePausing; return this; } public List<String> getOwners() { return owners; } public SingularityRequestBuilder setOwners(List<String> owners) { this.owners = owners; return this; } public int getNumRetriesOnFailure() { return numRetriesOnFailure; } public SingularityRequestBuilder setNumRetriesOnFailure(int numRetriesOnFailure) { this.numRetriesOnFailure = numRetriesOnFailure; return this; } public String getId() { return id; } public SingularityRequestBuilder setId(String id) { this.id = id; return this; } public String getVersion() { return version; } public SingularityRequestBuilder setVersion(String version) { this.version = version; return this; } public Long getTimestamp() { return timestamp; } public SingularityRequestBuilder setTimestamp(Long timestamp) { this.timestamp = timestamp; return this; } public Map<String, String> getMetadata() { return metadata; } public SingularityRequestBuilder setMetadata(Map<String, String> metadata) { this.metadata = metadata; return this; } public String getName() { return name; } public SingularityRequestBuilder setName(String name) { this.name = name; return this; } public String getExecutor() { return executor; } public SingularityRequestBuilder setExecutor(String executor) { this.executor = executor; return this; } public Resources getResources() { return resources; } public SingularityRequestBuilder setResources(Resources resources) { this.resources = resources; return this; } public String getSchedule() { return schedule; } public SingularityRequestBuilder setSchedule(String schedule) { this.schedule = schedule; return this; } public Integer getInstances() { return instances; } public SingularityRequestBuilder setInstances(Integer instances) { this.instances = instances; return this; } public Boolean getRackSensitive() { return rackSensitive; } public SingularityRequestBuilder setRackSensitive(Boolean rackSensitive) { this.rackSensitive = rackSensitive; return this; } public Boolean getDaemon() { return daemon; } public SingularityRequestBuilder setDaemon(Boolean daemon) { this.daemon = daemon; return this; } public String getCommand() { return command; } public SingularityRequestBuilder setCommand(String command) { this.command = command; return this; } public Map<String, String> getEnv() { return env; } public SingularityRequestBuilder setEnv(Map<String, String> env) { this.env = env; return this; } public List<String> getUris() { return uris; } public SingularityRequestBuilder setUris(List<String> uris) { this.uris = uris; return this; } public Object getExecutorData() { return executorData; } public SingularityRequestBuilder setExecutorData(Object executorData) { this.executorData = executorData; return this; } @Override public String toString() { return "SingularityRequestBuilder [id=" + id + ", name=" + name + ", version=" + version + ", timestamp=" + timestamp + ", metadata=" + metadata + ", executor=" + executor + ", resources=" + resources + ", schedule=" + schedule + ", instances=" + instances + ", rackSensitive=" + rackSensitive + ", daemon=" + daemon + ", command=" + command + ", env=" + env + ", uris=" + uris + ", executorData=" + executorData + "]"; } }
package org.nakedobjects.xat; import org.nakedobjects.object.Naked; import org.nakedobjects.object.NakedObject; import org.nakedobjects.object.NakedObjectSpecification; import org.nakedobjects.object.NakedValue; import org.nakedobjects.object.OneToOneAssociation; import org.nakedobjects.object.control.Allow; import org.nakedobjects.object.control.Consent; public class DummyValue implements OneToOneAssociation { public void clearAssociation(NakedObject inObject, NakedObject associate) {} public void clearValue(NakedObject inObject) {} public void initAssociation(NakedObject inObject, NakedObject associate) {} public void initValue(NakedObject inObject, Object value) {} public void setAssociation(NakedObject inObject, NakedObject associate) {} public void setValue(NakedObject inObject, Object value) {} public Consent isAssociationValid(NakedObject inObject, NakedObject associate) { return null; } public Consent isValueValid(NakedObject inObject, NakedValue value) { return null; } public Naked get(NakedObject fromObject) { return null; } public Class[] getExtensions() { return null; } public NakedObjectSpecification getSpecification() { return null; } public boolean isCollection() { return false; } public boolean isDerived() { return false; } public boolean isEmpty(NakedObject adapter) { return false; } public boolean isMandatory() { return false; } public boolean isObject() { return false; } public boolean isValue() { return false; } public String getDescription() { return null; } public Object getExtension(Class cls) { return null; } public String getId() { return null; } public String getName() { return null; } public boolean isAuthorised() { return true; } public Consent isUsable(NakedObject target) { return null; } public Consent isVisible(NakedObject target) { return Allow.DEFAULT; } public boolean isHidden() { return false; } }
package com.melodies.bandup; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.widget.EditText; import android.widget.Toast; import com.android.volley.AuthFailureError; import com.android.volley.NetworkError; import com.android.volley.NoConnectionError; import com.android.volley.ParseError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.ServerError; import com.android.volley.TimeoutError; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.facebook.CallbackManager; import com.facebook.FacebookCallback; import com.facebook.FacebookException; import com.facebook.FacebookSdk; import com.facebook.login.LoginResult; import com.facebook.login.widget.LoginButton; import com.google.android.gms.auth.api.Auth; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.auth.api.signin.GoogleSignInResult; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.SignInButton; import com.google.android.gms.common.api.GoogleApiClient; import com.melodies.bandup.setup.Instruments; import org.json.JSONException; import org.json.JSONObject; public class Login extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener, View.OnClickListener { // server url location for login private String url; private GoogleApiClient mGoogleApiClient; private static final int RC_SIGN_IN = 9001; private static final String TAG = "SignInActivity"; private ProgressDialog loginDialog; private EditText etUsername; private EditText etPassword; private CallbackManager callbackManager = CallbackManager.Factory.create(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FacebookSdk.sdkInitialize(getApplicationContext()); // need to initialize facebook before view setContentView(R.layout.activity_main); String route = "/login-local"; url = getResources().getString(R.string.api_address).concat(route); loginDialog = new ProgressDialog(Login.this); etUsername = (EditText) findViewById(R.id.etUsername); etPassword = (EditText) findViewById(R.id.etPassword); etPassword.setOnKeyListener(new View.OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { // If the event is a key-down event on the "enter" button if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // Perform action on key press try { Login.this.onClickSignIn(findViewById(R.id.btnSignIn)); } catch (JSONException e) { e.printStackTrace(); } return true; } return false; } }); LoginButton loginButton = (LoginButton) findViewById(R.id.login_button_facebook); loginButton.setReadPermissions("email"); loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() { @Override public void onSuccess(final LoginResult loginResult) { //Toast.makeText(Login.this, loginResult.getAccessToken().getToken(), Toast.LENGTH_LONG).show(); facebookCreateUser(loginResult); } @Override public void onCancel() { System.out.println("login canceled"); Toast.makeText(Login.this, "login cancelled", Toast.LENGTH_LONG).show(); } @Override public void onError(FacebookException error) { System.out.println("hit an error"); Toast.makeText(Login.this, error.getMessage(), Toast.LENGTH_LONG).show(); } }); // Button listener //findViewById(R.id.login_button_google).setOnClickListener(this); //findViewById(R.id.sign_out_button).setOnClickListener(this); //findViewById(R.id.disconnect_button).setOnClickListener(this); // configuring simple Google+ sign in requesting userId and email and basic profile (included in DEFAULT_SIGN_IN) GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(getString(R.string.default_web_client_id)) .requestId() .requestEmail() .build(); // Google client with access to the Google SignIn API and the options specified by gso. mGoogleApiClient = new GoogleApiClient.Builder(this) .enableAutoManage(this, this) .addApi(Auth.GOOGLE_SIGN_IN_API, gso) .build(); // Google+ Sign In button design SignInButton signInButton = (SignInButton) findViewById(R.id.login_button_google); signInButton.setSize(SignInButton.SIZE_STANDARD); signInButton.setScopes(gso.getScopeArray()); } /** * take result from facebook login process and create user in backend * * side effect: starts up instrument activity if succesfull * * @param loginResult facebook loginResult */ private void facebookCreateUser(LoginResult loginResult) { try{ url = getResources().getString(R.string.api_address).concat("/login-facebook"); JSONObject jsonObject = new JSONObject(); jsonObject.put("access_token", loginResult.getAccessToken().getToken()); JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, jsonObject, new Response.Listener<JSONObject>(){ @Override public void onResponse(JSONObject response) { saveSessionId(response); Intent instrumentsIntent = new Intent(Login.this, Instruments.class); Login.this.startActivity(instrumentsIntent); overridePendingTransition(R.anim.slide_in_right, R.anim.no_change); finish(); } }, new Response.ErrorListener(){ @Override public void onErrorResponse(VolleyError error) { Toast.makeText(Login.this, error.getMessage(), Toast.LENGTH_LONG).show(); } }); VolleySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest); }catch (JSONException ex){ System.out.println(ex.getMessage()); } } public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...) if (requestCode == RC_SIGN_IN) { GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data); handleSignInResult(result); }else{ callbackManager.onActivityResult(requestCode, resultCode, data); } } // Accessing user data from Google & storing on server private void handleSignInResult(GoogleSignInResult result) { Log.d(TAG, "handleSignInResult:" + result.isSuccess()); if (result.isSuccess()) { Toast.makeText(getApplicationContext(), "Signed In ", Toast.LENGTH_SHORT).show(); // Logged in, accessing user data GoogleSignInAccount acct = result.getSignInAccount(); final String idToken = acct.getIdToken(); String personName = acct.getDisplayName(); String personEmail = acct.getEmail(); String personId = acct.getId(); //Uri personPhoto = acct.getPhotoUrl(); // Sending user info to server sendGoogleUserToServer(personId, idToken, personName, personEmail); } } // Sending user info to server private void sendGoogleUserToServer(String personId, String idToken, String personName, String personEmail) { try{ url = getResources().getString(R.string.api_address).concat("/login-google"); JSONObject jsonObject = new JSONObject(); jsonObject.put("userId", personId); jsonObject.put("userToken", idToken); jsonObject.put("userName", personName); jsonObject.put("userEmail", personEmail); JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, jsonObject, new Response.Listener<JSONObject>(){ @Override public void onResponse(JSONObject response) { Toast.makeText(getApplicationContext(), "Success Response", Toast.LENGTH_SHORT).show(); saveSessionId(response); Intent instrumentsIntent = new Intent(Login.this, Instruments.class); Login.this.startActivity(instrumentsIntent); finish(); } }, new Response.ErrorListener(){ @Override public void onErrorResponse(VolleyError error) { Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_SHORT).show(); } }); VolleySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest); }catch (JSONException ex){ System.out.println(ex.getMessage()); } } // Google buttons public void onClick(View v) { switch (v.getId()) { case R.id.login_button_google: signIn(); break; } } // Unresorvable error occured and Google API will not be available public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { Log.d(TAG, "onConnectionFailed:" + connectionResult); Toast.makeText(getApplicationContext(), "Google+ SignIn Error!", Toast.LENGTH_SHORT).show(); } // Google+ Sign In public void signIn() { Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient); startActivityForResult(signInIntent, RC_SIGN_IN); } // Google+ Sign Out private void signOut() { Auth.GoogleSignInApi.signOut(mGoogleApiClient); } // Google+ Disconnecting Google account from the app private void revokeAccess() { Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient); } // when Sign In is Clicked grab data and ... public void onClickSignIn(View v) throws JSONException { // catching views into variables // converting into string final String username = etUsername.getText().toString(); final String password = etPassword.getText().toString(); if (v.getId() == R.id.btnSignIn) { // Check for empty field in the form if (username.isEmpty()) { Toast.makeText(getApplicationContext(), "Please enter your Username.", Toast.LENGTH_SHORT).show(); } else if (password.isEmpty()) { Toast.makeText(getApplicationContext(), "Please enter your Password.", Toast.LENGTH_SHORT).show(); } else { loginDialog = ProgressDialog.show(this, "Logging in", "Please wait...", true, false); createloginRequest(username, password); } } } // Login user into app private void createloginRequest(String username, String password) { // create request for Login JSONObject user = new JSONObject(); try { user.put("username", username); user.put("password", password); } catch (JSONException e) { e.printStackTrace(); } JsonObjectRequest jsonObjectRequest = new JsonObjectRequest( Request.Method.POST, url, user, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { saveSessionId(response); Toast.makeText(Login.this, "Login Successful!", Toast.LENGTH_SHORT).show(); try { Boolean hasFinishedSetup = response.getBoolean("hasFinishedSetup"); if (hasFinishedSetup) { Intent userListIntent = new Intent(Login.this, UserList.class); Login.this.startActivity(userListIntent); } else { Intent instrumentsIntent = new Intent(Login.this, Instruments.class); Login.this.startActivity(instrumentsIntent); } } catch (JSONException e) { Intent instrumentsIntent = new Intent(Login.this, Instruments.class); Login.this.startActivity(instrumentsIntent); } finally { loginDialog.dismiss(); overridePendingTransition(R.anim.slide_in_right, R.anim.no_change); finish(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { loginDialog.dismiss(); errorHandlerLogin(error); } } ); // insert request into queue VolleySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest); } // Handling errors that can occur while SignIn request private void errorHandlerLogin(VolleyError error) { if (error instanceof TimeoutError || error instanceof NoConnectionError) { Toast.makeText(Login.this, "Connection error!", Toast.LENGTH_LONG).show(); } else if (error instanceof AuthFailureError ) { Toast.makeText(Login.this, "Invalid username or password", Toast.LENGTH_LONG).show(); } else if (error instanceof ServerError) { Toast.makeText(Login.this, "Server error!", Toast.LENGTH_LONG).show(); } else if (error instanceof NetworkError) { Toast.makeText(Login.this, "Network error!", Toast.LENGTH_LONG).show(); } else if (error instanceof ParseError) { Toast.makeText(Login.this, "Server parse error!", Toast.LENGTH_LONG).show(); } else { Toast.makeText(Login.this, "Unknown error! Contact Administrator", Toast.LENGTH_LONG).show(); } } // Storing user sessionId in SessionIdData folder, which only this app can access public void saveSessionId(JSONObject response) { final EditText etUsername = (EditText) findViewById(R.id.etUsername); SharedPreferences srdPref = getSharedPreferences("SessionIdData", Context.MODE_PRIVATE); SharedPreferences.Editor editor = srdPref.edit(); editor.putString("sessionId", response.toString()); editor.apply(); } // when Sign Up is Clicked go to Registration View public void onClickSignUp(View v) { if (v.getId() == R.id.btnSignUp) { Intent signUpIntent = new Intent(Login.this, Register.class); Login.this.startActivity(signUpIntent); } } }
package com.tlongdev.bktf; import android.content.Context; import android.content.SharedPreferences; import android.graphics.drawable.Drawable; import android.graphics.drawable.LayerDrawable; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.preference.PreferenceManager; import android.util.Log; import com.tlongdev.bktf.enums.Quality; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.math.BigDecimal; import java.math.RoundingMode; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.Date; /** * Utility class (static only). */ public class Utility { public static final String LOG_TAG = Utility.class.getSimpleName(); public static final String CURRENCY_USD = "usd"; public static final String CURRENCY_METAL = "metal"; public static final String CURRENCY_KEY = "keys"; public static final String CURRENCY_BUD = "earbuds"; /** * Convenient method for getting the steamId (or vanity user name) of the user. */ public static String getSteamId(Context context) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); String steamId = prefs.getString(context.getString(R.string.pref_steam_id), null); if (steamId != null && steamId.equals("")){ return null; } return steamId; } /** * Convenient method for getting the steamId of the user. */ public static String getResolvedSteamId(Context context) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); return prefs.getString(context.getString(R.string.pref_resolved_steam_id), null); } /** * Properly formats the item name according to its properties. */ public static String formatItemName(String name, int tradable, int craftable, int quality, int index) { String formattedName = ""; if (tradable == 0) { formattedName += "Non-Tradable "; } if (craftable == 0) { formattedName += "Non-Craftable "; } //Convert the quality int to enum for better readability Quality q = Quality.values()[quality]; switch (q) { case NORMAL: formattedName += "Normal "; break; case GENUINE: formattedName += "Genuine "; break; case VINTAGE: formattedName += "Vintage "; break; case UNIQUE: if (index > 0) //A unique item with a number name = name + " #" + index; break; case UNUSUAL: formattedName += getUnusualEffectName(index) + " "; break; case COMMUNITY: formattedName += "Community "; break; case VALVE: formattedName += "Valve "; break; case SELF_MADE: formattedName += "Self-made "; break; case STRANGE: formattedName += "Strange "; break; case HAUNTED: formattedName += "Haunted "; break; case COLLECTORS: formattedName += "Collector's "; break; } return formattedName + name; } public static String formatSimpleItemName(String name, int quality, int index, boolean isProper) { String formattedName = ""; //Convert the quality int to enum for better readability Quality q = Quality.values()[quality]; switch (q) { case NORMAL: formattedName += "Normal "; break; case GENUINE: formattedName += "Genuine "; break; case VINTAGE: formattedName += "Vintage "; break; case UNIQUE: if (index > 0) //A unique item with a number name = name + " #" + index; if (isProper){ name = "The " + name; } break; case UNUSUAL: formattedName += "Unusual "; break; case COMMUNITY: formattedName += "Community "; break; case VALVE: formattedName += "Valve "; break; case SELF_MADE: formattedName += "Self-made "; break; case STRANGE: formattedName += "Strange "; break; case HAUNTED: formattedName += "Haunted "; break; case COLLECTORS: formattedName += "Collector's "; break; } return formattedName + name; } /** * Get the proper name of the unusual effect */ public static String getUnusualEffectName(int index) { switch (index) { case 4: return "Community Sparkle"; case 5: return "Holy Glow"; case 6: return "Green Confetti"; case 7: return "Purple Confetti"; case 8: return "Haunted Ghosts"; case 9: return "Green Energy"; case 10: return "Purple Energy"; case 11: return "Circling TF Logo"; case 12: return "Massed Flies"; case 13: return "Burning Flames"; case 14: return "Scorching Flames"; case 15: return "Searing Plasma"; case 16: return "Vivid Plasma"; case 17: return "Sunbeams"; case 18: return "Circling Peace Sign"; case 19: return "Circling Heart"; case 29: return "Stormy Storm"; case 30: return "Blizzardy Storm"; case 31: return "Nuts n' Bolts"; case 32: return "Orbiting Planets"; case 33: return "Orbiting Fire"; case 34: return "Bubbling"; case 35: return "Smoking"; case 36: return "Steaming"; case 37: return "Flaming Lantern"; case 38: return "Cloudy Moon"; case 39: return "Cauldron Bubbles"; case 40: return "Eerie Orbiting Fire"; case 43: return "Knifestorm"; case 44: return "Misty Skull"; case 45: return "Harvest Moon"; case 46: return "It's A Secret To Everybody"; case 47: return "Stormy 13th Hour"; case 56: return "Kill-a-Watt"; case 57: return "Terror-Watt"; case 58: return "Cloud 9"; case 59: return "Aces High"; case 60: return "Dead Presidents"; case 61: return "Miami Nights"; case 62: return "Disco Beat Down"; case 63: return "Phosphorous"; case 64: return "Sulphurous"; case 65: return "Memory Leak"; case 66: return "Overclocked"; case 67: return "Electrostatic"; case 68: return "Power Surge"; case 69: return "Anti-Freeze"; case 70: return "Time Warp"; case 71: return "Green Black Hole"; case 72: return "Roboactive"; case 73: return "Arcana"; case 74: return "Spellbound"; case 75: return "Chiroptera Venenata"; case 76: return "Poisoned Shadows"; case 77: return "Something Burning This Way Comes"; case 78: return "Hellfire"; case 79: return "Darkblaze"; case 80: return "Demonflame"; case 81: return "Bonzo The All-Gnawing"; case 82: return "Amaranthine"; case 83: return "Stare From Beyond"; case 84: return "The Ooze"; case 85: return "Ghastly Ghosts Jr"; case 86: return "Haunted Phantasm Jr"; case 87: return "Frostbite"; case 88: return "Molten Mallard"; case 89: return "Morning Glory"; case 90: return "Death at Dusk"; case 3001: return "Showstopper"; case 3003: return "Holy Grail"; case 3004: return "'72"; case 3005: return "Fountain of Delight"; case 3006: return "Screaming Tiger"; case 3007: return "Skill Gotten Gains"; case 3008: return "Midnight Whirlwind"; case 3009: return "Silver Cyclone"; case 3010: return "Mega Strike"; case 3011: return "Haunted Phantasm"; case 3012: return "Ghastly Ghosts"; default: return ""; } } /** * Returns a drawable based on the item's properties to use asa background */ public static LayerDrawable getItemBackground(Context context, int quality, int tradable, int craftable) { //Convert the quality int to enum for better readability Quality q = Quality.values()[quality]; Drawable itemFrame; Drawable craftableFrame; Drawable tradableFrame; switch (q) { case GENUINE: itemFrame = context.getResources().getDrawable(R.drawable.item_background_genuine); break; case VINTAGE: itemFrame = context.getResources().getDrawable(R.drawable.item_background_vintage); break; case UNUSUAL: itemFrame = context.getResources().getDrawable(R.drawable.item_background_unusual); break; case UNIQUE: itemFrame = context.getResources().getDrawable(R.drawable.item_background_unique); break; case COMMUNITY: itemFrame = context.getResources().getDrawable(R.drawable.item_background_community); break; case VALVE: itemFrame = context.getResources().getDrawable(R.drawable.item_background_valve); break; case SELF_MADE: itemFrame = context.getResources().getDrawable(R.drawable.item_background_community); break; case STRANGE: itemFrame = context.getResources().getDrawable(R.drawable.item_background_strange); break; case HAUNTED: itemFrame = context.getResources().getDrawable(R.drawable.item_background_haunted); break; case COLLECTORS: itemFrame = context.getResources().getDrawable(R.drawable.item_background_collectors); break; default: itemFrame = context.getResources().getDrawable(R.drawable.item_background_normal); break; } if (craftable == 0){ craftableFrame = context.getResources().getDrawable(R.drawable.non_craftable_border); } else { //Easier to use an empty drawable instead of resizing the layer drawable craftableFrame = context.getResources().getDrawable(R.drawable.empty_drawable); } if (tradable == 0){ tradableFrame = context.getResources().getDrawable(R.drawable.non_tradable_border); } else { //Easier to use an empty drawable instead of resizing the layer drawable tradableFrame = context.getResources().getDrawable(R.drawable.empty_drawable); } return new LayerDrawable(new Drawable[] {itemFrame, craftableFrame, tradableFrame}); } /** * Formats the given price and converts it to the desired currency. */ public static String formatPrice(Context context, double low, double high, String originalCurrency, String targetCurrency, boolean twoLines) throws Throwable { //Initial string String product = ""; //Convert the prices first low = convertPrice(context, low, originalCurrency, targetCurrency); if (high > 0.0) high = convertPrice(context, high, originalCurrency, targetCurrency); //Check if the price is an int if ((int)low == low) product += (int)low; //Check if the double has fraction smaller than 0.01, if so we need to format the double else if (("" + low).substring(("" + low).indexOf('.') + 1).length() > 2) product += new DecimalFormat("#0.00").format(low); else product += low; if (high > 0.0){ //Check if the price is an int if ((int)high == high) product += "-" + (int)high; //Check if the double has fraction smaller than 0.01, if so we need to format the double else if (("" + high).substring(("" + high).indexOf('.') + 1).length() > 2) product += "-" + new DecimalFormat("#0.00").format(high); else product += "-" + high; } //If the price needs to be in two lines, the currency will be in a seperate line. if (twoLines) { product += "\n"; } //Append the string with the proper currency switch(targetCurrency) { case CURRENCY_BUD: if (low == 1.0 && high == 0.0) return product + " bud"; else return product + " buds"; case CURRENCY_METAL: return product + " ref"; case CURRENCY_KEY: if (low == 1.0 && high == 0.0) return product + " key"; else return product + " keys"; case CURRENCY_USD: return "$" + product; default: //App should never reach this code if (isDebugging(context)) Log.e(LOG_TAG, "Error formatting price"); throw new Throwable("Error while formatting price"); } } /** * Converts the price to that desired currency. */ public static double convertPrice(Context context, double price, String originalCurrency, String targetCurrency) throws Throwable { if (originalCurrency.equals(targetCurrency)) //The target currency equals the original currency, nothing to do. return price; SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); //Magic converter block switch(originalCurrency){ case CURRENCY_BUD: switch(targetCurrency){ case CURRENCY_KEY: return price * (getDouble(prefs, context.getString(R.string.pref_buds_raw), 1) / getDouble(prefs, context.getString(R.string.pref_key_raw), 1)); case CURRENCY_METAL: return price * getDouble(prefs, context.getString(R.string.pref_buds_raw), 1); case CURRENCY_USD: return price * (getDouble(prefs, context.getString(R.string.pref_buds_raw), 1) * getDouble(prefs, context.getString(R.string.pref_metal_raw_usd), 1)); } case CURRENCY_METAL: switch(targetCurrency){ case CURRENCY_KEY: return price / getDouble(prefs, context.getString(R.string.pref_key_raw), 1); case CURRENCY_BUD: return price / getDouble(prefs, context.getString(R.string.pref_buds_raw), 1); case CURRENCY_USD: return price * getDouble(prefs, context.getString(R.string.pref_metal_raw_usd), 1); } case CURRENCY_KEY: switch(targetCurrency){ case CURRENCY_METAL: return price * getDouble(prefs, context.getString(R.string.pref_key_raw), 1); case CURRENCY_BUD: return price * (getDouble(prefs, context.getString(R.string.pref_key_raw), 1) / getDouble(prefs, context.getString(R.string.pref_buds_raw), 1)); case CURRENCY_USD: return price * getDouble(prefs, context.getString(R.string.pref_key_raw), 1) * getDouble(prefs, context.getString(R.string.pref_metal_raw_usd), 1); } case CURRENCY_USD: switch(targetCurrency){ case CURRENCY_METAL: return price / getDouble(prefs, context.getString(R.string.pref_metal_raw_usd), 1); case CURRENCY_BUD: return price / getDouble(prefs, context.getString(R.string.pref_metal_raw_usd), 1) / getDouble(prefs, context.getString(R.string.pref_buds_raw), 1); case CURRENCY_KEY: return price * getDouble(prefs, context.getString(R.string.pref_metal_raw_usd), 1) / getDouble(prefs, context.getString(R.string.pref_key_raw), 1); } default: String error = "Unknown currency: " + originalCurrency + " - " + targetCurrency; if (isDebugging(context)) Log.e(LOG_TAG, error); throw new Throwable(error); } } /** * Check if the given steamId is a 64bit steamId using Regex. */ public static boolean isSteamId(String id) { return id.matches("7656119[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]"); } /** * Format the unix timestamp the a user readable string. */ public static String formatUnixTimeStamp(long unixSeconds){ Date date = new Date(unixSeconds*1000L); // *1000 is to convert seconds to milliseconds SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); return sdf.format(date); } /** * Format the timestamp to a user friendly string that is the same as on steam profile pages. */ public static String formatLastOnlineTime(long time) { //If the time is longer than 2 days tho format is X days. if (time >= 172800000L) { long days = time / 86400000; return "" + days + " days ago"; } //If the time is longer than an hour, the format is X hour(s) Y minute(s) if (time >= 3600000L) { long hours = time / 3600000; if (time % 3600000L == 0) { if (hours == 1) return "" + hours + " hour ago"; else { return "" + hours + " hours ago"; } } else { long minutes = (time % 3600000L) / 60000; if (hours == 1) if (minutes == 1) return "" + hours + " hour " + minutes + " minute ago"; else return "" + hours + " hour " + minutes + " minutes ago"; else { if (minutes == 1) return "" + hours + " hours " + minutes + " minute ago"; else return "" + hours + " hours " + minutes + " minutes ago"; } } } //Else it was less than an hour ago, the format is X minute(s). else { long minutes = time / 60000; if (minutes == 0){ return "Just now"; } else if (minutes == 1){ return "1 minute ago"; } else { return "" + minutes + " minutes ago"; } } } /** * Retrieves the steamId from a properly formatted JSON. */ public static String parseSteamIdFromVanityJson(String userJsonStr) throws JSONException { final String OWM_RESPONSE = "response"; final String OWM_SUCCESS = "success"; final String OWM_STEAM_ID = "steamid"; final String OWM_MESSAGE = "message"; JSONObject jsonObject = new JSONObject(userJsonStr); JSONObject response = jsonObject.getJSONObject(OWM_RESPONSE); if (response.getInt(OWM_SUCCESS) != 1){ //Return the error message if unsuccessful. return response.getString(OWM_MESSAGE); } return response.getString(OWM_STEAM_ID); } /** * Retrieves the user name from a properly formatted JSON. */ public static String parseUserNameFromJson(String jsonString) throws JSONException { final String OWM_RESPONSE = "response"; final String OWM_PLAYERS = "players"; final String OWM_NAME = "personaname"; JSONObject jsonObject = new JSONObject(jsonString); JSONObject response = jsonObject.getJSONObject(OWM_RESPONSE); JSONArray players = response.getJSONArray(OWM_PLAYERS); JSONObject player = players.getJSONObject(0); return player.getString(OWM_NAME); } /** * Retrieves the url for the user avatar from a proerly formatted JSON. */ public static String parseAvatarUrlFromJson(String jsonString) throws JSONException { final String OWM_RESPONSE = "response"; final String OWM_PLAYERS = "players"; final String OWM_AVATAR = "avatarfull"; JSONObject jsonObject = new JSONObject(jsonString); JSONObject response = jsonObject.getJSONObject(OWM_RESPONSE); JSONArray players = response.getJSONArray(OWM_PLAYERS); JSONObject player = players.getJSONObject(0); return player.getString(OWM_AVATAR); } /** * Check whether the user if connected to the internet. */ public static boolean isNetworkAvailable(Context context) { ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } /** * Convenient method for storing double values in shared preferences. */ public static SharedPreferences.Editor putDouble(final SharedPreferences.Editor edit, final String key, final double value) { return edit.putLong(key, Double.doubleToRawLongBits(value)); } /** * Convenient method for getting double values from shared preferences. */ public static double getDouble(final SharedPreferences prefs, final String key, final double defaultValue) { return Double.longBitsToDouble(prefs.getLong(key, Double.doubleToLongBits(defaultValue))); } /** * Whether we should log or not */ public static boolean isDebugging(Context context){ return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(context.getString(R.string.pref_debug), false); } /** * Check whether the given timestamp is older than 3 months */ public static boolean isPriceOld(int unixTimeStamp){ return System.currentTimeMillis() - unixTimeStamp*1000L > 7884000000L; } /** * Rounds the given double */ public static double roundDouble(double value, int places) { if (places < 0) throw new IllegalArgumentException(); BigDecimal bd = new BigDecimal(value); bd = bd.setScale(places, RoundingMode.HALF_UP); return bd.doubleValue(); } public static double getRawMetal(int rawRef, int rawRec, int rawScraps) { return (1.0/9.0 * rawScraps) + (1.0/3.0 * rawRec) + rawRef; } public static String getPaintName(int index){ switch (index){ case 7511618: return "Indubitably Green"; case 4345659: return "Zepheniah's Greed"; case 5322826: return "Noble Hatter's Violet"; case 14204632: return "Color No. 216-190-216"; case 8208497: return "Deep Commitment to Purple"; case 13595446: return "Mann Co. Orange"; case 10843461: return "Muskelmannbraun"; case 12955537: return "Peculiarly Drab Tincture"; case 6901050: return "Radigan Conagher Brown"; case 8154199: return "Ye Olde Rustic Color"; case 15185211: return "Australium Gold"; case 8289918: return "Aged Moustache Grey"; case 15132390: return "An Extraordinary Abundance of Tinge"; case 1315860: return "A Distinctive Lack of Hue"; case 16738740: return "Pink as Hell"; case 3100495: return "Color Similar to Slate"; case 8421376: return "Drably Olive"; case 3329330: return "The Bitter Taste of Defeat and Lime"; case 15787660: return "The Color of a Gentlemann's Business Pants"; case 15308410: return "Salmon Injustice"; case 12073019: return "Team Spirit"; case 4732984: return "Operator's Overalls"; case 11049612: return "Waterlogged Lab Coat"; case 3874595: return "Balaclava's Are Forever"; case 6637376: return "Air of Debonair"; case 8400928: return "The Value of Teamwork"; case 12807213: return "Cream Spirit"; case 2960676: return "After Eight"; case 12377523: return "A Mann's Mint"; default: return null; } } public static boolean isPaint(int index){ switch (index){ case 7511618: return true; case 4345659: return true; case 5322826: return true; case 14204632: return true; case 8208497: return true; case 13595446: return true; case 10843461: return true; case 12955537: return true; case 6901050: return true; case 8154199: return true; case 15185211: return true; case 8289918: return true; case 15132390: return true; case 1315860: return true; case 16738740: return true; case 3100495: return true; case 8421376: return true; case 3329330: return true; case 15787660: return true; case 15308410: return true; case 12073019: return true; case 4732984: return true; case 11049612: return true; case 3874595: return true; case 6637376: return true; case 8400928: return true; case 12807213: return true; case 2960676: return true; case 12377523: return true; default: return false; } } public static boolean canHaveEffects(int defindex, int quality){ if (quality == 5 || quality == 7 || quality == 9) { return defindex != 267 && defindex != 266; } else if (defindex == 1899 || defindex == 125){ return true; } return false; } public static int fixDefindex(int defindex) { //Check if the defindex is of a duplicate defindex to provide the proper price for it. switch (defindex){ case 9: case 10: case 11: case 12: //duplicate shotguns return 9; case 23: //duplicate pistol return 22; case 28: //duplicate destruction tool return 26; case 190: case 191: case 192: case 193: case 194: //duplicate stock weapons case 195: case 196: case 197: case 198: case 199: return defindex - 190; case 200: case 201: case 202: case 203: case 204: //duplicate stock weapons case 205: case 206: case 207: case 208: case 209: return defindex - 187; case 210: return defindex - 186; case 211: case 212: return defindex - 182; case 736: //duplicate sapper return 735; case 737: //duplicate construction pda return 25; case 5041: case 5045: //duplicate crates return 5022; case 5735: case 5742: case 5752: case 5781: case 5802: //duplicate munitions return 5734; default: return defindex; } } public static int getIconIndex(int defindex) { //Check if the defindex is of a duplicate defindex to provide the proper price for it. switch (defindex){ case 9: case 10: case 11: case 12: //duplicate shotguns return 9; case 23: //duplicate pistol return 22; case 28: //duplicate destruction tool return 26; case 190: case 191: case 192: case 193: case 194: //duplicate stock weapons case 195: case 196: case 197: case 198: case 199: return defindex - 190; case 200: case 201: case 202: case 203: case 204: //duplicate stock weapons case 205: case 206: case 207: case 208: case 209: return defindex - 187; case 210: return defindex - 186; case 211: case 212: return defindex - 182; case 294: //lugermorph return 160; case 422: //companion cube pin return 299; case 681: case 682: case 683: case 684: //gold cup medal return 680; case 686: case 687: case 688: case 689: //silver cup medal return 685; case 691: case 692: case 693: case 694: case 695: case 696: case 697: case 698: //bronze cup medal return 690; case 736: //duplicate sapper return 735; case 737: //duplicate construction pda return 25; case 744: //pyrovision goggles return 743; case 791: case 928://pink promo gifts return 790; case 831: case 832: case 833: case 834: // promoasian items case 835: case 836: case 837: case 838: return defindex - 21; case 839: //gift bag return 729; case 1132: //spell magazine return 1070; case 2015: case 2049: case 2079: case 2123: case 2125: //map stamps packs return 2007; case 2035: case 2036: case 2037: case 2038: case 2039: //dr gorbort pack return 2034; case 2041: case 2045: case 2047: case 2048: //deus ex pack return 2040; case 2042: case 2095: //soldier pack return 2019; case 2043: case 2044: //more soldier packs return 2042; case 2046: //shogun pack return 2016; case 2070: //promo chicken hat return 785; case 2081: //hong kong pac return 2076; case 2094: case 2096: case 2097: case 2098: case 2099: case 2100: case 2101: case 2102: //class packs return defindex - 76; case 2103: //deus Ex arm return 524; case 5020: //desc tag return 2093; case 5041: case 5045: //duplicate crates return 5022; case 5049: case 5067: case 5072: case 5073: case 5079: case 5081: case 5628: case 5631: case 5632: case 5713: case 5716: case 5717: case 5762: case 5791: case 5792: return 5021; //mann co supply crate key case 5074: //something special for someone special return 699; case 5601: case 5602: case 5603: case 5604: //pyro dusts return 5600; case 5721: case 5722: case 5723: case 5724: case 5725: case 5753: case 5754: case 5755: case 5756: case 5757: case 5758: case 5759: case 5783: case 5784: case 6522: return 5661; //strangifiers case 5727: case 5728: case 5729: case 5730: case 5731: case 5732: case 5733: case 5743: case 5744: case 5745: case 5746: case 5747: case 5748: case 5749: case 5750: case 5751: case 5793: case 5794: case 5795: case 5796: case 5797: case 5798: case 5799: case 5800: case 5801: case 6527: //killstreak kits return 5726; case 5735: case 5742: case 5752: case 5781: case 5802: //duplicate munitions return 5734; case 5738: //sombrero crate return 5737; case 5773: //halloween cauldron return 5772; case 8003: case 8006: //ugc medal return 8000; case 8004: case 8007: //ugc medal return 8001; case 8005: case 8008: //ugc medal return 8002; case 8223: //duplicate soldier medal return 121; default: //don't change return defindex; } } public static class IntegerPair{ int x; int y; public IntegerPair(){ this(0); } public IntegerPair(int x) { this(x, 0); } public IntegerPair(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } } }
package de.doofmars.ghb.model; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class Day implements Comparable<Day> { private final static SimpleDateFormat DF = new SimpleDateFormat("d.MM.yyyy"); private long total; private long host_id; private String hostname; private int day; private int month; private int year; private Date date; public Day(String total, String host_id, String hostname, String day, String month, String year, String dateString) { this.total = Long.valueOf(total); this.host_id = Long.valueOf(host_id); this.hostname = hostname; this.day = Integer.valueOf(day); this.year = Integer.valueOf(year); try { this.date = DF.parse(dateString); } catch (ParseException e) { this.date = new Date(); } } public long getTotal() { return total; } public long getHost_id() { return host_id; } public String getHostname() { return hostname; } public int getDay() { return day; } public int getMonth() { return month; } public int getYear() { return year; } public Date getDate() { return date; } @Override public String toString() { return "Day{" + "total=" + total + ", host_id=" + host_id + ", hostname='" + hostname + '\'' + ", day=" + day + ", month=" + month + ", year=" + year + ", date=" + date + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Day day1 = (Day) o; if (day != day1.day) return false; if (host_id != day1.host_id) return false; if (month != day1.month) return false; if (total != day1.total) return false; if (year != day1.year) return false; if (date != null ? !date.equals(day1.date) : day1.date != null) return false; if (hostname != null ? !hostname.equals(day1.hostname) : day1.hostname != null) return false; return true; } @Override public int hashCode() { int result = (int) (total ^ (total >>> 32)); result = 31 * result + (int) (host_id ^ (host_id >>> 32)); result = 31 * result + (hostname != null ? hostname.hashCode() : 0); result = 31 * result + day; result = 31 * result + month; result = 31 * result + year; result = 31 * result + (date != null ? date.hashCode() : 0); return result; } @Override public int compareTo(Day that) { if (this.getDate().compareTo(that.getDate()) != 0) { return this.getDate().compareTo(that.getDate()); } if (this.getHostname().compareTo(that.getHostname()) != 0) { return this.getHostname().compareTo(that.getHostname()); } return 0; } }
package xyz.gsora.toot; import MastodonTypes.Status; import android.app.IntentService; import android.app.NotificationManager; import android.content.Context; import android.content.Intent; import android.support.v4.app.NotificationCompat; import android.util.Log; import io.reactivex.Observable; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.schedulers.Schedulers; import io.realm.Realm; import io.realm.RealmConfiguration; import retrofit2.Response; import xyz.gsora.toot.Mastodon.Mastodon; import java.util.ArrayList; import java.util.Random; import static xyz.gsora.toot.Timeline.TIMELINE_MAIN; /** * An {@link IntentService} subclass for handling asynchronous toot sending. * <p> */ @SuppressWarnings("WeakerAccess") public class PostStatus extends IntentService { public static final String STATUS = "xyz.gsora.toot.extra.status"; public static final String REPLYID = "xyz.gsora.toot.extra.replyid"; public static final String MEDIAIDS = "xyz.gsora.toot.extra.mediaids"; public static final String SENSITIVE = "xyz.gsora.toot.extra.sensitive"; public static final String SPOILERTEXT = "xyz.gsora.toot.extra.spoilertext"; public static final String VISIBILITY = "xyz.gsora.toot.extra.visibility"; private static final String TAG = PostStatus.class.getSimpleName(); private Realm realm; private NotificationManager nM; private int notificationId; public PostStatus() { super("PostStatus"); } @Override protected void onHandleIntent(Intent intent) { Mastodon m = Mastodon.getInstance(); realm = Realm.getInstance(new RealmConfiguration.Builder().name(TIMELINE_MAIN).build()); nM = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); Random r = new Random(); notificationId = r.nextInt(); if (intent != null) { final String status = intent.getStringExtra(STATUS); final String replyid = intent.getStringExtra(REPLYID); final ArrayList<String> mediaids = intent.getStringArrayListExtra(MEDIAIDS); final Boolean sensitive = intent.getBooleanExtra(SENSITIVE, false); final String spoilertext = intent.getStringExtra(SPOILERTEXT); final Integer visibility = intent.getIntExtra(VISIBILITY, 0); Mastodon.StatusVisibility trueVisibility = Mastodon.StatusVisibility.PUBLIC; switch (visibility) { case 0: trueVisibility = Mastodon.StatusVisibility.PUBLIC; break; case 1: trueVisibility = Mastodon.StatusVisibility.DIRECT; break; case 2: trueVisibility = Mastodon.StatusVisibility.UNLISTED; break; case 3: trueVisibility = Mastodon.StatusVisibility.PRIVATE; break; } // create a new "toot sending" notification NotificationCompat.Builder mBuilder = buildNotification( "Sending toot", null, true ); nM.notify(notificationId, mBuilder.build()); Observable<Response<Status>> post = m.postPublicStatus(status, replyid, mediaids, sensitive, spoilertext, trueVisibility); post .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe( this::postSuccessful, this::postError ); } } private void postSuccessful(Response<Status> response) { Log.d(TAG, "postSuccessful: post ok!"); // toot sent, remove notification nM.cancel(notificationId); } private void postError(Throwable error) { Log.d(TAG, "postError: post error! --> " + error.toString()); // cancel "sending" notification id nM.cancel(notificationId); // create a new "error" informative notification NotificationCompat.Builder mBuilder = buildNotification( "Failed to send toot", "We had some problems sending your toot, check your internet connection, or maybe the Mastodon instance you're using could be down.", false ); nM.notify(notificationId + 1, mBuilder.build()); } /** * Builds a {@link NotificationCompat.Builder} with some predefined properties * * @param title notification title * @param text notification body, can be null * @param hasUndefinedProgress declare if the notification have to contain an undefined progressbar * @return a {@link NotificationCompat.Builder} with the properties passed as parameter. */ private NotificationCompat.Builder buildNotification(String title, String text, Boolean hasUndefinedProgress) { NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this); mBuilder.setContentTitle(title); NotificationCompat.BigTextStyle style = new NotificationCompat.BigTextStyle(); if (text != null) { style.bigText(text); } mBuilder.setStyle(style); mBuilder.setSmallIcon(R.drawable.ic_reply_white_24dp); if (hasUndefinedProgress) { mBuilder.setProgress(0, 0, true); } return mBuilder; } }
package com.jareddickson.cordova.tagmanager; import org.apache.cordova.CordovaWebView; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CordovaInterface; import com.google.analytics.tracking.android.GAServiceManager; import com.google.tagmanager.Container; import com.google.tagmanager.ContainerOpener; import com.google.tagmanager.ContainerOpener.OpenType; import com.google.tagmanager.DataLayer; import com.google.tagmanager.TagManager; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * This class echoes a string called from JavaScript. */ public class CDVTagManager extends CordovaPlugin { private Container mContainer; private boolean inited = false; public CDVTagManager() { } public void initialize(CordovaInterface cordova, CordovaWebView webView) { super.initialize(cordova, webView); } @Override public boolean execute(String action, JSONArray args, CallbackContext callback) { if (action.equals("initGTM")) { return this.initGTM(args, callback); } else if (action.equals("exitGTM")) { return this.exitGTM(args, callback); } else if (action.equals("trackEvent")) { return this.trackEvent(args, callback); } else if (action.equals("trackPage")) { return this.trackPage(args, callback); } else if (action.equals("dispatch")) { return this.dispatch(args, callback); } return false; } protected boolean initGTM(JSONArray args, CallbackContext callback) { try { // Set the dispatch interval GAServiceManager .getInstance() .setLocalDispatchPeriod(args.getInt(1)); TagManager tagManager = TagManager .getInstance(this.cordova.getActivity().getApplicationContext()); ContainerOpener.openContainer( tagManager, // TagManager instance. args.getString(0), // Tag Manager Container ID. OpenType.PREFER_NON_DEFAULT, // Prefer not to get the default container, but stale is OK. null, // Time to wait for saved container to load (ms). Default is 2000ms. new ContainerOpener.Notifier() { // Called when container loads. @Override public void containerAvailable(Container container) { // Handle assignment in callback to avoid blocking main thread. mContainer = container; inited = true; } } ); callback.success( "initGTM - id = " + args.getString(0) + "; " + "interval = " + args.getInt(1) + " seconds" ); return true; } catch (final Exception e) { callback.error(e.getMessage()); return false; } } protected boolean exitGTM(JSONArray args, CallbackContext callback) { try { inited = false; callback.success("exitGTM"); return true; } catch (final Exception e) { callback.error(e.getMessage()); return false; } } protected boolean dispatch(JSONArray args, CallbackContext callback) { if (!inited) { callback.error("dispatch failed - not initialized"); return false; } try { GAServiceManager.getInstance().dispatchLocalHits(); callback.success("dispatch sent"); return true; } catch (final Exception e) { callback.error(e.getMessage()); return false; } } protected boolean trackEvent(JSONArray args, CallbackContext callback) { if (!inited) { callback.error("trackEvent failed - not initialized"); return false; } try { DataLayer dataLayer = TagManager .getInstance(this.cordova.getActivity().getApplicationContext()) .getDataLayer(); int eventValue = args.optInt(3, 0); String category = args.getString(0); String eventAction = args.getString(1); String eventLabel = args.getString(2); String userId = args.optString(4, null); if (userId != null) { dataLayer.push(DataLayer.mapOf( "event" , "interaction", "target" , category, "action" , eventAction, "target-properties" , eventLabel, "value" , eventValue, "user-id" , userId )); callback.success( "trackEvent - " + "category = " + category + "; " + "action = " + eventAction + "; " + "label = " + eventLabel + "; " + "value = " + eventValue + "; " + "userId = " + userId ); } else { dataLayer.push(DataLayer.mapOf( "event" , "interaction", "target" , category, "action" , eventAction, "target-properties" , eventLabel, "value" , eventValue )); callback.success( "trackEvent - " + "category = " + category + "; " + "action = " + eventAction + "; " + "label = " + eventLabel + "; " + "value = " + eventValue ); } return true; } catch (final Exception e) { callback.error(e.getMessage()); return false; } } protected boolean trackPage(JSONArray args, CallbackContext callback) { if (!inited) { callback.error("trackPage failed - not initialized"); return false; } try { DataLayer dataLayer = TagManager .getInstance(this.cordova.getActivity().getApplicationContext()) .getDataLayer(); String pageURL = args.getString(0); String userId = args.optString(1, null); if (userId != null) { dataLayer.push(DataLayer.mapOf( "event" , "content-view", "content-name" , pageURL, "user-id" , userId )); callback.success( "trackPage - " + "url = " + pageURL + "; " + "userId = " + userId ); } else { dataLayer.push(DataLayer.mapOf( "event" , "content-view", "content-name" , pageURL )); callback.success( "trackPage - " + "url = " + pageURL ); } return true; } catch (final Exception e) { callback.error(e.getMessage()); return false; } } }
package io.cozy.imagesbrowser; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaInterface; import org.apache.cordova.CordovaPlugin; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.annotation.SuppressLint; import android.content.CursorLoader; import android.content.res.Resources; import android.database.Cursor; import android.os.Looper; import android.provider.ContactsContract; import android.provider.ContactsContract.CommonDataKinds.Email; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.CommonDataKinds.Photo; import android.provider.ContactsContract.CommonDataKinds.StructuredName; import android.provider.ContactsContract.Data; import android.provider.MediaStore; public class ImagesBrowser extends CordovaPlugin { /** * Constructor. */ public ImagesBrowser() { } /** * Executes the request and returns PluginResult. * * @param action The action to execute. * @param args JSONArray of arguments for the plugin. * @param callbackContext The callback id used when calling back into JavaScript. * @return True if the action was valid, false if not. */ public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException { if (action.equals("getImagesList")) { cordova.getThreadPool().execute(new Runnable() { public void run() { if (Looper.myLooper() == null) { Looper.prepare(); } callbackContext.success(makeImageList(cordova)); } }); } else if(action.equals("getContactsList")){ cordova.getThreadPool().execute(new Runnable() { @Override public void run() { try { if (Looper.myLooper() == null) { Looper.prepare(); } callbackContext.success(getContacts(cordova)); } catch (JSONException e) { e.printStackTrace(); callbackContext.error(e.getMessage()); } } }); } else { return false; } return true; } @SuppressLint("NewApi") public JSONArray makeImageList(CordovaInterface cordova){ // get images ID & path String[] projection = {MediaStore.Images.Media._ID, MediaStore.Images.Media.DATA}; // Create the cursor pointing to the SDCard CursorLoader loader = new CursorLoader(cordova.getActivity(), MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, // Which columns to return null, // Return all rows null, MediaStore.Images.Media.DATE_TAKEN + " DESC"); // Get the column index of the Thumbnails Image ID Cursor cursor = loader.loadInBackground(); JSONArray results = new JSONArray(); // Cursor may be null when sdcard isnt mounted. if (cursor != null) { int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); while(cursor.moveToNext()){ results.put(cursor.getString(columnIndex)); } } return results; } @SuppressLint("NewApi") public JSONArray getContacts(CordovaInterface cordova) throws JSONException{ JSONArray result = new JSONArray(); Cursor datapoints = new CursorLoader(cordova.getActivity(), ContactsContract.Data.CONTENT_URI, null, null, null, ContactsContract.Data.CONTACT_ID ).loadInBackground(); int contact_id_idx = datapoints.getColumnIndex(ContactsContract.Data.CONTACT_ID); int mime_type_idx = datapoints.getColumnIndex(ContactsContract.Data.MIMETYPE); String currentId = ""; String versionHash = ""; JSONObject currentContact = new JSONObject(); JSONArray items = new JSONArray(); while(datapoints.moveToNext()){ String id = datapoints.getString(contact_id_idx); if(!id.equals(currentId)){ // new ID, store contact, create next if(items.length() > 0 && !currentId.equals("")){ currentContact.put("localVersion", versionHash); currentContact.put("datapoints", items); result.put(currentContact); } currentContact = new JSONObject(); currentContact.put("localId", id); items = new JSONArray(); currentId = id; versionHash = ""; } String type = datapoints.getString(mime_type_idx); if(type.equals(Phone.CONTENT_ITEM_TYPE)){ items.put(handleBaseColumns(datapoints, false)); versionHash += "-" + datapoints.getInt(datapoints.getColumnIndex(Data.DATA_VERSION)); }else if(type.equals(Email.CONTENT_ITEM_TYPE)){ items.put(handleBaseColumns(datapoints, true)); versionHash += "-" +datapoints.getInt(datapoints.getColumnIndex(Data.DATA_VERSION)); }else if(type.equals(StructuredName.CONTENT_ITEM_TYPE)){ handleName(currentContact, datapoints); versionHash += "-" +datapoints.getInt(datapoints.getColumnIndex(Data.DATA_VERSION)); }else if(type.equals(Photo.CONTENT_ITEM_TYPE)){ // byte[] blob = datapoints.getBlob(datapoints.getColumnIndex(Photo.PHOTO)); // currentContact.put("photo", Base64.encode(blob)); } } if(!currentId.equals("")){ currentContact.put("localVersion", versionHash); currentContact.put("datapoints", items); result.put(currentContact); } return result; } public JSONObject handleBaseColumns(Cursor item, boolean isEmail) throws JSONException{ JSONObject result = new JSONObject(); result.put("value", item.getString(item.getColumnIndex(Email.DATA))); result.put("type", getLabel(isEmail, item)); if(isEmail){ result.put("name", "email"); }else{ result.put("name", "tel"); } return result; } public String getLabel(boolean isEmail, Cursor item){ Resources res = cordova.getActivity().getResources(); int type = Integer.valueOf(item.getString(item.getColumnIndex(Email.TYPE))); if(Email.TYPE_CUSTOM == type){ return item.getString(item.getColumnIndex(Email.LABEL)); } if(isEmail){ return Email.getTypeLabel(res, type, "other").toString(); }else{ return Phone.getTypeLabel(res, type, "other").toString(); } } public void handleName(JSONObject contact, Cursor name) throws JSONException{ contact.put("fn", name.getString(name.getColumnIndex(StructuredName.DISPLAY_NAME))); String sep = ";"; contact.put("n", getString(name, StructuredName.FAMILY_NAME, "") + sep + getString(name, StructuredName.GIVEN_NAME, "") + sep + getString(name, StructuredName.MIDDLE_NAME, "") + sep + getString(name, StructuredName.PREFIX, "") + sep + getString(name, StructuredName.SUFFIX, "")); } public String getString(Cursor cur, String col, String def){ String result = cur.getString(cur.getColumnIndex(col)); if(result != null) return result; return def; } }
package sim; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Stack; import org.jsfml.graphics.Color; import org.jsfml.graphics.FloatRect; import org.jsfml.graphics.IntRect; import org.jsfml.graphics.RenderWindow; import org.jsfml.graphics.ShaderSourceException; import org.jsfml.graphics.TextureCreationException; import org.jsfml.graphics.View; import org.jsfml.system.Time; import org.jsfml.system.Vector2f; import org.jsfml.system.Vector2i; import org.jsfml.window.Keyboard; import org.jsfml.window.Keyboard.Key; import org.jsfml.window.Mouse; import org.jsfml.window.VideoMode; import org.jsfml.window.event.Event; import graphics.Tile.TileType; import graphics.BuildingRenderer; import graphics.FontManager; import graphics.LightLayer; import graphics.TextureManager; import graphics.Tile; import graphics.TileMap; import graphics.ZoneMapLayer; import gui.BlueprintGui; import gui.CheckBox; import gui.GameSpeedGui; import gui.GraphStatsGui; import gui.LogGui; import gui.StatsGui; import gui.TileInfoGui; import gui.TileSelector; import gui.ZoneDrawingGui; import maths.Distance; import world.Building; import world.Building.BuildingType; import world.Resource.ResourceType; import world.CityStats; import world.Need; import world.Resource; import world.ResourcesMap; import world.ResourcesStack; import world.Zone; import world.Zone.ZoneClass; import world.ZoneMap; /** * Contains init, update and render. */ public class Sim { // Constants. protected static final Vector2i TILEMAP_SIZE = new Vector2i(120, 75); protected static final Vector2f TILE_SIZE = new Vector2f(16.f, 16.f); // Attributes. protected RenderWindow window; protected TileMap tilemap; protected List<ArrayList<Tile>> tiles; protected ResourcesMap resourcesMap; protected ResourcesMap cachedResourceMap; protected List<Building> buildings; protected CityStats cityStats; protected TextureManager textureManager; protected FontManager fontManager; protected StatsGui statsGui; protected BuildingRenderer buildingRenderer; protected TileSelector tileSelector; protected TileInfoGui tileInfoGui; protected boolean displayTileInfo; protected Stack<Map<Integer, Building.BuildingType>> buildingStackRequired; protected ZoneMap zoneMap; protected ZoneMapLayer zoneMapLayer; protected ZoneDrawingGui zoneDrawingGui; protected GameSpeedGui gameSpeedGui; protected Time simulationSpeedTimer; protected View gameView; protected View staticView; protected GraphStatsGui graphStatsGui; protected LogGui logGui; protected List<CheckBox> checkboxes; protected int zoneDrawingCheckboxID; protected int cityGraphStatsCheckboxID; protected int logGuiCheckboxID; protected int blueprintCheckboxID; protected LightLayer lightLayer; protected int dayhour; protected int daycount; protected BlueprintGui blueprintGui; /** * Constructor * @param width : width of the window * @param height : height of the window * @param title : title of the window */ public Sim(int width, int height, String title) { this.window = new RenderWindow(new VideoMode(width, height), title); this.displayTileInfo = false; } /** * Inits the simulation. */ public void init() { // Inits the tiles array. this.tiles = new ArrayList<ArrayList<Tile>>(); for(int i = 0 ; i < TILEMAP_SIZE.y ; ++i) { ArrayList<Tile> row = new ArrayList<Tile>(); for(int j = 0 ; j < TILEMAP_SIZE.x ; ++j) { row.add(new Tile(TileType.TERRAIN_GRASS, new Vector2i(j, i))); } this.tiles.add(row); } // Instanciate the TextureManager this.textureManager = new TextureManager(); // Instanciate the fontManager this.fontManager = new FontManager(); //Instanciate the GUI this.statsGui = new StatsGui(textureManager, fontManager); this.tileSelector = new TileSelector(this.window, this.textureManager, TILEMAP_SIZE, TILE_SIZE); // Instanciate the building renderer. this.buildingRenderer = new BuildingRenderer(TILE_SIZE, this.textureManager); // Create the resources map. this.resourcesMap = new ResourcesMap(TILEMAP_SIZE); // Clone the resources map this.cachedResourceMap = this.resourcesMap.cloneResourcesMap(); // Create the buildings list. this.buildings = new ArrayList<Building>(); // Create the checkboxes. int checkboxID = 0; this.checkboxes = new ArrayList<CheckBox>(); this.zoneDrawingCheckboxID = checkboxID; this.checkboxes.add(new CheckBox(10, 100, this.textureManager, this.fontManager, "Afficher les zones", zoneDrawingCheckboxID)); checkboxID++; this.cityGraphStatsCheckboxID = checkboxID; this.checkboxes.add(new CheckBox(10, 120, this.textureManager, this.fontManager, "Afficher les statistiques", cityGraphStatsCheckboxID)); checkboxID++; this.logGuiCheckboxID = checkboxID; this.checkboxes.add(new CheckBox(10, 140, this.textureManager, this.fontManager, "Afficher les messages", logGuiCheckboxID)); checkboxID++; this.blueprintCheckboxID = checkboxID; this.checkboxes.add(new CheckBox(10, 160, this.textureManager, this.fontManager, "Gestion les plans", blueprintCheckboxID)); // Create the city stats. this.cityStats = new CityStats(); // Create the city graph stats gui. this.graphStatsGui = new GraphStatsGui(getWindow().getSize(), this.fontManager); // Create the zoneMap this.zoneMap = new ZoneMap(TILEMAP_SIZE.x, TILEMAP_SIZE.y); // Create the game speed GUI this.gameSpeedGui = new GameSpeedGui(this.textureManager, this.fontManager, this.window.getSize().x - 80, 20); // Create the logGui this.logGui = new LogGui(this.fontManager); // Create the blueprint gui. try { this.blueprintGui = new BlueprintGui(this.fontManager); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // Create the zoneMapLayer this.zoneMapLayer = new ZoneMapLayer(this.zoneMap); this.zoneMapLayer.addTypeColor(Zone.ZoneClass.FREE, new Color(12, 52, 30, 170)); this.zoneMapLayer.addTypeColor(Zone.ZoneClass.COMMERCIAL, new Color(125, 193, 129, 170)); this.zoneMapLayer.addTypeColor(Zone.ZoneClass.CULTURAL, new Color(51, 153, 255, 170)); this.zoneMapLayer.addTypeColor(Zone.ZoneClass.INDUSTRY, new Color(227, 168, 87, 170)); this.zoneMapLayer.addTypeColor(Zone.ZoneClass.ROAD, new Color(220, 220, 220, 170)); this.zoneMapLayer.addTypeColor(Zone.ZoneClass.RESIDENTIAL, new Color(70, 0, 0, 170)); this.zoneMapLayer.addTypeColor(Zone.ZoneClass.PUBLIC_SERVICE, new Color(255, 109, 201, 170)); // Houses. this.buildings.add(new Building(BuildingType.HOUSE, new Vector2i(31, 20))); // Roads this.buildings.add(new Building(BuildingType.ROAD, new Vector2i(31, 19))); this.buildings.add(new Building(BuildingType.ROAD, new Vector2i(32, 19))); // Inits the tilemap. this.tilemap = new TileMap(TILEMAP_SIZE, TILE_SIZE); this.tilemap.addTypeColor(TileType.TERRAIN_GRASS, new Color(0, 70, 0)); this.tilemap.setTiles(this.tiles); // Inits the building renderer. this.buildingRenderer.setColorPlaceholder(BuildingType.HOUSE, new Color(70, 0, 0)); this.buildingRenderer.setColorPlaceholder(BuildingType.ROAD, new Color(190, 190, 190)); this.buildingRenderer.setColorPlaceholder(BuildingType.GENERATOR, new Color(227, 168, 87)); this.buildingRenderer.setColorPlaceholder(BuildingType.HYDROLIC_STATION, new Color(51, 153, 255)); this.buildingRenderer.setColorPlaceholder(BuildingType.GROCERY_STORE, new Color(125, 193, 129)); this.buildingRenderer.setColorPlaceholder(BuildingType.ANTENNA_4G, new Color(63, 63, 63)); this.buildingRenderer.setColorPlaceholder(BuildingType.CASINOS, new Color(255, 122, 159)); this.buildingRenderer.setColorPlaceholder(BuildingType.CINEMA, new Color(114, 210, 255)); this.buildingRenderer.setColorPlaceholder(BuildingType.FIRE_STATION, new Color(255, 116, 2)); this.buildingRenderer.setColorPlaceholder(BuildingType.HOSPITAL, new Color(255, 233, 229)); this.buildingRenderer.setColorPlaceholder(BuildingType.MALL, new Color(255, 251, 33)); this.buildingRenderer.setColorPlaceholder(BuildingType.POLICE_STATION, new Color(45, 84, 255)); this.buildingRenderer.setColorPlaceholder(BuildingType.PUB, new Color(185, 255, 173)); this.buildingRenderer.setColorPlaceholder(BuildingType.RESTAURANT, new Color(255, 250, 0)); this.buildingRenderer.setColorPlaceholder(BuildingType.SCHOOL, new Color(255, 219, 137)); this.buildingRenderer.setColorPlaceholder(BuildingType.STADIUM, new Color(192, 192, 192)); this.buildingRenderer.setTextureRect(BuildingType.GROCERY_STORE, new FloatRect(0.f, 0.f, 64.f, 32.f)); // The stack of the maps which contains the required buildings of everyone. this.buildingStackRequired = new Stack<Map<Integer, Building.BuildingType>>(); // Instanciate the tileInfoGui this.tileInfoGui = new TileInfoGui(this.tiles, this.fontManager); // Instanciate the zone drawing GUI. this.zoneDrawingGui = new ZoneDrawingGui(this.textureManager, this.fontManager); // Building spawn timer. this.simulationSpeedTimer = Time.ZERO; // Views. this.staticView = new View(); this.staticView.setSize(getWindow().getView().getSize()); this.staticView.setCenter(getWindow().getView().getCenter()); this.gameView = (View)getWindow().getView(); // Light layer. try { this.lightLayer = new LightLayer(new Vector2i((int)(TILEMAP_SIZE.x * TILE_SIZE.x), (int)(TILEMAP_SIZE.y * TILE_SIZE.y))); this.lightLayer.virtualDraw(); } catch (TextureCreationException | IOException | ShaderSourceException e) { this.logGui.write("Error: could not create the light layer.\n", LogGui.ERROR); } // Day/night cycle. this.dayhour = 0; this.daycount = 0; } /** * Returns a reference to the checkbox. * * @param id : the id of the checkbox * @return the checkbox */ public CheckBox getCheckBox(int id) { for(CheckBox cb : this.checkboxes) { if(cb.getValue() == id) return cb; } return null; } /** * Returns true if the checkbox is checked. * * @param id : the id of the checkbox * @return true if checked, fasle otherwise */ public boolean isCheckBoxChecked(int id) { return getCheckBox(id).isChecked(); } /** * Returns true if no checkbox is checked. * * @return true if no checkbox is checked, false otherwise */ public boolean noCheckBoxChecked() { for(CheckBox cb : this.checkboxes) if(cb.isChecked()) return false; return true; } /** * Returns true if no checkbox except the given ID is checked. * * @return true if the specified checkbox is the only one checked */ public boolean isOnlyChecked(int id) { for(CheckBox cb : this.checkboxes) { if(cb.isChecked() && cb.getValue() != id) return false; } return isCheckBoxChecked(id); } /** * Returns the building object with the given id. * * @param buildingId : id to look for * @param buildingList : list to search in * @return the building object, null if not found */ public Building getBuilding(int buildingId, List<Building> buildingList) { for(Building b : buildingList) { if(b.getId() == buildingId) return b; } return null; } /** * Counts the number of buildings per building type. * Type NONE is not counted. * * @param buildings : the map of the buildings (association of building's ID and building type) * @return the map of the building counts (association of building's type and number of buildings in that category) */ public Map<Building.BuildingType, Integer> countBuildingsPerType(Map<Integer, Building.BuildingType> buildings) { Map<Building.BuildingType, Integer> buildingCounts = new HashMap<Building.BuildingType, Integer>(); for(Map.Entry<Integer, Building.BuildingType> entry : buildings.entrySet()) { Building.BuildingType buildingType = entry.getValue(); // Do not count NONE. if(buildingType == Building.BuildingType.NONE) continue; if(buildingCounts.containsKey(buildingType)) { Integer count = buildingCounts.get(buildingType); count = new Integer(count.intValue() + 1); buildingCounts.put(buildingType, count); } else { buildingCounts.put(buildingType, 1); } } return buildingCounts; } /** * Returns the map entry with the most buildings counted. * * @param buildingCounts : the map of the building counts (association of building's type and number of buildings in that category) * @return The max entry in the building counts map. */ public Map.Entry<Building.BuildingType, Integer> getMostRequiredBuildingType(Map<Building.BuildingType, Integer> buildingCounts) { Map.Entry<Building.BuildingType, Integer> maxEntry = null; for(Map.Entry<Building.BuildingType, Integer> entry : buildingCounts.entrySet()) { if(maxEntry == null || entry.getValue() > maxEntry.getValue()) { maxEntry = entry; } } return maxEntry; } /** * Computes the average position of all the buildings of the given type (limited to the given number of buildings). * * @param buildings : the list of all the buildings * @param buildingType : the buildings' type to take in account * @param numberOfBuildingsToCount : the number of buildings to count for the average position * @return The average position in tile coordinates. */ public Vector2i getBuildingsAveragePosition(Map<Integer, Building.BuildingType> buildings, Building.BuildingType buildingType, int numberOfBuildingsToCount) { Vector2i position = new Vector2i(0, 0); // Now sum the position of every building of the type specified. for(Map.Entry<Integer, Building.BuildingType> entry : buildings.entrySet()) { Building.BuildingType btype = entry.getValue(); if(btype == buildingType) { Building building = null; // Get the building. for(Building b : this.buildings) { if(b.getId() == entry.getKey()) { building = b; break; } } // Add its position. if(building != null) { Vector2i centerPosition = new Vector2i(building.getHitbox().left + building.getHitbox().width / 2, building.getHitbox().top + building.getHitbox().height / 2); position = Vector2i.add(position, centerPosition); } } } // Divide by the number of buildings counted to get the average position. return new Vector2i((int)(position.x / numberOfBuildingsToCount), (int)(position.y / numberOfBuildingsToCount)); } /** * Returns the distance to the furthest building from the given point. * * @param buildings : the list of all the buildings * @param buildingType : the buildings' type to take in account * @param point : the point to compute distance from * @return The distance between the furthest building of the given type to the given point. */ public float getFurthestBuildingTo(Map<Integer, Building.BuildingType> buildings, Building.BuildingType buildingType, Vector2i point) { float radius = 0.f; for(Map.Entry<Integer, Building.BuildingType> entry : buildings.entrySet()) { Building.BuildingType btype = entry.getValue(); if(btype == buildingType) { Building building = null; // Get the building. for(Building b : this.buildings) { if(b.getId() == entry.getKey()) { building = b; break; } } // Add its position. if(building != null) { Vector2i centerPosition = new Vector2i(building.getHitbox().left + building.getHitbox().width / 2, building.getHitbox().top + building.getHitbox().height / 2); float distance = (float)Distance.euclidean(point, centerPosition); if(distance > radius) radius = distance; } } } return radius; } /** * Returns true if there is a collision with another building (or is outside the map). * * @param hitbox : the hitbox to test * @return true in case of collision, false otherwise */ public boolean collideWithOtherBuildings(IntRect hitbox) { // Must be fully inside the map. if(hitbox.left < 0 || hitbox.top < 0 || hitbox.left + hitbox.width >= TILEMAP_SIZE.x || hitbox.top + hitbox.height >= TILEMAP_SIZE.y) return true; for(Building b : this.buildings) { if(hitbox.intersection(b.getHitbox()) != null) return true; } return false; } /** * Starts from the given left top position and check if the whole hitbox is in allowed zone classes. * * @param leftTop : the position to start checking from * @param hitbox : the hitbox (only width and height are used) * @param zoneClasses : the list of the zones allowed * @return true if the hitbox is in allowed zone classes, false otherwise */ public boolean checkZoneCompatibility(Vector2i leftTop, IntRect hitbox, List<Zone.ZoneClass> zoneClasses) { return checkZoneCompatibility(leftTop.x, leftTop.y, hitbox, zoneClasses); } /** * Starts from the given left top position and check if the whole hitbox is in allowed zone classes. * * @param x : the x component of the position to start checking from * @param y : the y component of the position to start checking from * @param hitbox : the hitbox (only width and height are used) * @param zoneClasses : the list of the zones allowed * @return true if the hitbox is in allowed zone classes, false otherwise */ public boolean checkZoneCompatibility(int x, int y, IntRect hitbox, List<Zone.ZoneClass> zoneClasses) { for(int rx = x ; rx < Math.min(x + hitbox.width, TILEMAP_SIZE.x) ; rx++) { for(int ry = y ; ry < Math.min(y + hitbox.height, TILEMAP_SIZE.y) ; ry++) { // Get the zone. Zone zone = this.zoneMap.getZoneMap().get(ry).get(rx); // check if the zone is suitable for(ZoneClass zoneBuilding : zoneClasses) { if(!zone.getType().equals(zoneBuilding)) { return false; } } } } return true; } /** * Sums the resources available under the whole hitbox. * * @param leftTop : the position to start checking from * @param hitbox : the hitbox (only width and height are used) * @return the resources available under the hitbox */ public ResourcesStack getResourcesUnderHitbox(Vector2i leftTop, IntRect hitbox) { return getResourcesUnderHitbox(leftTop.x, leftTop.y, hitbox); } /** * Sums the resources available under the whole hitbox. * * @param x : the x component of the position to start checking from * @param y : the y component of the position to start checking from * @param hitbox : the hitbox (only width and height are used) * @return he resources available under the hitbox */ public ResourcesStack getResourcesUnderHitbox(int x, int y, IntRect hitbox) { ResourcesStack rstack = new ResourcesStack(); for(int rx = x ; rx < Math.min(x + hitbox.width, TILEMAP_SIZE.x) ; rx++) { for(int ry = y ; ry < Math.min(y + hitbox.height, TILEMAP_SIZE.y) ; ry++) { rstack.add(resourcesMap.getResources(rx, ry)); } } return rstack; } /** * Checks the needs and precise the missing resources if any. * * @param needs : the list of the needs to check * @param rstack : the resources stack of the available resources * @param missingResources : reference to return the map of the missing resources * @return true if all the needs are satisfied, else otherwise */ public boolean checkNeeds(List<Need> needs, ResourcesStack rstack, Map<Resource.ResourceType, Integer> missingResources) { boolean allNeedsSatisfied = true; for(Need n : needs) { float minAmount = n.amount * n.fillFactor; // If one need is not satisfied to its minimum, we quit. if(rstack.get(n.type) < minAmount) { allNeedsSatisfied = false; int count = missingResources.get(n.type).intValue(); count += 1; missingResources.put(n.type, count); } } return allNeedsSatisfied; } /** * Counts the number of buildings in the given area. * * @param centerOfArea : the center of the area * @param range : the radius of the area * @param buildingList : the list of buildings to consider * @return the number of buildings in the area */ public int countBuildingsInArea(Vector2i centerOfArea, int range, List<Building> buildingList) { int inRange = 0; for(Building building : buildingList) { Vector2i buildingCenter = new Vector2i(building.getHitbox().left + building.getHitbox().width / 2, building.getHitbox().top + building.getHitbox().height / 2); int distance = (int)Distance.euclidean(buildingCenter, centerOfArea); if(distance < range) { inRange++; } } return inRange; } /** * Returns the list of the buildings of the given type. * * @param buildingList : the building list to filter * @param buildingType : the type of buildings to keep * @return the list filtered */ public List<Building> getBuildingsOfType(List<Building> buildingList, Building.BuildingType buildingType) { List<Building> buildingsOfGivenType = new ArrayList<Building>(); for(Building b : buildingList) { if(b.getType() == buildingType) buildingsOfGivenType.add(b); } return buildingsOfGivenType; } public List<Building> getBuildingsOfType(Map<Integer, Building.BuildingType> buildingMap, List<Building> buildingList, Building.BuildingType buildingType) { List<Building> buildingsOfGivenType = new ArrayList<Building>(); for(Map.Entry<Integer, Building.BuildingType> entry : buildingMap.entrySet()) { Building b = getBuilding(entry.getKey(), buildingList); if(b == null) continue; if(b.getType() == buildingType) buildingsOfGivenType.add(b); } return buildingsOfGivenType; } /** * Spawns the new buildings. */ public void spawnBuildings() { // Look into the required buildings stack. if(this.buildingStackRequired.empty()) return; // The map collecting the required buildings. // ID <-> Required building type. Map<Integer, Building.BuildingType> buildingsRequired = this.buildingStackRequired.peek(); // First count the required buildings. // Building type <-> how many times required Map<Building.BuildingType, Integer> buildingCounts = countBuildingsPerType(buildingsRequired); // Get the most required building type. // Building type <-> how many times required Map.Entry<Building.BuildingType, Integer> mostRequiredBuildingTypeEntry = getMostRequiredBuildingType(buildingCounts); // If no building type has been requested, we leave. if(mostRequiredBuildingTypeEntry == null) return; // Compute the average position, aka the center of the search area. Vector2i centerOfSearchArea = getBuildingsAveragePosition(buildingsRequired, mostRequiredBuildingTypeEntry.getKey(), mostRequiredBuildingTypeEntry.getValue()); // Get the furthest building from the average position, to compute the radius of the search area. float radius = getFurthestBuildingTo(buildingsRequired, mostRequiredBuildingTypeEntry.getKey(), centerOfSearchArea); // Create a fake building. Building requiredBuilding = new Building(mostRequiredBuildingTypeEntry.getKey(), new Vector2i(0, 0)); // We may need to expand the radius. if(requiredBuilding.getRange() > radius) radius = requiredBuilding.getRange(); // We use squared radius and squared euclidean distance for performance. double squaredRadius = Math.pow(radius, 2); // Map of the considered positions with the number of requiring building in range. // Position <-> number of buildings in range Map<Vector2i, Integer> candidatesPositions = new HashMap<Vector2i, Integer>(); // Map of the positions where it lacks resources only with the number of requiring building in range. // Position <-> number of buildings in range Map<Vector2i, Integer> candidatesPositionsLackingResources = new HashMap<Vector2i, Integer>(); // Map of the positions (which are in valid zone) with the number of requiring building in range. // Position <-> number of buildings in range Map<Vector2i, Integer> candidatesPositionsWithValidZone = new HashMap<Vector2i, Integer>(); // Missing resources for the required building. // Resource type <-> how many missing Map<Resource.ResourceType, Integer> missingResources = new HashMap<Resource.ResourceType, Integer>(); // Initiates missing resources to 0. for(Resource.ResourceType rtype : Resource.ResourceType.values()) missingResources.put(rtype, 0); // Check all resource map in square range. for(int x = Math.max(0, centerOfSearchArea.x - (int)radius) ; x < Math.min(resourcesMap.getSize().x, centerOfSearchArea.x + radius + 1) ; ++x) { for(int y = Math.max(0, centerOfSearchArea.y - (int)radius) ; y < Math.min(resourcesMap.getSize().y, centerOfSearchArea.y + radius + 1) ; ++y) { // Check only in radius. if(Distance.squaredEuclidean(centerOfSearchArea, new Vector2i(x, y)) <= squaredRadius) { // Check collision with other buildings. IntRect candidateHitbox = new IntRect(x, y, requiredBuilding.getHitbox().width, requiredBuilding.getHitbox().height); if(collideWithOtherBuildings(candidateHitbox)) { // This position is not suitable. continue; } // Check zone compatibility. if(!checkZoneCompatibility(x, y, requiredBuilding.getHitbox(), requiredBuilding.getZoneClasses())) { // This zone is not suitable continue; } // Check how many buildings (which required the building construction) are in range of the required building. List<Building> buildingsRequiring = getBuildingsOfType(buildingsRequired, this.buildings, requiredBuilding.getType()); int inRange = countBuildingsInArea(centerOfSearchArea, requiredBuilding.getRange(), buildingsRequiring); candidatesPositionsWithValidZone.put(new Vector2i(x, y), inRange); } } } // If we don't find any suitable zone, we need to notify the player. if(candidatesPositionsWithValidZone.isEmpty()) { this.logGui.write("No suitable position found for : " + mostRequiredBuildingTypeEntry.getKey().toString(), LogGui.WARNING); this.logGui.write("You should create one of the following zone(s), (near position {" + centerOfSearchArea.x + ", " + centerOfSearchArea.y + "}) :", LogGui.NORMAL); List<Zone.ZoneClass> suitableZonesForRequiredBuilding = Building.getSuitableZones(mostRequiredBuildingTypeEntry.getKey()); for(Zone.ZoneClass z : suitableZonesForRequiredBuilding) this.logGui.write("\t- " + z.toString(), false, LogGui.NORMAL); // We stop here. return; } for(Map.Entry<Vector2i, Integer> entry : candidatesPositionsWithValidZone.entrySet()) { // Decompose the map's entry. int x = entry.getKey().x; int y = entry.getKey().y; int inRange = entry.getValue(); // Get the resources available for the building. ResourcesStack rstack = getResourcesUnderHitbox(x, y, requiredBuilding.getHitbox()); // Check if they satisfy the needs. boolean allNeedsSatisfied = checkNeeds(requiredBuilding.getNeeds(), rstack, missingResources); // Add to the candidates positions if all resources are available. if(allNeedsSatisfied) candidatesPositions.put(new Vector2i(x, y), inRange); else candidatesPositionsLackingResources.put(new Vector2i(x, y), inRange); } // Check the position which reach the most buildings AND is the closer to the center of the search area. Map.Entry<Vector2i, Integer> bestPosition = null; double mindistance = Double.MAX_VALUE; for(Map.Entry<Vector2i, Integer> entry : candidatesPositions.entrySet()) { if((bestPosition == null) || (entry.getValue() >= bestPosition.getValue() && mindistance > Distance.euclidean(entry.getKey(), centerOfSearchArea))) { bestPosition = entry; mindistance = Distance.euclidean(bestPosition.getKey(), centerOfSearchArea); } } // Add the building to the position. if(bestPosition != null) { this.buildings.add(new Building(mostRequiredBuildingTypeEntry.getKey(), bestPosition.getKey())); // We spawned the building, so get it out of the stack. this.buildingStackRequired.pop(); this.logGui.write("Spawning : " + mostRequiredBuildingTypeEntry.getKey().toString() + " @ " + bestPosition.getKey().x + ", " + bestPosition.getKey().y, LogGui.SUCCESS); this.logGui.write("\tdistance to CoSA: " + Distance.euclidean(bestPosition.getKey(), centerOfSearchArea), false, LogGui.SUCCESS); this.logGui.write("\tefficiency: " + bestPosition.getValue() + "/" + mostRequiredBuildingTypeEntry.getValue(), false, LogGui.SUCCESS); } else { // Get the most rare resource. Map.Entry<Resource.ResourceType, Integer> mostRareResourceEntry = null; for(Map.Entry<Resource.ResourceType, Integer> entry : missingResources.entrySet()) { if(mostRareResourceEntry == null || entry.getValue() > mostRareResourceEntry.getValue()) { mostRareResourceEntry = entry; } } Resource.ResourceType rareResource = mostRareResourceEntry.getKey(); // Since the roads are manually spawned by the player, we can't ask to spawn them. if(rareResource != ResourceType.ROAD_PROXIMITY) { // Every building asking for the current building type should ask for its pre-requisite. Map<Integer, Building.BuildingType> prerequisiteBuildingMap = new HashMap<Integer, Building.BuildingType>(); for(Map.Entry<Integer, Building.BuildingType> entry : buildingsRequired.entrySet()) { if(requiredBuilding.getType() == entry.getValue()) prerequisiteBuildingMap.put(entry.getKey(), Building.getBuildingTypeGenerating(rareResource)); } // We add a new building to build on top of the stack. // This way, once the prerequiste building built, it will be poped off the stack and the original building will be built. this.buildingStackRequired.push(prerequisiteBuildingMap); this.logGui.write("No suitable position found for : " + mostRequiredBuildingTypeEntry.getKey().toString(), LogGui.WARNING); this.logGui.write("Most rare resource : " + rareResource.toString(), false, LogGui.WARNING); this.logGui.write("Asking to spawn : " + Building.getBuildingTypeGenerating(rareResource).toString(), false, LogGui.WARNING); } } } /** * Spawn road with the zone map */ public void spawnRoad() { // run the map for(int y = 0 ; y < this.zoneMap.getSize().y ; y++) { for(int x = 0 ; x < this.zoneMap.getSize().x ; x++) { // check if a zone type is road if(this.zoneMap.getZoneMap().get(y).get(x).getType().equals(ZoneClass.ROAD)) { // check if no building in this zone for(int i = 0 ; i < this.buildings.size() ;) { // if building remove it (ONLY if not a ROAD) if(this.buildings.get(i).getType() != Building.BuildingType.ROAD && this.buildings.get(i).getHitbox().contains(x, y)) { this.logGui.write("Removed building : " + this.buildings.get(i).getId(), LogGui.SUCCESS); this.buildings.remove(this.buildings.get(i)); } else { i++; } } // we spawn the road this.buildings.add(new Building(BuildingType.ROAD, new Vector2i(x, y))); } } } this.logGui.write("New road(s) added.", true, LogGui.SUCCESS); this.zoneDrawingGui.setNewRoadAdded(false); } /** * Spawns new houses depending on the attractivity. */ public void spawnNewcomers() { // Check attractivity. if(this.cityStats.getAttractivity(Zone.ZoneClass.COMMERCIAL) < 1.f) { this.logGui.write("Attractivity too small.", LogGui.ERROR); return; } // Find a new valid zone, searching from the center of the city. Vector2f citycenterf = new Vector2f(0.f, 0.f); for(Building b : this.buildings) { citycenterf = Vector2f.add(citycenterf, new Vector2f(b.getHitbox().left, b.getHitbox().top)); } citycenterf = Vector2f.mul(citycenterf, 1.f / this.buildings.size()); Vector2i citycenter = new Vector2i((int)citycenterf.x, (int)citycenterf.y); // Create a fake building. Building fakehouse = new Building(Building.BuildingType.HOUSE, new Vector2i(0, 0)); // List of positions already checked. List<Vector2i> exploredPositions = new ArrayList<Vector2i>(); // Closest position found. Vector2i closestPosition = null; double closestPositionDistance = Double.MAX_VALUE; //Look for roads. for(Building b : this.buildings) { if(b.getType() != Building.BuildingType.ROAD) continue; // Look for valid zones around the road. for(int x = Math.max(0, b.getHitbox().left - 4) ; x < Math.min(resourcesMap.getSize().x, b.getHitbox().left + 4) ; ++x) { for(int y = Math.max(0, b.getHitbox().top - 4) ; y < Math.min(resourcesMap.getSize().y, b.getHitbox().top + 4) ; ++y) { // Check if the position has already been tested. boolean alreadyExplored = false; for(Vector2i exploredPosition : exploredPositions) { if(exploredPosition.x == x && exploredPosition.y == y) alreadyExplored = true; } if(alreadyExplored) continue; // Computes the distance to the center of the city. double distance = Distance.euclidean(citycenter.x, citycenter.y, x, y); // Check only positions that are closer to the one found. if(distance >= closestPositionDistance) { continue; } // Check collision with other buildings. IntRect candidateHitbox = new IntRect(x, y, fakehouse.getHitbox().width, fakehouse.getHitbox().height); if(collideWithOtherBuildings(candidateHitbox)) { // This position is not suitable. continue; } // Check zone compatibility. if(!checkZoneCompatibility(x, y, fakehouse.getHitbox(), fakehouse.getZoneClasses())) { // This zone is not suitable continue; } // Get the resources available for the building. ResourcesStack rstack = getResourcesUnderHitbox(x, y, fakehouse.getHitbox()); // Keep this position if roads are available. if(rstack.get(Resource.ResourceType.ROAD_PROXIMITY) > 0.f) { closestPositionDistance = distance; closestPosition = new Vector2i(x, y); } } } } if(closestPosition != null) { Building house = new Building(Building.BuildingType.HOUSE, closestPosition); // Spawn the building. this.buildings.add(house); this.logGui.write("A new house has come, implemented at position {" + closestPosition.x + ", " + closestPosition.y + "}.", LogGui.SUCCESS); } } /** * Sets the static view to draw GUI & static elements on screen. */ public void setStaticView() { // Save the game view. this.gameView = (View)getWindow().getView(); // Set the static view. getWindow().setView(this.staticView); } /** * Sets the game view to draw the world. */ public void setGameView() { // No need to save the static view, since it's always the same. // Set the game view. getWindow().setView(this.gameView); } /** * Updates the day/night. */ public void updateDayNight() { this.dayhour += 3; this.dayhour %= 24; if(this.dayhour == 0) this.daycount++; } /** * Updates the visual render of the day/night. * @throws TextureCreationException */ public void updateDayNightVisual(float simulationTime, float dt) throws TextureCreationException { int goal = 0; if(this.dayhour < 9) { goal = 255; } else if(this.dayhour <= 17) { goal = 255; } else if(this.dayhour <= 23) { goal = 0; } float timeRemaining = 1.f - simulationTime; // Due to float computation errors, we have to check the time. if(timeRemaining <= 0.f) return; int actual = this.lightLayer.getAlpha(); int delta = goal - actual; float timestep = timeRemaining / dt; if(delta != 0) { int step = (int)(delta / timestep); actual += step; if(delta > 0 && actual > goal) actual = goal; else if(delta < 0 && actual < goal) actual = goal; this.lightLayer.setAlpha(actual); this.lightLayer.virtualDraw(); } } /** * Updates all the simulation. * @param dt : frame of time to use */ public void update(Time dt) { // Update the simulation timer. if(!this.gameSpeedGui.isInPause()) { this.simulationSpeedTimer = Time.add(this.simulationSpeedTimer, Time.mul(dt, this.gameSpeedGui.getSpeedCoeff())); } // Take real-time input. handleInput(dt); // Spawn road if(!this.gameSpeedGui.isInPause() && this.simulationSpeedTimer.asSeconds() >= 1.f) { // If there has been new road zones added. if(this.zoneDrawingGui.newRoadAdded()) { spawnRoad(); } // Spawn the newcomers. spawnNewcomers(); // Reset the resources. this.resourcesMap.reset(); // Get the list of the houses (to check clients and employees). List<Building> houses = getBuildingsOfType(this.buildings, Building.BuildingType.HOUSE); // Generate resources. for(Building b : this.buildings) { // Check the clients and employees. b.checkClients(houses); b.checkEmployees(houses); b.generateResources(this.resourcesMap, this.buildings); } for(Building b : this.buildings) { if(b.isEvolvable()) { if(b.checkLevelUp(this.resourcesMap)) { this.logGui.write("The building " + b.getId() + " leveled up to level " + b.getLevel(), LogGui.SUCCESS); } } } // Clone the resource map. this.cachedResourceMap = this.resourcesMap.cloneResourcesMap(); } // We update tile infos after generate. if(this.displayTileInfo) this.tileInfoGui.update(this.cachedResourceMap, this.tileSelector, this.buildings); if(!this.gameSpeedGui.isInPause() && this.simulationSpeedTimer.asSeconds() >= 1.f) { // Consume resources and get required buildings. Map<Integer, Building.BuildingType> buildingsRequired = new HashMap<Integer, Building.BuildingType>(); for(Building b : this.buildings) { BuildingType requiredBuilding = b.consumeResources(this.resourcesMap); // Don't do anything if none required. if(requiredBuilding != BuildingType.NONE && requiredBuilding != BuildingType.ROAD) { buildingsRequired.put(b.getId(), requiredBuilding); } } // We only push a requirement for a new building if there is none waiting. if(this.buildingStackRequired.isEmpty() && !buildingsRequired.isEmpty()) { this.buildingStackRequired.push(buildingsRequired); } // Spawn buildings. spawnBuildings(); // Display the building stack size if > 0. if(this.buildingStackRequired.size() > 0) { this.logGui.write("" + this.buildingStackRequired.size() + " building(s) waiting to be built.", LogGui.NORMAL); this.logGui.write("Stack dump : " + this.buildingStackRequired.toString(), LogGui.NORMAL); } // Update the city stats. this.cityStats.update(this.buildings); // Update the stats graphs (even if not displayed). this.graphStatsGui.update(this.cityStats.getPopulation(), this.cityStats.getMoney(), this.buildings.size()); // Update the lights positions. this.lightLayer.clearLights(); for(Building b : this.buildings) { Vector2f center = new Vector2f((b.getHitbox().left + b.getHitbox().width / 2.f) * TILE_SIZE.x, (b.getHitbox().top + b.getHitbox().height / 2.f) * TILE_SIZE.y); this.lightLayer.addLight(center, 1.25f * b.getHitbox().width * TILE_SIZE.x, new Color(255, 255, 255, 250), new Color(255, 255, 255, 50)); } // Update day/night. updateDayNight(); } // Update visual of day/night. if(!this.gameSpeedGui.isInPause()) { try { updateDayNightVisual(this.simulationSpeedTimer.asSeconds(), dt.asSeconds()); } catch(TextureCreationException e) { this.logGui.write("Error: could not create a texture in the light layer.\n", LogGui.ERROR); } } // Do the time substraction here. if(!this.gameSpeedGui.isInPause() && this.simulationSpeedTimer.asSeconds() >= 1.f) { this.simulationSpeedTimer = Time.sub(this.simulationSpeedTimer, Time.getSeconds(1.f)); } // Update the tilemap. this.tilemap.update(); // Update GUI. if(isCheckBoxChecked(this.zoneDrawingCheckboxID)) { // Force pause during zone drawing. this.gameSpeedGui.setPaused(true); this.zoneDrawingGui.update(dt, this.window, this.zoneMap, this.tileSelector); this.zoneMapLayer.update(); } if(isCheckBoxChecked(this.blueprintCheckboxID)) { // Force pause during blueprints management. this.gameSpeedGui.setPaused(true); this.zoneMapLayer.update(); } //Update stats this.gameSpeedGui.update(dt); this.statsGui.setMoney(this.cityStats.getMoney()); this.statsGui.setPopulation(this.cityStats.getPopulation()); this.tileSelector.update(); this.logGui.update(dt); } /** * Renders all the simulation. */ public void render(Time elapsedSinceLastUpdate) { this.window.clear(Color.BLACK); this.window.draw(this.tilemap); this.buildingRenderer.setBuildingList(this.buildings); this.window.draw(this.buildingRenderer); if(isCheckBoxChecked(this.zoneDrawingCheckboxID) || isCheckBoxChecked(this.blueprintCheckboxID)) this.window.draw(this.zoneMapLayer); else this.window.draw(this.lightLayer); this.window.draw(this.tileSelector); // Static elements. setStaticView(); this.window.draw(this.statsGui); this.window.draw(this.gameSpeedGui); if(isOnlyChecked(this.cityGraphStatsCheckboxID)) { this.window.draw(this.graphStatsGui); this.window.draw(getCheckBox(this.cityGraphStatsCheckboxID)); } else if(isOnlyChecked(this.zoneDrawingCheckboxID)) { this.window.draw(this.zoneDrawingGui); this.window.draw(getCheckBox(this.zoneDrawingCheckboxID)); } else if(isOnlyChecked(this.logGuiCheckboxID)) { this.window.draw(this.logGui); this.window.draw(getCheckBox(this.logGuiCheckboxID)); } else if(isOnlyChecked(this.blueprintCheckboxID)) { this.window.draw(this.blueprintGui); this.window.draw(getCheckBox(this.blueprintCheckboxID)); } else { for(CheckBox cb : this.checkboxes) { this.window.draw(cb); } } setGameView(); // End of static elements. if(this.displayTileInfo) this.window.draw(tileInfoGui); this.window.display(); } public void saveLog() { this.logGui.saveToFile(); } /** * Handles the real-time input from the player. * @param dt : elapsed time since last tick */ public void handleInput(Time dt) { //final int borderSize = 20; View view = (View)getWindow().getView(); // View movement. float viewMovementX = 0, viewMovementY = 0; // View mouvement via mouse. /* * Vector2i mousePosition = Mouse.getPosition(getWindow()); if(mousePosition.x <= borderSize) { Mouse.setPosition(new Vector2i(borderSize, mousePosition.y), getWindow()); viewMovementX -= 400.f; } else if(mousePosition.x >= getWindow().getSize().x - borderSize) { Mouse.setPosition(new Vector2i(getWindow().getSize().x - (borderSize), mousePosition.y), getWindow()); viewMovementX += 400.f; } if(mousePosition.y <= borderSize) { Mouse.setPosition(new Vector2i(mousePosition.x, borderSize), getWindow()); viewMovementY -= 400.f; } else if(mousePosition.y >= getWindow().getSize().y - borderSize) { Mouse.setPosition(new Vector2i(mousePosition.x, getWindow().getSize().y - (borderSize)), getWindow()); viewMovementY += 400.f; } */ // View movement via keyboard. if(Keyboard.isKeyPressed(Keyboard.Key.LEFT)) { viewMovementX -= 400.f; } else if(Keyboard.isKeyPressed(Keyboard.Key.RIGHT)) { viewMovementX += 400.f; } if(Keyboard.isKeyPressed(Keyboard.Key.UP)) { viewMovementY -= 400.f; } else if(Keyboard.isKeyPressed(Keyboard.Key.DOWN)) { viewMovementY += 400.f; } // Move the view. Vector2f viewMovement = new Vector2f(viewMovementX, viewMovementY); viewMovement = Vector2f.mul(viewMovement, dt.asSeconds()); view.move(viewMovement); getWindow().setView(view); } /** * Returns the window. * @return the window used by the simulation */ public RenderWindow getWindow() { return this.window; } /** * Remove building if we left click and pressed d * @param e : Event */ public void handleBuildingRemoval(Event e) { if(Keyboard.isKeyPressed(Key.D)) { if(e.type == Event.Type.MOUSE_BUTTON_RELEASED && e.asMouseButtonEvent().button == Mouse.Button.RIGHT) { for(int i = 0; i < this.buildings.size();){ if(this.buildings.get(i).getHitbox().contains(this.tileSelector.getSelectedTile())) { this.logGui.write("Removed building : Id : " + this.buildings.get(i).getId(), LogGui.SUCCESS); this.buildings.remove(this.buildings.get(i)); } else { i++; } } } } } /** * Handles the event. * @param event : the JSFML event to handle */ public void handleEvent(Event event) { if(event.type == Event.Type.MOUSE_BUTTON_RELEASED && event.asMouseButtonEvent().button == Mouse.Button.MIDDLE) { this.displayTileInfo = !this.displayTileInfo; } if(isOnlyChecked(this.cityGraphStatsCheckboxID)) { getCheckBox(this.cityGraphStatsCheckboxID).handleEvent(event); } else if(isOnlyChecked(this.zoneDrawingCheckboxID)) { CheckBox checkbox = getCheckBox(this.zoneDrawingCheckboxID); checkbox.handleEvent(event); this.zoneDrawingGui.handleEvent(event); this.gameSpeedGui.setPaused(checkbox.isChecked()); } else if(isOnlyChecked(this.logGuiCheckboxID)) { getCheckBox(this.logGuiCheckboxID).handleEvent(event); }else if(isOnlyChecked(this.blueprintCheckboxID)) { getCheckBox(blueprintCheckboxID).handleEvent(event); this.blueprintGui.handleEvent(this.window, event, this.zoneMap, this.logGui); } else { for(CheckBox cb : this.checkboxes) { cb.handleEvent(event); } } handleBuildingRemoval(event); this.logGui.handleEvent(new Vector2f(Mouse.getPosition(this.window).x, Mouse.getPosition(this.window).y), event); this.gameSpeedGui.handleEvent(event); } /** * Sets the game on play when the game gains focus. */ public void onGainFocus() { this.gameSpeedGui.setPaused(false); } /** * Sets the game on pause when the game loose focus. */ public void onLostFocus() { this.gameSpeedGui.setPaused(true); } }
package dyvil.tools.repl.context; import dyvil.array.ObjectArray; import dyvil.collection.List; import dyvil.io.Console; import dyvil.reflect.Modifiers; import dyvil.reflect.Opcodes; import dyvil.tools.compiler.ast.annotation.AnnotationList; import dyvil.tools.compiler.ast.expression.IValue; import dyvil.tools.compiler.ast.field.Field; import dyvil.tools.compiler.ast.modifiers.ModifierSet; import dyvil.tools.compiler.ast.type.IType; import dyvil.tools.compiler.ast.type.builtin.Types; import dyvil.tools.compiler.backend.*; import dyvil.tools.compiler.backend.exception.BytecodeException; import dyvil.tools.compiler.config.Formatting; import dyvil.tools.parsing.Name; import dyvil.tools.parsing.position.ICodePosition; import dyvil.tools.repl.DyvilREPL; import java.lang.reflect.InvocationTargetException; public class REPLVariable extends Field { private REPLContext context; protected String bytecodeName; protected String className; private Class<?> theClass; private Object displayValue; public REPLVariable(REPLContext context, ICodePosition position, Name name, IType type, String className, ModifierSet modifiers, AnnotationList annotations) { super(null, position, name, type, modifiers, annotations); this.context = context; this.className = className; REPLContext.updateModifiers(modifiers); } @Override public boolean hasModifier(int mod) { return mod == Modifiers.STATIC || this.modifiers.hasIntModifier(mod); } protected void compute(DyvilREPL repl, List<IClassCompilable> compilableList) { if (this.isConstant() && !compilableList.isEmpty()) { return; } final byte[] bytes; try { bytes = this.generateClass(this.className, compilableList); } catch (Throwable throwable) { throwable.printStackTrace(repl.getErrorOutput()); return; } if (this.type == Types.VOID && compilableList.isEmpty()) { // We don't have any variables, so the Class can be GC'd after it has been loaded and initialized. this.theClass = REPLCompiler.loadAnonymousClass(this.context.repl, this.className, bytes); return; } // The type contains the value, so we have to keep the class loaded. this.theClass = REPLCompiler.loadClass(this.context.repl, this.className, bytes); this.updateValue(repl); } protected void updateValue(DyvilREPL repl) { if (this.theClass == null || this.type == Types.VOID) { return; } final Object result; if (this.property != null) { try { final java.lang.reflect.Method method = this.theClass.getDeclaredMethod(this.name.qualified); method.setAccessible(true); result = method.invoke(null); } catch (InvocationTargetException ex) { ex.getCause().printStackTrace(repl.getOutput()); this.displayValue = "<error>"; this.value = null; return; } catch (ReflectiveOperationException ex) { ex.printStackTrace(repl.getErrorOutput()); this.displayValue = "<error>"; this.value = null; return; } } else { try { final java.lang.reflect.Field field = this.theClass.getDeclaredFields()[0]; field.setAccessible(true); result = field.get(null); } catch (ReflectiveOperationException ex) { ex.printStackTrace(repl.getErrorOutput()); this.displayValue = "<error>"; this.value = null; return; } } this.value = IValue.fromObject(result); this.displayValue = result; } private boolean isConstant() { return this.hasModifier(Modifiers.FINAL) && this.value != null && isConstant(this.value); } private static boolean isConstant(IValue value) { int tag = value.valueTag(); return tag >= 0 && tag != IValue.NIL && tag < IValue.STRING; } private byte[] generateClass(String className, List<IClassCompilable> compilableList) throws Throwable { final String name = this.bytecodeName = this.name.qualified; final String extendedType = this.type.getExtendedName(); final String methodType = "()" + extendedType; final ClassWriter classWriter = new ClassWriter(); // Generate Class Header classWriter .visit(ClassFormat.CLASS_VERSION, Modifiers.PUBLIC | Modifiers.FINAL | ClassFormat.ACC_SUPER, className, null, "java/lang/Object", null); classWriter.visitSource(className, null); if (this.type != Types.VOID) { // Generate the field holding the value classWriter.visitField(this.modifiers.toFlags(), name, extendedType, null, null); } // Compilables for (IClassCompilable compilable : compilableList) { compilable.write(classWriter); } // Generate <clinit> static initializer final MethodWriter clinitWriter = new MethodWriterImpl(classWriter, classWriter.visitMethod( Modifiers.STATIC | Modifiers.SYNTHETIC, "<clinit>", "()V", null, null)); clinitWriter.visitCode(); for (IClassCompilable c : compilableList) { c.writeStaticInit(clinitWriter); } if (this.property != null) { this.property.writeStaticInit(clinitWriter); } // Write a call to the computeResult method clinitWriter.visitMethodInsn(Opcodes.INVOKESTATIC, className, "computeResult", methodType, false); if (this.type != Types.VOID) { // Store the value to the field clinitWriter.visitFieldInsn(Opcodes.PUTSTATIC, className, name, extendedType); } // Finish the <clinit> static initializer clinitWriter.visitInsn(Opcodes.RETURN); clinitWriter.visitEnd(); // Writer the computeResult method if (this.value != null) { final MethodWriter computeWriter = new MethodWriterImpl(classWriter, classWriter.visitMethod( Modifiers.PRIVATE | Modifiers.STATIC, "computeResult", methodType, null, null)); computeWriter.visitCode(); this.value.writeExpression(computeWriter, this.type); computeWriter.visitEnd(this.type); } // Write the property, if necessary if (this.property != null) { this.property.write(classWriter); } // Finish Class compilation classWriter.visitEnd(); return classWriter.toByteArray(); } @Override public void writeGet(MethodWriter writer, IValue receiver, int lineNumber) throws BytecodeException { if (this.isConstant()) { this.value.writeExpression(writer, this.type); return; } if (this.className == null) { this.type.writeDefaultValue(writer); return; } String extended = this.type.getExtendedName(); writer.visitFieldInsn(Opcodes.GETSTATIC, this.className, this.bytecodeName, extended); } @Override public void writeSet(MethodWriter writer, IValue receiver, IValue value, int lineNumber) throws BytecodeException { if (value != null) { value.writeExpression(writer, this.type); } if (this.className == null) { writer.visitInsn(Opcodes.AUTO_POP); return; } String extended = this.type.getExtendedName(); writer.visitFieldInsn(Opcodes.PUTSTATIC, this.className, this.bytecodeName, extended); } @Override public void toString(String prefix, StringBuilder buffer) { final boolean colors = this.context.getCompilationContext().config.useAnsiColors(); if (this.annotations != null) { this.annotations.toString(prefix, buffer); } this.modifiers.toString(this.getKind(), buffer); this.type.toString(prefix, buffer); buffer.append(' '); if (colors) { buffer.append(Console.ANSI_BLUE); buffer.append(this.name); buffer.append(Console.ANSI_RESET); } else { buffer.append(this.name); } Formatting.appendSeparator(buffer, "field.assignment", '='); if (this.value != null) { this.value.toString(prefix, buffer); } else { ObjectArray.toString(this.displayValue, buffer); } } }
package okapi; import okapi.service.ModuleManager; import okapi.web.TenantWebService; import io.vertx.core.AbstractVerticle; import io.vertx.core.Context; import io.vertx.core.Future; import io.vertx.core.Vertx; import io.vertx.core.http.HttpHeaders; import io.vertx.core.http.HttpMethod; import io.vertx.core.json.JsonObject; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; import io.vertx.ext.web.Router; import io.vertx.ext.web.RoutingContext; import io.vertx.ext.web.handler.BodyHandler; import io.vertx.ext.web.handler.CorsHandler; import java.lang.management.ManagementFactory; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import okapi.bean.Ports; import okapi.deployment.DeploymentManager; import okapi.web.HealthService; import okapi.service.ModuleStore; import okapi.web.ModuleWebService; import okapi.service.ProxyService; import okapi.service.TenantManager; import okapi.service.TenantStore; import okapi.service.TimeStampStore; import okapi.service.impl.ModuleStoreMemory; import okapi.service.impl.ModuleStoreMongo; import okapi.service.impl.MongoHandle; import okapi.service.impl.TenantStoreMemory; import okapi.service.impl.TenantStoreMongo; import okapi.service.impl.TimeStampMemory; import okapi.service.impl.TimeStampMongo; import okapi.util.LogHelper; import static okapi.util.HttpResponse.*; import okapi.deployment.DeploymentWebService; import okapi.discovery.DiscoveryManager; import okapi.discovery.DiscoveryService; public class MainVerticle extends AbstractVerticle { private final Logger logger = LoggerFactory.getLogger("okapi"); private final LogHelper logHelper = new LogHelper(); private int port; private int port_start; private int port_end; private String storage; MongoHandle mongo = null; HealthService healthService; ModuleManager moduleManager; ModuleWebService moduleWebService; ProxyService proxyService; TenantWebService tenantWebService; DeploymentWebService deploymentWebService; DiscoveryService discoveryService; DiscoveryManager discoveryManager; Ports ports; // Little helper to get a config value // First from System (-D on command line), // then from config (from the way the verticle gets deployed, e.g. in tests) // finally a default value static String conf(String key, String def, JsonObject c) { return System.getProperty(key, c.getString(key, def)); } @Override public void init(Vertx vertx, Context context) { super.init(vertx, context); JsonObject config = context.config(); port = Integer.parseInt(conf("port", "9130", config)); port_start = Integer.parseInt(conf("port_start", Integer.toString(port + 1), config)); port_end = Integer.parseInt(conf("port_end", Integer.toString(port_start + 10), config)); final String host = conf("host", "localhost", config); ports = new Ports(port_start, port_end); storage = conf("storage", "inmemory", config); String loglevel = conf("loglevel", "", config); if (!loglevel.isEmpty()) { logHelper.setRootLogLevel(loglevel); } healthService = new HealthService(); moduleManager = new ModuleManager(vertx); TenantStore tenantStore = null; TenantManager tman = new TenantManager(moduleManager); ModuleStore moduleStore = null; TimeStampStore timeStampStore = null; switch (storage) { case "mongo": mongo = new MongoHandle(vertx, config); moduleStore = new ModuleStoreMongo(mongo); timeStampStore = new TimeStampMongo(mongo); tenantStore = new TenantStoreMongo(mongo); break; case "inmemory": moduleStore = new ModuleStoreMemory(vertx); timeStampStore = new TimeStampMemory(vertx); tenantStore = new TenantStoreMemory(); break; default: logger.fatal("Unknown storage type '" + storage + "'"); System.exit(1); } moduleWebService = new ModuleWebService(vertx, moduleManager, moduleStore, timeStampStore); tenantWebService = new TenantWebService(vertx, tman, tenantStore); DeploymentManager dm = new DeploymentManager(vertx, host, ports); deploymentWebService = new DeploymentWebService(dm); discoveryManager = new DiscoveryManager(); discoveryService = new DiscoveryService(discoveryManager); proxyService = new ProxyService(vertx, moduleManager, tman, discoveryManager); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { CountDownLatch latch = new CountDownLatch(1); moduleManager.deleteAll(ar -> { latch.countDown(); }); try { if (!latch.await(2, TimeUnit.MINUTES)) { logger.error("Timed out waiting to undeploy all"); } } catch (InterruptedException e) { throw new IllegalStateException(e); } } }); } public void NotFound(RoutingContext ctx) { responseText(ctx, 404).end("Okapi: unrecognized service"); } @Override public void start(Future<Void> fut) { if (mongo != null && mongo.isTransient()) { mongo.dropDatabase(res -> { if (res.succeeded()) { startModules(fut); } else { logger.fatal("createHttpServer failed", res.cause()); fut.fail(res.cause()); } }); } else { startModules(fut); } } private void startModules(Future<Void> fut) { this.moduleWebService.loadModules(res -> { if (res.succeeded()) { startTenants(fut); } else { fut.fail(res.cause()); } }); } private void startTenants(Future<Void> fut) { this.tenantWebService.loadTenants(res -> { if (res.succeeded()) { startDiscovery(fut); } else { fut.fail(res.cause()); } }); } private void startDiscovery(Future<Void> fut) { this.discoveryManager.init(vertx, res -> { if (res.succeeded()) { startListening(fut); } else { fut.fail(res.cause()); } }); } private void startListening(Future<Void> fut) { Router router = Router.router(vertx); //handle CORS router.route().handler(CorsHandler.create("*") .allowedMethod(HttpMethod.PUT) .allowedMethod(HttpMethod.DELETE) .allowedMethod(HttpMethod.GET) .allowedMethod(HttpMethod.POST) //allow request headers .allowedHeader(HttpHeaders.CONTENT_TYPE.toString()) .allowedHeader("X-Okapi-Tenant") .allowedHeader("X-Okapi-Token") //expose response headers .exposedHeader(HttpHeaders.LOCATION.toString()) .exposedHeader("X-Okapi-Trace") .exposedHeader("X-Okapi-Token") ); // Paths that start with /_/ are okapi internal configuration router.route("/_*").handler(BodyHandler.create()); //enable reading body to string router.postWithRegex("/_/proxy/modules").handler(moduleWebService::create); router.delete("/_/proxy/modules/:id").handler(moduleWebService::delete); router.get("/_/proxy/modules/:id").handler(moduleWebService::get); router.getWithRegex("/_/proxy/modules").handler(moduleWebService::list); router.put("/_/proxy/modules/:id").handler(moduleWebService::update); router.postWithRegex("/_/proxy/tenants").handler(tenantWebService::create); router.getWithRegex("/_/proxy/tenants").handler(tenantWebService::list); router.get("/_/proxy/tenants/:id").handler(tenantWebService::get); router.put("/_/proxy/tenants/:id").handler(tenantWebService::update); router.delete("/_/proxy/tenants/:id").handler(tenantWebService::delete); router.post("/_/proxy/tenants/:id/modules").handler(tenantWebService::enableModule); router.delete("/_/proxy/tenants/:id/modules/:mod").handler(tenantWebService::disableModule); router.get("/_/proxy/tenants/:id/modules").handler(tenantWebService::listModules); router.get("/_/proxy/tenants/:id/modules/:mod").handler(tenantWebService::getModule); router.getWithRegex("/_/proxy/health").handler(healthService::get); // Endpoints for internal testing only. // The reload points can be removed as soon as we have a good integration // test that verifies that changes propagate across a cluster... router.getWithRegex("/_/test/reloadmodules").handler(moduleWebService::reloadModules); router.get("/_/test/reloadtenant/:id").handler(tenantWebService::reloadTenant); router.getWithRegex("/_/test/loglevel").handler(logHelper::getRootLogLevel); router.postWithRegex("/_/test/loglevel").handler(logHelper::setRootLogLevel); router.postWithRegex("/_/deployment/modules").handler(deploymentWebService::create); router.delete("/_/deployment/modules/:instid").handler(deploymentWebService::delete); router.getWithRegex("/_/deployment/modules").handler(deploymentWebService::list); router.get("/_/deployment/modules/:instid").handler(deploymentWebService::get); router.put("/_/deployment/modules/:instid").handler(deploymentWebService::update); router.postWithRegex("/_/discovery/modules").handler(discoveryService::create); router.delete("/_/discovery/modules/:srvcid/:instid").handler(discoveryService::delete); router.get("/_/discovery/modules/:srvcid/:instid").handler(discoveryService::get); router.get("/_/discovery/modules/:srvcid").handler(discoveryService::getSrvcId); router.getWithRegex("/_/discovery/modules").handler(discoveryService::getAll); router.route("/_*").handler(this::NotFound); //everything else gets proxified to modules
package cx2x.xcodeml.helper; import cx2x.xcodeml.exception.*; import cx2x.xcodeml.xnode.*; import exc.xcodeml.XcodeMLtools_Fmod; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.Transformer; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.*; import java.io.File; import java.util.ArrayList; import java.util.List; /** * The class XnodeUtil contains only static method to help manipulating the * raw Elements in the XcodeML representation by using the abstracted Xnode. * * @author clementval */ public class XnodeUtil { /** * Find a function definition according to a function call. * @param xcodeml The XcodeML program to search in. * @param fctCall The function call used to find the function definition. * @return A function definition element if found. Null otherwise. */ public static XfunctionDefinition findFunctionDefinition(XcodeProgram xcodeml, Xnode fctCall) { if(xcodeml.getElement() == null){ return null; } String name = fctCall.findNode(Xcode.NAME).getValue(); NodeList nList = xcodeml.getElement(). getElementsByTagName(Xname.F_FUNCTION_DEFINITION); for (int i = 0; i < nList.getLength(); i++) { Node fctDefNode = nList.item(i); if (fctDefNode.getNodeType() == Node.ELEMENT_NODE) { Xnode dummyFctDef = new Xnode((Element)fctDefNode); Xnode fctDefName = dummyFctDef.find(Xcode.NAME); if(name != null && fctDefName.getValue().toLowerCase().equals(name.toLowerCase())) { return new XfunctionDefinition(dummyFctDef.getElement()); } } } return null; } /** * Find a function definition in a module definition. * @param module Module definition in which we search for the function * definition. * @param name Name of the function to be found. * @return A function definition element if found. Null otherwise. */ public static XfunctionDefinition findFunctionDefinitionInModule( XmoduleDefinition module, String name) { if(module.getElement() == null){ return null; } NodeList nList = module.getElement(). getElementsByTagName(Xname.F_FUNCTION_DEFINITION); for (int i = 0; i < nList.getLength(); i++) { Node n = nList.item(i); if (n.getNodeType() == Node.ELEMENT_NODE) { XfunctionDefinition fctDef = new XfunctionDefinition((Element)n); if(fctDef.getName().getValue().equals(name)){ return fctDef; } } } return null; } /** * Find all array references elements in a given body and give var name. * @param parent The body element to search for the array references. * @param arrayName Name of the array for the array reference to be found. * @return A list of all array references found. */ public static List<Xnode> getAllArrayReferences(Xnode parent, String arrayName) { List<Xnode> references = new ArrayList<>(); NodeList nList = parent.getElement(). getElementsByTagName(Xname.F_ARRAY_REF); for (int i = 0; i < nList.getLength(); i++) { Node n = nList.item(i); if (n.getNodeType() == Node.ELEMENT_NODE) { Xnode ref = new Xnode((Element) n); Xnode var = ref.find(Xcode.VARREF, Xcode.VAR); if(var != null && var.getValue().toLowerCase(). equals(arrayName.toLowerCase())) { references.add(ref); } } } return references; } /** * Demote an array reference to a var reference. * @param ref The array reference to be modified. */ public static void demoteToScalar(Xnode ref){ Xnode var = ref.find(Xcode.VARREF, Xcode.VAR).cloneObject(); insertAfter(ref, var); ref.delete(); } /** * Demote an array reference to a reference with fewer dimensions. * @param ref The array reference to be modified. * @param keptDimensions List of dimensions to be kept. Dimension index starts * at 1. */ public static void demote(Xnode ref, List<Integer> keptDimensions){ for(int i = 1; i < ref.getChildren().size(); ++i){ if(!keptDimensions.contains(i)){ ref.getChild(i).delete(); } } } /** * Retrieve the index ranges of an array notation. * @param arrayRef The array reference statements to extract the ranges from. * @return A list if indexRanges elements. */ public static List<Xnode> getIdxRangesFromArrayRef(Xnode arrayRef){ List<Xnode> ranges = new ArrayList<>(); if(arrayRef.Opcode() != Xcode.FARRAYREF){ return ranges; } for(Xnode el : arrayRef.getChildren()){ if(el.Opcode() == Xcode.INDEXRANGE){ ranges.add(el); } } return ranges; } /** * Compare two list of indexRange. * @param list1 First list of indexRange. * @param list2 Second list of indexRange. * @return True if the indexRange at the same position in the two list are all * identical. False otherwise. */ public static boolean compareIndexRanges(List<Xnode> list1, List<Xnode> list2) { if(list1.size() != list2.size()){ return false; } for(int i = 0; i < list1.size(); ++i){ if(!isIndexRangeIdentical(list1.get(i), list2.get(i), true)){ return false; } } return true; } /** * <pre> * Intersect two sets of elements in XPath 1.0 * * This method use Xpath to select the correct nodes. Xpath 1.0 does not have * the intersect operator but only union. By using the Kaysian Method, we can * it is possible to express the intersection of two node sets. * * $set1[count(.|$set2)=count($set2)] * * </pre> * @param s1 First set of element. * @param s2 Second set of element. * @return Xpath query that performs the intersect operator between s1 and s2. */ private static String xPathIntersect(String s1, String s2){ return String.format("%s[count(.|%s)=count(%s)]", s1, s2, s2); } /** * <pre> * Find all assignment statement from a node until the end pragma. * * We intersect all assign statements which are next siblings of * the "from" element with all the assign statements which are previous * siblings of the ending pragma. * </pre> * * @param from The element from which the search is initiated. * @param endPragma Value of the end pragma. Search will be performed until * there. * @return A list of all assign statements found. List is empty if no * statements are found. */ public static List<Xnode> getArrayAssignInBlock(Xnode from, String endPragma){ /* Define all the assign element with array refs which are next siblings of * the "from" element */ String s1 = String.format( "following-sibling::%s[%s]", Xname.F_ASSIGN_STMT, Xname.F_ARRAY_REF ); /* Define all the assign element with array refs which are previous siblings * of the end pragma element */ String s2 = String.format( "following-sibling::%s[text()=\"%s\"]/preceding-sibling::%s[%s]", Xname.PRAGMA_STMT, endPragma, Xname.F_ASSIGN_STMT, Xname.F_ARRAY_REF ); // Use the Kaysian method to express the intersect operator String intersect = XnodeUtil.xPathIntersect(s1, s2); return getFromXpath(from, intersect); } /** * Get all array references in the siblings of the given element. * @param from Element to start from. * @param identifier Array name value. * @return List of all array references found. List is empty if nothing is * found. */ public static List<Xnode> getAllArrayReferencesInSiblings(Xnode from, String identifier) { String s1 = String.format("following-sibling::*//%s[%s[%s[text()=\"%s\"]]]", Xname.F_ARRAY_REF, Xname.VAR_REF, Xname.VAR, identifier ); return getFromXpath(from, s1); } /** * Get the first assignment statement for an array reference. * @param from Statement to look from. * @param arrayName Identifier of the array. * @return The assignment statement if found. Null otherwise. */ public static Xnode getFirstArrayAssign(Xnode from, String arrayName){ String s1 = String.format( "following::%s[%s[%s[%s[text()=\"%s\"]] and position()=1]]", Xname.F_ASSIGN_STMT, Xname.F_ARRAY_REF, Xname.VAR_REF, Xname.VAR, arrayName ); try { NodeList output = evaluateXpath(from.getElement(), s1); if(output.getLength() == 0){ return null; } Element assign = (Element) output.item(0); return new Xnode(assign); } catch (XPathExpressionException ignored) { return null; } } /** * Find all the nested do statement groups following the inductions iterations * define in inductionVars and being located between the "from" element and * the end pragma. * @param from Element from which the search is started. * @param endPragma End pragma that terminates the search block. * @param inductionVars Induction variables that define the nested group to * locates. * @return List of do statements elements (outer most loops for each nested * group) found between the "from" element and the end pragma. */ public static List<Xnode> findDoStatement(Xnode from, Xnode endPragma, List<String> inductionVars) { /* s1 is selecting all the nested do statement groups that meet the criteria * from the "from" element down to the end of the block. */ String s1 = "following::"; String dynamic_part_s1 = ""; for(int i = inductionVars.size() - 1; i >= 0; --i){ /* * Here is example of there xpath query format for 1,2 and 3 nested loops * * FdoStatement[Var[text()="induction_var"]] * * FdoStatement[Var[text()="induction_var"] and * body[FdoStatement[Var[text()="induction_var"]]] * * FdoStatement[Var[text()="induction_var"] and * body[FdoStatement[Var[text()="induction_var"] and * body[FdoStatement[Var[text()="induction_var"]]]] */ String tempQuery; if(i == inductionVars.size() - 1) { // first iteration tempQuery = String.format("%s[%s[text()=\"%s\"]]", Xname.F_DO_STATEMENT, Xname.VAR, inductionVars.get(i)); } else { tempQuery = String.format("%s[%s[text()=\"%s\"] and %s[%s]]", Xname.F_DO_STATEMENT, Xname.VAR, inductionVars.get(i), Xname.BODY, dynamic_part_s1); // Including previously formed xpath query } dynamic_part_s1 = tempQuery; } s1 = s1 + dynamic_part_s1; List<Xnode> doStatements = new ArrayList<>(); try { NodeList output = evaluateXpath(from.getElement(), s1); for (int i = 0; i < output.getLength(); i++) { Element el = (Element) output.item(i); Xnode doStmt = new Xnode(el); if(doStmt.getLineNo() != 0 && doStmt.getLineNo() < endPragma.getLineNo()) { doStatements.add(doStmt); } } } catch (XPathExpressionException ignored) { } return doStatements; } /** * Evaluates an Xpath expression and return its result as a NodeList. * @param from Element to start the evaluation. * @param xpath Xpath expression. * @return Result of evaluation as a NodeList. * @throws XPathExpressionException if evaluation fails. */ private static NodeList evaluateXpath(Element from, String xpath) throws XPathExpressionException { XPathExpression ex = XPathFactory.newInstance().newXPath().compile(xpath); return (NodeList)ex.evaluate(from, XPathConstants.NODESET); } /** * Find all array references in the next children that match the given * criteria. * * This methods use powerful Xpath expression to locate the correct nodes in * the AST * * Here is an example of such a query that return all node that are array * references for the array "array6" with an offset of 0 -1 * * //FarrayRef[varRef[Var[text()="array6"]] and arrayIndex and * arrayIndex[minusExpr[Var and FintConstant[text()="1"]]]] * * @param from The element from which the search is initiated. * @param identifier Identifier of the array. * @param offsets List of offsets to be search for. * @return A list of all array references found. */ public static List<Xnode> getAllArrayReferencesByOffsets(Xnode from, String identifier, List<Integer> offsets) { String offsetXpath = ""; for (int i = 0; i < offsets.size(); ++i){ if(offsets.get(i) == 0){ offsetXpath += String.format("%s[position()=%s and %s]", Xname.ARRAY_INDEX, i+1, Xname.VAR ); } else if(offsets.get(i) > 0) { offsetXpath += String.format("%s[position()=%s and %s[%s and %s[text()=\"%s\"]]]", Xname.ARRAY_INDEX, i+1, Xname.MINUS_EXPR, Xname.VAR, Xname.F_INT_CONST, offsets.get(i)); } else { offsetXpath += String.format("%s[position()=%s and %s[%s and %s[text()=\"%s\"]]]", Xname.ARRAY_INDEX, i+1, Xname.MINUS_EXPR, Xname.VAR, Xname.F_INT_CONST, Math.abs(offsets.get(i))); } if(i != offsets.size()-1){ offsetXpath += " and "; } } // Start of the Xpath query String xpathQuery = String.format(".//%s[%s[%s[text()=\"%s\"]] and %s]", Xname.F_ARRAY_REF, Xname.VAR_REF, Xname.VAR, identifier, offsetXpath ); return getFromXpath(from, xpathQuery); } /** * Find a pragma element in the previous nodes containing a given keyword. * @param from Element to start from. * @param keyword Keyword to be found in the pragma. * @return The pragma if found. Null otherwise. */ public static Xnode findPreviousPragma(Xnode from, String keyword) { if (from == null || from.getElement() == null) { return null; } Node prev = from.getElement().getPreviousSibling(); Node parent = from.getElement(); do { while (prev != null) { if (prev.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) prev; if (element.getTagName().equals(Xcode.FPRAGMASTATEMENT.code()) && element.getTextContent().toLowerCase(). contains(keyword.toLowerCase())) { return new Xnode(element); } } prev = prev.getPreviousSibling(); } parent = parent.getParentNode(); prev = parent; } while (parent != null); return null; } /** * Find all the index elements (arrayIndex and indexRange) in an element. * @param parent Root element to search from. * @return A list of all index ranges found. */ public static List<Xnode> findIndexes(Xnode parent){ List<Xnode> indexRanges = new ArrayList<>(); if(parent == null || parent.getElement() == null){ return indexRanges; } Node node = parent.getElement().getFirstChild(); while (node != null){ if(node.getNodeType() == Node.ELEMENT_NODE){ Element element = (Element)node; switch (element.getTagName()){ case Xname.ARRAY_INDEX: case Xname.INDEX_RANGE: indexRanges.add(new Xnode(element)); break; } } node = node.getNextSibling(); } return indexRanges; } /** * Find all the name elements in an element. * @param parent Root element to search from. * @return A list of all name elements found. */ public static List<Xnode> findAllNames(Xnode parent){ return findAll(Xcode.NAME, parent); } /** * Find all the var elements that are real references to a variable. Var * element nested in an arrayIndex element are excluded. * @param parent Root element to search from. * @return A list of all var elements found. */ public static List<Xnode> findAllReferences(Xnode parent){ List<Xnode> vars = findAll(Xcode.VAR, parent); List<Xnode> realReferences = new ArrayList<>(); for(Xnode var : vars){ if(!((Element)var.getElement().getParentNode()).getTagName(). equals(Xcode.ARRAYINDEX.code())) { realReferences.add(var); } } return realReferences; } /** * Find all the var elements that are real references to a variable. Var * element nested in an arrayIndex element are excluded. * @param parent Root element to search from. * @param id Identifier of the var to be found. * @return A list of all var elements found. */ public static List<Xnode> findAllReferences(Xnode parent, String id){ List<Xnode> vars = findAll(Xcode.VAR, parent); List<Xnode> realReferences = new ArrayList<>(); for(Xnode var : vars){ if(!((Element)var.getElement().getParentNode()).getTagName(). equals(Xcode.ARRAYINDEX.code()) && var.getValue().toLowerCase().equals(id.toLowerCase())) { realReferences.add(var); } } return realReferences; } /** * Find all the pragma element in an XcodeML tree. * @param xcodeml The XcodeML program to search in. * @return A list of all pragmas found in the XcodeML program. */ public static List<Xnode> findAllPragmas(XcodeProgram xcodeml){ NodeList pragmaList = xcodeml.getDocument() .getElementsByTagName(Xcode.FPRAGMASTATEMENT.code()); List<Xnode> pragmas = new ArrayList<>(); for (int i = 0; i < pragmaList.getLength(); i++) { Node pragmaNode = pragmaList.item(i); if (pragmaNode.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) pragmaNode; pragmas.add(new Xnode(element)); } } return pragmas; } /** * Extract the body of a do statement and place it directly after it. * @param loop The do statement containing the body to be extracted. */ public static void extractBody(Xnode loop){ extractBody(loop, loop); } /** * Extract the body of a do statement and place it after the reference node. * @param loop The do statement containing the body to be extracted. * @param ref Element after which statement are shifted. */ public static void extractBody(Xnode loop, Xnode ref){ Element loopElement = loop.getElement(); Element body = XnodeUtil.findFirstElement(loopElement, Xname.BODY); if(body == null){ return; } Node refNode = ref.getElement(); for(Node childNode = body.getFirstChild(); childNode!=null;){ Node nextChild = childNode.getNextSibling(); // Do something with childNode, including move or delete... if(childNode.getNodeType() == Node.ELEMENT_NODE){ insertAfter(refNode, childNode); refNode = childNode; } childNode = nextChild; } } /** * Delete an element for the tree. * @param element Element to be deleted. */ public static void delete(Element element){ if(element == null || element.getParentNode() == null){ return; } element.getParentNode().removeChild(element); } /** * Write the XcodeML to file or std out * @param xcodeml The XcodeML to write in the output * @param outputFile Path of the output file or null to output on std out * @param indent Number of spaces used for the indentation * @return true if the output could be write without problems. */ public static boolean writeXcodeML(XcodeProgram xcodeml, String outputFile, @SuppressWarnings("SameParameterValue") int indent) { try { XnodeUtil.cleanEmptyTextNodes(xcodeml.getDocument()); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty( "{http://xml.apache.org/xslt}indent-amount", Integer.toString(indent)); DOMSource source = new DOMSource(xcodeml.getDocument()); if(outputFile == null){ // Output to console StreamResult console = new StreamResult(System.out); transformer.transform(source, console); } else { // Output to file StreamResult console = new StreamResult(new File(outputFile)); transformer.transform(source, console); } } catch (TransformerConfigurationException ex){ xcodeml.addError("Cannot output file: " + ex.getMessage(), 0); return false; } catch (TransformerException ex){ xcodeml.addError("Cannot output file: " + ex.getMessage(), 0); return false; } return true; } /** * Removes text nodes that only contains whitespace. The conditions for * removing text nodes, besides only containing whitespace, are: If the * parent node has at least one child of any of the following types, all * whitespace-only text-node children will be removed: - ELEMENT child - * CDATA child - COMMENT child. * @param parentNode Root node to start the cleaning. */ private static void cleanEmptyTextNodes(Node parentNode) { boolean removeEmptyTextNodes = false; Node childNode = parentNode.getFirstChild(); while (childNode != null) { removeEmptyTextNodes |= checkNodeTypes(childNode); childNode = childNode.getNextSibling(); } if (removeEmptyTextNodes) { removeEmptyTextNodes(parentNode); } } /* * PRIVATE SECTION */ /** * Remove all empty text nodes in the subtree. * @param parentNode Root node to start the search. */ private static void removeEmptyTextNodes(Node parentNode) { Node childNode = parentNode.getFirstChild(); while (childNode != null) { // grab the "nextSibling" before the child node is removed Node nextChild = childNode.getNextSibling(); short nodeType = childNode.getNodeType(); if (nodeType == Node.TEXT_NODE) { boolean containsOnlyWhitespace = childNode.getNodeValue() .trim().isEmpty(); if (containsOnlyWhitespace) { parentNode.removeChild(childNode); } } childNode = nextChild; } } /** * Check the type of the given node. * @param childNode Node to be checked. * @return True if the node contains data. False otherwise. */ private static boolean checkNodeTypes(Node childNode) { short nodeType = childNode.getNodeType(); if (nodeType == Node.ELEMENT_NODE) { cleanEmptyTextNodes(childNode); // recurse into subtree } return nodeType == Node.ELEMENT_NODE || nodeType == Node.CDATA_SECTION_NODE || nodeType == Node.COMMENT_NODE; } /** * Insert a node directly after a reference node. * @param refNode The reference node. New node will be inserted after this * one. * @param newNode The new node to be inserted. */ private static void insertAfter(Node refNode, Node newNode){ refNode.getParentNode().insertBefore(newNode, refNode.getNextSibling()); } /** * Find the first element with tag corresponding to elementName nested under * the parent element. * @param parent The root element to search from. * @param elementName The tag of the element to search for. * @return The first element found under parent with the corresponding tag. * Null if no element is found. */ private static Element findFirstElement(Element parent, String elementName){ NodeList elements = parent.getElementsByTagName(elementName); if(elements.getLength() == 0){ return null; } return (Element) elements.item(0); } /** * Find the first element with tag corresponding to elementName in the direct * children of the parent element. * @param parent The root element to search from. * @param elementName The tag of the element to search for. * @return The first element found in the direct children of the element * parent with the corresponding tag. Null if no element is found. */ private static Element findFirstChildElement(Element parent, String elementName){ NodeList nodeList = parent.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { Node nextNode = nodeList.item(i); if(nextNode.getNodeType() == Node.ELEMENT_NODE){ Element element = (Element) nextNode; if(element.getTagName().equals(elementName)){ return element; } } } return null; } /** * Get the depth of an element in the AST. * @param element XML element for which the depth is computed. * @return A depth value greater or equal to 0. */ private static int getDepth(Element element){ Node parent = element.getParentNode(); int depth = 0; while(parent != null && parent.getNodeType() == Node.ELEMENT_NODE) { ++depth; parent = parent.getParentNode(); } return depth; } /** * Shift all statements from the first siblings of the "from" element until * the "until" element (not included). * @param from Start element for the swifting. * @param until End element for the swifting. * @param targetBody Body element in which statements are inserted. */ public static void shiftStatementsInBody(Xnode from, Xnode until, Xnode targetBody) { Node currentSibling = from.getElement().getNextSibling(); Node firstStatementInBody = targetBody.getElement().getFirstChild(); while(currentSibling != null && currentSibling != until.getElement()){ Node nextSibling = currentSibling.getNextSibling(); targetBody.getElement().insertBefore(currentSibling, firstStatementInBody); currentSibling = nextSibling; } } /** * Copy the whole body element into the destination one. Destination is * overwritten. * @param from The body to be copied. * @param to The destination of the copied body. */ public static void copyBody(Xnode from, Xnode to){ Node copiedBody = from.cloneNode(); if(to.getBody() != null){ to.getBody().delete(); } to.getElement().appendChild(copiedBody); } /** * Check whether the given type is a built-in type or is a type defined in the * type table. * @param type Type to check. * @return True if the type is built-in. False otherwise. */ public static boolean isBuiltInType(String type){ switch (type){ case Xname.TYPE_F_CHAR: case Xname.TYPE_F_COMPLEX: case Xname.TYPE_F_INT: case Xname.TYPE_F_LOGICAL: case Xname.TYPE_F_REAL: case Xname.TYPE_F_VOID: return true; default: return false; } } /* XNODE SECTION */ /** * Find module definition element in which the child is included if any. * @param from The child element to search from. * @return A XmoduleDefinition object if found. Null otherwise. */ public static XmoduleDefinition findParentModule(Xnode from) { Xnode moduleDef = findParent(Xcode.FMODULEDEFINITION, from); if(moduleDef == null){ return null; } return new XmoduleDefinition(moduleDef.getElement()); } /** * Find function definition in the ancestor of the give element. * @param from Element to start search from. * @return The function definition found. Null if nothing found. */ public static XfunctionDefinition findParentFunction(Xnode from){ Xnode fctDef = findParent(Xcode.FFUNCTIONDEFINITION, from); if(fctDef == null){ return null; } return new XfunctionDefinition(fctDef.getElement()); } /** * Find element of the the given type that is directly after the given from * element. * @param opcode Code of the element to be found. * @param from Element to start the search from. * @return The element found. Null if no element is found. */ public static Xnode findDirectNext(Xcode opcode, Xnode from) { if(from == null){ return null; } Node nextNode = from.getElement().getNextSibling(); while (nextNode != null){ if(nextNode.getNodeType() == Node.ELEMENT_NODE){ Element element = (Element) nextNode; if(element.getTagName().equals(opcode.code())){ return new Xnode(element); } return null; } nextNode = nextNode.getNextSibling(); } return null; } /** * Delete all the elements between the two given elements. * @param start The start element. Deletion start from next element. * @param end The end element. Deletion end just before this element. */ public static void deleteBetween(Xnode start, Xnode end){ List<Element> toDelete = new ArrayList<>(); Node node = start.getElement().getNextSibling(); while (node != null && node != end.getElement()){ if(node.getNodeType() == Node.ELEMENT_NODE){ Element element = (Element)node; toDelete.add(element); } node = node.getNextSibling(); } for(Element e : toDelete){ delete(e); } } /** * Insert an element just after a reference element. * @param refElement The reference element. * @param element The element to be inserted. */ public static void insertAfter(Xnode refElement, Xnode element){ XnodeUtil.insertAfter(refElement.getElement(), element.getElement()); } /** * Find the first element with tag corresponding to elementName. * @param opcode The XcodeML code of the element to search for. * @param parent The root element to search from. * @param any If true, find in any nested element under parent. If false, * only direct children are search for. * @return first element found. Null if no element is found. */ public static Xnode find(Xcode opcode, Xnode parent, boolean any){ Element el; if(any){ el = findFirstElement(parent.getElement(), opcode.code()); } else { el = findFirstChildElement(parent.getElement(), opcode.code()); } return (el == null) ? null : new Xnode(el); } /** * Find element of the the given type that is directly after the given from * element. * @param opcode Code of the element to be found. * @param from Element to start the search from. * @return The element found. Null if no element is found. */ public static Xnode findNext(Xcode opcode, Xnode from) { return findInDirection(opcode, from, true); } /** * Find an element in the ancestor of the given element. * @param opcode Code of the element to be found. * @param from Element to start the search from. * @return The element found. Null if nothing found. */ public static Xnode findParent(Xcode opcode, Xnode from){ return findInDirection(opcode, from, false); } /** * Find an element either in the next siblings or in the ancestors. * @param opcode Code of the element to be found. * @param from Element to start the search from. * @param down If True, search in the siblings. If false, search in the * ancestors. * @return The element found. Null if nothing found. */ private static Xnode findInDirection(Xcode opcode, Xnode from, boolean down){ if(from == null){ return null; } Node nextNode = down ? from.getElement().getNextSibling() : from.getElement().getParentNode(); while(nextNode != null){ if (nextNode.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) nextNode; if(element.getTagName().equals(opcode.code())){ return new Xnode(element); } } nextNode = down ? nextNode.getNextSibling() : nextNode.getParentNode(); } return null; } public static void appendBody(Xnode originalBody, Xnode extraBody) throws IllegalTransformationException { if(originalBody == null || originalBody.getElement() == null || extraBody == null || extraBody.getElement() == null || originalBody.Opcode() != Xcode.BODY || extraBody.Opcode() != Xcode.BODY) { throw new IllegalTransformationException("One of the body is null."); } // Append content of loop-body (loop) to this loop-body Node childNode = extraBody.getElement().getFirstChild(); while(childNode != null){ Node nextChild = childNode.getNextSibling(); // Do something with childNode, including move or delete... if(childNode.getNodeType() == Node.ELEMENT_NODE){ originalBody.getElement().appendChild(childNode); } childNode = nextChild; } } /** * Check if the two element are direct children of the same parent element. * @param e1 First element. * @param e2 Second element. * @return True if the two element are direct children of the same parent. * False otherwise. */ public static boolean hasSameParentBlock(Xnode e1, Xnode e2) { return !(e1 == null || e2 == null || e1.getElement() == null || e2.getElement() == null) && e1.getElement().getParentNode() == e2.getElement().getParentNode(); } /** Compare the iteration range of two do statements. * @param e1 First do statement. * @param e2 Second do statement. * @param withLowerBound Compare lower bound or not. * @return True if the iteration range are identical. */ private static boolean compareIndexRanges(Xnode e1, Xnode e2, boolean withLowerBound) { // The two nodes must be do statement if (e1.Opcode() != Xcode.FDOSTATEMENT || e2.Opcode() != Xcode.FDOSTATEMENT) { return false; } Xnode inductionVar1 = XnodeUtil.find(Xcode.VAR, e1, false); Xnode inductionVar2 = XnodeUtil.find(Xcode.VAR, e2, false); Xnode indexRange1 = XnodeUtil.find(Xcode.INDEXRANGE, e1, false); Xnode indexRange2 = XnodeUtil.find(Xcode.INDEXRANGE, e2, false); return compareValues(inductionVar1, inductionVar2) && isIndexRangeIdentical(indexRange1, indexRange2, withLowerBound); } /** * Compare the iteration range of two do statements. * @param e1 First do statement. * @param e2 Second do statement. * @return True if the iteration range are identical. */ public static boolean hasSameIndexRange(Xnode e1, Xnode e2) { return compareIndexRanges(e1, e2, true); } /** * Compare the iteration range of two do statements. * @param e1 First do statement. * @param e2 Second do statement. * @return True if the iteration range are identical besides the lower bound. */ public static boolean hasSameIndexRangeBesidesLower(Xnode e1, Xnode e2) { return compareIndexRanges(e1, e2, false); } /** * Compare the inner values of two nodes. * @param n1 First node. * @param n2 Second node. * @return True if the values are identical. False otherwise. */ private static boolean compareValues(Xnode n1, Xnode n2) { return !(n1 == null || n2 == null) && n1.getValue().toLowerCase().equals(n2.getValue().toLowerCase()); } /** * Compare the inner value of the first child of two nodes. * @param n1 First node. * @param n2 Second node. * @return True if the value are identical. False otherwise. */ private static boolean compareFirstChildValues(Xnode n1, Xnode n2) { if(n1 == null || n2 == null){ return false; } Xnode c1 = n1.getChild(0); Xnode c2 = n2.getChild(0); return compareValues(c1, c2); } /** * Compare the inner values of two optional nodes. * @param n1 First node. * @param n2 Second node. * @return True if the values are identical or elements are null. False * otherwise. */ private static boolean compareOptionalValues(Xnode n1, Xnode n2){ return n1 == null && n2 == null || (n1 != null && n2 != null && n1.getValue().toLowerCase().equals(n2.getValue().toLowerCase())); } /** * Compare the iteration range of two do statements * @param idx1 First do statement. * @param idx2 Second do statement. * @param withLowerBound If true, compare lower bound. If false, lower bound * is not compared. * @return True if the index range are identical. */ private static boolean isIndexRangeIdentical(Xnode idx1, Xnode idx2, boolean withLowerBound) { if (idx1.Opcode() != Xcode.INDEXRANGE || idx2.Opcode() != Xcode.INDEXRANGE) { return false; } if (idx1.getBooleanAttribute(Xattr.IS_ASSUMED_SHAPE) && idx2.getBooleanAttribute(Xattr.IS_ASSUMED_SHAPE)) { return true; } Xnode low1 = idx1.find(Xcode.LOWERBOUND); Xnode up1 = idx1.find(Xcode.UPPERBOUND); Xnode low2 = idx2.find(Xcode.LOWERBOUND); Xnode up2 = idx2.find(Xcode.UPPERBOUND); Xnode s1 = idx1.find(Xcode.STEP); Xnode s2 = idx2.find(Xcode.STEP); if (s1 != null) { s1 = s1.getChild(0); } if (s2 != null) { s2 = s2.getChild(0); } if(withLowerBound){ return compareFirstChildValues(low1, low2) && compareFirstChildValues(up1, up2) && compareOptionalValues(s1, s2); } else { return compareFirstChildValues(up1, up2) && compareOptionalValues(s1, s2); } } public static void swapIterationRange(Xnode e1, Xnode e2) throws IllegalTransformationException { // The two nodes must be do statement if(e1.Opcode() != Xcode.FDOSTATEMENT || e2.Opcode() != Xcode.FDOSTATEMENT){ return; } Xnode inductionVar1 = XnodeUtil.find(Xcode.VAR, e1, false); Xnode inductionVar2 = XnodeUtil.find(Xcode.VAR, e2, false); Xnode indexRange1 = XnodeUtil.find(Xcode.INDEXRANGE, e1, false); Xnode indexRange2 = XnodeUtil.find(Xcode.INDEXRANGE, e2, false); if(inductionVar1 == null || inductionVar2 == null || indexRange1 == null || indexRange2 == null) { throw new IllegalTransformationException("Induction variable or index " + "range missing."); } Xnode low1 = indexRange1.find(Xcode.LOWERBOUND).getChild(0); Xnode up1 = indexRange1.find(Xcode.UPPERBOUND).getChild(0); Xnode s1 = indexRange1.find(Xcode.STEP).getChild(0); Xnode low2 = indexRange2.find(Xcode.LOWERBOUND).getChild(0); Xnode up2 = indexRange2.find(Xcode.UPPERBOUND).getChild(0); Xnode s2 = indexRange2.find(Xcode.STEP).getChild(0); // Set the range of loop2 to loop1 XnodeUtil.insertAfter(inductionVar2, inductionVar1.cloneObject()); XnodeUtil.insertAfter(low2, low1.cloneObject()); XnodeUtil.insertAfter(up2, up1.cloneObject()); XnodeUtil.insertAfter(s2, s1.cloneObject()); XnodeUtil.insertAfter(inductionVar1, inductionVar2.cloneObject()); XnodeUtil.insertAfter(low1, low2.cloneObject()); XnodeUtil.insertAfter(up1, up2.cloneObject()); XnodeUtil.insertAfter(s1, s2.cloneObject()); inductionVar1.delete(); inductionVar2.delete(); low1.delete(); up1.delete(); s1.delete(); low2.delete(); up2.delete(); s2.delete(); } /** * Get the depth of an element in the AST. * @param element The element for which the depth is computed. * @return A depth value greater or equal to 0. */ public static int getDepth(Xnode element) { if(element == null || element.getElement() == null){ return -1; } return getDepth(element.getElement()); } /** * Copy the enhanced information from an element to a target element. * Enhanced information include line number and original file name. * @param base Base element to copy information from. * @param target Target element to copy information to. */ public static void copyEnhancedInfo(Xnode base, Xnode target) { target.setLine(base.getLineNo()); target.setFile(base.getFile()); } /** * Insert an element just before a reference element. * @param ref The reference element. * @param insert The element to be inserted. */ public static void insertBefore(Xnode ref, Xnode insert){ ref.getElement().getParentNode().insertBefore(insert.getElement(), ref.getElement()); } public static Xnode createVar(String type, String value, @SuppressWarnings("SameParameterValue") Xscope scope, XcodeProgram xcodeml) { Xnode var = new Xnode(Xcode.VAR, xcodeml); var.setAttribute(Xattr.TYPE, type); var.setAttribute(Xattr.SCOPE, scope.toString()); var.setValue(value); return var; } /** * Get a list of T elements from an xpath query executed from the * given element. * @param from Element to start from. * @param query XPath query to be executed. * @return List of all array references found. List is empty if nothing is * found. */ private static List<Xnode> getFromXpath(Xnode from, String query) { List<Xnode> elements = new ArrayList<>(); try { XPathExpression ex = XPathFactory.newInstance().newXPath().compile(query); NodeList output = (NodeList) ex.evaluate(from.getElement(), XPathConstants.NODESET); for (int i = 0; i < output.getLength(); i++) { Element element = (Element) output.item(i); elements.add(new Xnode(element)); } } catch (XPathExpressionException ignored) { } return elements; } /** * Find specific argument in a function call. * @param value Value of the argument to be found. * @param fctCall Function call to search from. * @return The argument if found. Null otherwise. */ public static Xnode findArg(String value, Xnode fctCall){ if(fctCall.Opcode() != Xcode.FUNCTIONCALL) { return null; } Xnode args = fctCall.find(Xcode.ARGUMENTS); if(args == null){ return null; } for(Xnode arg : args.getChildren()){ if(value.toLowerCase().equals(arg.getValue().toLowerCase())){ return arg; } } return null; } /** * Find all elements of a given type in the subtree. * @param opcode Type of the element to be found. * @param parent Root of the subtree. * @return List of all elements found in the subtree. */ public static List<Xnode> findAll(Xcode opcode, Xnode parent) { List<Xnode> elements = new ArrayList<>(); if(parent == null) { return elements; } NodeList nodes = parent.getElement().getElementsByTagName(opcode.code()); for (int i = 0; i < nodes.getLength(); i++) { Node n = nodes.item(i); if (n.getNodeType() == Node.ELEMENT_NODE) { elements.add(new Xnode((Element)n)); } } return elements; } /** * Create a new FunctionCall element with elements name and arguments as * children. * @param xcodeml The current XcodeML program unit in which the elements * are created. * @param returnType Value of the type attribute for the functionCall element. * @param name Value of the name element. * @param nameType Value of the type attribute for the name element. * @return The newly created element. */ public static Xnode createFctCall(XcodeProgram xcodeml, String returnType, String name, String nameType){ Xnode fctCall = new Xnode(Xcode.FUNCTIONCALL, xcodeml); fctCall.setAttribute(Xattr.TYPE, returnType); Xnode fctName = new Xnode(Xcode.NAME, xcodeml); fctName.setValue(name); fctName.setAttribute(Xattr.TYPE, nameType); Xnode args = new Xnode(Xcode.ARGUMENTS, xcodeml); fctCall.appendToChildren(fctName, false); fctCall.appendToChildren(args, false); return fctCall; } /** * Create a new FarrayRef element with varRef element as a child with the * given Var element. * @param xcodeml The current XcodeML program unit in which the elements * are created. * @param type Value of the type attribute for the FarrayRef element. * @param var Var element nested in the varRef element. * @return The newly created element. */ public static Xnode createArrayRef(XcodeProgram xcodeml, XbasicType type, Xnode var) { Xnode ref = new Xnode(Xcode.FARRAYREF, xcodeml); ref.setAttribute(Xattr.TYPE, type.getRef()); Xnode varRef = new Xnode(Xcode.VARREF, xcodeml); varRef.setAttribute(Xattr.TYPE, type.getType()); varRef.appendToChildren(var, false); ref.appendToChildren(varRef, false); return ref; } /** * Create a new Id element with all the underlying needed elements. * @param xcodeml The current XcodeML program unit in which the elements * are created. * @param type Value for the attribute type. * @param sclass Value for the attribute sclass. * @param nameValue Value of the name inner element. * @return The newly created element. */ public static Xid createId(XcodeProgram xcodeml, String type, String sclass, String nameValue) { Xnode id = new Xnode(Xcode.ID, xcodeml); Xnode internalName = new Xnode(Xcode.NAME, xcodeml); internalName.setValue(nameValue); id.appendToChildren(internalName, false); id.setAttribute(Xattr.TYPE, type); id.setAttribute(Xattr.SCLASS, sclass); return new Xid(id.getElement()); } /** * Constructs a new basicType element with the given information. * @param xcodeml The current XcodeML file unit in which the elements * are created. * @param type Type hash. * @param ref Reference type. * @param intent Optional intent information. * @return The newly created element. */ public static XbasicType createBasicType(XcodeML xcodeml, String type, String ref, Xintent intent) { Xnode bt = new Xnode(Xcode.FBASICTYPE, xcodeml); bt.setAttribute(Xattr.TYPE, type); if(ref != null) { bt.setAttribute(Xattr.REF, ref); } if(intent != null) { bt.setAttribute(Xattr.INTENT, intent.toString()); } return new XbasicType(bt.getElement()); } /** * Create a new XvarDecl object with all the underlying elements. * @param xcodeml The current XcodeML file unit in which the elements * are created. * @param nameType Value for the attribute type of the name element. * @param nameValue Value of the name inner element. * @return The newly created element. */ public static XvarDecl createVarDecl(XcodeML xcodeml, String nameType, String nameValue) { Xnode varD = new Xnode(Xcode.VARDECL, xcodeml); Xnode internalName = new Xnode(Xcode.NAME, xcodeml); internalName.setValue(nameValue); internalName.setAttribute(Xattr.TYPE, nameType); varD.appendToChildren(internalName, false); return new XvarDecl(varD.getElement()); } /** * Constructs a new name element with name value and optional type. * @param xcodeml Current XcodeML file unit in which the element is * created. * @param name Name value. * @param type Optional type value. * @return The newly created element. */ public static Xnode createName(XcodeML xcodeml, String name, String type) { Xnode n = new Xnode(Xcode.NAME, xcodeml); n.setValue(name); if(type != null){ n.setAttribute(Xattr.TYPE, type); } return n; } /** * Create an empty assumed shape indexRange element. * @param xcodeml Current XcodeML file unit in which the element is * created. * @return The newly created element. */ public static Xnode createEmptyAssumedShaped(XcodeML xcodeml) { Xnode range = new Xnode(Xcode.INDEXRANGE, xcodeml); range.setAttribute(Xattr.IS_ASSUMED_SHAPE, Xname.TRUE); return range; } /** * Create an indexRange element to loop over an assumed shape array. * @param xcodeml Current XcodeML file unit in which the element is * created. * @param arrayVar Var element representing the array variable. * @param startIndex Lower bound index value. * @param dimension Dimension index for the upper bound value. * @return The newly created element. */ public static Xnode createAssumedShapeRange(XcodeML xcodeml, Xnode arrayVar, int startIndex, int dimension) { // Base structure Xnode indexRange = new Xnode(Xcode.INDEXRANGE, xcodeml); Xnode lower = new Xnode(Xcode.LOWERBOUND, xcodeml); Xnode upper = new Xnode(Xcode.UPPERBOUND, xcodeml); indexRange.appendToChildren(lower, false); indexRange.appendToChildren(upper, false); // Lower bound Xnode lowerBound = new Xnode(Xcode.FINTCONSTANT, xcodeml); lowerBound.setValue(String.valueOf(startIndex)); lower.appendToChildren(lowerBound, false); // Upper bound Xnode fctCall = new Xnode(Xcode.FUNCTIONCALL, xcodeml); upper.appendToChildren(fctCall, false); fctCall.setAttribute(Xattr.IS_INTRINSIC, Xname.TRUE); fctCall.setAttribute(Xattr.TYPE, Xname.TYPE_F_INT); Xnode name = new Xnode(Xcode.NAME, xcodeml); name.setValue(Xname.INTRINSIC_SIZE); fctCall.appendToChildren(name, false); Xnode args = new Xnode(Xcode.ARGUMENTS, xcodeml); fctCall.appendToChildren(args, false); args.appendToChildren(arrayVar, true); Xnode dim = new Xnode(Xcode.FINTCONSTANT, xcodeml); dim.setValue(String.valueOf(dimension)); args.appendToChildren(dim, false); return indexRange; } /** * Create a new FifStatement element with an empty then body. * @param xcodeml Current XcodeML file unit in which the element is * created. * @return The newly created element. */ public static Xnode createIfThen(XcodeML xcodeml){ Xnode root = new Xnode(Xcode.FIFSTATEMENT, xcodeml); Xnode cond = new Xnode(Xcode.CONDITION, xcodeml); Xnode thenBlock = new Xnode(Xcode.THEN, xcodeml); Xnode thenBody = new Xnode(Xcode.BODY, xcodeml); thenBlock.appendToChildren(thenBody, false); root.appendToChildren(cond, false); root.appendToChildren(thenBlock, false); return root; } /** * Create a new FdoStatement element with an empty body. * @param xcodeml Current XcodeML file unit in which the element is * created. * @param inductionVar Var element for the induction variable. * @param indexRange indexRange element for the iteration range. * @return The newly created element. */ public static Xnode createDoStmt(XcodeML xcodeml, Xnode inductionVar, Xnode indexRange) { Xnode root = new Xnode(Xcode.FDOSTATEMENT, xcodeml); root.appendToChildren(inductionVar, false); root.appendToChildren(indexRange, false); Xnode body = new Xnode(Xcode.BODY, xcodeml); root.appendToChildren(body, false); return root; } /** * Find module containing the function and read its .xmod file. * @param fctDef Function definition nested in the module. * @return Xmod object if the module has been found and read. Null otherwise. */ public static Xmod findContainingModule(XfunctionDefinition fctDef){ XmoduleDefinition mod = findParentModule(fctDef); if(mod == null){ return null; } String modName = mod.getAttribute(Xattr.NAME); for(String dir : XcodeMLtools_Fmod.getSearchPath()){ String path = dir + "/" + modName + ".xmod"; File f = new File(path); if(f.exists()){ Document doc = readXmlFile(path); return doc != null ? new Xmod(doc, path) : null; } } return null; } /** * Read XML file. * @param input Xml file path. * @return Document if the XML file could be read. Null otherwise. */ public static Document readXmlFile(String input){ try { File fXmlFile = new File(input); if(!fXmlFile.exists()){ return null; } DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(fXmlFile); doc.getDocumentElement().normalize(); return doc; } catch(Exception ignored){} return null; } }
package cx2x.xcodeml.helper; import cx2x.translator.common.ClawConstant; import cx2x.xcodeml.exception.IllegalTransformationException; import cx2x.xcodeml.xnode.*; import exc.xcodeml.XcodeMLtools_Fmod; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import java.io.File; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * The class XnodeUtil contains only static method to help manipulating the * raw Elements in the XcodeML representation by using the abstracted Xnode. * * @author clementval */ public class XnodeUtil { public static final String XMOD_FILE_EXTENSION = ".xmod"; /** * Find all array references elements in a given body and give var name. * * @param parent The body element to search for the array references. * @param arrayName Name of the array for the array reference to be found. * @return A list of all array references found. */ public static List<Xnode> getAllArrayReferences(Xnode parent, String arrayName) { List<Xnode> references = new ArrayList<>(); NodeList nList = parent.element(). getElementsByTagName(Xname.F_ARRAY_REF); for(int i = 0; i < nList.getLength(); i++) { Node n = nList.item(i); if(n.getNodeType() == Node.ELEMENT_NODE) { Xnode ref = new Xnode((Element) n); Xnode var = ref.matchSeq(Xcode.VARREF, Xcode.VAR); if(var != null && var.value().equals(arrayName.toLowerCase())) { references.add(ref); } } } return references; } /** * Find all var references elements in a given body and give var name. * * @param parent The body element to search for the array references. * @param varName Name of the var for the reference to be found. * @return A list of all references found. */ public static List<Xnode> getAllVarReferences(Xnode parent, String varName) { List<Xnode> references = new ArrayList<>(); NodeList nList = parent.element().getElementsByTagName(Xname.VAR); for(int i = 0; i < nList.getLength(); i++) { Node n = nList.item(i); if(n.getNodeType() == Node.ELEMENT_NODE) { Xnode var = new Xnode((Element) n); if(var.value().equals(varName.toLowerCase())) { references.add(var); } } } return references; } /** * Demote an array reference to a var reference. * * @param ref The array reference to be modified. */ public static void demoteToScalar(Xnode ref) { Xnode var = ref.matchSeq(Xcode.VARREF, Xcode.VAR).cloneNode(); ref.insertAfter(var); ref.delete(); } /** * Demote an array reference to a reference with fewer dimensions. * * @param ref The array reference to be modified. * @param keptDimensions List of dimensions to be kept. Dimension index starts * at 1. */ public static void demote(Xnode ref, List<Integer> keptDimensions) { for(int i = 1; i < ref.children().size(); ++i) { if(!keptDimensions.contains(i)) { ref.child(i).delete(); } } } /** * Retrieve the index ranges of an array notation. * * @param arrayRef The array reference statements to extract the ranges from. * @return A list if indexRanges elements. */ public static List<Xnode> getIdxRangesFromArrayRef(Xnode arrayRef) { List<Xnode> ranges = new ArrayList<>(); if(arrayRef.opcode() != Xcode.FARRAYREF) { return ranges; } for(Xnode el : arrayRef.children()) { if(el.opcode() == Xcode.INDEXRANGE) { ranges.add(el); } } return ranges; } /** * Compare two list of indexRange. * * @param list1 First list of indexRange. * @param list2 Second list of indexRange. * @return True if the indexRange at the same position in the two list are all * identical. False otherwise. */ public static boolean compareIndexRanges(List<Xnode> list1, List<Xnode> list2) { if(list1.size() != list2.size()) { return false; } for(int i = 0; i < list1.size(); ++i) { if(!isIndexRangeIdentical(list1.get(i), list2.get(i), true)) { return false; } } return true; } /** * <pre> * Intersect two sets of elements in XPath 1.0 * * This method use Xpath to select the correct nodes. Xpath 1.0 does not have * the intersect operator but only union. By using the Kaysian Method, we can * it is possible to express the intersection of two node sets. * * $set1[count(.|$set2)=count($set2)] * * </pre> * * @param s1 First set of element. * @param s2 Second set of element. * @return Xpath query that performs the intersect operator between s1 and s2. */ private static String xPathIntersect(String s1, String s2) { return String.format("%s[count(.|%s)=count(%s)]", s1, s2, s2); } /** * <pre> * Find all assignment statement from a node until the end pragma. * * We intersect all assign statements which are next siblings of * the "from" element with all the assign statements which are previous * siblings of the ending pragma. * </pre> * * @param from The element from which the search is initiated. * @param endPragma Value of the end pragma. Search will be performed until * there. * @return A list of all assign statements found. List is empty if no * statements are found. */ public static List<Xnode> getArrayAssignInBlock(Xnode from, String endPragma) { /* Define all the assign element with array refs which are next siblings of * the "from" element */ String s1 = String.format( "following-sibling::%s[%s]", Xname.F_ASSIGN_STATEMENT, Xname.F_ARRAY_REF ); /* Define all the assign element with array refs which are previous siblings * of the end pragma element */ String s2 = String.format( "following-sibling::%s[text()=\"%s\"]/preceding-sibling::%s[%s]", Xname.F_PRAGMA_STMT, endPragma, Xname.F_ASSIGN_STATEMENT, Xname.F_ARRAY_REF ); // Use the Kaysian method to express the intersect operator String intersect = XnodeUtil.xPathIntersect(s1, s2); return getFromXpath(from, intersect); } /** * Get all array references in the siblings of the given element. * * @param from Element to start from. * @param identifier Array name value. * @return List of all array references found. List is empty if nothing is * found. */ public static List<Xnode> getAllArrayReferencesInSiblings(Xnode from, String identifier) { String s1 = String.format("following-sibling::*//%s[%s[%s[text()=\"%s\"]]]", Xname.F_ARRAY_REF, Xname.VAR_REF, Xname.VAR, identifier ); return getFromXpath(from, s1); } /** * Get the first assignment statement for an array reference. * * @param from Statement to look from. * @param arrayName Identifier of the array. * @return The assignment statement if found. Null otherwise. */ public static Xnode getFirstArrayAssign(Xnode from, String arrayName) { String s1 = String.format( "following::%s[%s[%s[%s[text()=\"%s\"]] and position()=1]]", Xname.F_ASSIGN_STATEMENT, Xname.F_ARRAY_REF, Xname.VAR_REF, Xname.VAR, arrayName ); try { NodeList output = evaluateXpath(from.element(), s1); if(output.getLength() == 0) { return null; } Element assign = (Element) output.item(0); return new Xnode(assign); } catch(XPathExpressionException ignored) { return null; } } /** * Find all the nested do statement groups following the inductions iterations * define in inductionVars and being located between the "from" element and * the end pragma. * * @param from Element from which the search is started. * @param endPragma End pragma that terminates the search block. * @param inductionVars Induction variables that define the nested group to * locates. * @return List of do statements elements (outer most loops for each nested * group) found between the "from" element and the end pragma. */ public static List<Xnode> findDoStatement(Xnode from, Xnode endPragma, List<String> inductionVars) { /* s1 is selecting all the nested do statement groups that meet the criteria * from the "from" element down to the end of the block. */ String s1 = "following::"; String dynamic_part_s1 = ""; for(int i = inductionVars.size() - 1; i >= 0; --i) { /* * Here is example of there xpath query format for 1,2 and 3 nested loops * * FdoStatement[Var[text()="induction_var"]] * * FdoStatement[Var[text()="induction_var"] and * body[FdoStatement[Var[text()="induction_var"]]] * * FdoStatement[Var[text()="induction_var"] and * body[FdoStatement[Var[text()="induction_var"] and * body[FdoStatement[Var[text()="induction_var"]]]] */ String tempQuery; if(i == inductionVars.size() - 1) { // first iteration tempQuery = String.format("%s[%s[text()=\"%s\"]]", Xname.F_DO_STATEMENT, Xname.VAR, inductionVars.get(i)); } else { tempQuery = String.format("%s[%s[text()=\"%s\"] and %s[%s]]", Xname.F_DO_STATEMENT, Xname.VAR, inductionVars.get(i), Xname.BODY, dynamic_part_s1); // Including previously formed xpath query } dynamic_part_s1 = tempQuery; } s1 = s1 + dynamic_part_s1; List<Xnode> doStatements = new ArrayList<>(); try { NodeList output = evaluateXpath(from.element(), s1); for(int i = 0; i < output.getLength(); i++) { Element el = (Element) output.item(i); Xnode doStmt = new Xnode(el); if(doStmt.lineNo() != 0 && doStmt.lineNo() < endPragma.lineNo()) { doStatements.add(doStmt); } } } catch(XPathExpressionException ignored) { } return doStatements; } /** * Evaluates an Xpath expression and return its result as a NodeList. * * @param from Element to start the evaluation. * @param xpath Xpath expression. * @return Result of evaluation as a NodeList. * @throws XPathExpressionException if evaluation fails. */ private static NodeList evaluateXpath(Element from, String xpath) throws XPathExpressionException { XPathExpression ex = XPathFactory.newInstance().newXPath().compile(xpath); return (NodeList) ex.evaluate(from, XPathConstants.NODESET); } /** * Find all array references in the next children that match the given * criteria. * <p> * This methods use powerful Xpath expression to locate the correct nodes in * the AST * <p> * Here is an example of such a query that return all node that are array * references for the array "array6" with an offset of 0 -1 * <p> * //FarrayRef[varRef[Var[text()="array6"]] and arrayIndex and * arrayIndex[minusExpr[Var and FintConstant[text()="1"]]]] * * @param from The element from which the search is initiated. * @param identifier Identifier of the array. * @param offsets List of offsets to be search for. * @return A list of all array references found. */ public static List<Xnode> getAllArrayReferencesByOffsets(Xnode from, String identifier, List<Integer> offsets) { StringBuilder offsetXpath = new StringBuilder(); for(int i = 0; i < offsets.size(); ++i) { if(offsets.get(i) == 0) { offsetXpath.append(String.format("%s[position()=%s and %s]", Xname.ARRAY_INDEX, i + 1, Xname.VAR )); } else if(offsets.get(i) > 0) { offsetXpath.append(String.format("%s[position()=%s and %s[%s and %s[text()=\"%s\"]]]", Xname.ARRAY_INDEX, i + 1, Xname.MINUS_EXPR, Xname.VAR, Xname.F_INT_CONST, offsets.get(i))); } else { offsetXpath.append(String.format("%s[position()=%s and %s[%s and %s[text()=\"%s\"]]]", Xname.ARRAY_INDEX, i + 1, Xname.MINUS_EXPR, Xname.VAR, Xname.F_INT_CONST, Math.abs(offsets.get(i)))); } if(i != offsets.size() - 1) { offsetXpath.append(" and "); } } // Start of the Xpath query String xpathQuery = String.format(".//%s[%s[%s[text()=\"%s\"]] and %s]", Xname.F_ARRAY_REF, Xname.VAR_REF, Xname.VAR, identifier, offsetXpath.toString() ); return getFromXpath(from, xpathQuery); } /** * Find a pragma element in the previous nodes containing a given keyword. * * @param from Element to start from. * @param keyword Keyword to be found in the pragma. * @return The pragma if found. Null otherwise. */ public static Xnode findPreviousPragma(Xnode from, String keyword) { if(from == null || from.element() == null) { return null; } Node prev = from.element().getPreviousSibling(); Node parent = from.element(); do { while(prev != null) { if(prev.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) prev; if(element.getTagName().equals(Xcode.FPRAGMASTATEMENT.code()) && element.getTextContent().toLowerCase(). contains(keyword.toLowerCase())) { return new Xnode(element); } } prev = prev.getPreviousSibling(); } parent = parent.getParentNode(); prev = parent; } while(parent != null); return null; } /** * Find all the index elements (arrayIndex and indexRange) in an element. * * @param parent Root element to search from. * @return A list of all index ranges found. */ public static List<Xnode> findIndexes(Xnode parent) { List<Xnode> indexRanges = new ArrayList<>(); if(parent == null || parent.element() == null) { return indexRanges; } Node node = parent.element().getFirstChild(); while(node != null) { if(node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) node; switch(element.getTagName()) { case Xname.ARRAY_INDEX: case Xname.INDEX_RANGE: indexRanges.add(new Xnode(element)); break; } } node = node.getNextSibling(); } return indexRanges; } /** * Find all the var elements that are real references to a variable. Var * element nested in an arrayIndex element are excluded. * * @param parent Root element to search from. * @return A list of all var elements found. */ public static List<Xnode> findAllReferences(Xnode parent) { List<Xnode> vars = parent.matchAll(Xcode.VAR); List<Xnode> realReferences = new ArrayList<>(); for(Xnode var : vars) { if(!((Element) var.element().getParentNode()).getTagName(). equals(Xcode.ARRAYINDEX.code())) { realReferences.add(var); } } return realReferences; } /** * Get all the variables names from a list of var elements. * * @param nodes List containing var element. * @return A set of all variable's name. */ public static Set<String> getNamesFromReferences(List<Xnode> nodes) { Set<String> names = new HashSet<>(); for(Xnode node : nodes) { if(node.opcode() != Xcode.VAR) { continue; } names.add(node.value()); } return names; } /** * Find all the var elements that are real references to a variable. Var * element nested in an arrayIndex element are excluded. * * @param parent Root element to search from. * @param id Identifier of the var to be found. * @return A list of all var elements found. */ public static List<Xnode> findAllReferences(Xnode parent, String id) { List<Xnode> vars = parent.matchAll(Xcode.VAR); List<Xnode> realReferences = new ArrayList<>(); for(Xnode var : vars) { if(!((Element) var.element().getParentNode()).getTagName(). equals(Xcode.ARRAYINDEX.code()) && var.value().equals(id.toLowerCase())) { realReferences.add(var); } } return realReferences; } /** * Extract the body of a do statement and place it after the reference node. * * @param loop The do statement containing the body to be extracted. * @param ref Element after which statement are shifted. */ public static void extractBody(Xnode loop, Xnode ref) { if(loop.opcode() != Xcode.FDOSTATEMENT) { return; } Xnode body = loop.body(); if(body == null) { return; } Xnode refNode = ref; for(Xnode child : body.children()) { refNode.insertAfter(child); refNode = child; } } /** * Extract the body of a do statement and place it directly after it. * * @param loop The do statement containing the body to be extracted. */ public static void extractBody(Xnode loop) { extractBody(loop, loop); } /** * Extract the body of the inner do statement and place it directly after the * outer do statement. * * @param nest Nest do statement group. */ public static void extractBody(NestedDoStatement nest) { extractBody(nest.getInnerStatement(), nest.getOuterStatement()); } /** * Check whether the index of an arrayIndex element is an induction variable * given in the list. * * @param arrayIndex arrayIndex to be checked. * @param inductionVariables List of potential induction variables. * @return True if the arrayIndex uses a var from induction variables list. * False in any other cases. */ public static boolean isInductionIndex(Xnode arrayIndex, List<String> inductionVariables) { if(arrayIndex == null || arrayIndex.opcode() != Xcode.ARRAYINDEX || inductionVariables == null || inductionVariables.isEmpty()) { return false; } Xnode var = arrayIndex.matchDirectDescendant(Xcode.VAR); return var != null && inductionVariables.contains(var.value()); } /** * Shift all statements from the first siblings of the "from" element until * the "until" element (not included). * * @param from Start element for the swifting. * @param until End element for the swifting. * @param targetBody Body element in which statements are inserted. */ public static void shiftStatementsInBody(Xnode from, Xnode until, Xnode targetBody, boolean included) { Node currentSibling = from.element(); if(!included) { currentSibling = from.element().getNextSibling(); } Node firstStatementInBody = targetBody.element().getFirstChild(); while(currentSibling != null && currentSibling != until.element()) { Node nextSibling = currentSibling.getNextSibling(); targetBody.element().insertBefore(currentSibling, firstStatementInBody); currentSibling = nextSibling; } if(included && currentSibling == until.element()) { targetBody.element().insertBefore(currentSibling, firstStatementInBody); } } /** * Copy the whole body element into the destination one. Destination is * overwritten. * * @param from The body to be copied. * @param to The destination of the copied body. */ public static void copyBody(Xnode from, Xnode to) { Node copiedBody = from.cloneRawNode(); if(to.body() != null) { to.body().delete(); } to.element().appendChild(copiedBody); } /** * Get given statements in the subtree. * * @param root Root of the subtree. * @param statements List of statements to look for. * @return List of statement found. */ public static List<Xnode> getStatements(Xnode root, List<Xcode> statements) { List<Xnode> unsupportedStatements = new ArrayList<>(); if(root == null) { return unsupportedStatements; } for(Xcode opcode : statements) { unsupportedStatements.addAll(root.matchAll(opcode)); } return unsupportedStatements; } /** * Get given statements in between from and to included. * * @param from Node from. * @param to Node to. * @param statements List of statements to look for. * @return List of statement found. */ public static List<Xnode> getStatements(Xnode from, Xnode to, List<Xcode> statements) { List<Xnode> unsupportedStatements = new ArrayList<>(); Xnode crt = from; while(crt != null && crt.element() != to.element()) { if(statements.contains(crt.opcode())) { unsupportedStatements.add(crt); } unsupportedStatements.addAll(getStatements(crt, statements)); crt = crt.nextSibling(); } return unsupportedStatements; } /** * Check whether the given type is a built-in type or is a type defined in the * type table. * * @param type Type to check. * @return True if the type is built-in. False otherwise. */ public static boolean isBuiltInType(String type) { switch(type) { case Xname.TYPE_F_CHAR: case Xname.TYPE_F_COMPLEX: case Xname.TYPE_F_INT: case Xname.TYPE_F_LOGICAL: case Xname.TYPE_F_REAL: case Xname.TYPE_F_VOID: return true; default: return false; } } /* XNODE SECTION */ /** * Find function definition in the ancestor of the give element. * * @param from Element to start search from. * @return The function definition found. Null if nothing found. */ public static XfunctionDefinition findParentFunction(Xnode from) { if(from == null) { return null; } Xnode fctDef = from.matchAncestor(Xcode.FFUNCTIONDEFINITION); if(fctDef == null) { return null; } return new XfunctionDefinition(fctDef.element()); } /** * Delete all the elements between the two given elements. * * @param start The start element. Deletion start from next element. * @param end The end element. Deletion end just before this element. */ public static void deleteBetween(Xnode start, Xnode end) { List<Xnode> toDelete = new ArrayList<>(); Xnode node = start.nextSibling(); while(node != null && node.element() != end.element()) { toDelete.add(node); node = node.nextSibling(); } for(Xnode n : toDelete) { n.delete(); } } public static void appendBody(Xnode originalBody, Xnode extraBody) throws IllegalTransformationException { if(originalBody == null || originalBody.element() == null || extraBody == null || extraBody.element() == null || originalBody.opcode() != Xcode.BODY || extraBody.opcode() != Xcode.BODY) { throw new IllegalTransformationException("One of the body is null."); } // Append content of loop-body (loop) to this loop-body Node childNode = extraBody.element().getFirstChild(); while(childNode != null) { Node nextChild = childNode.getNextSibling(); // Do something with childNode, including move or delete... if(childNode.getNodeType() == Node.ELEMENT_NODE) { originalBody.element().appendChild(childNode); } childNode = nextChild; } } /** * Check if the two element are direct children of the same parent element. * * @param e1 First element. * @param e2 Second element. * @return True if the two element are direct children of the same parent. * False otherwise. */ public static boolean hasSameParentBlock(Xnode e1, Xnode e2) { return !(e1 == null || e2 == null || e1.element() == null || e2.element() == null) && e1.element().getParentNode() == e2.element().getParentNode(); } /** * Compare the iteration range of two do statements. * * @param e1 First do statement. * @param e2 Second do statement. * @param withLowerBound Compare lower bound or not. * @return True if the iteration range are identical. */ private static boolean compareIndexRanges(Xnode e1, Xnode e2, boolean withLowerBound) { // The two nodes must be do statement if(e1.opcode() != Xcode.FDOSTATEMENT || e2.opcode() != Xcode.FDOSTATEMENT) { return false; } Xnode inductionVar1 = e1.matchDirectDescendant(Xcode.VAR); Xnode inductionVar2 = e2.matchDirectDescendant(Xcode.VAR); Xnode indexRange1 = e1.matchDirectDescendant(Xcode.INDEXRANGE); Xnode indexRange2 = e2.matchDirectDescendant(Xcode.INDEXRANGE); return compareValues(inductionVar1, inductionVar2) && isIndexRangeIdentical(indexRange1, indexRange2, withLowerBound); } /** * Compare the iteration range of two do statements. * * @param e1 First do statement. * @param e2 Second do statement. * @return True if the iteration range are identical. */ public static boolean hasSameIndexRange(Xnode e1, Xnode e2) { return compareIndexRanges(e1, e2, true); } /** * Compare the iteration range of two do statements. * * @param e1 First do statement. * @param e2 Second do statement. * @return True if the iteration range are identical besides the lower bound. */ public static boolean hasSameIndexRangeBesidesLower(Xnode e1, Xnode e2) { return compareIndexRanges(e1, e2, false); } /** * Compare the inner values of two nodes. * * @param n1 First node. * @param n2 Second node. * @return True if the values are identical. False otherwise. */ private static boolean compareValues(Xnode n1, Xnode n2) { return !(n1 == null || n2 == null) && n1.value().equals(n2.value()); } /** * Compare the inner value of the first child of two nodes. * * @param n1 First node. * @param n2 Second node. * @return True if the value are identical. False otherwise. */ private static boolean compareFirstChildValues(Xnode n1, Xnode n2) { if(n1 == null || n2 == null) { return false; } Xnode c1 = n1.child(0); Xnode c2 = n2.child(0); return compareValues(c1, c2); } /** * Compare the inner values of two optional nodes. * * @param n1 First node. * @param n2 Second node. * @return True if the values are identical or elements are null. False * otherwise. */ private static boolean compareOptionalValues(Xnode n1, Xnode n2) { return n1 == null && n2 == null || (n1 != null && n2 != null && n1.value().toLowerCase().equals(n2.value())); } /** * Compare the iteration range of two do statements * * @param idx1 First do statement. * @param idx2 Second do statement. * @param withLowerBound If true, compare lower bound. If false, lower bound * is not compared. * @return True if the index range are identical. */ private static boolean isIndexRangeIdentical(Xnode idx1, Xnode idx2, boolean withLowerBound) { if(idx1.opcode() != Xcode.INDEXRANGE || idx2.opcode() != Xcode.INDEXRANGE) { return false; } if(idx1.getBooleanAttribute(Xattr.IS_ASSUMED_SHAPE) && idx2.getBooleanAttribute(Xattr.IS_ASSUMED_SHAPE)) { return true; } Xnode low1 = idx1.matchSeq(Xcode.LOWERBOUND); Xnode up1 = idx1.matchSeq(Xcode.UPPERBOUND); Xnode low2 = idx2.matchSeq(Xcode.LOWERBOUND); Xnode up2 = idx2.matchSeq(Xcode.UPPERBOUND); Xnode s1 = idx1.matchSeq(Xcode.STEP); Xnode s2 = idx2.matchSeq(Xcode.STEP); if(s1 != null) { s1 = s1.child(0); } if(s2 != null) { s2 = s2.child(0); } if(withLowerBound) { return compareFirstChildValues(low1, low2) && compareFirstChildValues(up1, up2) && compareOptionalValues(s1, s2); } else { return compareFirstChildValues(up1, up2) && compareOptionalValues(s1, s2); } } public static void swapIterationRange(Xnode e1, Xnode e2) throws IllegalTransformationException { // The two nodes must be do statement if(e1.opcode() != Xcode.FDOSTATEMENT || e2.opcode() != Xcode.FDOSTATEMENT) { return; } Xnode inductionVar1 = e1.matchDirectDescendant(Xcode.VAR); Xnode inductionVar2 = e2.matchDirectDescendant(Xcode.VAR); Xnode indexRange1 = e1.matchDirectDescendant(Xcode.INDEXRANGE); Xnode indexRange2 = e2.matchDirectDescendant(Xcode.INDEXRANGE); if(inductionVar1 == null || inductionVar2 == null || indexRange1 == null || indexRange2 == null) { throw new IllegalTransformationException("Induction variable or index " + "range missing."); } Xnode low1 = indexRange1.matchSeq(Xcode.LOWERBOUND).child(0); Xnode up1 = indexRange1.matchSeq(Xcode.UPPERBOUND).child(0); Xnode s1 = indexRange1.matchSeq(Xcode.STEP).child(0); Xnode low2 = indexRange2.matchSeq(Xcode.LOWERBOUND).child(0); Xnode up2 = indexRange2.matchSeq(Xcode.UPPERBOUND).child(0); Xnode s2 = indexRange2.matchSeq(Xcode.STEP).child(0); // Set the range of loop2 to loop1 inductionVar2.insertAfter(inductionVar1.cloneNode()); low2.insertAfter(low1.cloneNode()); up2.insertAfter(up1.cloneNode()); s2.insertAfter(s1.cloneNode()); inductionVar1.insertAfter(inductionVar2.cloneNode()); low1.insertAfter(low2.cloneNode()); up1.insertAfter(up2.cloneNode()); s1.insertAfter(s2.cloneNode()); inductionVar1.delete(); inductionVar2.delete(); low1.delete(); up1.delete(); s1.delete(); low2.delete(); up2.delete(); s2.delete(); } /** * Copy the enhanced information from an element to a target element. * Enhanced information include line number and original file name. * * @param base Base element to copy information from. * @param target Target element to copy information to. */ public static void copyEnhancedInfo(Xnode base, Xnode target) { target.setLine(base.lineNo()); target.setFilename(base.filename()); } /** * Get a list of T elements from an xpath query executed from the * given element. * * @param from Element to start from. * @param query XPath query to be executed. * @return List of all array references found. List is empty if nothing is * found. */ private static List<Xnode> getFromXpath(Xnode from, String query) { List<Xnode> elements = new ArrayList<>(); try { XPathExpression ex = XPathFactory.newInstance().newXPath().compile(query); NodeList output = (NodeList) ex.evaluate(from.element(), XPathConstants.NODESET); for(int i = 0; i < output.getLength(); i++) { Element element = (Element) output.item(i); elements.add(new Xnode(element)); } } catch(XPathExpressionException ignored) { } return elements; } /** * Find specific argument in a function call. * * @param value Value of the argument to be found. * @param fctCall Function call to search from. * @return The argument if found. Null otherwise. */ public static Xnode findArg(String value, Xnode fctCall) { if(fctCall.opcode() != Xcode.FUNCTIONCALL) { return null; } Xnode args = fctCall.matchSeq(Xcode.ARGUMENTS); if(args == null) { return null; } for(Xnode arg : args.children()) { if(value.toLowerCase().equals(arg.value())) { return arg; } } return null; } /** * Find module by name. * * @param moduleName Name of the module. * @return Module object if found. Null otherwise. */ public static Xmod findModule(String moduleName) { for(String dir : XcodeMLtools_Fmod.getSearchPath()) { String path = dir + "/" + moduleName + XMOD_FILE_EXTENSION; File f = new File(path); if(f.exists()) { Document doc = readXmlFile(path); return doc != null ? new Xmod(doc, moduleName, dir) : null; } } return null; } /** * Read XML file. * * @param input Xml file path. * @return Document if the XML file could be read. Null otherwise. */ public static Document readXmlFile(String input) { try { File fXmlFile = new File(input); if(!fXmlFile.exists()) { return null; } DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(fXmlFile); doc.getDocumentElement().normalize(); return doc; } catch(Exception ignored) { } return null; } public static Xnode duplicateBound(Xnode baseBound, XcodeML xcodemlDst, XcodeML xcodemlSrc) throws IllegalTransformationException { if(baseBound.opcode() != Xcode.LOWERBOUND && baseBound.opcode() != Xcode.UPPERBOUND) { throw new IllegalTransformationException("Cannot duplicate bound"); } if(xcodemlSrc == xcodemlDst) { return baseBound.cloneNode(); } Xnode boundChild = baseBound.child(0); if(boundChild == null) { throw new IllegalTransformationException("Cannot duplicate bound as it " + "has no children element"); } Xnode bound = xcodemlDst.createNode(baseBound.opcode()); if(boundChild.opcode() == Xcode.FINTCONSTANT || boundChild.opcode() == Xcode.VAR) { bound.append(xcodemlDst.importConstOrVar(boundChild, xcodemlSrc)); } else if(boundChild.opcode() == Xcode.PLUSEXPR) { Xnode lhs = boundChild.child(0); Xnode rhs = boundChild.child(1); Xnode plusExpr = xcodemlDst.createNode(Xcode.PLUSEXPR); bound.append(plusExpr); plusExpr.append(xcodemlDst.importConstOrVar(lhs, xcodemlSrc)); plusExpr.append(xcodemlDst.importConstOrVar(rhs, xcodemlSrc)); } else { throw new IllegalTransformationException( String.format("Lower/upper bound type currently not supported (%s)", boundChild.opcode().toString()) ); } return bound; } /** * Delete all sibling elements from the start element included. * * @param start Element to start from. */ public static void deleteFrom(Xnode start) { List<Xnode> toDelete = new ArrayList<>(); toDelete.add(start); Xnode sibling = start.nextSibling(); while(sibling != null) { toDelete.add(sibling); sibling = sibling.nextSibling(); } for(Xnode n : toDelete) { n.delete(); } } /** * Delete a node in the ast. * * @param node Node to be deleted. */ public static void safeDelete(Xnode node) { if(node != null) { node.delete(); } } /** * Clean up extra pragma that have no more sense after transformation. * * @param node Do statement that will be removed. * @param previous List of pragma to be removed before the do statement. * @param next List of pragmas to be removed after the do statement. */ public static void cleanPragmas(Xnode node, String[] previous, String[] next) { if(node.opcode() != Xcode.FDOSTATEMENT) { return; } Xnode doStatement = node; while(node.prevSibling() != null && node.prevSibling().opcode() == Xcode.FPRAGMASTATEMENT) { String pragma = node.prevSibling().value(); Xnode toDelete = null; for(String p : previous) { if(!pragma.startsWith(ClawConstant.CLAW) && pragma.contains(p)) { toDelete = node.prevSibling(); break; } } node = node.prevSibling(); safeDelete(toDelete); } node = doStatement; // Reset node to the initial position. while(node.nextSibling() != null && node.nextSibling().opcode() == Xcode.FPRAGMASTATEMENT) { String pragma = node.nextSibling().value(); Xnode toDelete = null; for(String n : next) { if(!pragma.startsWith(ClawConstant.CLAW) && pragma.contains(n)) { toDelete = node.nextSibling(); break; } } node = node.nextSibling(); safeDelete(toDelete); } } /** * Remove the "pure" attribute from the function type. Issue a warning. * * @param fctDef Function definition node where the pure attribute must be * removed. * @param fctType Function type node where the pure attribute must be * removed. * @return True if the PURE specifier had to be removed false otherwise. */ public static boolean removePure(Xnode fctDef, Xnode fctType) { if(fctType.opcode() != Xcode.FFUNCTIONTYPE || fctDef.opcode() != Xcode.FFUNCTIONDEFINITION) { return false; } if(fctType.getBooleanAttribute(Xattr.IS_PURE)) { fctType.element().removeAttribute(Xattr.IS_PURE.toString()); return true; } return false; } /** * Check whether the end node is a direct sibling of the start node. If other * nodes are between the two nodes and their opcode is not listed in the * skippedNodes list, the nodes are not direct siblings. * * @param start First node in the tree. * @param end Node to be check to be a direct sibling. * @param skippedNodes List of opcode that are allowed between the two nodes. * @return True if the nodes are direct siblings. */ public static boolean isDirectSibling(Xnode start, Xnode end, List<Xcode> skippedNodes) { if(start == null || end == null) { return false; } Xnode nextSibling = start.nextSibling(); while(nextSibling != null) { if(nextSibling.equals(end)) { return true; } if(skippedNodes.contains(nextSibling.opcode())) { nextSibling = nextSibling.nextSibling(); } else { return false; } } return false; } /** * Return the directive prefix. * * @param pragma The pragma node. * @return Directive prefix if any. Empty string otherwise. */ public static String getPragmaPrefix(Xnode pragma) { if(pragma == null || pragma.opcode() != Xcode.FPRAGMASTATEMENT || pragma.value().isEmpty()) { return ""; } if(!pragma.value().contains(" ")) { return pragma.value(); } return pragma.value().substring(0, pragma.value().indexOf(" ")); } /** * Get the string representation of the induction variable of a do statement. * * @param doStatement Do statement to extract the induction variable. * @return The string value of the induction variable. Empty string if the * passed Xnode is not a FdoStatement element. */ public static String extractInductionVariable(Xnode doStatement) { if(doStatement.opcode() != Xcode.FDOSTATEMENT) { return ""; } return doStatement.matchDirectDescendant(Xcode.VAR).value(); } /** * Split a long pragma into chunk depending on the maxColumns sepcified. * The split is done on spaces or commas. * * @param fullPragma The original full pragma value. * @param maxColumns Maximum number of columns. This length take into * account the added prefix and continuation symbol. * @param pragmaPrefix Prefix used by the pragma. * @return A list of chunks from the original pragma. */ public static List<String> splitByLength(String fullPragma, int maxColumns, String pragmaPrefix) { List<String> splittedPragmas = new ArrayList<>(); fullPragma = fullPragma.toLowerCase(); if(fullPragma.length() > maxColumns) { fullPragma = XnodeUtil.dropEndingComment(fullPragma); int addLength = pragmaPrefix.length() + 5; // "!$<prefix> PRAGMA &" while(fullPragma.length() > (maxColumns - addLength)) { int splitIndex = fullPragma.substring(0, maxColumns - addLength).lastIndexOf(" "); // Cannot cut as it should. Take first possible cutting point. if(splitIndex == -1) { splitIndex = fullPragma.substring(0, maxColumns - addLength).lastIndexOf(","); if(splitIndex == -1) { splitIndex = (fullPragma.contains(" ")) ? fullPragma.lastIndexOf(" ") : (fullPragma.contains(",")) ? fullPragma.lastIndexOf(",") : fullPragma.length(); } } String splittedPragma = fullPragma.substring(0, splitIndex); fullPragma = fullPragma.substring(splitIndex, fullPragma.length()).trim(); splittedPragmas.add(splittedPragma); } } if(fullPragma.length() > 0) { splittedPragmas.add(fullPragma); } return splittedPragmas; } /** * Remove any trailing comment from a pragma string. * * @param pragma Original pragma string. * @return Pragma string without the trailing comment if any. */ public static String dropEndingComment(String pragma) { if(pragma != null && pragma.indexOf("!") > 0) { return pragma.substring(0, pragma.indexOf("!")).trim(); } return pragma; } /** * Gather arguments of a function call. * * @param xcodeml Current XcodeML translation unit. * @param fctCall functionCall node in which the arguments are retrieved. * @param intent Intent to use for gathering. * @param arrayOnly If true, gather only arrays arguments. * @return List of arguments as their string representation. */ public static List<String> gatherArguments(XcodeProgram xcodeml, Xnode fctCall, Xintent intent, boolean arrayOnly) { List<String> gatheredArguments = new ArrayList<>(); if(fctCall == null || fctCall.opcode() != Xcode.FUNCTIONCALL) { return gatheredArguments; } Xnode argumentsNode = fctCall.matchDescendant(Xcode.ARGUMENTS); if(argumentsNode == null) { return gatheredArguments; } // Retrieve function type to check intents and types of parameters XfunctionType fctType = (XfunctionType) xcodeml.getTypeTable().get(fctCall); List<Xnode> parameters = fctType.getParams().getAll(); List<Xnode> arguments = argumentsNode.children(); for(int i = 0; i < parameters.size(); ++i) { // TODO handle optional arguments, named value args Xnode parameter = parameters.get(i); Xnode arg = arguments.get(i); Xtype typeParameter = xcodeml.getTypeTable().get(parameter); Xtype typeArg = xcodeml.getTypeTable().get(arg); String rep = ""; if(isBuiltInType(arg.getType()) && !arrayOnly && typeParameter instanceof XbasicType) { XbasicType btParameter = (XbasicType) typeParameter; if(!intent.isCompatible(btParameter.getIntent())) { continue; } rep = arg.constructRepresentation(false); } else if(typeParameter instanceof XbasicType && typeArg instanceof XbasicType) { XbasicType btParameter = (XbasicType) typeParameter; XbasicType btArg = (XbasicType) typeArg; if((arrayOnly && !btArg.isArray()) || !intent.isCompatible(btParameter.getIntent())) { continue; } rep = arg.constructRepresentation(false); } if(rep != null && !rep.isEmpty()) { gatheredArguments.add(rep); } } return gatheredArguments; } }
package com.redbooth; import android.animation.Animator; import android.animation.ObjectAnimator; import android.os.Build; import android.view.MotionEvent; import android.view.VelocityTracker; import android.view.ViewTreeObserver; import android.view.animation.DecelerateInterpolator; class WelcomeCoordinatorTouchController { public static final int MAX_VELOCITY = 300; public static final int CURRENT_VELOCITY = 1000; public static final long SMOOTH_SCROLL_DURATION = 300; public static final String PROPERTY_SCROLL_X = "scrollX"; private final WelcomeCoordinatorLayout view; private float iniEventX; private int currentScrollX; private int minScroll = 0; private int maxScroll = 0; private VelocityTracker velocityTracker; private ObjectAnimator smoothScrollAnimator; private OnPageScrollListener onPageScrollListener; public WelcomeCoordinatorTouchController(final WelcomeCoordinatorLayout view) { this.view = view; configureLayoutListener(); } private void configureLayoutListener() { view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { WelcomeCoordinatorLayout welcomeCoordinatorLayout = WelcomeCoordinatorTouchController.this.view; int pagesSteps = welcomeCoordinatorLayout.getNumOfPages() - 1; maxScroll = pagesSteps * welcomeCoordinatorLayout.getWidth(); ViewTreeObserver viewTreeObserver = welcomeCoordinatorLayout.getViewTreeObserver(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { viewTreeObserver.removeOnGlobalLayoutListener(this); } else { viewTreeObserver.removeGlobalOnLayoutListener(this); } configureScrollListener(); } }); } private void configureScrollListener() { view.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() { @Override public void onScrollChanged() { view.notifyProgressScroll(view.getScrollX() / (float) view.getWidth()); } }); } protected boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: if (velocityTracker == null) { velocityTracker = VelocityTracker.obtain(); } else { velocityTracker.clear(); } velocityTracker.addMovement(event); currentScrollX = view.getScrollX(); iniEventX = event.getX(); break; case MotionEvent.ACTION_MOVE: setScrollX(scrollLimited(event.getX())); velocityTracker.addMovement(event); velocityTracker.computeCurrentVelocity(CURRENT_VELOCITY); break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: evaluateMoveToPage(); break; } return true; } private void evaluateMoveToPage() { float xVelocity = velocityTracker.getXVelocity(); currentScrollX = view.getScrollX(); moveToPagePosition(xVelocity); } private int scrollLimited(float scrollX) { int newScrollPosition = (int) (currentScrollX + iniEventX - scrollX); return Math.max(minScroll, Math.min(newScrollPosition, maxScroll)); } private void setScrollX(int value) { if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { view.setScrollX(value); } else { view.scrollTo(value, view.getScrollY()); } if (onPageScrollListener != null) { onPageScrollListener.onScrollPage(value); } } private void moveToPagePosition(float xVelocity) { float width = view.getWidth(); int currentPage = (int) Math.floor(currentScrollX / width); float percentageOfNewPageVisible = (currentScrollX % width) / width; if (xVelocity < -MAX_VELOCITY) { scrollToPage(currentPage + 1); } else if (xVelocity > MAX_VELOCITY) { scrollToPage(currentPage); } else if (percentageOfNewPageVisible > 0.5f) { scrollToPage(currentPage + 1); } else { scrollToPage(currentPage); } } private void scrollToPage(int newCurrentPage) { int width = view.getWidth(); int limitedNumPage = Math.max(0, Math.min(view.getNumOfPages() -1, newCurrentPage)); int scrollX = limitedNumPage * width; smoothScrollX(scrollX); } private void smoothScrollX(int scrollX) { cancelScrollAnimationIfNecessary(); if (view.getScrollX() != scrollX) { smoothScrollAnimator = ObjectAnimator.ofInt(view, PROPERTY_SCROLL_X, view.getScrollX(), scrollX); smoothScrollAnimator.setDuration(SMOOTH_SCROLL_DURATION); smoothScrollAnimator.setInterpolator(new DecelerateInterpolator()); smoothScrollAnimator.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { if (onPageScrollListener != null) { int width = view.getWidth(); int page = view.getScrollX() / width; int limitedNumPage = Math.max(0, Math.min(view.getNumOfPages() - 1, page)); onPageScrollListener.onPageSelected(limitedNumPage); } } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }); smoothScrollAnimator.start(); } } private void cancelScrollAnimationIfNecessary() { if ((smoothScrollAnimator != null) && (smoothScrollAnimator.isRunning())) { smoothScrollAnimator.cancel(); view.clearAnimation(); smoothScrollAnimator = null; } } public void setOnPageScrollListener(OnPageScrollListener onPageScrollListener) { this.onPageScrollListener = onPageScrollListener; } public interface OnPageScrollListener { void onScrollPage(float scrollProgress); void onPageSelected(int pageSelected); } }
package com.edysantosa.sakacalendar; import java.util.*; public class SakaCalendar extends GregorianCalendar { public final static int NO_WUKU = 0; public final static int ANGKA_WUKU = 1; public final static int URIP_WUKU = 2; public final static int NO_SAPTAWARA = 0; public final static int URIP_SAPTAWARA = 1; public final static int NO_PANCAWARA = 0; public final static int URIP_PANCAWARA = 1; public final static int TAHUN_SAKA = 0; public final static int PENANGGAL = 1; public final static int NO_NGUNARATRI = 2; public final static int NO_SASIH = 3; public final static int NGUNARATRI = 0; public final static int PANGELONG = 1; public final static int NAMPIH = 2; SakaCalendarPivot pivot; private int tahunSaka; private int penanggal; private int noNgunaratri; private int noSasih; private boolean isNgunaratri; private boolean isPangelong; private boolean isNampih; // TODO : Tambah disini public SakaCalendar(){ super(); this.initialize(); } public SakaCalendar(int year, int month, int dayOfMonth){ super(year, month , dayOfMonth); this.initialize(); } public SakaCalendar(int year, int month, int dayOfMonth, int hourOfDay, int minute, int second){ super(year, month , dayOfMonth, hourOfDay, minute, second); this.initialize(); } public SakaCalendar(Locale aLocale){ super(aLocale); this.initialize(); } public SakaCalendar(TimeZone zone){ super(zone); this.initialize(); } public SakaCalendar(TimeZone zone, Locale aLocale){ super(zone, aLocale); } private void initialize(){ this.pivot = getPivots(this.getTimeInMillis()); } /*** Fungsi menambahkan tanggal-tanggal pivot ***/ private SakaCalendarPivot getPivots(long timestamp) { SakaCalendarPivot pivot = new SakaCalendarPivot(); if (timestamp >= 946684800){ // Setelah 30 Desember 1999 // Pengalantaka Eka Sungsang ke Pahing // TODO : Pastikan kapan mulai berlakunya Pengalantaka Eka Sungsang ke Pahing! pivot.setTimeInMillis(946684800); //2000-01-01 pivot.noWuku = 10; pivot.angkaWuku = 70; pivot.tahunSaka = 1921; pivot.noSasih = 7; pivot.penanggal = 10; pivot.isPangelong = true; pivot.noNgunaratri = 424; pivot.isNgunaratri = false; }else{ // 30 Desember 1999 kebelakang // Pengalantaka Eka Sungsang ke Pon pivot.setTimeInMillis(0); //1970-01-01 pivot.noWuku = 5; pivot.angkaWuku =33; pivot.tahunSaka = 1891; pivot.noSasih = 7; pivot.penanggal = 8; pivot.isPangelong = true; pivot.noNgunaratri = 50; pivot.isNgunaratri = false; } return pivot; } /*** Fungsi menghitung perbedaan hari antara 2 Timestamp ***/ private long getDateDiff(long d1, long d2) { /* Catatan : Kode lebih cantik jika menggunakan class baru dari java 8, java.time "return ChronoUnit.DAYS.between(d1.toInstant(), d2.toInstant());" Akan tetapi, setelah testing performanya lebih rendah rata-rata 2 s/d 3 milisecond. */ double x = (d2 - d1) / (1000d * 60 * 60 * 24); return (long)x; } private class SakaCalendarPivot extends GregorianCalendar { int noWuku; int angkaWuku; int tahunSaka; int noSasih; int penanggal; boolean isPangelong; int noNgunaratri; //Jumlah hari sejak nemugelang pengalantaka boolean isNgunaratri; } /*** Fungsi menghitung pawukon ***/ public int getWuku(int field){ long bedaHari = getDateDiff(pivot.getTimeInMillis(),this.getTimeInMillis()); int angkaWuku; int uripWuku; int noWuku; if (bedaHari >= 0){ angkaWuku = (int)(pivot.angkaWuku + bedaHari)%210 ; }else{ angkaWuku = 210 - (int)((-(pivot.angkaWuku + bedaHari))%210) ; } if (angkaWuku == 0){ angkaWuku = 210; } noWuku = (int) Math.ceil(angkaWuku /7.0); if (noWuku > 30) { noWuku %=30; } if (noWuku == 0) { noWuku =30; } switch (noWuku) { case 1: //Sinta uripWuku = 7; break; case 2: //Landep uripWuku = 1; break; case 3: //Ukir uripWuku = 4; break; case 4: //Kulantir uripWuku = 6; break; case 5: //Tolu uripWuku = 5; break; case 6: //Gumbreg uripWuku = 8; break; case 7: //Wariga uripWuku = 9; break; case 8: //Warigadean uripWuku = 3; break; case 9: //Julungwangi uripWuku = 7; break; case 10: //Sungsang uripWuku = 1; break; case 11: //Dunggulan uripWuku = 4; break; case 12: //Kuningan uripWuku = 6; break; case 13: //Langkir uripWuku = 5; break; case 14: //Medangsia uripWuku = 8; break; case 15: //Pujut uripWuku = 9; break; case 16: //Pahang uripWuku = 3; break; case 17: //Krulut uripWuku = 7; break; case 18: //Merakih uripWuku = 1; break; case 19: //Tambir uripWuku = 4; break; case 20: //Medangkungan uripWuku = 6; break; case 21: //Matal uripWuku = 5; break; case 22: //Uye uripWuku = 8; break; case 23: //Menail uripWuku = 9; break; case 24: //Perangbakat uripWuku = 3; break; case 25: //Bala uripWuku = 7; break; case 26: //Ugu uripWuku = 1; break; case 27: //Wayang uripWuku = 4; break; case 28: //kelawu uripWuku = 6; break; case 29: //Dukut uripWuku = 5; break; case 30: //Watugunung uripWuku = 8; break; default: uripWuku =0; break; } switch(field){ case NO_WUKU: return noWuku; case ANGKA_WUKU: return angkaWuku; case URIP_WUKU: return uripWuku; default: return noWuku; } } public int getSaptawara(int field){ /* * Perhitungan saptawara hanya mengecek DAY_OF_WEEK dari SakaCalendar */ int noSaptawara = 0; int uripSaptawara = 5; switch (this.get(Calendar.DAY_OF_WEEK)) { case 1: //Redite noSaptawara = 0; uripSaptawara = 5; break; case 2: //Soma noSaptawara = 1; uripSaptawara = 4; break; case 3: //Anggara noSaptawara = 2; uripSaptawara = 3; break; case 4: //Buda noSaptawara = 3; uripSaptawara = 7; break; case 5: //Wrespati noSaptawara = 4; uripSaptawara = 8; break; case 6: //Sukra noSaptawara = 5; uripSaptawara = 6; break; case 7: //Saniscara noSaptawara = 6; uripSaptawara = 9; break; default: break; } switch(field){ case NO_SAPTAWARA: return noSaptawara; case URIP_SAPTAWARA: return uripSaptawara; default: return noSaptawara; } } public int getPancawara(int field){ /* * Perhitungan pancawara * Menggunakan rumus dari babadbali.com : "Murni aritmatika, modulus 5 dari angka pawukon menghasilkan 0=Umanis, 1=Paing, 2=Pon, 3=Wage, 4=Kliwon. * Pada SakaCalendar menjadi : * 0 + 1 = 1 Umanis * 1 + 1 = 2 Paing * 2 + 1 = 3 Pon * 3 + 1 = 4 Wage * 4 + 1 = 5 Kliwon */ int noPancawara = (this.getWuku(ANGKA_WUKU) % 5) + 1 ; int uripPancawara = 5; // mendapatkan urip pancawara switch (noPancawara) { case 1: uripPancawara = 5;break; case 2: uripPancawara = 9;break; case 3: uripPancawara = 7;break; case 4: uripPancawara = 4;break; case 5: uripPancawara = 8;break; default:break; } switch(field){ case NO_PANCAWARA: return noPancawara; case URIP_PANCAWARA: return uripPancawara; default: return noPancawara; } } public int getTriwara(){ /* * Perhitungan triwara * Menggunakan rumus dari babadbali.com : "Perhitungan triwara murni aritmatika, berdaur dari ketiganya. Angka Pawukon dibagi 3, jika sisanya (modulus) 1 adalah Pasah, 2 adalah Beteng, 0 adalah Kajeng" * Pada SakaCalendar menjadi : * 1 Pasah * 2 Beteng * 0 -> 3 kajeng */ int noTriwara = this.getWuku(ANGKA_WUKU) % 3; if (noTriwara == 0){noTriwara = 3;} return noTriwara; } public int getEkawara(){ /* * Perhitungan ekawara * Pada SakaCalendar : * 1 Luang * 2 Bukan luang (kosong) */ int noEkawara = (this.getPancawara(URIP_PANCAWARA) + this.getSaptawara(URIP_SAPTAWARA)) % 2; if (noEkawara!=0){ return 1; //Jika tidak habis dibagi 2 maka luang }else{ return 0; //Jika habis dibagi 2 maka bukan luang } } public int getDwiwara(){ /* * Perhitungan dwiwara * Pada SakaCalendar : * 1 Menga * 2 Pepet */ int noDwiwara = (this.getPancawara(URIP_PANCAWARA) + this.getSaptawara(URIP_SAPTAWARA)) % 2; if (noDwiwara==0){ return 1; //Jika habis dibagi 2 maka menga }else{ return 2; //Jika tidak habis dibagi 2 maka pepet } } public int getCaturwara(){ /* * Perhitungan caturwara * Pada wuku dengan angka wuku 71,72,73 caturwara tetap jaya yang disebut dengan Jayatiga * Pada SakaCalendar : * 1 Sri * 2 Laba * 3 Jaya * 0 -> Menala */ int angkaWuku = this.getWuku(ANGKA_WUKU); int noCaturwara; if (angkaWuku == 71 || angkaWuku == 72 || angkaWuku == 73){ noCaturwara = 3; }else if (angkaWuku <= 70){ noCaturwara = angkaWuku % 4; }else{ noCaturwara = (angkaWuku + 2) % 4; } if (noCaturwara == 0){noCaturwara = 4;} return noCaturwara; } public int getSadwara(){ /* * Perhitungan sadwara * Pada SakaCalendar : * 1 Tungleh * 2 Aryang * 3 Urukung * 4 Paniron * 5 Was * 0 -> 6 Maulu */ int noSadwara = this.getWuku(ANGKA_WUKU) % 6; if (noSadwara == 0){noSadwara = 6;} return noSadwara; } public int getAstawara(){ /* * Perhitungan astawara * Pada wuku dengan angka wuku 71,72,73 astawara tetap kala yang disebut dengan Kalatiga * Pada SakaCalendar : * 1 Sri * 2 Indra * 3 Guru * 4 Yama * 5 Ludra * 6 Brahma * 7 kala * 0 -> 8 Uma */ int noAstawara; int angkaWuku = this.getWuku(ANGKA_WUKU); if (angkaWuku == 71 || angkaWuku == 72 || angkaWuku == 73){ noAstawara = 7; }else if (angkaWuku <= 70){ noAstawara = angkaWuku % 8; }else{ noAstawara = (angkaWuku + 6) % 8; } if (noAstawara == 0){noAstawara = 8;} return noAstawara; } public int getSangawara(){ /* * Perhitungan sangawara * Pada wuku dengan angka wuku 1-4 sangawara tetap dangu yang disebut dengan Caturdangu * Pada SakaCalendar : * 1 Dangu * 2 Jangur * 3 Gigis * 4 Nohan * 5 Ogan * 6 Erangan * 7 Urungan * 8 Tulus * 0 -> 9 Dadi */ int noSangawara; int angkaWuku = this.getWuku(ANGKA_WUKU); if (angkaWuku <= 4){ noSangawara = 1 ; }else{ noSangawara = (angkaWuku + 6) % 9; } if (noSangawara == 0){noSangawara = 9;} return noSangawara; } public int getDasawara(){ /* * Perhitungan dasawara * Pada SakaCalendar menjadi : * 0 + 1 = 1 Pandita * 1 + 1 = 2 Pati * 2 + 1 = 3 Suka * 3 + 1 = 4 Duka * 4 + 1 = 5 Sri * 5 + 1 = 6 Manuh * 6 + 1 = 7 Manusa * 7 + 1 = 8 Raja * 8 + 1 = 9 Dewa * 9 + 1 = 10 Raksasa */ return (((this.getPancawara(URIP_PANCAWARA) + this.getSaptawara(URIP_SAPTAWARA)) % 10)+1); } public int getIngkel(){ /* * Pada SakaCalendar : * 1 Wong * 2 Sato * 3 Mina * 4 Manuk * 5 Taru * 6 Buku */ int noIngkel; int noWuku = this.getWuku(NO_WUKU); if (noWuku==1||noWuku==7||noWuku==13||noWuku==19||noWuku==25){ noIngkel = 1; } else if (noWuku==2||noWuku==8||noWuku==14||noWuku==20||noWuku==26){ noIngkel = 2; } else if (noWuku==3||noWuku==9||noWuku==15||noWuku==21||noWuku==27){ noIngkel = 3; } else if (noWuku==4||noWuku==10||noWuku==16||noWuku==22||noWuku==28){ noIngkel = 4; } else if (noWuku==5||noWuku==11||noWuku==17||noWuku==23||noWuku==29){ noIngkel = 5; } else { noIngkel = 6; } return noIngkel; } /*** Fungsi menghitung jejepan ***/ public int getJejepan(){ /* * Pada SakaCalendar : * 1 Mina * 2 taru * 3 Sato * 4 Patra * 5 Wong * 0 -> 6 Paksi */ int noJejepan; int angkaWuku = this.getWuku(ANGKA_WUKU); noJejepan = angkaWuku % 6; if (noJejepan == 0){noJejepan = 6;} return noJejepan; } /*** Fungsi menghitung pewatekan alit ***/ public int getWatekAlit(){ /* * Pada SakaCalendar : * 1 Uler * 2 Gajah * 3 Lembu * 0 -> 4 Lintah */ int noWatekAlit; noWatekAlit = (this.getPancawara(URIP_PANCAWARA) + this.getSaptawara(URIP_SAPTAWARA)) % 4; if (noWatekAlit == 0){noWatekAlit = 4;} return noWatekAlit; } /*** Fungsi menghitung pewatekan madya ***/ public int getWatekMadya(){ /* * Pada SakaCalendar : * 1 Gajah * 2 Watu * 3 Buta * 4 Suku * 0 ->5 Wong */ int noWatekMadya; noWatekMadya = (this.getPancawara(URIP_PANCAWARA) + this.getSaptawara(URIP_SAPTAWARA)) % 5; if (noWatekMadya == 0){noWatekMadya = 5;} return noWatekMadya; } /*** Fungsi menghitung eka jala rsi ***/ public int getEkaJalaRsi(){ /* * Pada SakaCalendar : * 1 Bagna mapasah * 2 Bahu putra * 3 Buat astawa * 4 Buat lara * 5 Buat merang * 6 Buat sebet * 7 Buat kingking * 8 Buat suka * 9 Dahat kingking * 10 Kamaranan * 11 Kamretaan * 12 Kasobagian * 13 Kinasihan amreta * 14 Kinasihan jana * 15 Langgeng kayohanaan * 16 Lewih bagia * 17 Manggih bagia * 18 Manggih suka * 19 Patining amreta * 20 Rahayu * 21 Sidha kasobagian * 22 Subagia * 23 Suka kapanggih * 24 Suka pinanggih * 25 Suka rahayu * 26 Tininggaling suka * 27 Wredhi putra * 28 Wredhi sarwa mule */ int noEkaJalaRsi=0; int noWuku = this.getWuku(NO_WUKU); int noSaptawara = this.getSaptawara(NO_SAPTAWARA); switch(noWuku){ case 1: switch(noSaptawara){ case 0 : noEkaJalaRsi = 24;break; case 1 : noEkaJalaRsi = 8;break; case 2 : noEkaJalaRsi = 18;break; case 3 : noEkaJalaRsi = 8;break; case 4 : noEkaJalaRsi = 24;break; case 5 : noEkaJalaRsi = 24;break; case 6 : noEkaJalaRsi = 18;break; } break; case 2: switch(noSaptawara){ case 0 : noEkaJalaRsi = 10;break; case 1 : noEkaJalaRsi = 8;break; case 2 : noEkaJalaRsi = 14;break; case 3 : noEkaJalaRsi = 27;break; case 4 : noEkaJalaRsi = 25;break; case 5 : noEkaJalaRsi = 24;break; case 6 : noEkaJalaRsi = 21;break; } break; case 3: switch(noSaptawara){ case 0 : noEkaJalaRsi = 14;break; case 1 : noEkaJalaRsi = 8;break; case 2 : noEkaJalaRsi = 14;break; case 3 : noEkaJalaRsi = 26;break; case 4 : noEkaJalaRsi = 20;break; case 5 : noEkaJalaRsi = 6;break; case 6 : noEkaJalaRsi = 3;break; } break; case 4: switch(noSaptawara){ case 0 : noEkaJalaRsi = 15;break; case 1 : noEkaJalaRsi = 27;break; case 2 : noEkaJalaRsi = 18;break; case 3 : noEkaJalaRsi = 21;break; case 4 : noEkaJalaRsi = 26;break; case 5 : noEkaJalaRsi = 23;break; case 6 : noEkaJalaRsi = 1;break; } break; case 5: switch(noSaptawara){ case 0 : noEkaJalaRsi = 11;break; case 1 : noEkaJalaRsi = 6;break; case 2 : noEkaJalaRsi = 16;break; case 3 : noEkaJalaRsi = 24;break; case 4 : noEkaJalaRsi = 8;break; case 5 : noEkaJalaRsi = 18;break; case 6 : noEkaJalaRsi = 24;break; } break; case 6: switch(noSaptawara){ case 0 : noEkaJalaRsi = 18;break; case 1 : noEkaJalaRsi = 26;break; case 2 : noEkaJalaRsi = 5;break; case 3 : noEkaJalaRsi = 24;break; case 4 : noEkaJalaRsi = 3;break; case 5 : noEkaJalaRsi = 3;break; case 6 : noEkaJalaRsi = 3;break; } break; case 7: switch(noSaptawara){ case 0 : noEkaJalaRsi = 13;break; case 1 : noEkaJalaRsi = 13;break; case 2 : noEkaJalaRsi = 5;break; case 3 : noEkaJalaRsi = 15;break; case 4 : noEkaJalaRsi = 13;break; case 5 : noEkaJalaRsi = 27;break; case 6 : noEkaJalaRsi = 27;break; } break; case 8: switch(noSaptawara){ case 0 : noEkaJalaRsi = 2;break; case 1 : noEkaJalaRsi = 24;break; case 2 : noEkaJalaRsi = 24;break; case 3 : noEkaJalaRsi = 16;break; case 4 : noEkaJalaRsi = 26;break; case 5 : noEkaJalaRsi = 16;break; case 6 : noEkaJalaRsi = 6;break; } break; case 9: switch(noSaptawara){ case 0 : noEkaJalaRsi = 10;break; case 1 : noEkaJalaRsi = 26;break; case 2 : noEkaJalaRsi = 19;break; case 3 : noEkaJalaRsi = 26;break; case 4 : noEkaJalaRsi = 12;break; case 5 : noEkaJalaRsi = 16;break; case 6 : noEkaJalaRsi = 22;break; } break; case 10: switch(noSaptawara){ case 0 : noEkaJalaRsi = 26;break; case 1 : noEkaJalaRsi = 26;break; case 2 : noEkaJalaRsi = 13;break; case 3 : noEkaJalaRsi = 1;break; case 4 : noEkaJalaRsi = 18;break; case 5 : noEkaJalaRsi = 14;break; case 6 : noEkaJalaRsi = 1;break; } break; case 11: switch(noSaptawara){ case 0 : noEkaJalaRsi = 16;break; case 1 : noEkaJalaRsi = 24;break; case 2 : noEkaJalaRsi = 13;break; case 3 : noEkaJalaRsi = 8;break; case 4 : noEkaJalaRsi = 17;break; case 5 : noEkaJalaRsi = 26;break; case 6 : noEkaJalaRsi = 19;break; } break; case 12: switch(noSaptawara){ case 0 : noEkaJalaRsi = 25;break; case 1 : noEkaJalaRsi = 13;break; case 2 : noEkaJalaRsi = 13;break; case 3 : noEkaJalaRsi = 6;break; case 4 : noEkaJalaRsi = 8;break; case 5 : noEkaJalaRsi = 6;break; case 6 : noEkaJalaRsi = 27;break; } break; case 13: switch(noSaptawara){ case 0 : noEkaJalaRsi = 8;break; case 1 : noEkaJalaRsi = 6;break; case 2 : noEkaJalaRsi = 13;break; case 3 : noEkaJalaRsi = 8;break; case 4 : noEkaJalaRsi = 26;break; case 5 : noEkaJalaRsi = 3;break; case 6 : noEkaJalaRsi = 13;break; } break; case 14: switch(noSaptawara){ case 0 : noEkaJalaRsi = 26;break; case 1 : noEkaJalaRsi = 26;break; case 2 : noEkaJalaRsi = 15;break; case 3 : noEkaJalaRsi = 16;break; case 4 : noEkaJalaRsi = 27;break; case 5 : noEkaJalaRsi = 8;break; case 6 : noEkaJalaRsi = 13;break; } break; case 15: switch(noSaptawara){ case 0 : noEkaJalaRsi = 21;break; case 1 : noEkaJalaRsi = 8;break; case 2 : noEkaJalaRsi = 6;break; case 3 : noEkaJalaRsi = 26;break; case 4 : noEkaJalaRsi = 26;break; case 5 : noEkaJalaRsi = 6;break; case 6 : noEkaJalaRsi = 14;break; } break; case 16: switch(noSaptawara){ case 0 : noEkaJalaRsi = 26;break; case 1 : noEkaJalaRsi = 18;break; case 2 : noEkaJalaRsi = 14;break; case 3 : noEkaJalaRsi = 24;break; case 4 : noEkaJalaRsi = 6;break; case 5 : noEkaJalaRsi = 27;break; case 6 : noEkaJalaRsi = 21;break; } break; case 17: switch(noSaptawara){ case 0 : noEkaJalaRsi = 26;break; case 1 : noEkaJalaRsi = 26;break; case 2 : noEkaJalaRsi = 24;break; case 3 : noEkaJalaRsi = 8;break; case 4 : noEkaJalaRsi = 19;break; case 5 : noEkaJalaRsi = 19;break; case 6 : noEkaJalaRsi = 18;break; } break; case 18: switch(noSaptawara){ case 0 : noEkaJalaRsi = 8;break; case 1 : noEkaJalaRsi = 18;break; case 2 : noEkaJalaRsi = 8;break; case 3 : noEkaJalaRsi = 5;break; case 4 : noEkaJalaRsi = 27;break; case 5 : noEkaJalaRsi = 18;break; case 6 : noEkaJalaRsi = 6;break; } break; case 19: switch(noSaptawara){ case 0 : noEkaJalaRsi = 10;break; case 1 : noEkaJalaRsi = 13;break; case 2 : noEkaJalaRsi = 13;break; case 3 : noEkaJalaRsi = 14;break; case 4 : noEkaJalaRsi = 26;break; case 5 : noEkaJalaRsi = 19;break; case 6 : noEkaJalaRsi = 19;break; } break; case 20: switch(noSaptawara){ case 0 : noEkaJalaRsi = 6;break; case 1 : noEkaJalaRsi = 3;break; case 2 : noEkaJalaRsi = 26;break; case 3 : noEkaJalaRsi = 26;break; case 4 : noEkaJalaRsi = 3;break; case 5 : noEkaJalaRsi = 26;break; case 6 : noEkaJalaRsi = 18;break; } break; case 21: switch(noSaptawara){ case 0 : noEkaJalaRsi = 21;break; case 1 : noEkaJalaRsi = 15;break; case 2 : noEkaJalaRsi = 28;break; case 3 : noEkaJalaRsi = 24;break; case 4 : noEkaJalaRsi = 18;break; case 5 : noEkaJalaRsi = 9;break; case 6 : noEkaJalaRsi = 26;break; } break; case 22: switch(noSaptawara){ case 0 : noEkaJalaRsi = 18;break; case 1 : noEkaJalaRsi = 6;break; case 2 : noEkaJalaRsi = 18;break; case 3 : noEkaJalaRsi = 8;break; case 4 : noEkaJalaRsi = 7;break; case 5 : noEkaJalaRsi = 16;break; case 6 : noEkaJalaRsi = 19;break; } break; case 23: switch(noSaptawara){ case 0 : noEkaJalaRsi = 26;break; case 1 : noEkaJalaRsi = 3;break; case 2 : noEkaJalaRsi = 8;break; case 3 : noEkaJalaRsi = 14;break; case 4 : noEkaJalaRsi = 26;break; case 5 : noEkaJalaRsi = 21;break; case 6 : noEkaJalaRsi = 8;break; } break; case 24: switch(noSaptawara){ case 0 : noEkaJalaRsi = 16;break; case 1 : noEkaJalaRsi = 16;break; case 2 : noEkaJalaRsi = 24;break; case 3 : noEkaJalaRsi = 8;break; case 4 : noEkaJalaRsi = 9;break; case 5 : noEkaJalaRsi = 25;break; case 6 : noEkaJalaRsi = 3;break; } break; case 25: switch(noSaptawara){ case 0 : noEkaJalaRsi = 13;break; case 1 : noEkaJalaRsi = 10;break; case 2 : noEkaJalaRsi = 25;break; case 3 : noEkaJalaRsi = 25;break; case 4 : noEkaJalaRsi = 18;break; case 5 : noEkaJalaRsi = 25;break; case 6 : noEkaJalaRsi = 21;break; } break; case 26: switch(noSaptawara){ case 0 : noEkaJalaRsi = 8;break; case 1 : noEkaJalaRsi = 13;break; case 2 : noEkaJalaRsi = 13;break; case 3 : noEkaJalaRsi = 15;break; case 4 : noEkaJalaRsi = 19;break; case 5 : noEkaJalaRsi = 26;break; case 6 : noEkaJalaRsi = 21;break; } break; case 27: switch(noSaptawara){ case 0 : noEkaJalaRsi = 5;break; case 1 : noEkaJalaRsi = 19;break; case 2 : noEkaJalaRsi = 5;break; case 3 : noEkaJalaRsi = 21;break; case 4 : noEkaJalaRsi = 27;break; case 5 : noEkaJalaRsi = 13;break; case 6 : noEkaJalaRsi = 24;break; } break; case 28: switch(noSaptawara){ case 0 : noEkaJalaRsi = 19;break; case 1 : noEkaJalaRsi = 18;break; case 2 : noEkaJalaRsi = 18;break; case 3 : noEkaJalaRsi = 26;break; case 4 : noEkaJalaRsi = 16;break; case 5 : noEkaJalaRsi = 3;break; case 6 : noEkaJalaRsi = 25;break; } break; case 29: switch(noSaptawara){ case 0 : noEkaJalaRsi = 4;break; case 1 : noEkaJalaRsi = 3;break; case 2 : noEkaJalaRsi = 24;break; case 3 : noEkaJalaRsi = 26;break; case 4 : noEkaJalaRsi = 19;break; case 5 : noEkaJalaRsi = 26;break; case 6 : noEkaJalaRsi = 21;break; } break; case 30: switch(noSaptawara){ case 0 : noEkaJalaRsi = 15;break; case 1 : noEkaJalaRsi = 4;break; case 2 : noEkaJalaRsi = 3;break; case 3 : noEkaJalaRsi = 26;break; case 4 : noEkaJalaRsi = 8;break; case 5 : noEkaJalaRsi = 26;break; case 6 : noEkaJalaRsi = 18;break; } break; } return noEkaJalaRsi; } /*** Fungsi menghitung palalintangan ***/ public int getLintang(){ /* * Pada SakaCalendar : * 1 Gajah * 2 Kiriman * 3 Jong Sarat * 4 Atiwa-tiwa * 5 Sangka Tikel * 6 Bubu Bolong * 7 Sugenge * 8 Uluku/Tenggala * 9 Pedati * 10 Kuda * 11 Gajah Mina * 12 Bade * 13 Magelut * 14 Pagelangan * 15 Kala Sungsang * 16 Kukus * 17 Asu * 18 Kartika * 19 Naga * 20 Banak Angerem * 21 Hru/Panah * 22 Patrem * 23 Lembu * 24 Depat/Sidamalung * 25 Tangis * 26 Salah Ukur * 27 Perahu Pegat * 28 Puwuh Atarung * 29 Lawean/Goang * 30 Kelapa * 31 Yuyu * 32 Lumbung * 33 Kumbha * 34 Udang * 35 Begoong */ int noLintang=0; int noSaptawara = this.getSaptawara(NO_SAPTAWARA); int noPancawara = this.getPancawara(NO_PANCAWARA); switch(noSaptawara){ case 0: switch(noPancawara){ case 1 : noLintang = 15;break; case 2 : noLintang = 1;break; case 3 : noLintang = 22;break; case 4 : noLintang = 8;break; case 5 : noLintang = 29;break; } break; case 1: switch(noPancawara){ case 1 : noLintang = 30;break; case 2 : noLintang = 16;break; case 3 : noLintang = 2;break; case 4 : noLintang = 23;break; case 5 : noLintang = 9;break; } break; case 2: switch(noPancawara){ case 1 : noLintang = 10;break; case 2 : noLintang = 31;break; case 3 : noLintang = 17;break; case 4 : noLintang = 23;break; case 5 : noLintang = 24;break; } break; case 3: switch(noPancawara){ case 1 : noLintang = 25;break; case 2 : noLintang = 11;break; case 3 : noLintang = 32;break; case 4 : noLintang = 18;break; case 5 : noLintang = 4;break; } break; case 4: switch(noPancawara){ case 1 : noLintang = 5;break; case 2 : noLintang = 26;break; case 3 : noLintang = 12;break; case 4 : noLintang = 33;break; case 5 : noLintang = 19;break; } break; case 5: switch(noPancawara){ case 1 : noLintang = 20;break; case 2 : noLintang = 6;break; case 3 : noLintang = 27;break; case 4 : noLintang = 13;break; case 5 : noLintang = 34;break; } break; case 6: switch(noPancawara){ case 1 : noLintang = 35;break; case 2 : noLintang = 21;break; case 3 : noLintang = 7;break; case 4 : noLintang = 28;break; case 5 : noLintang = 15;break; } break; } return noLintang; } /*** Fungsi menghitung panca sudha ***/ public int getPancasudha(){ /* * Pada SakaCalendar : * 1 Wisesa segara * 2 Tunggak semi * 3 Satria wibhawa * 4 Sumur sinaba * 5 Bumi kapetak * 6 Satria wirang * 7 Lebu katiup angin */ int noPancasudha = 0; int noSaptawara = this.getSaptawara(NO_SAPTAWARA); int noPancawara = this.getPancawara(NO_PANCAWARA); if (noSaptawara==0 && noPancawara==2 || noSaptawara==3 && noPancawara==2 || noSaptawara==1 && noPancawara==4 || noSaptawara==5 && noPancawara==5 || noSaptawara==2 && noPancawara==1 ||noSaptawara==6 && noPancawara==3){ noPancasudha = 1; } else if (noSaptawara==1 && noPancawara==1 || noSaptawara==4 && noPancawara==4 || noSaptawara==5 && noPancawara==2 || noSaptawara==6 && noPancawara==5){ noPancasudha = 2; } else if (noSaptawara==0 && noPancawara==4 || noSaptawara==2 && noPancawara==3 || noSaptawara==3 && noPancawara==4 || noSaptawara==4 && noPancawara==1 || noSaptawara==6 && noPancawara==2){ noPancasudha = 3; } else if (noSaptawara==0 && noPancawara==1 || noSaptawara==1 && noPancawara==3 || noSaptawara==2 && noPancawara==5 || noSaptawara==3 && noPancawara==1 || noSaptawara==5 && noPancawara==4){ noPancasudha = 4; } else if (noSaptawara==0 && noPancawara==3 || noSaptawara==1 && noPancawara==2 || noSaptawara==3 && noPancawara==3 || noSaptawara==4 && noPancawara==5 || noSaptawara==6 && noPancawara==1){ noPancasudha = 5; } else if (noSaptawara==1 && noPancawara==5 || noSaptawara==2 && noPancawara==2 || noSaptawara==4 && noPancawara==3 || noSaptawara==5 && noPancawara==1 || noSaptawara==6 && noPancawara==4){ noPancasudha = 6; } else if (noSaptawara==0 && noPancawara==5 || noSaptawara==2 && noPancawara==4 || noSaptawara==3 && noPancawara==5 || noSaptawara==4 && noPancawara==2 || noSaptawara==5 && noPancawara==3){ noPancasudha = 7; } return noPancasudha; } /*** Fungsi menghitung pararasan ***/ public int getPararasan(){ /* * Pada SakaCalendar : * 1 Laku bumi * 2 Laku api * 3 Laku angin * 4 Laku pandita sakti * 5 Aras tuding * 6 Aras kembang * 7 Laku bintang * 8 Laku bulan * 9 Laku surya * 10 Laku air/toya * 11 Laku pretiwi * 12 Laku agni agung */ int noPararasan = 0; int noSaptawara = this.getSaptawara(NO_SAPTAWARA); int noPancawara = this.getPancawara(NO_PANCAWARA); if (noSaptawara==2 && noPancawara==4){ noPararasan = 1; } else if (noSaptawara==1 && noPancawara==4 || noSaptawara==2 && noPancawara==1){ noPararasan = 2; } else if (noSaptawara==0 && noPancawara==4 || noSaptawara==1 && noPancawara==1){ noPararasan = 3; } else if (noSaptawara==0 && noPancawara==1 || noSaptawara==2 && noPancawara==3 || noSaptawara==5 && noPancawara==4){ noPararasan = 4; } else if (noSaptawara==1 && noPancawara==3 || noSaptawara==2 && noPancawara==5 || noSaptawara==3 && noPancawara==4 || noSaptawara==5 && noPancawara==1){ noPararasan = 5; } else if (noSaptawara==0 && noPancawara==3 || noSaptawara==2 && noPancawara==2 || noSaptawara==1 && noPancawara==5 || noSaptawara==3 && noPancawara==1 || noSaptawara==4 && noPancawara==4){ noPararasan = 6; } else if (noSaptawara==0 && noPancawara==5 || noSaptawara==1 && noPancawara==2 || noSaptawara==4 && noPancawara==1 || noSaptawara==5 && noPancawara==3 || noSaptawara==6 && noPancawara==4){ noPararasan = 7; } else if (noSaptawara==0 && noPancawara==2 || noSaptawara==3 && noPancawara==3 || noSaptawara==5 && noPancawara==5 || noSaptawara==6 && noPancawara==1){ noPararasan = 8; } else if (noSaptawara==3 && noPancawara==5 || noSaptawara==4 && noPancawara==3 || noSaptawara==5 && noPancawara==2){ noPararasan = 9; } else if (noSaptawara==3 && noPancawara==2 || noSaptawara==4 && noPancawara==5 || noSaptawara==6 && noPancawara==3){ noPararasan = 10; } else if (noSaptawara==4 && noPancawara==2 || noSaptawara==6 && noPancawara==5){ noPararasan = 11; } else if (noSaptawara==6 && noPancawara==2){ noPararasan = 12; } return noPararasan; } /*** Fungsi menghitung rakam ***/ public int getRakam(){ /* * Menggunakan rumus dari babadbali.com : "Dari hari Sukra diberi angka urut 1 sampai Wrespati - kemudian dari Kliwon juga diberi angka urut sampai Wage. Angka urutan itu dibagi dengan 6, sisanya mencerminkan sifat pimpinan yang akan dinobatkan nanti." * Pada SakaCalendar menjadi : * 1 Kala tinatang * 2 Demang kandhuruwan * 3 Sanggar waringin * 4 Mantri sinaroja * 5 Macam katawan * 0 -> 6 Nuju pati */ int noRakam; int saptawara = 0, pancawara = 0; int noSaptawara = this.getSaptawara(NO_SAPTAWARA); int noPancawara = this.getPancawara(NO_PANCAWARA); switch (noSaptawara){ case 0:saptawara = 3;break; case 1:saptawara = 4;break; case 2:saptawara = 5;break; case 3:saptawara = 6;break; case 4:saptawara = 7;break; case 5:saptawara = 1;break; case 6:saptawara = 2;break; } switch (noPancawara){ case 1:pancawara = 2;break; case 2:pancawara = 3;break; case 3:pancawara = 4;break; case 4:pancawara = 5;break; case 5:pancawara = 1;break; } noRakam = (pancawara + saptawara) % 6; if (noRakam == 0){noRakam = 6;} return noRakam; } /*** Fungsi menghitung zodiak ***/ public int getZodiak(){ /* * Pada SakaCalendar : * 1 Aries * 2 Taurus * 3 Gemini * 4 Cancer * 5 Leo * 6 Virgo * 7 Libra * 8 Scorpio * 9 Sagitarius * 10 Capricon * 11 Aquarius * 12 Pisces */ int noZodiak = 0; int M = this.get(Calendar.MONTH)+1; int D = this.get(Calendar.DATE); if ((M == 12 && D >= 22 && D <= 31) || (M == 1 && D >= 1 && D <= 19)) noZodiak = 10; else if ((M == 1 && D >= 20 && D <= 31) || (M == 2 && D >= 1 && D <= 17)) noZodiak = 11; else if ((M == 2 && D >= 18 && D <= 29) || (M == 3 && D >= 1 && D <= 19)) noZodiak = 12; else if ((M == 3 && D >= 20 && D <= 31) || (M == 4 && D >= 1 && D <= 19)) noZodiak = 1; else if ((M == 4 && D >= 20 && D <= 30) || (M == 5 && D >= 1 && D <= 20)) noZodiak = 2; else if ((M == 5 && D >= 21 && D <= 31) || (M == 6 && D >= 1 && D <= 20)) noZodiak = 3; else if ((M == 6 && D >= 21 && D <= 30) || (M == 7 && D >= 1 && D <= 22)) noZodiak = 4; else if ((M == 7 && D >= 23 && D <= 31) || (M == 8 && D >= 1 && D <= 22)) noZodiak = 5; else if ((M == 8 && D >= 23 && D <= 31) || (M == 9 && D >= 1 && D <= 22)) noZodiak = 6; else if ((M == 9 && D >= 23 && D <= 30) || (M == 10 && D >= 1 && D <= 22)) noZodiak = 7; else if ((M == 10 && D >= 23 && D <= 31) || (M == 11 && D >= 1 && D <= 21)) noZodiak = 8; else if ((M == 11 && D >= 22 && D <= 30) || (M == 12 && D >= 1 && D <= 21)) noZodiak = 9; return noZodiak; } /*** Fungsi menghitung kalender saka ***/ private void hitungSaka(){ int bedaHari = (int)getDateDiff(pivot.getTimeInMillis(),this.getTimeInMillis()); /* MENGHITUNG PENANGGAL PANGELONG ***/ int hasilNgunaratri; int jumlahNgunaratri = 0; int mulai=0; int noWuku = this.getWuku(NO_WUKU); int noPancawara = this.getPancawara(NO_PANCAWARA); int noSaptawara = this.getSaptawara(NO_SAPTAWARA); if (bedaHari >= 0){ //mengetahui jumlah ngunaratri if (pivot.noNgunaratri > 63){ if (pivot.noNgunaratri % 63 == 0){ mulai = pivot.noNgunaratri-63; } else { mulai = pivot.noNgunaratri - (pivot.noNgunaratri % 63); } } this.noNgunaratri = pivot.noNgunaratri + bedaHari; //Masukkan no ngunaratri if (this.noNgunaratri > (mulai + 63)){ jumlahNgunaratri = ((this.noNgunaratri - (mulai + 63))/63) + 1; if ((this.noNgunaratri - (mulai + 63))%63==0){jumlahNgunaratri } if (pivot.isNgunaratri){jumlahNgunaratri++;} //Jika pivot adalah ngunaratri, tambah jumlah ngunaratri // Menghitung angka penanggal/pangelong, jika 0 maka diubah ke 15 hasilNgunaratri = (bedaHari + pivot.penanggal + jumlahNgunaratri) % 15; if (hasilNgunaratri == 0) { hasilNgunaratri =15; } this.penanggal=hasilNgunaratri; // Menghitung apakah penanggal atau pangelong this.isPangelong = ((((bedaHari + pivot.penanggal + jumlahNgunaratri - 1) / 15) % 2) == 0) == pivot.isPangelong; }else{ // Jika tanggal yang dihitung sebelum tanggal pivot //mengetahui jumlah ngunaratri if ((pivot.noNgunaratri+63) > 63){ if ((pivot.noNgunaratri+63) % 63 == 0){ mulai = (pivot.noNgunaratri+63)-63; } else { mulai = (pivot.noNgunaratri+63) - ((pivot.noNgunaratri+63) % 63); } } this.noNgunaratri = pivot.noNgunaratri + bedaHari; //Masukkan no ngunaratri if (this.noNgunaratri < (mulai - 63)){ jumlahNgunaratri = ((-(this.noNgunaratri - (mulai - 63)))/63) + 1; if ((-(this.noNgunaratri - (mulai - 63)))%63==0){jumlahNgunaratri } // Menghitung angka penanggal/pangelong, jika 0 maka diubah ke 15 hasilNgunaratri = bedaHari + pivot.penanggal - jumlahNgunaratri; hasilNgunaratri = 15 - (-hasilNgunaratri%15) ; this.penanggal=hasilNgunaratri; // Menghitung apakah penanggal atau pangelong this.isPangelong = ((((-bedaHari + this.penanggal + jumlahNgunaratri - 1) / 15) % 2) == 0) == pivot.isPangelong; } /* MENENTUKAN APAKAH NGUNARATRI ATAU TIDAK ***/ this.isNgunaratri = false; if (this.get(Calendar.YEAR) > 1999 ){ // Pengalantaka Eka Sungsang ke Pahing if (noSaptawara == 2){ if (bedaHari > 0){ if ((noWuku==10 && noPancawara==2 && (this.penanggal==14||this.penanggal==9||this.penanggal==4)) || (noWuku==19 && noPancawara==5 && (this.penanggal==3||this.penanggal==13||this.penanggal==8)) || (noWuku==28 && noPancawara==3 && (this.penanggal==7||this.penanggal==2||this.penanggal==12)) || (noWuku==7 && noPancawara==1 && (this.penanggal==11||this.penanggal==6||this.penanggal==1)) || (noWuku==16 && noPancawara==4 && (this.penanggal==15||this.penanggal==10||this.penanggal==5)) || (noWuku==25 && noPancawara==2 && (this.penanggal==4||this.penanggal==14||this.penanggal==9)) || (noWuku==4 && noPancawara==5 && (this.penanggal==8||this.penanggal==3||this.penanggal==13)) || (noWuku==13 && noPancawara==3 && (this.penanggal==12||this.penanggal==7||this.penanggal==2)) || (noWuku==22 && noPancawara==1 && (this.penanggal==1||this.penanggal==11||this.penanggal==6)) || (noWuku==1 && noPancawara==4 && (this.penanggal==5||this.penanggal==15||this.penanggal==10))){ this.isNgunaratri = true; } }else{ if ((noWuku==10 && noPancawara==2 && (this.penanggal==15||this.penanggal==10||this.penanggal==5)) || (noWuku==19 && noPancawara==5 && (this.penanggal==4||this.penanggal==14||this.penanggal==9)) || (noWuku==28 && noPancawara==3 && (this.penanggal==8||this.penanggal==3||this.penanggal==13)) || (noWuku==7 && noPancawara==1 && (this.penanggal==12||this.penanggal==7||this.penanggal==2)) || (noWuku==16 && noPancawara==4 && (this.penanggal==1||this.penanggal==11||this.penanggal==6)) || (noWuku==25 && noPancawara==2 && (this.penanggal==5||this.penanggal==15||this.penanggal==10)) || (noWuku==4 && noPancawara==5 && (this.penanggal==9||this.penanggal==4||this.penanggal==14)) || (noWuku==13 && noPancawara==3 && (this.penanggal==13||this.penanggal==8||this.penanggal==3)) || (noWuku==22 && noPancawara==1 && (this.penanggal==2||this.penanggal==12||this.penanggal==7)) || (noWuku==1 && noPancawara==4 && (this.penanggal==6||this.penanggal==1||this.penanggal==11))){ this.isNgunaratri = true; this.penanggal = this.penanggal -1; //Jika ngunaratri mundur satu hari if (this.penanggal == 0 && !this.isPangelong) {this.isPangelong = true;} // Ubah pangelong menjadi true apabila mundur dari penanggal 1 if (this.penanggal == 0) {this.penanggal = 15;} //Ubah penanggal jadi 15 jika pengurangan akibat ngunaratri menjadi 0 } } } }else{ // Pengalantaka Eka Sungsang ke Pon if (noSaptawara == 3){ if (bedaHari > 0){ if ((noWuku==10 && noPancawara==3 && (this.penanggal==14||this.penanggal==9||this.penanggal==4)) || (noWuku==19 && noPancawara==1 && (this.penanggal==3||this.penanggal==13||this.penanggal==8)) || (noWuku==28 && noPancawara==4 && (this.penanggal==7||this.penanggal==2||this.penanggal==12)) || (noWuku==7 && noPancawara==2 && (this.penanggal==11||this.penanggal==6||this.penanggal==1)) || (noWuku==16 && noPancawara==5 && (this.penanggal==15||this.penanggal==10||this.penanggal==5)) || (noWuku==25 && noPancawara==3 && (this.penanggal==4||this.penanggal==14||this.penanggal==9)) || (noWuku==4 && noPancawara==1 && (this.penanggal==8||this.penanggal==3||this.penanggal==13)) || (noWuku==13 && noPancawara==4 && (this.penanggal==12||this.penanggal==7||this.penanggal==2)) || (noWuku==22 && noPancawara==2 && (this.penanggal==1||this.penanggal==11||this.penanggal==6)) || (noWuku==1 && noPancawara==5 && (this.penanggal==5||this.penanggal==15||this.penanggal==10))){ this.isNgunaratri = true; } }else{ if ((noWuku==10 && noPancawara==3 && (this.penanggal==15||this.penanggal==10||this.penanggal==5)) || (noWuku==19 && noPancawara==1 && (this.penanggal==4||this.penanggal==14||this.penanggal==9)) || (noWuku==28 && noPancawara==4 && (this.penanggal==8||this.penanggal==3||this.penanggal==13)) || (noWuku==7 && noPancawara==2 && (this.penanggal==12||this.penanggal==7||this.penanggal==2)) || (noWuku==16 && noPancawara==5 && (this.penanggal==1||this.penanggal==11||this.penanggal==6)) || (noWuku==25 && noPancawara==3 && (this.penanggal==5||this.penanggal==15||this.penanggal==10)) || (noWuku==4 && noPancawara==1 && (this.penanggal==9||this.penanggal==4||this.penanggal==14)) || (noWuku==13 && noPancawara==4 && (this.penanggal==13||this.penanggal==8||this.penanggal==3)) || (noWuku==22 && noPancawara==2 && (this.penanggal==2||this.penanggal==12||this.penanggal==7)) || (noWuku==1 && noPancawara==5 && (this.penanggal==6||this.penanggal==1||this.penanggal==11))){ this.isNgunaratri = true; this.penanggal = this.penanggal -1; //Jika ngunaratri mundur satu hari if (this.penanggal == 0 && !this.isPangelong) {this.isPangelong = true;} // Ubah pangelong menjadi true apabila mundur dari penanggal 1 if (this.penanggal == 0) {this.penanggal = 15;} //Ubah penanggal jadi 15 jika pengurangan akibat ngunaratri menjadi 0 } } } } /* MENGHITUNG SASIH ***/ /* * Pada SakaCalendar : * 1 Kasa * 2 Karo * 3 Katiga * 4 Kapat * 5 Kalima * 6 Kanem * 7 Kapitu * 8 Kawolu * 9 Kasanga * 10 Kadasa * 11 Destha * 12 Sadha */ int hasilSasih; int jumlahNampih = 0; int tahunSaka = pivot.tahunSaka; int perulangan1 = 0; int perulangan2 = pivot.noSasih; boolean isNampih=false; if (this.get(Calendar.YEAR) > 2002 || this.get(Calendar.YEAR) < 1992 ){ // Sistem nampih sasih if (bedaHari >= 0){ if (pivot.isPangelong){ bedaHari = bedaHari + 15 + (pivot.penanggal - 1); hasilSasih = (bedaHari + jumlahNgunaratri ) / 30 ; }else{ bedaHari = bedaHari + (pivot.penanggal - 1); hasilSasih = (bedaHari + jumlahNgunaratri ) / 30 ; } // menghitung tahun saka dan jumlah nampih sasih while (perulangan1 < hasilSasih){ perulangan1++; perulangan2++; perulangan2 = perulangan2 % 12; if (perulangan2 == 0) { perulangan2 = 12;} if (perulangan2 == 10){ tahunSaka++; } if (isNampih) { isNampih = false; }else{ if (((tahunSaka % 19) == 0)||((tahunSaka % 19) == 6)||((tahunSaka % 19) == 11)){ this.isNampih = perulangan2 == 12; if (perulangan2==1){perulangan2--;jumlahNampih++;isNampih=true;} }else if (((tahunSaka % 19) == 3)||((tahunSaka % 19) == 8)||((tahunSaka % 19) == 14)||((tahunSaka % 19) == 16)) { this.isNampih = perulangan2 == 1; if (perulangan2==2){perulangan2--;jumlahNampih++;isNampih=true;} } } } this.noSasih = (hasilSasih - jumlahNampih + pivot.noSasih)%12 ; if (this.isNampih){this.noSasih if (this.noSasih < 0){ this.noSasih = 12 - (-this.noSasih%12); } if (this.noSasih == 0 ){this.noSasih = 12;} this.tahunSaka = tahunSaka; }else{ //Mundur if (pivot.isPangelong){ bedaHari = bedaHari - (15 - pivot.penanggal); hasilSasih = -(bedaHari - jumlahNgunaratri ) / 30 ; }else{ bedaHari = bedaHari - 15 - (15 - pivot.penanggal); hasilSasih = -(bedaHari - jumlahNgunaratri ) / 30 ; } while (perulangan1 < hasilSasih){ perulangan1++; perulangan2 perulangan2 = perulangan2 % 12; if (perulangan2 == 0) { perulangan2 = 12;} if (perulangan2 == 9){ tahunSaka } if (isNampih) { isNampih = false; }else{ if (((tahunSaka % 19) == 0)||((tahunSaka % 19) == 6)||((tahunSaka % 19) == 11)){ this.isNampih = perulangan2 == 11; if (perulangan2==10){perulangan2++;jumlahNampih++;isNampih=true;} }else if (((tahunSaka % 19) == 3)||((tahunSaka % 19) == 8)||((tahunSaka % 19) == 14)||((tahunSaka % 19) == 16)) { this.isNampih = perulangan2 == 12; if (perulangan2==11){perulangan2++;jumlahNampih++;isNampih=true;} } } } this.noSasih = pivot.noSasih - hasilSasih + jumlahNampih; if (this.noSasih < 0){ this.noSasih = 12 - (-this.noSasih%12); } if (this.noSasih == 0 ){this.noSasih = 12;} this.tahunSaka = tahunSaka; if (this.isPangelong && this.penanggal == 15 && this.isNgunaratri && this.isNampih){this.isNampih = false;} // Ubah isnampih menjadi false apabila berada di ngunaratri di awal penanggal } }else{ // Nampih Sasih berkesinambungan if (bedaHari >= 0){ if (pivot.isPangelong){ bedaHari = bedaHari + 15 + (pivot.penanggal - 1); hasilSasih = (bedaHari + jumlahNgunaratri ) / 30 ; }else{ bedaHari = bedaHari + (pivot.penanggal - 1); hasilSasih = (bedaHari + jumlahNgunaratri ) / 30 ; } // menghitung tahun saka dan jumlah nampih sasih while (perulangan1 < hasilSasih){ perulangan1++; perulangan2++; perulangan2 = perulangan2 % 12; if (perulangan2 == 0) { perulangan2 = 12;} if (perulangan2 == 10){ tahunSaka++; } if (isNampih) { isNampih = false; }else{ if (((tahunSaka % 19) == 2)||((tahunSaka % 19) == 10)){ this.isNampih = perulangan2 == 12; if (perulangan2==1){perulangan2--;jumlahNampih++;isNampih=true;} }else if (((tahunSaka % 19) == 4)) { this.isNampih = perulangan2 == 4; if (perulangan2==5){perulangan2--;jumlahNampih++;isNampih=true;} }else if (((tahunSaka % 19) == 7)) { this.isNampih = perulangan2 == 2; if (perulangan2==3){perulangan2--;jumlahNampih++;isNampih=true;} }else if (((tahunSaka % 19) == 13)) { this.isNampih = perulangan2 == 11; if (perulangan2==12){perulangan2--;jumlahNampih++;isNampih=true;} }else if (((tahunSaka % 19) == 15)) { this.isNampih = perulangan2 == 3; if (perulangan2==4){perulangan2--;jumlahNampih++;isNampih=true;} }else if (((tahunSaka % 19) == 18)) { this.isNampih = perulangan2 == 1; if (perulangan2==2){perulangan2--;jumlahNampih++;isNampih=true;} } } } this.noSasih = (hasilSasih - jumlahNampih + pivot.noSasih)%12 ; if (this.isNampih){this.noSasih if (this.noSasih < 0){ this.noSasih = 12 - (-this.noSasih%12); } if (this.noSasih == 0 ){this.noSasih = 12;} this.tahunSaka = tahunSaka; }else{ //Mundur if (pivot.isPangelong){ bedaHari = bedaHari - (15 - pivot.penanggal); hasilSasih = -(bedaHari - jumlahNgunaratri ) / 30 ; }else{ bedaHari = bedaHari - 15 - (15 - pivot.penanggal); hasilSasih = -(bedaHari - jumlahNgunaratri ) / 30 ; } while (perulangan1 < hasilSasih){ perulangan1++; perulangan2 perulangan2 = perulangan2 % 12; if (perulangan2 == 0) { perulangan2 = 12;} if (perulangan2 == 9){ tahunSaka } if (isNampih) { isNampih = false; }else{ if (((tahunSaka % 19) == 2)||((tahunSaka % 19) == 10)){ this.isNampih = perulangan2 == 11; if (perulangan2==10){perulangan2++;jumlahNampih++;isNampih=true;} }else if (((tahunSaka % 19) == 4)) { this.isNampih = perulangan2 == 3; if (perulangan2==2){perulangan2++;jumlahNampih++;isNampih=true;} }else if (((tahunSaka % 19) == 7)) { this.isNampih = perulangan2 == 1; if (perulangan2==12){perulangan2++;jumlahNampih++;isNampih=true;} }else if (((tahunSaka % 19) == 13)) { this.isNampih = perulangan2 == 10; if (perulangan2==9){perulangan2++;jumlahNampih++;isNampih=true;} }else if (((tahunSaka % 19) == 15)) { this.isNampih = perulangan2 == 2; if (perulangan2==1){perulangan2++;jumlahNampih++;isNampih=true;} }else if (((tahunSaka % 19) == 18)) { this.isNampih = perulangan2 == 12; if (perulangan2==11){perulangan2++;jumlahNampih++;isNampih=true;} } } } this.noSasih = pivot.noSasih - hasilSasih + jumlahNampih; if (this.noSasih < 0){ this.noSasih = 12 - (-this.noSasih%12); } if (this.noSasih == 0 ){this.noSasih = 12;} this.tahunSaka = tahunSaka; if (this.isPangelong && this.penanggal == 15 && this.isNgunaratri && this.isNampih){this.isNampih = false;} // Ubah is nampih menjadi false apabila berada di ngunaratri di awal penanggal } } } public int getSakaCalendar(int field) { if(this.tahunSaka == 0){ hitungSaka(); } switch (field){ case TAHUN_SAKA: return this.tahunSaka; case PENANGGAL: return this.penanggal; case NO_NGUNARATRI: return noNgunaratri; case NO_SASIH: return noSasih; default: return this.tahunSaka; } } public boolean getSakaCalendarStatus(int field) { if(this.tahunSaka == 0){ hitungSaka(); } switch (field){ case NGUNARATRI: return this.isNgunaratri; case PANGELONG: return this.isPangelong; case NAMPIH: return isNampih; default: return this.isNgunaratri; } } }
/** * Skeleton code created using TextMate version 2.0 on a Mac OS X 10.10.5 system. */ import java.lang.String; import java.util.Vector; /** * A Centroid is calculated using an equation, * which in turn divides the sample space for each dimension into equal parts. * depending on the "numberOfClusters" parameter (as predetermined in ClusteringAlgorithm.java). * * Class Centroid holds three variables: * - two Cartesian (spacial) coordinates (x, y), and * - cluster (reference). */ public class Centroid { /** * Variables. */ private double x, y; private Cluster cluster; /** * Default constructor. * * @param x * @param y */ public Centroid(double x, double y) { // Pass the parameters. this.x = x; this.y = y; this.cluster = null; /* Set later. */ } /** * Calculates/recalculates the Centroid's position within a Cluster. * Called from ClusteringAlgorithm.java. */ public void calculate() { // Get a reference to the current number of Cluster points. int numberOfDataPoints = getCluster().getNumberOfDataPoints(); double _x = 0.0; double _y = 0.0; // Reset the positions array. for (int i = 0; i < numberOfDataPoints; ++i) { // Update the current x value. _x += getCluster().getDataPoint(i).getX(); // Update the current x value. _y += getCluster().getDataPoint(i).getY(); } // Update the coordinates. setX(_x / numberOfDataPoints); setY(_y / numberOfDataPoints); for (int i = 0; i < numberOfDataPoints; ++i) { // Calculate the new Euclidean Distance for each DataPoint instance in the Cluster reference. getCluster().getDataPoint(i).calculateEuclideanDistance(); } // Recalculate SumOfSquares for the Cluster reference. getCluster().calculateSumOfSquares(); } /** * @return cluster */ public double getCluster() { return this.cluster; } /** * @param cluster */ public void setCluster(Cluster cluster) { this.cluster = cluster; } /** * @param x */ public void setX(double x) { this.x = x; } /** * @param y */ public void setY(double y) { this.y = y; } }
package authoring_environment; import gamedata.gamecomponents.Patch; import gamedata.gamecomponents.Piece; import java.awt.geom.Point2D; import java.util.ArrayList; import java.util.List; import java.util.Observable; import java.util.Observer; import javafx.event.EventHandler; import javafx.scene.input.MouseEvent; import authoring.data.PatchData; import authoring.data.PatchTypeData; import authoring.data.PieceData; import authoring.data.PieceTypeData; // TODO: REMOVE THE DUPLICATED CODE. SO MUCH. /** * Authoring, engine, and player may all use this grid!! * * @author Jennie Ju * */ public class GUIGrid extends SuperGrid implements Observer { private PieceData myPieceData; private PatchData myPatchData; public GUIGrid () { super(); } public GUIGrid (int cols, int rows, double tileSize, String shape) { super(cols, rows, tileSize, shape); myPieceData = new PieceData(); myPatchData = new PatchData(); } public GUIGrid (int cols, int rows, double tileSize, String shape, PieceData pieceData, PatchData patchData) { super(cols, rows, tileSize, shape); myPieceData = pieceData; myPatchData = patchData; } public GUIGrid (int cols, int rows, double tileSize, String shape, GUIGrid copyGrid) { super(cols, rows, tileSize, shape); myPieceData = copyGrid.myPieceData; myPatchData = copyGrid.myPatchData; // removeRunOffPieces(cols, rows, myPieceData); // removeRunOffPieces(cols, rows, myPieceData); } /** * Returns number of rows * * @return int number of rows */ public int getNumRows () { return super.myHeight; } /** * Returns number of columns * * @return int number of columns */ public int getNumCols () { return super.myWidth; } public void addPiece (Piece pieceType, Point2D loc) { Piece clone = new Piece(pieceType, loc); myPieceData.add(clone); SuperTile myTile = myGrid.get((int) loc.getY()).get((int) loc.getX()); myTile.addPieceImage(clone.getImageView()); System.out.println(myPieceData.getData().size()); } public void addPatch (Patch patchType, Point2D loc) { Patch clone = new Patch(patchType, loc); myPatchData.add(clone); SuperTile myTile = myGrid.get((int) loc.getY()).get((int) loc.getX()); myTile.addPatchImage(clone.getImageView()); System.out.println(myPatchData.getData().size()); } /** * Removes a piece at the given coordinates. * NOTE: Point2D coordinates given as * X = column number, Y = row number * * @param coor - Point2D containing coordinates of * the piece to remove given as [Col, Row] */ public void removePieceAtCoordinate (Point2D coor) { Piece toRemove = getPiece(coor); removePiece(toRemove); } /** * Removes a piece at the given coordinates. * NOTE: Point2D coordinates given as * X = column number, Y = row number * * @param coor - Point2D containing coordinates of * the piece to remove given as [Col, Row] */ public void removePatchAtCoordinate (Point2D coor) { Patch toRemove = getPatch(coor); removePatch(toRemove); } private void replacePieceType (Piece pieceType) { List<Point2D> pointsToReplace = myPieceData.replace(pieceType); for (Point2D loc : pointsToReplace) { SuperTile tile = super.findClickedTile(loc); tile.addPatchImage(pieceType.getImageView()); } } private void replacePatchType (Patch patchType) { List<Point2D> pointsToReplace = myPatchData.replace(patchType); // System.out.println(pointsToReplace.toString()); for (Point2D loc : pointsToReplace) { SuperTile tile = super.findClickedTile(loc); tile.addPatchImage(patchType.getImageView()); } } private void removePieceType (PieceTypeData typeData) { List<Point2D> pointsToRemove = myPieceData.removeUnknown(typeData.getIdSet()); for (Point2D loc : pointsToRemove) { SuperTile tile = super.findClickedTile(loc); tile.removePieceImage(); } } private void removePatchType (PatchTypeData typeData) { List<Point2D> pointsToRemove = myPatchData.removeUnknown(typeData .getIdSet()); for (Point2D loc : pointsToRemove) { SuperTile tile = super.findClickedTile(loc); tile.removePatchImage(); } } /** * Returns the piece at loc * * @param loc * @return */ public Piece getPiece (Point2D loc) { for (Piece p : myPieceData.getData()) { if ((p.getLoc().getX() == loc.getX()) & (p.getLoc().getY() == loc.getY())) { return p; } } return null; } /** * Returns the patch at loc * * @param loc * @return */ public Patch getPatch (Point2D loc) { for (Patch p : myPatchData.getData()) { if ((p.getLoc().getX() == loc.getX()) & (p.getLoc().getY() == loc.getY())) { return p; } } return null; } public void removePiece (Piece p) { SuperTile currentTile = findClickedTile(p.getLoc()); myPieceData.remove(p); currentTile.clearPieceImage(); } public void removePatch (Patch p) { myPatchData.remove(p); SuperTile currentTile = findClickedTile(p.getLoc()); currentTile.removePatchImage(); } /** * Gets Pieces that have been tagged for removal * * @return */ public List<Piece> getRemovedPieces () { List<Piece> l = new ArrayList<Piece>(); for (Piece p : myPieceData.getData()) { // TODO: FOR TESTING ONLY if (p.getStats().getValue("health") <= 0) { p.markForRemoval(); } if (p.shouldRemove()) { l.add(p); } } return l; } /** * Returns all pieces that belong to a given player * * @param playerId * - ID of player * @return List of pieces belonging to the player */ public List<Piece> getPlayerPieces (int playerId) { List<Piece> l = new ArrayList<Piece>(); for (Piece p : myPieceData.getData()) { if (p.getPlayerID() == playerId) { l.add(p); } } return l; } public void repopulateGrid () { this.initGridTiles(this.myShape); for (Patch p : myPatchData.getData()) { this.addPatchToTile(p, p.getLoc()); } for (Piece p : myPieceData.getData()) { this.addPieceToTile(p, p.getLoc()); } } @Override public void update (Observable o, Object arg) { if (o instanceof PieceTypeData) { PieceTypeData typeData = (PieceTypeData) o; if (arg == null) { System.out.println("AH!"); // TODO : FIX! removePieceType(typeData); } if (arg instanceof Piece) { Piece pieceType = (Piece) arg; replacePieceType(pieceType); } } if (o instanceof PatchTypeData) { PatchTypeData typeData = (PatchTypeData) o; if (arg == null) { System.out.println("GAH!"); // TODO : FIX! removePatchType(typeData); } if (arg instanceof Patch) { Patch patchType = (Patch) arg; replacePatchType(patchType); } } } public void addPieceToTile (Piece pieceType, Point2D loc) { SuperTile myTile = myGrid.get((int) loc.getY()).get((int) loc.getX()); myTile.addPieceImage(pieceType.getImageView()); } public void addPatchToTile (Patch patchType, Point2D loc) { SuperTile myTile = myGrid.get((int) loc.getY()).get((int) loc.getX()); myTile.addPatchImage(patchType.getImageView()); } // TODO: separate the two types of mouse events (drag and click) public void paneSetOnMouseEvent (EventHandler<MouseEvent> handler) { myPane.setOnMouseClicked(handler); myPane.setOnMouseDragged(handler); } public PieceData getPieces(){ return myPieceData; } public PatchData getPatches(){ return myPatchData; } }
// -*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: // @homepage@ package example; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.geom.RoundRectangle2D; import java.awt.image.BufferedImage; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.*; public final class MainPanel extends JPanel { private MainPanel() { super(); BufferedImage img = null; try { img = ImageIO.read(getClass().getResource("test.jpg")); } catch (IOException ex) { ex.printStackTrace(); img = makeMissingImage(); } BufferedImage image = img; int width = image.getWidth(); int height = image.getHeight(); Shape shape = new RoundRectangle2D.Float(0f, 0f, width / 2f, height / 2f, 50f, 50f); BufferedImage clippedImage = makeClippedImage(image, shape); JButton button1 = new JButton("clipped window"); button1.addActionListener(e -> { JWindow window = new JWindow(); window.getContentPane().add(makePanel(image)); window.setShape(shape); window.pack(); window.setLocationRelativeTo(((AbstractButton) e.getSource()).getRootPane()); window.setVisible(true); }); JButton button2 = new JButton("soft clipped window"); button2.addActionListener(e -> { JWindow window = new JWindow(); window.setBackground(new Color(0x0, true)); window.getContentPane().add(makePanel(clippedImage)); window.pack(); window.setLocationRelativeTo(((AbstractButton) e.getSource()).getRootPane()); window.setVisible(true); }); add(button1); add(button2); setPreferredSize(new Dimension(320, 240)); } private static Component makePanel(BufferedImage image) { JPanel panel = new JPanel(new BorderLayout()) { @Override public Dimension getPreferredSize() { return new Dimension(image.getWidth(this) / 2, image.getHeight(this) / 2); } @Override protected void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g.create(); g2.drawImage(image, 0, 0, this); g2.dispose(); super.paintComponent(g); } }; DragWindowListener dwl = new DragWindowListener(); panel.addMouseListener(dwl); panel.addMouseMotionListener(dwl); JButton close = new JButton("close"); close.addActionListener(e -> { Component c = (Component) e.getSource(); Window window = SwingUtilities.getWindowAncestor(c); window.dispose(); }); Box box = Box.createHorizontalBox(); box.setBorder(BorderFactory.createEmptyBorder(2, 0, 10, 30)); box.add(Box.createHorizontalGlue()); box.add(close); // box.setOpaque(false); panel.add(box, BorderLayout.SOUTH); panel.setOpaque(false); return panel; } // campbell: Java 2D Trickery: Soft Clipping Blog | Oracle Community private static BufferedImage makeClippedImage(BufferedImage source, Shape shape) { int width = source.getWidth(); int height = source.getHeight(); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = image.createGraphics(); // g2.setComposite(AlphaComposite.Clear); // g2.fillRect(0, 0, width, height); g2.setComposite(AlphaComposite.Src); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // g2.setColor(Color.WHITE); g2.fill(shape); g2.setComposite(AlphaComposite.SrcAtop); g2.drawImage(source, 0, 0, null); g2.dispose(); return image; } private static BufferedImage makeMissingImage() { BufferedImage image = new BufferedImage(320, 240, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = image.createGraphics(); g2.setPaint(Color.RED); g2.fillRect(0, 0, image.getWidth(), image.getHeight()); g2.dispose(); return image; } public static void main(String... args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { createAndShowGui(); } }); } public static void createAndShowGui() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } class DragWindowListener extends MouseAdapter { private final Point startPt = new Point(); @Override public void mousePressed(MouseEvent e) { if (SwingUtilities.isLeftMouseButton(e)) { startPt.setLocation(e.getPoint()); } } @Override public void mouseDragged(MouseEvent e) { Component c = SwingUtilities.getRoot(e.getComponent()); if (c instanceof Window && SwingUtilities.isLeftMouseButton(e)) { Window window = (Window) c; Point pt = window.getLocation(); window.setLocation(pt.x - startPt.x + e.getX(), pt.y - startPt.y + e.getY()); } } }
package com.pixnfit.ws; import android.content.Context; import android.content.SharedPreferences; import android.os.AsyncTask; import android.util.Base64; import android.util.Log; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public abstract class WsAsyncTask<Params, Progress, Result> extends AsyncTask<Params, Progress, Result> implements WsConstants { public static final String TAG = WsAsyncTask.class.getSimpleName(); private Context context; public WsAsyncTask(Context context) { this.context = context; } public Context getContext() { return context; } protected String getLogin() { SharedPreferences sharedPreferences = context.getSharedPreferences("pixnfit", Context.MODE_PRIVATE); return sharedPreferences.getString("login", ""); } protected String getPassword() { SharedPreferences sharedPreferences = context.getSharedPreferences("pixnfit", Context.MODE_PRIVATE); return sharedPreferences.getString("password", ""); } private String getBasicAuthString() { String login = getLogin(); String password = getPassword(); return Base64.encodeToString(("" + login + ":" + password).getBytes(), Base64.DEFAULT); } private String getAuthorization() { return "Basic " + getBasicAuthString(); } protected HttpURLConnection initConnection(String path) throws IOException { return initConnection(path, null); } protected HttpURLConnection initConnection(String path, String method) throws IOException { method = method == null ? "GET" : method; URL url = new URL(BASE_URL + path); Log.i(TAG, method + " " + url.toString()); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestProperty("Authorization", getAuthorization()); httpURLConnection.setRequestProperty("Accept", "application/json"); httpURLConnection.setConnectTimeout(10000); httpURLConnection.setReadTimeout(10000); if (method != null) { httpURLConnection.setRequestMethod(method); } if ("POST".equals(method) || "PUT".equals(method) || "DELETE".equals(method)) { httpURLConnection.setDoOutput(true); httpURLConnection.setUseCaches(false); httpURLConnection.setRequestProperty("Content-Type", "application/json"); } return httpURLConnection; } protected String readConnection(HttpURLConnection connection) throws IOException { InputStream inputStream = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream)); String line = ""; StringBuilder stringBuilder = new StringBuilder(); while ((line = rd.readLine()) != null) { stringBuilder.append(line); } return stringBuilder.toString(); } }
package diaspora.forager; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.RadioButton; import android.widget.TextView; import android.widget.Toast; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.VolleyLog; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.crash.FirebaseCrash; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; public class StartGame extends AppCompatActivity { private static final Logger logger = Logger.getLogger(StartGame.class.getName()); private TextView question; private TextView counter; private Button skipButton; private Button submitButton; private RequestQueue queue; private DatabaseReference databaseReference; private FirebaseAuth firebaseAuth; private int questionCurrent = 0; private String uid; private String questionId; private static final String KEY = "wp_v2_x2000_2piyq"; private static final String SERVER = "https://crowd9api-dot-wikidetox.appspot.com/client_jobs/"; private static final Logger LOGGER = Logger.getLogger(StartGame.class.getName()); private RadioButton vToxic; private RadioButton sToxic; private RadioButton nToxic; private RadioButton vInsult; private RadioButton sInsult; private RadioButton nInsult; private RadioButton vObscene; private RadioButton sObscene; private RadioButton nObscene; private RadioButton vThreat; private RadioButton sThreat; private RadioButton nThreat; private RadioButton vIdentity; private RadioButton sIdentity; private RadioButton nIdentity; private CheckBox readable; private EditText comments; private void setComponents() { question = (TextView) findViewById(R.id.question); counter = (TextView) findViewById(R.id.counter); skipButton = (Button) findViewById(R.id.skipButton); submitButton = (Button) findViewById(R.id.Submit); // Instantiate the RequestQueue. queue = Volley.newRequestQueue(this); //Initialise FirebaseAuth firebaseAuth = FirebaseAuth.getInstance(); databaseReference = FirebaseDatabase.getInstance().getReference(); uid = firebaseAuth.getCurrentUser().getUid(); readable = (CheckBox) findViewById(R.id.legibleCheckBox); vToxic = (RadioButton) findViewById(R.id.veryToxic); sToxic = (RadioButton) findViewById(R.id.somewhatToxic); nToxic = (RadioButton) findViewById(R.id.notToxic); vInsult = (RadioButton) findViewById(R.id.veryInsult); sInsult = (RadioButton) findViewById(R.id.somewhatInsult); nInsult = (RadioButton) findViewById(R.id.notInsult); vObscene = (RadioButton) findViewById(R.id.veryObscene); sObscene = (RadioButton) findViewById(R.id.somewhatObscene); nObscene = (RadioButton) findViewById(R.id.notObscene); vThreat = (RadioButton) findViewById(R.id.veryThreat); sThreat = (RadioButton) findViewById(R.id.somewhatThreat); nThreat = (RadioButton) findViewById(R.id.notThreat); vIdentity = (RadioButton) findViewById(R.id.veryHate); sIdentity = (RadioButton) findViewById(R.id.somewhatHate); nIdentity = (RadioButton) findViewById(R.id.notHate); comments = (EditText) findViewById(R.id.comments); } private void loadQuestion() { String url = SERVER + KEY + "/next10_unanswered_questions"; // Request a string response from the provided URL. StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { int questionNo = Integer.parseInt(counter.getText().toString()) - 1; // Display the first 500 characters of the response string. try { JSONArray responseObject = new JSONArray(response); JSONObject questionObject = new JSONObject(responseObject.getString(questionNo)); question.setText(questionObject.toString()); JSONObject revisionObject = new JSONObject(questionObject.getString("question")); String questiontoRate = revisionObject.getString("revision_text"); question.setText(questiontoRate); questionId = questionObject.getString("question_id"); } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { question.setText("That didn't work!"); } }); // Add the request to the RequestQueue. queue.add(stringRequest); } private Map buildParams() { Map<String, String> params = new HashMap<String, String>(); if (readable.isChecked()) { params.put("readableAndInEnglish", "Yes"); } else { params.put("readableAndInEnglish", "No"); } if (vToxic.isChecked()) { params.put("toxic", "Very"); } if (sToxic.isChecked()) { params.put("toxic", "Somewhat"); } if (nToxic.isChecked()) { params.put("toxic", "NotAtAll"); } if (vObscene.isChecked()) { params.put("obscene", "Very"); } if (sObscene.isChecked()) { params.put("obscene", "Somewhat"); } if (nObscene.isChecked()) { params.put("obscene", "NotAtAll"); } if (vIdentity.isChecked()) { params.put("identityHate", "Very"); } if (sIdentity.isChecked()) { params.put("identityHate", "Somewhat"); } if (nIdentity.isChecked()) { params.put("identityHate", "NotAtAll"); } if (vInsult.isChecked()) { params.put("insult", "Very"); } if (sInsult.isChecked()) { params.put("insult", "Somewhat"); } if (nInsult.isChecked()) { params.put("insult", "NotAtAll"); } if (vThreat.isChecked()) { params.put("threat", "Very"); } if (sThreat.isChecked()) { params.put("threat", "Somewhat"); } if (nThreat.isChecked()) { params.put("threat", "NotAtAll"); } if ((comments.getText() != null) || (!comments.getText().equals(""))) { params.put("comments", comments.getText().toString()); } else { params.put("comments", ""); } return params; } // private void pushAnswer() { // String url = SERVER + KEY + "/questions/" + questionId + "/answers/" + uid; // StringRequest postRequest = new StringRequest(Request.Method.POST, url, // new Response.Listener<String>() { // @Override // public void onResponse(String response) { // // response // loadQuestion(); // new Response.ErrorListener() { // @Override // public void onErrorResponse(VolleyError error) { // // error // Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_LONG).show(); // @Override // public Map<String, String> getParams() { // Map<String, String> params = new HashMap<String, String>(); // params.put("answer", new JSONObject(buildParams()).toString()); // Log.e("TheDiaspora", params.get("answer")); // Log.e("TheDiaspora", new JSONObject(params).toString()); // return params; // @Override // public Map<String, String> getHeaders() throws AuthFailureError { // Map<String, String> headers = new HashMap<String, String>(); // headers.put("Content-Type", "application/json"); // Log.e("TheDiaspora", new JSONObject(headers).toString()); // return headers; // queue.add(postRequest); private void pushAnswer() { String url = SERVER + KEY + "/questions/" + questionId + "/answers/" + uid; Map<String, String> params = new HashMap<String, String>(); params.put("answer", new JSONObject(buildParams()).toString()); JsonObjectRequest req = new JsonObjectRequest(url, new JSONObject(params), new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { Log.e("Response: ", response.toString()); } catch (Exception e) { e.printStackTrace(); } nextQuestion(); //TODO: Test this } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("Error: ", error.getMessage()); nextQuestion(); //TODO: Test this also } }) { @Override public Map<String, String> getHeaders() throws AuthFailureError { HashMap<String, String> headers = new HashMap<String, String>(); headers.put("Content-Type", "application/json"); return headers; } }; queue.add(req); } private void nextQuestion(){ readable.setChecked(true); vToxic.setChecked(false); sToxic.setChecked(false); nToxic.setChecked(false); vInsult.setChecked(false); sInsult.setChecked(false); nInsult.setChecked(false); vObscene.setChecked(false); sObscene.setChecked(false); nObscene.setChecked(false); vThreat.setChecked(false); sThreat.setChecked(false); nThreat.setChecked(false); vIdentity.setChecked(false); sIdentity.setChecked(false); nIdentity.setChecked(false); comments.setText(""); //comments = (EditText) findViewById(R.id.comments); question.setText("Loading question..."); int questionNo = Integer.parseInt(counter.getText().toString()); questionNo++; if ((questionNo) > 10) { counter.setText(Integer.toString(1)); } else { counter.setText(Integer.toString(questionNo)); } loadQuestion(); } private void setOnClick() { skipButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { nextQuestion(); } }); submitButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { pushAnswer(); subtractFromDistanceRemaining(databaseReference, firebaseAuth.getCurrentUser()); addMushroomToDatabase(databaseReference, firebaseAuth.getCurrentUser()); addPointToDatabase(databaseReference, firebaseAuth.getCurrentUser()); } }); } private void subtractFromDistanceRemaining(final DatabaseReference databaseReference, FirebaseUser firebaseUser) { try { databaseReference.child("global") .child("distanceRemaining") .addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { // Update the database subtractFromDistanceRemaining(databaseReference, (dataSnapshot.getValue(Long.class).intValue() - 1)); } @Override public void onCancelled(DatabaseError databaseError) { logger.log(Level.SEVERE, "Database Error Occurred", databaseError.toException()); FirebaseCrash.report(databaseError.toException()); } }); } catch (Throwable e) { logger.log(Level.SEVERE, "Unidentified Error Occurred", e); FirebaseCrash.report(e); } } private void subtractFromDistanceRemaining(DatabaseReference databaseReference, int distanceRemaining) { try { databaseReference.child("global") .child("distanceRemaining").setValue(distanceRemaining); } catch (Throwable e) { logger.log(Level.SEVERE, "Unidentified Error Occurred", e); FirebaseCrash.report(e); } } private void addMushroomToDatabase(final DatabaseReference databaseReference, final FirebaseUser firebaseUser) { try { databaseReference.child("users") .child(firebaseUser.getUid()) .addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { // Update the cloud database addMushroomToDatabase(databaseReference, firebaseUser, (dataSnapshot.getValue(User.class).getNumberOfMushrooms() + 1)); } @Override public void onCancelled(DatabaseError databaseError) { logger.log(Level.SEVERE, "Database Error Occurred", databaseError.toException()); FirebaseCrash.report(databaseError.toException()); } }); } catch (Throwable e) { logger.log(Level.SEVERE, "Unidentified Error Occurred", e); FirebaseCrash.report(e); } } private void addMushroomToDatabase(DatabaseReference databaseReference, FirebaseUser firebaseUser, int numberOfMushrooms) { try { databaseReference.child("users") .child(firebaseUser.getUid()) .child("numberOfMushrooms").setValue(numberOfMushrooms); } catch (Throwable e) { logger.log(Level.SEVERE, "Unidentified Error Occurred", e); FirebaseCrash.report(e); } } private void addPointToDatabase(final DatabaseReference databaseReference, final FirebaseUser firebaseUser) { try { databaseReference.child("users") .child(firebaseUser.getUid()) .addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { // Update the cloud database addPointToDatabase(databaseReference, firebaseUser, (dataSnapshot.getValue(User.class).getNumberOfPoints() + 1)); } @Override public void onCancelled(DatabaseError databaseError) { logger.log(Level.SEVERE, "Database Error Occurred", databaseError.toException()); FirebaseCrash.report(databaseError.toException()); } }); } catch (Throwable e) { logger.log(Level.SEVERE, "Unidentified Error Occurred", e); FirebaseCrash.report(e); } } private void addPointToDatabase(DatabaseReference databaseReference, FirebaseUser firebaseUser, int numberOfPoints) { try { databaseReference.child("users") .child(firebaseUser.getUid()) .child("numberOfPoints").setValue(numberOfPoints); } catch (Throwable e) { logger.log(Level.SEVERE, "Unidentified Error Occurred", e); FirebaseCrash.report(e); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_start_game); setComponents(); setOnClick(); loadQuestion(); } }
package it.asg.hustle; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.support.design.widget.CollapsingToolbarLayout; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.GravityCompat; import android.support.v4.view.ViewPager; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Locale; public class ShowActivity extends AppCompatActivity { private ImageView posterImageView; private JSONObject show = null; private Bitmap posterBitmap = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null) posterBitmap = savedInstanceState.getParcelable("poster"); if (savedInstanceState != null) try { show = new JSONObject(savedInstanceState.getString("show")); } catch (JSONException e) { e.printStackTrace(); } setContentView(R.layout.activity_show); Bundle b = getIntent().getExtras(); if (b != null) { String s = b.getString("show"); try { show = new JSONObject(s); doGetShowPoster(show.getString("fanart")); } catch (JSONException e) { e.printStackTrace(); } } // get toolbar Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); CollapsingToolbarLayout collapsingToolbar = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar); try { collapsingToolbar.setTitle(show.getString("seriesname")); } catch (JSONException e) { e.printStackTrace(); } SeasonsAdapter a = new SeasonsAdapter(getSupportFragmentManager()); ViewPager viewPager = (ViewPager)findViewById(R.id.viewpager); viewPager.setAdapter(a); TabLayout tabLayout = (TabLayout)findViewById(R.id.tablayout); tabLayout.setupWithViewPager(viewPager); //get poster image posterImageView = (ImageView) findViewById(R.id.show_activity_poster); if(posterBitmap!=null){posterImageView.setImageBitmap(posterBitmap);} // TODO: mostra la serie nell'activity Log.d("HUSTLE", "Devo mostrare la serie: " + show); } private void doGetShowPoster(String imageUrl) { AsyncTask<String, Void, Bitmap> at = new AsyncTask<String, Void, Bitmap>() { @Override protected Bitmap doInBackground(String... params) { Bitmap bm = null; InputStream in = null; try { in = new java.net.URL(params[0]).openStream(); } catch (IOException e) { e.printStackTrace(); } bm = BitmapFactory.decodeStream(in); return bm; } @Override protected void onPostExecute(Bitmap bitmap) { super.onPostExecute(bitmap); posterImageView.setImageBitmap(bitmap); posterBitmap = bitmap; } }; at.execute(imageUrl); } public void onSaveInstanceState(Bundle savedInstanceState) { // Save the user's current game state savedInstanceState.putParcelable("poster", posterBitmap); savedInstanceState.putString("show", show.toString()); // Always call the superclass so it can save the view hierarchy state super.onSaveInstanceState(savedInstanceState); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_show, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); switch (id) { case R.id.action_settings: return true; } return super.onOptionsItemSelected(item); } // sottoclasse per gestire i fragment della pagina inziale public static class SeasonsFragment extends Fragment { private static final String TAB_POSITION = "tab_position"; public SeasonsFragment() { } public static SeasonsFragment newInstance(int tabPosition) { SeasonsFragment fragment = new SeasonsFragment(); Bundle args = new Bundle(); args.putInt(TAB_POSITION, tabPosition); fragment.setArguments(args); return fragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Bundle args = getArguments(); int tabPosition = args.getInt(TAB_POSITION); // TODO: modifica questo fragment in modo da mostrare le info sulla serie TV ArrayList<String> items = new ArrayList<String>(); for(int i=0 ; i < 20 ; i++){ items.add("Element "+i); } View v = inflater.inflate(R.layout.fragment_episodes_view, container, false); RecyclerView recyclerView = (RecyclerView)v.findViewById(R.id.recyclerview); recyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); recyclerView.setAdapter(new EpisodeRecyclerAdapter(items)); return v; } } //sottoclasse per l'adapter per i fragment (delle varie tab) class SeasonsAdapter extends FragmentStatePagerAdapter { private int number_of_tabs=2; public SeasonsAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { return SeasonsFragment.newInstance(position); } @Override public int getCount() { return number_of_tabs; } @Override public CharSequence getPageTitle(int position) { switch (position){ case 0: return getResources().getString(R.string.tab_show_info); // break; case 1: return getResources().getString(R.string.tab_season); // break; } return ""; } } }
package org.wikipedia; import android.annotation.SuppressLint; import android.app.Activity; import android.app.Application; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.os.Build; import android.os.Handler; import android.text.TextUtils; import android.view.Window; import android.webkit.WebView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatDelegate; import com.facebook.drawee.backends.pipeline.Fresco; import com.facebook.imagepipeline.core.ImagePipelineConfig; import com.squareup.leakcanary.LeakCanary; import com.squareup.leakcanary.RefWatcher; import org.wikipedia.analytics.FunnelManager; import org.wikipedia.analytics.SessionFunnel; import org.wikipedia.auth.AccountUtil; import org.wikipedia.concurrency.RxBus; import org.wikipedia.connectivity.NetworkConnectivityReceiver; import org.wikipedia.crash.hockeyapp.HockeyAppCrashReporter; import org.wikipedia.database.Database; import org.wikipedia.database.DatabaseClient; import org.wikipedia.dataclient.ServiceFactory; import org.wikipedia.dataclient.SharedPreferenceCookieManager; import org.wikipedia.dataclient.WikiSite; import org.wikipedia.dataclient.fresco.DisabledCache; import org.wikipedia.dataclient.okhttp.CacheableOkHttpNetworkFetcher; import org.wikipedia.dataclient.okhttp.OkHttpConnectionFactory; import org.wikipedia.edit.summaries.EditSummary; import org.wikipedia.events.ChangeTextSizeEvent; import org.wikipedia.events.ThemeChangeEvent; import org.wikipedia.history.HistoryEntry; import org.wikipedia.language.AcceptLanguageUtil; import org.wikipedia.language.AppLanguageState; import org.wikipedia.notifications.NotificationPollBroadcastReceiver; import org.wikipedia.page.tabs.Tab; import org.wikipedia.pageimages.PageImage; import org.wikipedia.search.RecentSearch; import org.wikipedia.settings.Prefs; import org.wikipedia.settings.RemoteConfig; import org.wikipedia.settings.SiteInfoClient; import org.wikipedia.theme.Theme; import org.wikipedia.util.DimenUtil; import org.wikipedia.util.ReleaseUtil; import org.wikipedia.util.log.L; import org.wikipedia.views.ViewAnimations; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.UUID; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.internal.functions.Functions; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.schedulers.Schedulers; import static org.apache.commons.lang3.StringUtils.defaultString; import static org.wikipedia.settings.Prefs.getTextSizeMultiplier; import static org.wikipedia.util.DimenUtil.getFontSizeFromSp; import static org.wikipedia.util.ReleaseUtil.getChannel; public class WikipediaApp extends Application { private final RemoteConfig remoteConfig = new RemoteConfig(); private final Map<Class<?>, DatabaseClient<?>> databaseClients = Collections.synchronizedMap(new HashMap<>()); private Handler mainThreadHandler; private AppLanguageState appLanguageState; private FunnelManager funnelManager; private SessionFunnel sessionFunnel; private NetworkConnectivityReceiver connectivityReceiver = new NetworkConnectivityReceiver(); private ActivityLifecycleHandler activityLifecycleHandler = new ActivityLifecycleHandler(); private Database database; private String userAgent; private WikiSite wiki; private HockeyAppCrashReporter crashReporter; private RefWatcher refWatcher; private RxBus bus; private Theme currentTheme = Theme.getFallback(); private List<Tab> tabList = new ArrayList<>(); private static WikipediaApp INSTANCE; public WikipediaApp() { INSTANCE = this; } public static WikipediaApp getInstance() { return INSTANCE; } public SessionFunnel getSessionFunnel() { return sessionFunnel; } public RefWatcher getRefWatcher() { return refWatcher; } public RxBus getBus() { return bus; } public Database getDatabase() { return database; } public FunnelManager getFunnelManager() { return funnelManager; } public RemoteConfig getRemoteConfig() { return remoteConfig; } /** * Gets the currently-selected theme for the app. * @return Theme that is currently selected, which is the actual theme ID that can * be passed to setTheme() when creating an activity. */ @NonNull public Theme getCurrentTheme() { return currentTheme; } @NonNull public AppLanguageState language() { return appLanguageState; } @NonNull public String getAppOrSystemLanguageCode() { String code = appLanguageState.getAppLanguageCode(); if (AccountUtil.getUserIdForLanguage(code) == 0) { getUserIdForLanguage(code); } return code; } @Override public void onCreate() { super.onCreate(); WikiSite.setDefaultBaseUrl(Prefs.getMediaWikiBaseUrl()); // Register here rather than in AndroidManifest.xml so that we can target Android N. // https://developer.android.com/topic/performance/background-optimization.html#connectivity-action registerReceiver(connectivityReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); initExceptionHandling(); refWatcher = Prefs.isMemoryLeakTestEnabled() ? LeakCanary.install(this) : RefWatcher.DISABLED; // See Javadocs and http://developer.android.com/tools/support-library/index.html#rev23-4-0 AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); // This handler will catch exceptions thrown from Observables after they are disposed, // or from Observables that are (deliberately or not) missing an onError handler. // TODO: consider more comprehensive handling of these errors. RxJavaPlugins.setErrorHandler(Functions.emptyConsumer()); bus = new RxBus(); ViewAnimations.init(getResources()); currentTheme = unmarshalCurrentTheme(); appLanguageState = new AppLanguageState(this); updateCrashReportProps(); funnelManager = new FunnelManager(this); sessionFunnel = new SessionFunnel(this); database = new Database(this); initTabs(); enableWebViewDebugging(); ImagePipelineConfig config = ImagePipelineConfig.newBuilder(this) .setNetworkFetcher(new CacheableOkHttpNetworkFetcher(OkHttpConnectionFactory.getClient())) .setFileCacheFactory(DisabledCache.factory()) .build(); try { Fresco.initialize(this, config); } catch (Exception e) { L.e(e); // TODO: Remove when we're able to initialize Fresco in test builds. } registerActivityLifecycleCallbacks(activityLifecycleHandler); // Kick the notification receiver, in case it hasn't yet been started by the system. NotificationPollBroadcastReceiver.startPollTask(this); } public int getVersionCode() { // Our ABI-specific version codes are structured in increments of 10000, so just // take the actual version code modulo the increment. final int versionCodeMod = 10000; return BuildConfig.VERSION_CODE % versionCodeMod; } public String getUserAgent() { if (userAgent == null) { String channel = getChannel(this); channel = channel.equals("") ? channel : " ".concat(channel); userAgent = String.format("WikipediaApp/%s (Android %s; %s)%s", BuildConfig.VERSION_NAME, Build.VERSION.RELEASE, getString(R.string.device_type), channel ); } return userAgent; } /** * @return the value that should go in the Accept-Language header. */ @NonNull public String getAcceptLanguage(@Nullable WikiSite wiki) { String wikiLang = wiki == null || "meta".equals(wiki.languageCode()) ? "" : defaultString(wiki.languageCode()); return AcceptLanguageUtil.getAcceptLanguage(wikiLang, appLanguageState.getAppLanguageCode(), appLanguageState.getSystemLanguageCode()); } /** * Default wiki for the app * You should use PageTitle.getWikiSite() to get the article wiki */ @NonNull public synchronized WikiSite getWikiSite() { // TODO: why don't we ensure that the app language hasn't changed here instead of the client? if (wiki == null) { String lang = Prefs.getMediaWikiBaseUriSupportsLangCode() ? getAppOrSystemLanguageCode() : ""; WikiSite newWiki = WikiSite.forLanguageCode(lang); // Kick off a task to retrieve the site info for the current wiki SiteInfoClient.updateFor(newWiki); wiki = newWiki; return newWiki; } return wiki; } public <T> DatabaseClient<T> getDatabaseClient(Class<T> cls) { if (!databaseClients.containsKey(cls)) { DatabaseClient<?> client; if (cls.equals(HistoryEntry.class)) { client = new DatabaseClient<>(this, HistoryEntry.DATABASE_TABLE); } else if (cls.equals(PageImage.class)) { client = new DatabaseClient<>(this, PageImage.DATABASE_TABLE); } else if (cls.equals(RecentSearch.class)) { client = new DatabaseClient<>(this, RecentSearch.DATABASE_TABLE); } else if (cls.equals(EditSummary.class)) { client = new DatabaseClient<>(this, EditSummary.DATABASE_TABLE); } else { throw new RuntimeException("No persister found for class " + cls.getCanonicalName()); } databaseClients.put(cls, client); } //noinspection unchecked return (DatabaseClient<T>) databaseClients.get(cls); } /** * Get this app's unique install ID, which is a UUID that should be unique for each install * of the app. Useful for anonymous analytics. * @return Unique install ID for this app. */ public String getAppInstallID() { String id = Prefs.getAppInstallId(); if (id == null) { id = UUID.randomUUID().toString(); Prefs.setAppInstallId(id); } return id; } /** * Sets the theme of the app. If the new theme is the same as the current theme, nothing happens. * Otherwise, an event is sent to notify of the theme change. */ public void setCurrentTheme(@NonNull Theme theme) { if (theme != currentTheme) { currentTheme = theme; Prefs.setThemeId(currentTheme.getMarshallingId()); bus.post(new ThemeChangeEvent()); } } public boolean setFontSizeMultiplier(int multiplier) { int minMultiplier = getResources().getInteger(R.integer.minTextSizeMultiplier); int maxMultiplier = getResources().getInteger(R.integer.maxTextSizeMultiplier); if (multiplier < minMultiplier) { multiplier = minMultiplier; } else if (multiplier > maxMultiplier) { multiplier = maxMultiplier; } if (multiplier != getTextSizeMultiplier()) { Prefs.setTextSizeMultiplier(multiplier); bus.post(new ChangeTextSizeEvent()); return true; } return false; } public void putCrashReportProperty(String key, String value) { if (!ReleaseUtil.isPreBetaRelease()) { crashReporter.putReportProperty(key, value); } } public void checkCrashes(@NonNull Activity activity) { if (!ReleaseUtil.isPreBetaRelease()) { crashReporter.checkCrashes(activity); } } public Handler getMainThreadHandler() { if (mainThreadHandler == null) { mainThreadHandler = new Handler(getMainLooper()); } return mainThreadHandler; } public List<Tab> getTabList() { return tabList; } public void commitTabState() { if (tabList.isEmpty()) { Prefs.clearTabs(); initTabs(); } else { Prefs.setTabs(tabList); } } public int getTabCount() { // handle the case where we have a single tab with an empty backstack, // which shouldn't count as a valid tab: return tabList.size() > 1 ? tabList.size() : tabList.isEmpty() ? 0 : tabList.get(0).getBackStack().isEmpty() ? 0 : tabList.size(); } public boolean isOnline() { return connectivityReceiver.isOnline(); } /** * Gets the current size of the app's font. This is given as a device-specific size (not "sp"), * and can be passed directly to setTextSize() functions. * @param window The window on which the font will be displayed. * @return Actual current size of the font. */ public float getFontSize(Window window) { return getFontSizeFromSp(window, getResources().getDimension(R.dimen.textSize)) * (1.0f + getTextSizeMultiplier() * DimenUtil.getFloat(R.dimen.textSizeMultiplierFactor)); } public synchronized void resetWikiSite() { wiki = null; updateCrashReportProps(); } @SuppressLint("CheckResult") public void logOut() { L.d("Logging out"); AccountUtil.removeAccount(); ServiceFactory.get(getWikiSite()).getCsrfToken() .subscribeOn(Schedulers.io()) .flatMap(response -> ServiceFactory.get(getWikiSite()).postLogout(response.query().csrfToken()).subscribeOn(Schedulers.io())) .doFinally(() -> SharedPreferenceCookieManager.getInstance().clearAllCookies()) .subscribe(response -> L.d("Logout complete."), L::e); } private void initExceptionHandling() { // HockeyApp exception handling interferes with the test runner, so enable it only for beta and stable releases if (!ReleaseUtil.isPreBetaRelease()) { crashReporter = new HockeyAppCrashReporter(getString(R.string.hockeyapp_app_id), consentAccessor()); L.setRemoteLogger(crashReporter); } } private void updateCrashReportProps() { // HockeyApp exception handling interferes with the test runner, so enable it only for beta and stable releases if (!ReleaseUtil.isPreBetaRelease()) { putCrashReportProperty("locale", Locale.getDefault().toString()); if (appLanguageState != null) { putCrashReportProperty("app_primary_language", appLanguageState.getAppLanguageCode()); putCrashReportProperty("app_languages", appLanguageState.getAppLanguageCodes().toString()); } } } private HockeyAppCrashReporter.AutoUploadConsentAccessor consentAccessor() { return Prefs::isCrashReportAutoUploadEnabled; } private void enableWebViewDebugging() { if (BuildConfig.DEBUG) { WebView.setWebContentsDebuggingEnabled(true); } } private Theme unmarshalCurrentTheme() { int id = Prefs.getThemeId(); Theme result = Theme.ofMarshallingId(id); if (result == null) { L.d("Theme id=" + id + " is invalid, using fallback."); result = Theme.getFallback(); } return result; } @SuppressLint("CheckResult") private void getUserIdForLanguage(@NonNull final String code) { if (!AccountUtil.isLoggedIn() || TextUtils.isEmpty(AccountUtil.getUserName())) { return; } final WikiSite wikiSite = WikiSite.forLanguageCode(code); ServiceFactory.get(wikiSite).getUserInfo(AccountUtil.getUserName()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(response -> { if (AccountUtil.isLoggedIn() && response.query().getUserResponse(AccountUtil.getUserName()) != null) { // noinspection ConstantConditions int id = response.query().userInfo().id(); AccountUtil.putUserIdForLanguage(code, id); L.d("Found user ID " + id + " for " + code); } }, caught -> L.e("Failed to get user ID for " + code, caught)); } private void initTabs() { if (Prefs.hasTabs()) { tabList.addAll(Prefs.getTabs()); } if (tabList.isEmpty()) { tabList.add(new Tab()); } } public boolean haveMainActivity() { return activityLifecycleHandler.haveMainActivity(); } public boolean isAnyActivityResumed() { return activityLifecycleHandler.isAnyActivityResumed(); } }
package com.gooddata.processor; import com.gooddata.connector.*; import com.gooddata.exception.*; import com.gooddata.integration.model.Column; import com.gooddata.integration.model.SLI; import com.gooddata.integration.rest.GdcRESTApiWrapper; import com.gooddata.integration.rest.MetadataObject; import com.gooddata.integration.rest.configuration.NamePasswordConfiguration; import com.gooddata.modeling.model.SourceSchema; import com.gooddata.naming.N; import com.gooddata.processor.parser.DIScriptParser; import com.gooddata.processor.parser.ParseException; import com.gooddata.util.DatabaseToCsv; import com.gooddata.util.FileUtil; import com.gooddata.util.StringUtil; import org.apache.commons.cli.*; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import org.joda.time.DateTimeZone; import java.io.*; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Properties; /** * The GoodData Data Integration CLI processor. * * @author jiri.zaloudek * @author Zdenek Svoboda <zd@gooddata.org> * @version 1.0 */ public class GdcDI implements Executor { private static Logger l = Logger.getLogger(GdcDI.class); //Options data public static String[] CLI_PARAM_HELP = {"help", "H"}; public static String[] CLI_PARAM_USERNAME = {"username", "u"}; public static String[] CLI_PARAM_PASSWORD = {"password", "p"}; public static String[] CLI_PARAM_HOST = {"host", "h"}; public static String[] CLI_PARAM_FTP_HOST = {"ftphost", "f"}; public static String[] CLI_PARAM_PROJECT = {"project", "i"}; public static String[] CLI_PARAM_PROTO = {"proto", "t"}; public static String[] CLI_PARAM_INSECURE = {"insecure", "s"}; public static String[] CLI_PARAM_EXECUTE = {"execute", "e"}; public static String[] CLI_PARAM_VERSION = {"version", "V"}; public static String[] CLI_PARAM_DEFAULT_DATE_FOREIGN_KEY = {"default-date-fk", "D"}; public static String[] CLI_PARAM_HTTP_PROXY_HOST = {"proxyhost", "K"}; public static String[] CLI_PARAM_HTTP_PROXY_PORT = {"proxyport", "L"}; public static String[] CLI_PARAM_HTTP_PORT = {"port", "S"}; public static String[] CLI_PARAM_FTP_PORT = {"ftpport", "O"}; public static String[] CLI_PARAM_HTTP_PROXY_USERNAME = {"proxyusername", "U"}; public static String[] CLI_PARAM_HTTP_PROXY_PASSWORD = {"proxypassword", "P"}; public static String[] CLI_PARAM_TIMEZONE = {"timezone", "T"}; public static String CLI_PARAM_SCRIPT = "script"; private static String DEFAULT_PROPERTIES = "gdi.properties"; // Command line options private static Options ops = new Options(); public static Option[] Options = { new Option(CLI_PARAM_HELP[1], CLI_PARAM_HELP[0], false, "Print command reference"), new Option(CLI_PARAM_USERNAME[1], CLI_PARAM_USERNAME[0], true, "GoodData username"), new Option(CLI_PARAM_PASSWORD[1], CLI_PARAM_PASSWORD[0], true, "GoodData password"), new Option(CLI_PARAM_HTTP_PROXY_HOST[1], CLI_PARAM_HTTP_PROXY_HOST[0], true, "HTTP proxy hostname."), new Option(CLI_PARAM_HTTP_PROXY_PORT[1], CLI_PARAM_HTTP_PROXY_PORT[0], true, "HTTP proxy port."), new Option(CLI_PARAM_HTTP_PORT[1], CLI_PARAM_HTTP_PORT[0], true, "HTTP port."), new Option(CLI_PARAM_FTP_PORT[1], CLI_PARAM_FTP_PORT[0], true, "Data stage port (deprecated)"), new Option(CLI_PARAM_HTTP_PROXY_USERNAME[1], CLI_PARAM_HTTP_PROXY_USERNAME[0], true, "HTTP proxy username."), new Option(CLI_PARAM_HTTP_PROXY_PASSWORD[1], CLI_PARAM_HTTP_PROXY_PASSWORD[0], true, "HTTP proxy password."), new Option(CLI_PARAM_HOST[1], CLI_PARAM_HOST[0], true, "GoodData host"), new Option(CLI_PARAM_FTP_HOST[1], CLI_PARAM_FTP_HOST[0], true, "GoodData data stage host (deprecated)"), new Option(CLI_PARAM_PROJECT[1], CLI_PARAM_PROJECT[0], true, "GoodData project identifier (a string like nszfbgkr75otujmc4smtl6rf5pnmz9yl)"), new Option(CLI_PARAM_PROTO[1], CLI_PARAM_PROTO[0], true, "HTTP or HTTPS (deprecated)"), new Option(CLI_PARAM_INSECURE[1], CLI_PARAM_INSECURE[0], false, "Disable encryption"), new Option(CLI_PARAM_VERSION[1], CLI_PARAM_VERSION[0], false, "Prints the tool version."), new Option(CLI_PARAM_TIMEZONE[1], CLI_PARAM_TIMEZONE[0], true, "Specify the default timezone (the computer timezone is the default)."), new Option(CLI_PARAM_EXECUTE[1], CLI_PARAM_EXECUTE[0], true, "Commands and params to execute before the commands in provided files"), new Option(CLI_PARAM_DEFAULT_DATE_FOREIGN_KEY[1], CLI_PARAM_DEFAULT_DATE_FOREIGN_KEY[0], true, "Foreign key to represent an 'unknown' date") }; private CliParams cliParams = null; private Connector[] connectors = null; private ProcessingContext context = new ProcessingContext(); private boolean finishedSucessfuly = false; private static long LOCK_EXPIRATION_TIME = 1000 * 3600; // 1 hour private final static String BUILD_NUMBER = ""; public GdcDI(CommandLine ln, Properties defaults) { try { cliParams = parse(ln, defaults); if(cliParams.containsKey(CLI_PARAM_TIMEZONE[0])) { String timezone = cliParams.get(CLI_PARAM_TIMEZONE[0]); if(timezone != null && timezone.length()>0) { try { DateTimeZone.setDefault(DateTimeZone.forID(timezone)); } catch (IllegalArgumentException e) { throw new InvalidArgumentException("Invalid timezone: '" + timezone+"'."); } } else { DateTimeZone.setDefault(DateTimeZone.forID("UTC")); } } if(cliParams.containsKey(CLI_PARAM_HTTP_PORT[0])) { String httpPortString = cliParams.get(CLI_PARAM_HTTP_PORT[0]); int httpPort = 0; try { httpPort = Integer.parseInt(httpPortString); } catch(NumberFormatException e) { throw new InvalidArgumentException("Invalid HTTP port value: '" + httpPortString+"'."); } cliParams.setHttpConfig(new NamePasswordConfiguration( cliParams.containsKey(CLI_PARAM_INSECURE[0]) ? "http" : "https", cliParams.get(CLI_PARAM_HOST[0]), cliParams.get(CLI_PARAM_USERNAME[0]), cliParams.get(CLI_PARAM_PASSWORD[0]), httpPort)); } else { cliParams.setHttpConfig(new NamePasswordConfiguration( cliParams.containsKey(CLI_PARAM_INSECURE[0]) ? "http" : "https", cliParams.get(CLI_PARAM_HOST[0]), cliParams.get(CLI_PARAM_USERNAME[0]), cliParams.get(CLI_PARAM_PASSWORD[0]))); } if(cliParams.containsKey(CLI_PARAM_FTP_PORT[0])) { String ftpPortString = cliParams.get(CLI_PARAM_FTP_PORT[0]); int ftpPort = 0; try { ftpPort = Integer.parseInt(ftpPortString); } catch(NumberFormatException e) { throw new InvalidArgumentException("Invalid WebDav port value: '" + ftpPortString+"'."); } cliParams.setFtpConfig(new NamePasswordConfiguration( cliParams.containsKey(CLI_PARAM_INSECURE[0]) ? "http" : "https", cliParams.get(CLI_PARAM_FTP_HOST[0]), cliParams.get(CLI_PARAM_USERNAME[0]), cliParams.get(CLI_PARAM_PASSWORD[0]),ftpPort)); } else { cliParams.setFtpConfig(new NamePasswordConfiguration( cliParams.containsKey(CLI_PARAM_INSECURE[0]) ? "http" : "https", cliParams.get(CLI_PARAM_FTP_HOST[0]), cliParams.get(CLI_PARAM_USERNAME[0]), cliParams.get(CLI_PARAM_PASSWORD[0]))); } connectors = instantiateConnectors(); String execute = cliParams.get(CLI_PARAM_EXECUTE[0]); String scripts = cliParams.get(CLI_PARAM_SCRIPT); if (execute != null && scripts != null && execute.length() > 0 && scripts.length() > 0) { throw new InvalidArgumentException("You can't execute a script and use the -e command line parameter at the same time."); } if (execute != null && execute.length() > 0) { l.debug("Executing arg=" + execute); execute(execute); } if (scripts != null && scripts.length() > 0) { String[] sas = scripts.split(","); for (String script : sas) { l.debug("Executing file=" + script); execute(new File(script)); } } if (cliParams.containsKey(CLI_PARAM_HELP[0])) l.info(commandsHelp()); finishedSucessfuly = true; } catch (InvalidArgumentException e) { l.error("Invalid or missing argument: " + e.getMessage()); l.debug(e); Throwable c = e.getCause(); while (c != null) { l.debug("Caused by: ", c); c = c.getCause(); } HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("gooddata-cli [<options> ...] -H|--help|<script>|-e <command>", ops); finishedSucessfuly = false; } catch (InvalidCommandException e) { l.error("Invalid command: " + e.getMessage()); l.debug(e); Throwable c = e.getCause(); while (c != null) { l.debug("Caused by: ", c); c = c.getCause(); } finishedSucessfuly = false; } catch (InvalidParameterException e) { l.error("Invalid command parameter: " + e.getMessage()); l.debug(e); Throwable c = e.getCause(); while (c != null) { l.debug("Caused by: ", c); c = c.getCause(); } finishedSucessfuly = false; } catch (SfdcException e) { l.error("Error communicating with SalesForce: " + e.getMessage()); l.debug(e); Throwable c = e.getCause(); while (c != null) { l.debug("Caused by: ", c); c = c.getCause(); } finishedSucessfuly = false; } catch (ProcessingException e) { l.error("Error processing command: " + e.getMessage()); l.debug(e); Throwable c = e.getCause(); while (c != null) { l.debug("Caused by: ", c); c = c.getCause(); } finishedSucessfuly = false; } catch (ModelException e) { l.error("Model issue: " + e.getMessage()); l.debug(e); Throwable c = e.getCause(); while (c != null) { l.debug("Caused by: ", c); c = c.getCause(); } finishedSucessfuly = false; } catch (IOException e) { l.error("Encountered an IO problem. Please check that all files that you use in your command line arguments and commands exist." + e.getMessage()); l.debug(e); Throwable c = e.getCause(); while (c != null) { l.debug("Caused by: ", c); c = c.getCause(); } finishedSucessfuly = false; } catch (InternalErrorException e) { Throwable c = e.getCause(); if (c != null && c instanceof SQLException) { l.error("Error extracting data. Can't process the incoming data. Please check the CSV file " + "separator and consistency (same number of columns in each row). Also, please make sure " + "that the number of columns in your XML config file matches the number of rows in your " + "data source. Make sure that your file is readable by other users (particularly the mysql user). " + "More info: ", c); } else { l.error("Internal error: " + e.getMessage()); l.debug(e); c = e.getCause(); while (c != null) { l.debug("Caused by: ", c); c = c.getCause(); } } finishedSucessfuly = false; } catch (HttpMethodException e) { l.debug("Error executing GoodData REST API: " + e); Throwable c = e.getCause(); while (c != null) { l.debug("Caused by: ", c); c = c.getCause(); } String msg = e.getMessage(); String requestId = e.getRequestId(); if (requestId != null) { msg += "\n\n" + "If you believe this is not your fault, good people from support\n" + "portal (http://support.gooddata.com) may help you.\n\n" + "Show them this error ID: " + requestId; } l.error(msg); finishedSucessfuly = false; } catch (GdcRestApiException e) { l.error("REST API invocation error: " + e.getMessage()); l.debug(e, e); Throwable c = e.getCause(); while (c != null) { if (c instanceof HttpMethodException) { HttpMethodException ex = (HttpMethodException) c; String msg = ex.getMessage(); if (msg != null && msg.length() > 0 && msg.indexOf("/ldm/manage") > 0) { l.error("Error creating/updating logical data model (executing MAQL DDL)."); if (msg.indexOf(".date") > 0) { l.error("Bad time dimension schemaReference."); } else { l.error("You are either trying to create a data object that already exists " + "(executing the same MAQL multiple times) or providing a wrong reference " + "or schemaReference in your XML configuration."); } } } l.debug("Caused by: ", c); c = c.getCause(); } finishedSucessfuly = false; } catch (GdcException e) { l.error("Unrecognized error: " + e.getMessage()); l.debug(e); Throwable c = e.getCause(); while (c != null) { l.debug("Caused by: ", c); c = c.getCause(); } finishedSucessfuly = false; } finally { /* if (cliParams != null) context.getRestApi(cliParams).logout(); */ } } /** * Parse and validate the cli arguments * * @param ln parsed command line * @return parsed cli parameters wrapped in the CliParams * @throws InvalidArgumentException in case of nonexistent or incorrect cli args */ protected CliParams parse(CommandLine ln, Properties defaults) throws InvalidArgumentException { l.debug("Parsing cli " + ln); CliParams cp = new CliParams(); for (Option o : Options) { String name = o.getLongOpt(); if (ln.hasOption(name)) { cp.put(name, ln.getOptionValue(name)); } else if (defaults.getProperty(name) != null) { cp.put(name, defaults.getProperty(name)); } } if(cp.containsKey(CLI_PARAM_HTTP_PROXY_HOST[0])) { System.setProperty("http.proxyHost", cp.get(CLI_PARAM_HTTP_PROXY_HOST[0])); } if(cp.containsKey(CLI_PARAM_HTTP_PROXY_PORT[0])) { System.setProperty("http.proxyPort", cp.get(CLI_PARAM_HTTP_PROXY_PORT[0])); } if(cp.containsKey(CLI_PARAM_HTTP_PROXY_USERNAME[0])) { System.setProperty("http.proxyUser", cp.get(CLI_PARAM_HTTP_PROXY_USERNAME[0])); System.setProperty("http.proxyUserName", cp.get(CLI_PARAM_HTTP_PROXY_USERNAME[0])); System.setProperty("http.proxyUsername", cp.get(CLI_PARAM_HTTP_PROXY_USERNAME[0])); } if(cp.containsKey(CLI_PARAM_HTTP_PROXY_PASSWORD[0])) { System.setProperty("http.proxyPassword", cp.get(CLI_PARAM_HTTP_PROXY_PASSWORD[0])); } if (cp.containsKey(CLI_PARAM_VERSION[0])) { l.info("GoodData CL version 1.2.57" + ((BUILD_NUMBER.length() > 0) ? ", build " + BUILD_NUMBER : ".")); System.exit(0); } // use default host if there is no host in the CLI params if (!cp.containsKey(CLI_PARAM_HOST[0])) { cp.put(CLI_PARAM_HOST[0], Defaults.DEFAULT_HOST); } l.debug("Using host " + cp.get(CLI_PARAM_HOST[0])); // create default FTP host if there is no host in the CLI params /* if (!cp.containsKey(CLI_PARAM_FTP_HOST[0])) { String[] hcs = cp.get(CLI_PARAM_HOST[0]).split("\\."); if (hcs != null && hcs.length > 0) { String ftpHost = ""; for (int i = 0; i < hcs.length; i++) { if (i > 0) ftpHost += "." + hcs[i]; else ftpHost = hcs[i] + N.FTP_SRV_SUFFIX; } cp.put(CLI_PARAM_FTP_HOST[0], ftpHost); } else { throw new InvalidArgumentException("Invalid format of the GoodData REST API host: " + cp.get(CLI_PARAM_HOST[0])); } } l.debug("Using FTP host " + cp.get(CLI_PARAM_FTP_HOST[0])); */ // Default to secure protocol if there is no host in the CLI params // Assume insecure protocol if user specifies "HTTPS", for backwards compatibility if (cp.containsKey(CLI_PARAM_PROTO[0])) { String proto = ln.getOptionValue(CLI_PARAM_PROTO[0]).toLowerCase(); if (!"http".equalsIgnoreCase(proto) && !"https".equalsIgnoreCase(proto)) { throw new InvalidArgumentException("Invalid '" + CLI_PARAM_PROTO[0] + "' parameter. Use HTTP or HTTPS."); } if ("http".equalsIgnoreCase(proto)) { cp.put(CLI_PARAM_INSECURE[0], "true"); } } if (cp.containsKey(CLI_PARAM_INSECURE[0])) cp.put(CLI_PARAM_INSECURE[0], "true"); l.debug("Using " + (cp.containsKey(CLI_PARAM_INSECURE[0]) ? "in" : "") + "secure protocols"); if (ln.getArgs().length == 0 && !ln.hasOption(CLI_PARAM_EXECUTE[0]) && !ln.hasOption(CLI_PARAM_HELP[0])) { throw new InvalidArgumentException("No command has been given, quitting."); } String scripts = ""; for (final String arg : ln.getArgs()) { if (scripts.length() > 0) scripts += "," + arg; else scripts += arg; } cp.put(CLI_PARAM_SCRIPT, scripts); return cp; } /** * Executes the commands in String * * @param commandsStr commands string */ public void execute(final String commandsStr) { List<Command> cmds = new ArrayList<Command>(); cmds.addAll(parseCmd(commandsStr)); for (Command command : cmds) { boolean processed = false; for (int i = 0; i < connectors.length && !processed; i++) { processed = connectors[i].processCommand(command, cliParams, context); } if (!processed) this.processCommand(command, cliParams, context); } } /** * Executes the commands in file * * @param scriptFile file with commands * @throws IOException in case of an IO issue */ public void execute(final File scriptFile) throws IOException { List<Command> cmds = new ArrayList<Command>(); cmds.addAll(parseCmd(FileUtil.readStringFromFile(scriptFile.getAbsolutePath()))); for (Command command : cmds) { boolean processed = false; for (int i = 0; i < connectors.length && !processed; i++) { processed = connectors[i].processCommand(command, cliParams, context); } if (!processed) processed = this.processCommand(command, cliParams, context); if (!processed) throw new InvalidCommandException("Unknown command '" + command.getCommand() + "'"); } } /** * Returns the help for commands * * @return help text */ public static String commandsHelp() { try { final InputStream is = CliParams.class.getResourceAsStream("/com/gooddata/processor/COMMANDS.txt"); if (is == null) throw new IOException(); return FileUtil.readStringFromStream(is); } catch (IOException e) { l.error("Could not read com/gooddata/processor/COMMANDS.txt"); } return ""; } private static boolean checkJavaVersion() { String version = System.getProperty("java.version"); if (version.startsWith("1.8") || version.startsWith("1.7") || version.startsWith("1.6") || version.startsWith("1.5")) return true; l.error("You're running Java " + version + ". Please use Java 1.5 or higher for running this tool. " + "Please refer to http://java.sun.com/javase/downloads/index.jsp for a more recent Java version."); throw new InternalErrorException("You're running Java " + version + ". Please use use Java 1.5 or higher for running this tool. " + "Please refer to http://java.sun.com/javase/downloads/index.jsp for a more recent Java version."); } /** * The main CLI processor * * @param args command line argument */ public static void main(String[] args) { checkJavaVersion(); Properties defaults = loadDefaults(); for (Option o : Options) ops.addOption(o); try { CommandLineParser parser = new GnuParser(); CommandLine cmdline = parser.parse(ops, args); GdcDI gdi = new GdcDI(cmdline, defaults); if (!gdi.finishedSucessfuly) { System.exit(1); } } catch (org.apache.commons.cli.ParseException e) { l.error("Error parsing command line parameters: ", e); l.debug("Error parsing command line parameters", e); } } private void setupHttpProxies() { //CredentialsProvider proxyCredentials = new BasicCredentialsProvider (); } /** * Parses the commands * * @param cmd commands string * @return array of commands * @throws InvalidCommandException in case there is an invalid command */ protected static List<Command> parseCmd(String cmd) throws InvalidCommandException { l.debug("Parsing comands: " + cmd); try { if (cmd != null && cmd.length() > 0) { Reader r = new StringReader(cmd); DIScriptParser parser = new DIScriptParser(r); List<Command> commands = parser.parse(); l.debug("Running " + commands.size() + " commands."); for (Command c : commands) { l.debug("Command=" + c.getCommand() + " params=" + c.getParameters()); } return commands; } } catch (ParseException e) { throw new InvalidCommandException("Can't parse command '" + cmd + "'"); } throw new InvalidCommandException("Can't parse command (empty command)."); } /** * {@inheritDoc} */ public boolean processCommand(Command c, CliParams cli, ProcessingContext ctx) throws ProcessingException { l.debug("Processing command " + c.getCommand()); try { // take project id from command line, may be override in the script if (cliParams.get(CLI_PARAM_PROJECT[0]) != null) { ctx.setProjectId(cliParams.get(CLI_PARAM_PROJECT[0])); } if (c.match("CreateProject")) { createProject(c, cli, ctx); } else if (c.match("DropProject") || c.match("DeleteProject")) { dropProject(c, cli, ctx); } else if (c.match("OpenProject")) { ctx.setProjectId(c.getParamMandatory("id")); c.paramsProcessed(); l.debug("Opened project id=" + ctx.getProjectId()); l.info("Opened project id=" + ctx.getProjectId()); } else if (c.match("StoreProject") || c.match("RememberProject")) { storeProject(c, cli, ctx); } else if (c.match("ExecuteDml")) { executeDML(c, cli, ctx); } else if (c.match("RetrieveProject") || c.match("UseProject")) { retrieveProject(c, cli, ctx); } else if (c.match("ExportProject")) { exportProject(c, cli, ctx); } else if (c.match("ImportProject")) { importProject(c, cli, ctx); } else if (c.match("Lock")) { lock(c, cli, ctx); } else if (c.match("GetReports")) { getReports(c, cli, ctx); } else if (c.match("CreateUser")) { createUser(c, cli, ctx); } else if (c.match("AddUsersToProject")) { addUsersToProject(c, cli, ctx); } else if (c.match("DisableUsersInProject")) { disableUsersInProject(c, cli, ctx); } else if (c.match("GetProjectUsers")) { getProjectUsers(c, cli, ctx); } else if (c.match("InviteUser")) { inviteUser(c, cli, ctx); } else if (c.match("ExecuteReports")) { executeReports(c, cli, ctx); } else if (c.match("StoreMetadataObject")) { storeMdObject(c, cli, ctx); } else if (c.match("DropMetadataObject")) { dropMdObject(c, cli, ctx); } else if (c.match("RetrieveMetadataObject")) { getMdObject(c, cli, ctx); } else if (c.match("ExportMetadataObjects")) { exportMDObject(c, cli, ctx); } else if (c.match("ImportMetadataObjects")) { importMDObject(c, cli, ctx); } else if (c.match("ExportJdbcToCsv")) { exportJdbcToCsv(c, cli, ctx); } else if (c.match("MigrateDatasets")) { migrateDatasets(c, cli, ctx); } else if (c.match("GenerateManifests")) { generateManifests(c, cli, ctx); } else { l.debug("No match command " + c.getCommand()); return false; } } catch (IOException e) { l.debug("Processing command " + c.getCommand() + " failed", e); throw new ProcessingException(e); } catch (InterruptedException e) { l.debug("Processing command " + c.getCommand() + " failed", e); throw new ProcessingException(e); } l.debug("Command processing " + c.getCommand() + " finished."); return true; } /** * Executes MAQL DML * * @param c command * @param p cli parameters * @param ctx current context * @throws IOException IO issues */ private void executeDML(Command c, CliParams p, ProcessingContext ctx) throws IOException { try { l.debug("Executing MAQL DML."); String pid = ctx.getProjectIdMandatory(); final String cmd = c.getParamMandatory("maql"); c.paramsProcessed(); String taskUri = ctx.getRestApi(p).executeDML(pid, cmd); if (taskUri != null && taskUri.length() > 0) { l.debug("Checking MAQL DML execution status."); String status = ""; while (!"OK".equalsIgnoreCase(status) && !"ERROR".equalsIgnoreCase(status) && !"WARNING".equalsIgnoreCase(status)) { status = ctx.getRestApi(p).getMigrationStatus(taskUri); l.debug("MAQL DML execution status = " + status); Thread.sleep(500); } l.info("MAQL DML execution finished with status " + status); if ("ERROR".equalsIgnoreCase(status)) { l.error("Error executing the MAQL DML. Check debug log for more details."); throw new GdcRestApiException("Error executing the MAQL DML. Check debug log for more details."); } } else { l.error("MAQL DML execution hasn't returned any task URI."); throw new InternalErrorException("MAQL DML execution hasn't returned any task URI."); } l.debug("Finished MAQL DML execution."); l.info("MAQL DML command '" + cmd + "' successfully executed."); } catch (InterruptedException e) { throw new InternalErrorException(e); } } /** * Exports project * * @param c command * @param p cli parameters * @param ctx current context * @throws IOException IO issues */ private void exportProject(Command c, CliParams p, ProcessingContext ctx) throws IOException { try { l.info("Exporting project."); String pid = ctx.getProjectIdMandatory(); final String eu = c.getParamMandatory("exportUsers"); final boolean exportUsers = (eu != null && "true".equalsIgnoreCase(eu)); final String ed = c.getParamMandatory("exportData"); final boolean exportData = (ed != null && "true".equalsIgnoreCase(ed)); final String fileName = c.getParamMandatory("tokenFile"); String au = c.getParam("authorizedUsers"); c.paramsProcessed(); String[] authorizedUsers = null; if (au != null && au.length() > 0) { authorizedUsers = au.split(","); } GdcRESTApiWrapper.ProjectExportResult r = ctx.getRestApi(p).exportProject(pid, exportUsers, exportData, authorizedUsers); String taskUri = r.getTaskUri(); String token = r.getExportToken(); if (taskUri != null && taskUri.length() > 0) { l.debug("Checking project export status."); String status = ""; while (!"OK".equalsIgnoreCase(status) && !"ERROR".equalsIgnoreCase(status) && !"WARNING".equalsIgnoreCase(status)) { status = ctx.getRestApi(p).getMigrationStatus(taskUri); l.debug("Project export status = " + status); Thread.sleep(500); } l.info("Project export finished with status " + status); if ("OK".equalsIgnoreCase(status) || "WARNING".equalsIgnoreCase(status)) { FileUtil.writeStringToFile(token, fileName); } else { l.error("Error exporting project. Check debug log for more details."); throw new GdcRestApiException("Error exporting project. Check debug log for more details."); } } else { l.error("Project export hasn't returned any task URI."); throw new InternalErrorException("Project export hasn't returned any task URI."); } l.debug("Finished project export."); l.info("Project " + pid + " successfully exported. Import token is " + token); } catch (InterruptedException e) { throw new InternalErrorException(e); } } /** * Imports project * * @param c command * @param p cli parameters * @param ctx current context * @throws IOException IO issues */ private void importProject(Command c, CliParams p, ProcessingContext ctx) throws IOException { try { l.info("Importing project."); String pid = ctx.getProjectIdMandatory(); final String tokenFile = c.getParamMandatory("tokenFile"); c.paramsProcessed(); String token = FileUtil.readStringFromFile(tokenFile).trim(); String taskUri = ctx.getRestApi(p).importProject(pid, token); if (taskUri != null && taskUri.length() > 0) { l.debug("Checking project import status."); String status = ""; while (!"OK".equalsIgnoreCase(status) && !"ERROR".equalsIgnoreCase(status) && !"WARNING".equalsIgnoreCase(status)) { status = ctx.getRestApi(p).getMigrationStatus(taskUri); l.debug("Project import status = " + status); Thread.sleep(500); } l.info("Project import finished with status " + status); if ("ERROR".equalsIgnoreCase(status)) { l.error("Error importing project. Check debug log for more details."); throw new GdcRestApiException("Error importing project. Check debug log for more details."); } } else { l.error("Project import hasn't returned any task URI."); throw new InternalErrorException("Project import hasn't returned any task URI."); } l.debug("Finished project import."); l.info("Project " + pid + " successfully imported."); } catch (InterruptedException e) { throw new InternalErrorException(e); } } /** * Exports MD objects * * @param c command * @param p cli parameters * @param ctx current context * @throws IOException IO issues */ private void exportMDObject(Command c, CliParams p, ProcessingContext ctx) throws IOException { try { l.info("Exporting metadata objects."); String token; String pid = ctx.getProjectIdMandatory(); final String fileName = c.getParamMandatory("tokenFile"); final String idscs = c.getParamMandatory("objectIDs"); c.paramsProcessed(); if (idscs != null && idscs.length() > 0) { String[] idss = idscs.split(","); List<Integer> ids = new ArrayList<Integer>(); for (String id : idss) { try { ids.add(Integer.parseInt(id)); } catch (NumberFormatException e) { l.debug("Invalid metadata object ID " + id, e); l.error("Invalid metadata object ID " + id); throw new InvalidParameterException("Invalid metadata object ID " + id, e); } } GdcRESTApiWrapper.ProjectExportResult r = ctx.getRestApi(p).exportMD(pid, ids); String taskUri = r.getTaskUri(); token = r.getExportToken(); if (taskUri != null && taskUri.length() > 0) { l.debug("Checking MD export status."); String status = ""; while (!"OK".equalsIgnoreCase(status) && !"ERROR".equalsIgnoreCase(status) && !"WARNING".equalsIgnoreCase(status)) { status = ctx.getRestApi(p).getTaskManStatus(taskUri); l.debug("MD export status = " + status); Thread.sleep(500); } l.info("MD export finished with status " + status); if ("OK".equalsIgnoreCase(status) || "WARNING".equalsIgnoreCase(status)) { FileUtil.writeStringToFile(token, fileName); } else { l.error("Error exporting metadata. Check debug log for more details."); throw new GdcRestApiException("Error exporting metadata. Check debug log for more details."); } } else { l.error("MD export hasn't returned any task URI."); throw new InternalErrorException("MD export hasn't returned any task URI."); } } else { l.debug("The objectIDs parameter must contain a comma separated list of metadata object IDs!"); l.error("The objectIDs parameter must contain a comma separated list of metadata object IDs!"); throw new InvalidParameterException("The objectIDs parameter must contain a comma separated list of metadata object IDs!"); } l.debug("Finished MD export."); l.info("Project " + pid + " metadata successfully exported. Import token is " + token); } catch (InterruptedException e) { throw new InternalErrorException(e); } } /** * Imports MD objects * * @param c command * @param p cli parameters * @param ctx current context * @throws IOException IO issues */ private void importMDObject(Command c, CliParams p, ProcessingContext ctx) throws IOException { try { l.info("Importing metadata objects."); String pid = ctx.getProjectIdMandatory(); final String tokenFile = c.getParamMandatory("tokenFile"); String token = FileUtil.readStringFromFile(tokenFile).trim(); /* Currently not supported final String ov = c.getParam("overwrite"); final boolean overwrite = (ov != null && "true".equalsIgnoreCase(ov)); */ final String ul = c.getParam("updateLDM"); final boolean updateLDM = (ul != null && "true".equalsIgnoreCase(ul)); final boolean overwrite = true; c.paramsProcessed(); String taskUri = ctx.getRestApi(p).importMD(pid, token, overwrite, updateLDM); if (taskUri != null && taskUri.length() > 0) { l.debug("Checking MD import status."); String status = ""; while (!"OK".equalsIgnoreCase(status) && !"ERROR".equalsIgnoreCase(status) && !"WARNING".equalsIgnoreCase(status)) { status = ctx.getRestApi(p).getTaskManStatus(taskUri); l.debug("MD import status = " + status); Thread.sleep(500); } l.info("MD import finished with status " + status); if ("ERROR".equalsIgnoreCase(status)) { l.error("Error importing MD. Check debug log for more details."); throw new GdcRestApiException("Error importing MD. Check debug log for more details."); } } else { l.error("MD import hasn't returned any task URI."); throw new InternalErrorException("MD import hasn't returned any task URI."); } l.debug("Finished metadata import."); l.info("Project " + pid + " metadata successfully imported."); } catch (InterruptedException e) { throw new InternalErrorException(e); } } /** * Creates a new user * * @param c command * @param p cli parameters * @param ctx current context * @throws IOException IO issues */ private void createUser(Command c, CliParams p, ProcessingContext ctx) throws IOException { l.info("Creating new user."); String domain = c.getParamMandatory("domain"); GdcRESTApiWrapper.GdcUser user = new GdcRESTApiWrapper.GdcUser(); user.setLogin(c.getParamMandatory("username")); user.setPassword(c.getParamMandatory("password")); user.setVerifyPassword(user.getPassword()); user.setFirstName(c.getParamMandatory("firstName")); user.setLastName(c.getParamMandatory("lastName")); user.setCompanyName(c.getParam("company")); user.setPosition(c.getParam("position")); user.setCountry(c.getParam("country")); user.setPhoneNumber(c.getParam("phone")); user.setSsoProvider(c.getParam("ssoProvider")); user.setEmail(c.getParam("email")); String usersFile = c.getParam("usersFile"); String appnd = c.getParam("append"); c.paramsProcessed(); final boolean append = (appnd != null && "true".equalsIgnoreCase(appnd)); String r = ctx.getRestApi(p).createUser(domain, user); if (r != null && r.length() > 0 && usersFile != null && usersFile.length() > 0) { FileUtil.writeStringToFile(r + "\n", usersFile, append); } l.info("User " + user.getLogin() + "' successfully created. User URI: " + r); } /** * Adds a new user to project * * @param c command * @param p cli parameters * @param ctx current context * @throws IOException IO issues */ private void addUsersToProject(Command c, CliParams p, ProcessingContext ctx) throws IOException { l.info("Adding users to project."); String pid = ctx.getProjectIdMandatory(); String usersFile = c.getParamMandatory("usersFile"); List<String> uris = new ArrayList<String>(); BufferedReader r = FileUtil.createBufferedUtf8Reader(usersFile); String uri = r.readLine(); while (uri != null && uri.trim().length() > 0) { uris.add(uri.trim()); uri = r.readLine(); } String role = c.getParam("role"); c.paramsProcessed(); ctx.getRestApi(p).addUsersToProject(pid, uris, role); l.info("Users " + uris + "' successfully added to project " + pid); } /** * Adds a new user to project * * @param c command * @param p cli parameters * @param ctx current context * @throws IOException IO issues */ private void disableUsersInProject(Command c, CliParams p, ProcessingContext ctx) throws IOException { l.info("Disabling users in project."); String pid = ctx.getProjectIdMandatory(); String usersFile = c.getParamMandatory("usersFile"); c.paramsProcessed(); List<String> uris = new ArrayList<String>(); BufferedReader r = FileUtil.createBufferedUtf8Reader(usersFile); String uri = r.readLine(); while (uri != null && uri.trim().length() > 0) { uris.add(uri.trim()); uri = r.readLine(); } ctx.getRestApi(p).disableUsersInProject(pid, uris); l.info("Users " + uris + "' successfully disabled in project " + pid); } /** * Adds a new user to project * * @param c command * @param p cli parameters * @param ctx current context * @throws IOException IO issues */ private void getProjectUsers(Command c, CliParams p, ProcessingContext ctx) throws IOException { String pid = ctx.getProjectIdMandatory(); l.info("Getting users from project " + pid); String usersFile = c.getParamMandatory("usersFile"); String field = c.getParamMandatory("field"); String activeOnlys = c.getParam("activeOnly"); c.paramsProcessed(); final boolean activeOnly = (activeOnlys != null && "true".equalsIgnoreCase(activeOnlys)); if ("email".equalsIgnoreCase(field) || "uri".equalsIgnoreCase(field)) { List<GdcRESTApiWrapper.GdcUser> users = ctx.getRestApi(p).getProjectUsers(pid, activeOnly); for (GdcRESTApiWrapper.GdcUser user : users) { if ("email".equalsIgnoreCase(field)) { FileUtil.writeStringToFile(user.getLogin() + "\n", usersFile, true); } if ("uri".equalsIgnoreCase(field)) { FileUtil.writeStringToFile(user.getUri() + "\n", usersFile, true); } l.info("User " + user.getLogin() + "' successfully added. User URI: " + user.getUri()); } } else { l.error("Invalid field parameter. Only values 'email' and 'uri' are currently supported."); } } /** * Create new project command processor * * @param c command * @param p cli parameters * @param ctx current context */ private void createProject(Command c, CliParams p, ProcessingContext ctx) { try { String name = c.getParamMandatory("name"); String desc = c.getParam("desc"); String pTempUri = c.getParam("templateUri"); String driver = c.getParam("driver"); String token = c.getParam("accessToken"); c.paramsProcessed(); if (desc == null || desc.length() <= 0) desc = name; ctx.setProjectId(ctx.getRestApi(p).createProject(StringUtil.toTitle(name), StringUtil.toTitle(desc), pTempUri, driver, token)); String pid = ctx.getProjectIdMandatory(); checkProjectCreationStatus(pid, p, ctx); l.info("Project id = '" + pid + "' created."); } catch (InterruptedException e) { throw new InternalErrorException(e); } } /** * Exports all DB tables to CSV * * @param c command * @param p cli parameters * @param ctx current context */ private void exportJdbcToCsv(Command c, CliParams p, ProcessingContext ctx) throws IOException { try { String usr = null; if (c.checkParam("username")) usr = c.getParam("username"); String psw = null; if (c.checkParam("password")) psw = c.getParam("password"); String drv = c.getParamMandatory("driver"); String url = c.getParamMandatory("url"); String fl = c.getParamMandatory("dir"); c.paramsProcessed(); File dir = new File(fl); if (!dir.exists() || !dir.isDirectory()) { throw new InvalidParameterException("The dir parameter in the ExportJdbcToCsv command must be an existing directory."); } DatabaseToCsv d = new DatabaseToCsv(drv, url, usr, psw); d.export(dir.getAbsolutePath()); l.info("All tables successfully exported to " + dir.getAbsolutePath()); } catch (SQLException e) { throw new IOException(e); } } /** * Checks the project status. Waits till the status is LOADING * * @param projectId project ID * @param p cli parameters * @param ctx current context * @throws InterruptedException internal problem with making file writable */ private void checkProjectCreationStatus(String projectId, CliParams p, ProcessingContext ctx) throws InterruptedException { l.debug("Checking project " + projectId + " loading status."); String status = "LOADING"; while ("LOADING".equalsIgnoreCase(status)) { status = ctx.getRestApi(p).getProjectStatus(projectId); l.debug("Project " + projectId + " loading status = " + status); Thread.sleep(500); } } /** * Drop project command processor * * @param c command * @param p cli parameters * @param ctx current context */ private void dropProject(Command c, CliParams p, ProcessingContext ctx) { String id = ctx.getProjectId(); if (id == null) { id = c.getParamMandatory("id"); } else { String override = c.getParam("id"); if (override != null) id = override; } c.paramsProcessed(); ctx.getRestApi(p).dropProject(id); l.info("Project id = '" + id + "' dropped."); } /** * Invite user to a project * * @param c command * @param p cli parameters * @param ctx current context */ private void inviteUser(Command c, CliParams p, ProcessingContext ctx) throws IOException { String pid = ctx.getProjectIdMandatory(); String email = c.getParamMandatory("email"); String msg = c.getParam("msg"); String role = c.getParam("role"); c.paramsProcessed(); ctx.getRestApi(p).inviteUser(pid, email, (msg != null) ? (msg) : (""), role); l.info("Successfully invited user " + email + " to the project " + pid); } /** * Migrate specified datasets * * @param c command * @param p cli parameters * @param ctx current context */ private void migrateDatasets(Command c, CliParams p, ProcessingContext ctx) throws IOException, InterruptedException { String pid = ctx.getProjectIdMandatory(); l.info("Migrating project " + pid); String configFiles = c.getParamMandatory("configFiles"); c.paramsProcessed(); if (configFiles != null && configFiles.length() > 0) { String[] schemas = configFiles.split(","); if (schemas != null && schemas.length > 0) { List<String> manifests = new ArrayList<String>(); for (String schema : schemas) { File sf = new File(schema); if (sf.exists()) { SourceSchema srcSchema = SourceSchema.createSchema(sf); String ssn = srcSchema.getName(); List<Column> columns = AbstractConnector.populateColumnsFromSchema(srcSchema); SLI sli = ctx.getRestApi(p).getSLIById("dataset." + ssn, pid); String manifest = sli.getSLIManifest(columns); manifests.add(manifest); } else { l.debug("The configFile " + schema + " doesn't exists!"); l.error("The configFile " + schema + " doesn't exists!"); throw new InvalidParameterException("The configFile " + schema + " doesn't exists!"); } } String taskUri = ctx.getRestApi(p).migrateDataSets(pid, manifests); if (taskUri != null && taskUri.length() > 0) { l.debug("Checking migration status."); String status = ""; while (!"OK".equalsIgnoreCase(status) && !"ERROR".equalsIgnoreCase(status) && !"WARNING".equalsIgnoreCase(status)) { status = ctx.getRestApi(p).getMigrationStatus(taskUri); l.debug("Migration status = " + status); Thread.sleep(500); } l.info("Migration finished with status " + status); } else { l.info("No migration needed anymore."); } } else { l.debug("The configFiles parameter must contain a comma separated list of schema configuration files!"); l.error("The configFiles parameter must contain a comma separated list of schema configuration files!"); throw new InvalidParameterException("The configFiles parameter must contain a comma separated list of schema configuration files!"); } } else { l.debug("The configFiles parameter must contain a comma separated list of schema configuration files!"); l.error("The configFiles parameter must contain a comma separated list of schema configuration files!"); throw new InvalidParameterException("The configFiles parameter must contain a comma separated list of schema configuration files!"); } } /** * Generate manifests for specified datasets * * @param c command * @param p cli parameters * @param ctx current context */ private void generateManifests(Command c, CliParams p, ProcessingContext ctx) throws IOException, InterruptedException { String pid = ctx.getProjectIdMandatory(); l.info("Generating manifests for project " + pid); String configFiles = c.getParamMandatory("configFiles"); String dir = c.getParamMandatory("dir"); c.paramsProcessed(); if (dir != null && dir.length() > 0) { File targetDir = new File(dir); if (targetDir.exists() && targetDir.isDirectory()) { if (configFiles != null && configFiles.length() > 0) { String[] schemas = configFiles.split(","); if (schemas != null && schemas.length > 0) { for (String schema : schemas) { File sf = new File(schema); if (sf.exists()) { SourceSchema srcSchema = SourceSchema.createSchema(sf); AbstractConnector.expandDates(srcSchema); String ssn = srcSchema.getName(); List<Column> columns = AbstractConnector.populateColumnsFromSchema(srcSchema); SLI sli = ctx.getRestApi(p).getSLIById("dataset." + ssn, pid); String manifest = sli.getSLIManifest(columns); FileUtil.writeStringToFile(manifest, targetDir.getAbsolutePath() + System.getProperty("file.separator") + ssn + ".json"); } else { l.debug("The configFile " + schema + " doesn't exists!"); l.error("The configFile " + schema + " doesn't exists!"); throw new InvalidParameterException("The configFile " + schema + " doesn't exists!"); } } } else { l.debug("The configFiles parameter must contain a comma separated list of schema configuration files!"); l.error("The configFiles parameter must contain a comma separated list of schema configuration files!"); throw new InvalidParameterException("The configFiles parameter must contain a comma separated list of schema configuration files!"); } } else { l.debug("The configFiles parameter must contain a comma separated list of schema configuration files!"); l.error("The configFiles parameter must contain a comma separated list of schema configuration files!"); throw new InvalidParameterException("The configFiles parameter must contain a comma separated list of schema configuration files!"); } } else { l.debug("The `dir` parameter must point to a valid directory."); l.error("The `dir` parameter must point to a valid directory."); throw new InvalidParameterException("The `dir` parameter must point to a valid directory."); } } else { l.debug("Please specify a valid `dir` parameter for the GenerateManifests command."); l.error("Please specify a valid `dir` parameter for the GenerateManifests command."); throw new InvalidParameterException("Please specify a valid `dir` parameter for the GenerateManifests command."); } } /** * Retrieves a MD object * * @param c command * @param p cli parameters * @param ctx current context */ private void getMdObject(Command c, CliParams p, ProcessingContext ctx) throws IOException { String pid = ctx.getProjectIdMandatory(); String ids = c.getParamMandatory("id"); String fl = c.getParamMandatory("file"); c.paramsProcessed(); int id; try { id = Integer.parseInt(ids); } catch (NumberFormatException e) { throw new InvalidParameterException("The id in getMetadataObject must be an integer."); } MetadataObject ret = ctx.getRestApi(p).getMetadataObject(pid, id); FileUtil.writeJSONToFile(ret, fl); l.info("Retrieved metadata object " + id + " from the project " + pid + " and stored it in file " + fl); } /** * Stores a MD object * * @param c command * @param p cli parameters * @param ctx current context */ private void storeMdObject(Command c, CliParams p, ProcessingContext ctx) throws IOException { String pid = ctx.getProjectIdMandatory(); String fl = c.getParamMandatory("file"); String ids = c.getParam("id"); c.paramsProcessed(); if (ids != null && ids.length() > 0) { int id; try { id = Integer.parseInt(ids); } catch (NumberFormatException e) { throw new InvalidParameterException("The id in storeMetadataObject must be an integer."); } ctx.getRestApi(p).modifyMetadataObject(pid, id, FileUtil.readJSONFromFile(fl)); l.info("Modified metadata object " + id + " to the project " + pid); } else { ctx.getRestApi(p).createMetadataObject(pid, FileUtil.readJSONFromFile(fl)); l.info("Created a new metadata object in the project " + pid); } } /** * Drops a MD object * * @param c command * @param p cli parameters * @param ctx current context */ private void dropMdObject(Command c, CliParams p, ProcessingContext ctx) throws IOException { String pid = ctx.getProjectIdMandatory(); String ids = c.getParamMandatory("id"); c.paramsProcessed(); int id; try { id = Integer.parseInt(ids); } catch (NumberFormatException e) { throw new InvalidParameterException("The id in dropMetadataObject must be an integer."); } ctx.getRestApi(p).deleteMetadataObject(pid, id); l.info("Dropped metadata object " + id + " from the project " + pid); } /** * Enumerate reports * * @param c command * @param p cli parameters * @param ctx current context */ private void getReports(Command c, CliParams p, ProcessingContext ctx) throws IOException { String pid = ctx.getProjectIdMandatory(); String fileName = c.getParamMandatory("fileName"); c.paramsProcessed(); List<String> uris = ctx.getRestApi(p).enumerateReports(pid); String result = ""; for (String uri : uris) { if (result.length() > 0) result += "\n" + uri; else result += uri; } FileUtil.writeStringToFile(result, fileName); l.info("Reports written into " + fileName); } /** * Enumerate reports * * @param c command * @param p cli parameters * @param ctx current context */ private void executeReports(Command c, CliParams p, ProcessingContext ctx) throws IOException, InterruptedException { String pid = ctx.getProjectIdMandatory(); String fileName = c.getParamMandatory("fileName"); c.paramsProcessed(); String result = FileUtil.readStringFromFile(fileName).trim(); if (result != null && result.length() > 0) { String[] uris = result.split("\n"); for (String uri : uris) { try { String defUri = ctx.getRestApi(p).getReportDefinition(uri.trim()); l.info("Executing report uri=" + defUri); String task = ctx.getRestApi(p).executeReportDefinition(defUri.trim()); l.info("Report " + defUri + " execution finished: " + task); } catch (GdcRestApiException e) { l.debug("The report uri=" + uri + " can't be computed!"); l.info("The report uri=" + uri + " can't be computed!"); } } } else { throw new IOException("There are no reports to execute."); } l.info("All reports executed."); } /** * Store project command processor * * @param c command * @param p cli parameters * @param ctx current context * @throws IOException in case of an IO issue */ private void storeProject(Command c, CliParams p, ProcessingContext ctx) throws IOException { String fileName = c.getParamMandatory("fileName"); c.paramsProcessed(); String pid = ctx.getProjectIdMandatory(); FileUtil.writeStringToFile(pid, fileName); l.debug("Stored project id=" + pid + " to " + fileName); l.info("Stored project id=" + pid + " to " + fileName); } /** * Retrieve project command processor * * @param c command * @param p cli parameters * @param ctx current context * @throws IOException in case of an IO issue */ private void retrieveProject(Command c, CliParams p, ProcessingContext ctx) throws IOException { String fileName = c.getParamMandatory("fileName"); c.paramsProcessed(); ctx.setProjectId(FileUtil.readStringFromFile(fileName).trim()); l.debug("Retrieved project id=" + ctx.getProjectId() + " from " + fileName); l.info("Retrieved project id=" + ctx.getProjectId() + " from " + fileName); } /** * Lock project command processor * * @param c command * @param p cli parameters * @param ctx current context * @throws IOException in case of an IO issue */ private void lock(Command c, CliParams p, ProcessingContext ctx) throws IOException { final String path = c.getParamMandatory("path"); c.paramsProcessed(); final File lock = new File(path); if (!lock.createNewFile()) { if (System.currentTimeMillis() - lock.lastModified() > LOCK_EXPIRATION_TIME) { lock.delete(); if (!lock.exists()) { lock(c, p, ctx); // retry } } l.debug("A concurrent process found using the " + path + " lock file."); throw new IOException("A concurrent process found using the " + path + " lock file."); } lock.deleteOnExit(); } /** * Instantiate all known connectors * TODO: this should be automated * * @return array of all active connectors * @throws IOException in case of IO issues */ private Connector[] instantiateConnectors() throws IOException { return new Connector[]{ CsvConnector.createConnector(), GaConnector.createConnector(), SfdcConnector.createConnector(), JdbcConnector.createConnector(), PtConnector.createConnector(), DateDimensionConnector.createConnector(), FacebookConnector.createConnector(), FacebookInsightsConnector.createConnector(), MsDynamicsConnector.createConnector(), SugarCrmConnector.createConnector(), ChargifyConnector.createConnector() }; } /** * Loads default values of common parameters from a properties file searching * the working directory and user's home. * * @return default configuration */ private static Properties loadDefaults() { final String[] dirs = new String[]{"user.dir", "user.home"}; final Properties props = new Properties(); for (final String d : dirs) { String path = System.getProperty(d) + File.separator + DEFAULT_PROPERTIES; File f = new File(path); if (f.exists() && f.canRead()) { try { FileInputStream is = new FileInputStream(f); props.load(is); l.debug("Successfully red the gdi configuration from '" + f.getAbsolutePath() + "'."); return props; } catch (IOException e) { l.warn("Readable gdi configuration '" + f.getAbsolutePath() + "' found be error occurred reading it."); l.debug("Error reading gdi configuration '" + f.getAbsolutePath() + "': ", e); } } } return props; } }
package se.raddo.raddose3D.tests; import java.util.HashMap; import org.testng.Assert; import org.testng.annotations.*; import se.raddo.raddose3D.CoefCalcAverage; import se.raddo.raddose3D.Crystal; import se.raddo.raddose3D.CrystalCuboid; import se.raddo.raddose3D.Wedge; /** * Tests for the Cuboid crystal class. * * @author Oliver Zeldin */ public class CrystalCuboidTest { final static double dblRoundingTolerance = 1e-13; /** * Tests value against target. Includes testing for null and nice error * messages */ private void EqualsAssertion(Double value, Double target, String name) { Assert.assertNotNull(value, name + " is null"); Assert.assertTrue(Math.abs(value - target) < dblRoundingTolerance, name + " set incorrectly (" + value + ")"); } @Test(groups = { "advanced" }) /** Checks that a full 360 rotation in P or L makes the crystal invariant, * and that you get correct negatives under 180deg rotation. **/ public void testCuboidCrystalPandL() { final Double ang360 = 360d; final Double ang180 = 180d; HashMap<Object, Object> properties = new HashMap<Object, Object>(); properties.put(Crystal.CRYSTAL_DIM_X, 100d); properties.put(Crystal.CRYSTAL_DIM_Y, 100d); properties.put(Crystal.CRYSTAL_DIM_Z, 100d); properties.put(Crystal.CRYSTAL_RESOLUTION, 0.5d); properties.put(Crystal.CRYSTAL_COEFCALC, new CoefCalcAverage()); properties.put(Crystal.CRYSTAL_ANGLE_P, 0d); properties.put(Crystal.CRYSTAL_ANGLE_L, 0d); Crystal c = new CrystalCuboid(properties); properties.put(Crystal.CRYSTAL_ANGLE_P, ang360); properties.put(Crystal.CRYSTAL_ANGLE_L, 0d); Crystal cEquivalentP360 = new CrystalCuboid(properties); // Should be the same as c properties.put(Crystal.CRYSTAL_ANGLE_P, 0d); properties.put(Crystal.CRYSTAL_ANGLE_L, ang360); Crystal cEquivalentL360 = new CrystalCuboid(properties); // Should be the same as c properties.put(Crystal.CRYSTAL_ANGLE_P, ang360); properties.put(Crystal.CRYSTAL_ANGLE_L, ang360); Crystal cEquivalentPL360 = new CrystalCuboid(properties); // Should be the same as c properties.put(Crystal.CRYSTAL_ANGLE_P, ang180); properties.put(Crystal.CRYSTAL_ANGLE_L, 0d); Crystal cP180 = new CrystalCuboid(properties); // (i,j,k) should = c(-i, -j, k) properties.put(Crystal.CRYSTAL_ANGLE_P, 0d); properties.put(Crystal.CRYSTAL_ANGLE_L, ang180); Crystal cL180 = new CrystalCuboid(properties); // (i,j,k) should = c(i , -j, -k) int x = c.getCrystSizeVoxels()[0]; int y = c.getCrystSizeVoxels()[1]; int z = c.getCrystSizeVoxels()[2]; for (int i = 0; i < x; i++) { for (int j = 0; j < y; j++) { for (int k = 0; k < z; k++) { double id[] = c.getCrystCoord(i, j, k); EqualsAssertion(cEquivalentP360.getCrystCoord(i, j, k)[0], id[0], "P360-x"); EqualsAssertion(cEquivalentP360.getCrystCoord(i, j, k)[1], id[1], "P360-y"); EqualsAssertion(cEquivalentP360.getCrystCoord(i, j, k)[2], id[2], "P360-z"); EqualsAssertion(cEquivalentL360.getCrystCoord(i, j, k)[0], id[0], "L360-x"); EqualsAssertion(cEquivalentL360.getCrystCoord(i, j, k)[1], id[1], "L360-y"); EqualsAssertion(cEquivalentL360.getCrystCoord(i, j, k)[2], id[2], "L360-z"); EqualsAssertion(cEquivalentPL360.getCrystCoord(i, j, k)[0], id[0], "PL360-x"); EqualsAssertion(cEquivalentPL360.getCrystCoord(i, j, k)[1], id[1], "PL360-y"); EqualsAssertion(cEquivalentPL360.getCrystCoord(i, j, k)[2], id[2], "PL360-z"); EqualsAssertion(-1 * cP180.getCrystCoord(i, j, k)[0], id[0], "P180-x"); EqualsAssertion(-1 * cP180.getCrystCoord(i, j, k)[1], id[1], "P180-y"); EqualsAssertion(cP180.getCrystCoord(i, j, k)[2], id[2], "P180-z"); EqualsAssertion(cL180.getCrystCoord(i, j, k)[0], id[0], "L180-x"); EqualsAssertion(-1 * cL180.getCrystCoord(i, j, k)[1], id[1], "L180-y"); EqualsAssertion(-1 * cL180.getCrystCoord(i, j, k)[2], id[2], "L180-z"); } } } System.out.println("@Test - testCuboidCrystalPandL"); } //This should work now... Am going to tart up Wedge and have another go. @Test(groups = { "advanced" }) public static void testFindDepth() { HashMap<Object, Object> properties = new HashMap<Object, Object>(); properties.put(Crystal.CRYSTAL_DIM_X, 100d); properties.put(Crystal.CRYSTAL_DIM_Y, 100d); properties.put(Crystal.CRYSTAL_DIM_Z, 100d); properties.put(Crystal.CRYSTAL_RESOLUTION, 1d); properties.put(Crystal.CRYSTAL_ANGLE_P, 0d); properties.put(Crystal.CRYSTAL_ANGLE_L, 0d); properties.put(Crystal.CRYSTAL_COEFCALC, new CoefCalcAverage()); Crystal c = new CrystalCuboid(properties); Wedge w = new Wedge(2d, 0d, 90d, 100d, 0d, 0d, 0d, 0d, 0d, 0d, 0d); /* Some random test coordinates to work on */ double[] testCoords = { 0, 0, 0 };//{ 12.23, 21.56, -44.32}; double[] testInvCoords = { 0, 0, 0 };//{-12.23, 21.56, 44.32}; for (double angles = 0; angles < Math.toRadians(500); angles += Math .toRadians(18.8)) { // Loop over y as well, to make it more thorough //System.out.println(String.format("%n%n angle is %g", angles)); /* Rotating crystal into position */ double[] tempCoords = new double[3]; double[] tempInvCoords = new double[3]; //Debug System.out.println(i+j+k); tempCoords[0] = testCoords[0] * Math.cos(angles) - testCoords[2] * Math.sin(angles); //Rotate X tempCoords[1] = testCoords[1]; tempCoords[2] = testCoords[0] * Math.sin(angles) + testCoords[2] * Math.cos(angles); //Rotate Z /* Symmetry related pair of tempCoords */ tempInvCoords[0] = testInvCoords[0] * Math.cos(angles) - testInvCoords[2] * Math.sin(angles); //Rotate X tempInvCoords[1] = testInvCoords[1]; tempInvCoords[2] = testInvCoords[0] * Math.sin(angles) + testInvCoords[2] * Math.cos(angles); //Rotate Z Assert.assertTrue(Math.abs(tempCoords[1] - tempInvCoords[1]) <= 1e-10, "y does not match under inversion"); if (Math.abs(tempCoords[1] - tempInvCoords[1]) <= 1e-10) System.out.println("y coords match"); // System.out.println("tempcoords = " + tempCoords[0] + ", " + tempCoords[1] + ", " + tempCoords[2]); // System.out.println("tempInvCoords = " + tempInvCoords[0] + ", " + tempInvCoords[1] + ", " + tempInvCoords[2]); // System.out.println("depth tempCoords @ theta = 0: " + c.findDepth(tempCoords, angles, w)); // System.out.println("depth tempInvCoords @ theta = 0: " + c.findDepth(tempInvCoords, angles, w)); // System.out.println("depth tempCoords @ theta = 180: " + c.findDepth(tempCoords, angles + Math.PI, w)); // System.out.println("depth tempInvCoords @ theta = 180: "+ c.findDepth(tempInvCoords, angles + Math.PI, w)); /* um of depths should be constant under 180Deg rotation */ c.setupDepthFinding(angles, w); double sumdepths1 = c.findDepth(tempCoords, angles, w) + c.findDepth(tempInvCoords, angles, w); c.setupDepthFinding(angles + Math.PI, w); double sumdepths2 = c.findDepth(tempCoords, angles + Math.PI, w) + c.findDepth(tempInvCoords, angles + Math.PI, w); // System.out.println("sumdepths1 = " + sumdepths1); // System.out.println("sumdepths2 = " + sumdepths2); double depthDelta = sumdepths1 - sumdepths2; System.out.println("depthdelta = " + depthDelta); Assert.assertTrue(Math.abs(sumdepths1 - sumdepths2) <= 1e-10, "depths are not matched under symmetry"); } } @Test(groups = { "advanced" }) public static void secondDepthTest() { // make a new map for a Cuboid Crystal, dimensions 90 x 74 x 40 um, // 0.5 voxels per um, no starting rotation. HashMap<Object, Object> properties = new HashMap<Object, Object>(); properties.put(Crystal.CRYSTAL_DIM_X, 90d); properties.put(Crystal.CRYSTAL_DIM_Y, 74d); properties.put(Crystal.CRYSTAL_DIM_Z, 40d); properties.put(Crystal.CRYSTAL_RESOLUTION, 0.5d); properties.put(Crystal.CRYSTAL_ANGLE_P, 0d); properties.put(Crystal.CRYSTAL_ANGLE_L, 0d); properties.put(Crystal.CRYSTAL_COEFCALC, new CoefCalcAverage()); Crystal c = new CrystalCuboid(properties); // create a new wedge with no rotation at 100 seconds' exposure // (doesn't matter) Wedge w = new Wedge(0d, 0d, 0d, 100d, 0d, 0d, 0d, 0d, 0d, 0d, 0d); // beam is along z axis. So when the crystal is not rotated, the // maximum depth along the z axis should be 40 um (length of crystal). double[] crystCoords = new double[3]; // this coordinate is in voxel coordinates. // this translates to bottom left corner of the crystal // in crystCoords (-45, -37, -20) // and should therefore be first to intercept the beam and have // a depth of 0. crystCoords = c.getCrystCoord(0, 0, 0); Assertion.equals(crystCoords[2], -20, "crystal coordinate z axis = -20"); c.setupDepthFinding(0, w); double depth = c.findDepth(crystCoords, 0, w); Assertion.equals(depth, 0, "depth = 0 at front edge of crystal"); } }
package service.updateservice; import static org.eclipse.egit.github.core.client.IGitHubConstants.CONTENT_TYPE_JSON; import static org.eclipse.egit.github.core.client.IGitHubConstants.SEGMENT_COMMENTS; import static org.eclipse.egit.github.core.client.IGitHubConstants.SEGMENT_ISSUES; import static org.eclipse.egit.github.core.client.IGitHubConstants.SEGMENT_REPOS; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import java.util.stream.Collectors; import org.eclipse.egit.github.core.Comment; import org.eclipse.egit.github.core.IRepositoryIdProvider; import org.eclipse.egit.github.core.client.PagedRequest; import service.GitHubClientExtended; import service.ServiceManager; import com.google.gson.reflect.TypeToken; public class CommentUpdateService extends UpdateService<Comment>{ private int issueId; private List<Comment> commentsList; private long pollInterval = 60000; //time between polls in ms private Timer pollTimer; public CommentUpdateService(GitHubClientExtended client, int issueId, List<Comment> list) { super(client); this.issueId = issueId; this.commentsList = list; lastCheckTime = new Date(); } private Map<String, String> createUpdatedCommentsParams(){ //Comments must be retrieved in descending order although they are always displayed in ascending order because of paging. //Otherwise, new comments will not be seen because the first page of comments remains the same Map<String, String> params = new HashMap<String, String>(); params.put("sort", "created"); params.put("direction", "desc"); return params; } @Override protected PagedRequest<Comment> createUpdatedRequest(IRepositoryIdProvider repoId){ PagedRequest<Comment> request = new PagedRequest<Comment>(); String path = SEGMENT_REPOS + "/" + repoId.generateId() + SEGMENT_ISSUES + "/" + issueId + SEGMENT_COMMENTS; request.setUri(path); request.setParams(createUpdatedCommentsParams()); request.setResponseContentType(CONTENT_TYPE_JSON); request.setType(new TypeToken<Comment>(){}.getType()); request.setArrayType(new TypeToken<ArrayList<Comment>>(){}.getType()); return request; } private void updateCommentsInList(Comment comment){ comment.setBodyHtml(ServiceManager.getInstance().getMarkupForComment(comment)); int index = getCommentsInListWithId(comment.getId()); if(index != -1){ commentsList.set(index, comment); }else{ commentsList.add(comment); } } private int getCommentsInListWithId(long id){ for(int i = 0; i < commentsList.size(); i++){ if(commentsList.get(i).getId() == id){ return i; } } return -1; } protected void updateCachedComments(IRepositoryIdProvider repoId){ List<Comment> updatedComments = super.getUpdatedItems(repoId); //updateComments is the list of all comments for the issue. Collections.reverse(updatedComments); if(!updatedComments.isEmpty()){ List<Comment> removed = getRemovedComments(updatedComments); commentsList.removeAll(removed); updatedComments.stream().forEach(comment -> updateCommentsInList(comment)); updateGlobalCachedCommentsForIssue(updatedComments); } } private void updateGlobalCachedCommentsForIssue(List<Comment> comments){ ServiceManager.getInstance().getModel().cacheCommentsListForIssue(comments, issueId); } private List<Comment> getRemovedComments(List<Comment> updatedComments){ //TODO: optimise for sorted list return commentsList.stream().filter(item -> !hasComment(updatedComments, item)).collect(Collectors.toList()); } private boolean hasComment(List<Comment> comments, Comment comment){ for(Comment item: comments){ if(comment.getId() == item.getId()){ return true; } } return false; } public void startCommentsListUpdate(){ stopCommentsListUpdate(); pollTimer = new Timer(); TimerTask pollTask = new TimerTask(){ @Override public void run() { updateCachedComments(ServiceManager.getInstance().getRepoId()); } }; pollTimer.scheduleAtFixedRate(pollTask, 0, pollInterval); } public void restartCommentsListUpdate(){ stopCommentsListUpdate(); startCommentsListUpdate(); } public void stopCommentsListUpdate(){ if(pollTimer != null){ pollTimer.cancel(); pollTimer = null; } } }
package be.ibridge.kettle.job; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.MessageDialogWithToggle; import org.eclipse.swt.widgets.Shell; import org.w3c.dom.Document; import org.w3c.dom.Node; import be.ibridge.kettle.core.Const; import be.ibridge.kettle.core.DBCache; import be.ibridge.kettle.core.KettleVariables; import be.ibridge.kettle.core.LogWriter; import be.ibridge.kettle.core.NotePadMeta; import be.ibridge.kettle.core.Point; import be.ibridge.kettle.core.Props; import be.ibridge.kettle.core.Rectangle; import be.ibridge.kettle.core.Row; import be.ibridge.kettle.core.SQLStatement; import be.ibridge.kettle.core.TransAction; import be.ibridge.kettle.core.XMLHandler; import be.ibridge.kettle.core.XMLInterface; import be.ibridge.kettle.core.database.Database; import be.ibridge.kettle.core.database.DatabaseMeta; import be.ibridge.kettle.core.exception.KettleDatabaseException; import be.ibridge.kettle.core.exception.KettleException; import be.ibridge.kettle.core.exception.KettleXMLException; import be.ibridge.kettle.core.reflection.StringSearchResult; import be.ibridge.kettle.core.reflection.StringSearcher; import be.ibridge.kettle.core.util.StringUtil; import be.ibridge.kettle.core.value.Value; import be.ibridge.kettle.job.entry.JobEntryCopy; import be.ibridge.kettle.job.entry.JobEntryInterface; import be.ibridge.kettle.job.entry.eval.JobEntryEval; import be.ibridge.kettle.job.entry.special.JobEntrySpecial; import be.ibridge.kettle.repository.Repository; import be.ibridge.kettle.repository.RepositoryDirectory; /** * Defines a Job and provides methods to load, save, verify, etc. * * @author Matt * @since 11-08-2003 * */ public class JobMeta implements Cloneable, XMLInterface { public LogWriter log; private long id; private String name; private String filename; public ArrayList jobentries; public ArrayList jobcopies; public ArrayList jobhops; public ArrayList notes; public ArrayList databases; private RepositoryDirectory directory; private String arguments[]; private boolean changed, changed_entries, changed_hops, changed_notes; private DatabaseMeta logconnection; private String logTable; public DBCache dbcache; private ArrayList undo; private int max_undo; private int undo_position; public static final int TYPE_UNDO_CHANGE = 1; public static final int TYPE_UNDO_NEW = 2; public static final int TYPE_UNDO_DELETE = 3; public static final int TYPE_UNDO_POSITION = 4; public static final String STRING_SPECIAL_START = "START"; public static final String STRING_SPECIAL_DUMMY = "DUMMY"; // Remember the size and position of the different windows... public boolean max[] = new boolean[1]; public Rectangle size[] = new Rectangle[1]; public String created_user, modified_user; public Value created_date, modified_date; private boolean useBatchId; private boolean batchIdPassed; private boolean logfieldUsed; public JobMeta(LogWriter l) { log=l; clear(); } public long getID() { return id; } public void setID(long id) { this.id = id; } public void clear() { name = null; jobcopies = new ArrayList(); jobentries = new ArrayList(); jobhops = new ArrayList(); notes = new ArrayList(); databases = new ArrayList(); logconnection = null; logTable = null; arguments = null; max_undo = Const.MAX_UNDO; dbcache = DBCache.getInstance(); undo = new ArrayList(); undo_position=-1; addDefaults(); setChanged(false); modified_user = "-"; modified_date = new Value("MODIFIED_DATE", Value.VALUE_TYPE_DATE).sysdate(); directory = new RepositoryDirectory(); // setInternalKettleVariables(); Don't clear the internal variables for ad-hoc jobs, it's ruines the previews etc. } public void addDefaults() { addStart(); // Add starting point! addDummy(); // Add dummy! addOK(); // errors == 0 evaluation addError(); // errors != 0 evaluation clearChanged(); } private void addStart() { JobEntrySpecial je = new JobEntrySpecial(STRING_SPECIAL_START, true, false); JobEntryCopy jge = new JobEntryCopy(log); jge.setID(-1L); jge.setEntry(je); jge.setLocation(50,50); jge.setDrawn(false); jge.setDescription("A job starts to process here."); addJobEntry(jge); } private void addDummy() { JobEntrySpecial dummy = new JobEntrySpecial(STRING_SPECIAL_DUMMY, false, true); JobEntryCopy dummyge = new JobEntryCopy(log); dummyge.setID(-1L); dummyge.setEntry(dummy); dummyge.setLocation(50,50); dummyge.setDrawn(false); dummyge.setDescription("A dummy entry."); addJobEntry(dummyge); } public void addOK() { JobEntryEval ok = new JobEntryEval("OK", "errors == 0"); JobEntryCopy jgok = new JobEntryCopy(log); jgok.setEntry(ok); jgok.setLocation(0,0); jgok.setDrawn(false); jgok.setDescription("This comparisson is true when no errors have occured."); addJobEntry(jgok); } public void addError() { JobEntryEval err = new JobEntryEval("ERROR", "errors != 0"); JobEntryCopy jgerr = new JobEntryCopy(log); jgerr.setEntry(err); jgerr.setLocation(0,0); jgerr.setDrawn(false); jgerr.setDescription("This comparisson is true when one or more errors have occured."); addJobEntry(jgerr); } public JobEntryCopy getStart() { for (int i=0;i<nrJobEntries();i++) { JobEntryCopy cge = getJobEntry(i); if (cge.isStart()) return cge; } return null; } public JobEntryCopy getDummy() { for (int i=0;i<nrJobEntries();i++) { JobEntryCopy cge = getJobEntry(i); if (cge.isDummy()) return cge; } return null; } public boolean equals(Object obj) { return name.equalsIgnoreCase(((JobMeta)obj).name); } public Object clone() { try { Object retval = super.clone(); return retval; } catch(CloneNotSupportedException e) { return null; } } public String getName() { return name; } public void setName(String name) { this.name=name; setInternalKettleVariables(); } /** * @return Returns the directory. */ public RepositoryDirectory getDirectory() { return directory; } /** * @param directory The directory to set. */ public void setDirectory(RepositoryDirectory directory) { this.directory = directory; setInternalKettleVariables(); } public String getFilename() { return filename; } public void setFilename(String filename) { this.filename=filename; setInternalKettleVariables(); } public DatabaseMeta getLogConnection() { return logconnection; } public void setLogConnection(DatabaseMeta ci) { logconnection=ci; } /** * @return Returns the databases. */ public ArrayList getDatabases() { return databases; } /** * @param databases The databases to set. */ public void setDatabases(ArrayList databases) { this.databases = databases; } public void setChanged() { setChanged(true); } public void setChanged(boolean ch) { changed=ch; } public void clearChanged() { changed_entries = false; changed_hops = false; changed_notes = false; for (int i=0;i<nrJobEntries();i++) { JobEntryCopy entry = getJobEntry(i); entry.setChanged(false); } for (int i=0;i<nrJobHops();i++) { JobHopMeta hop = getJobHop(i); hop.setChanged(false); } changed=false; } public boolean hasChanged() { if (changed || changed_notes || changed_entries || changed_hops) return true; for (int i=0;i<nrJobEntries();i++) { JobEntryCopy entry = getJobEntry(i); if (entry.hasChanged()) return true; } for (int i=0;i<nrJobHops();i++) { JobHopMeta hop = getJobHop(i); if (hop.hasChanged()) return true; } return false; } private void saveRepJob(Repository rep) throws KettleException { try { // The ID has to be assigned, even when it's a new item... rep.insertJob( getID(), directory.getID(), getName(), logconnection==null?-1:logconnection.getID(), logTable, modified_user, modified_date, useBatchId, batchIdPassed, logfieldUsed ); } catch(KettleDatabaseException dbe) { throw new KettleException("Unable to save job info to repository", dbe); } } public boolean showReplaceWarning(Repository rep) { if (getID()<0) { try { if ( rep.getJobID( getName(), directory.getID() )>0 ) return true; } catch(KettleDatabaseException dbe) { return true; } } return false; } public String getXML() { DatabaseMeta ci = getLogConnection(); StringBuffer retval = new StringBuffer(); retval.append("<job>"+Const.CR); retval.append(" "+XMLHandler.addTagValue("name", getName())); retval.append(" "+XMLHandler.addTagValue("directory", directory.getPath())); for (int i=0;i<nrDatabases();i++) { DatabaseMeta dbinfo = getDatabase(i); retval.append(dbinfo.getXML()); } retval.append(" "+XMLHandler.addTagValue("logconnection", ci==null?"":ci.getName())); retval.append(" "+XMLHandler.addTagValue("logtable", logTable)); retval.append( " " + XMLHandler.addTagValue("use_batchid", useBatchId)); retval.append( " " + XMLHandler.addTagValue("pass_batchid", batchIdPassed)); retval.append( " " + XMLHandler.addTagValue("use_logfield", logfieldUsed)); retval.append(" <entries>"+Const.CR); for (int i=0;i<nrJobEntries();i++) { JobEntryCopy jge = getJobEntry(i); retval.append(jge.getXML()); } retval.append(" </entries>"+Const.CR); retval.append(" <hops>"+Const.CR); for (int i=0;i<nrJobHops();i++) { JobHopMeta hi = getJobHop(i); retval.append(hi.getXML()); } retval.append(" </hops>"+Const.CR); retval.append(" <notepads>"+Const.CR); for (int i=0;i<nrNotes();i++) { NotePadMeta ni= getNote(i); retval.append(ni.getXML()); } retval.append(" </notepads>"+Const.CR); retval.append(" </job>"+Const.CR); return retval.toString(); } /** * Load the job from the XML file specified. * @param log the logging channel * @param fname The filename to load as a job * @param rep The repository to bind againt, null if there is no repository available. * @throws KettleXMLException */ public JobMeta(LogWriter log, String fname, Repository rep) throws KettleXMLException { this.log = log; try { Document doc = XMLHandler.loadXMLFile(fname); if (doc!=null) { // Clear the job clear(); // The jobnode Node jobnode = XMLHandler.getSubNode(doc, "job"); loadXML(jobnode, rep); // Do this at the end setFilename(fname); } else { throw new KettleXMLException("Error reading/validating information from XML file: "+fname); } } catch(Exception e) { throw new KettleXMLException("Unable to load the job from XML file ["+fname+"]", e); } } public JobMeta(LogWriter log, Node jobnode, Repository rep) throws KettleXMLException { this.log = log; loadXML(jobnode, rep); } public void loadXML(Node jobnode, Repository rep) throws KettleXMLException { Props props = null; if (Props.isInitialized()) props=Props.getInstance(); try { // clear the jobs; clear(); // get job info: name = XMLHandler.getTagValue(jobnode, "name"); // Load the default list of databases if (rep!=null) { readDatabases(rep); clearChanged(); } // Read the database connections int nr = XMLHandler.countNodes(jobnode, "connection"); for (int i=0;i<nr;i++) { Node dbnode = XMLHandler.getSubNodeByNr(jobnode, "connection", i); DatabaseMeta dbcon = new DatabaseMeta(dbnode); DatabaseMeta exist = findDatabase(dbcon.getName()); if (exist == null) { addDatabase(dbcon); } else { boolean askOverwrite = Props.isInitialized() ? props.askAboutReplacingDatabaseConnections() : false; boolean overwrite = Props.isInitialized() ? props.replaceExistingDatabaseConnections() : true; if (askOverwrite) { // That means that we have a Display variable set in Props... if (props.getDisplay()!=null) { Shell shell = props.getDisplay().getActiveShell(); MessageDialogWithToggle md = new MessageDialogWithToggle(shell, "Warning", null, "Connection ["+dbcon.getName()+"] already exists, do you want to overwrite this database connection?", MessageDialog.WARNING, new String[] { "Yes", "No" },//"Yes", "No" 1, "Please, don't show this warning anymore.", !props.askAboutReplacingDatabaseConnections() ); int idx = md.open(); props.setAskAboutReplacingDatabaseConnections(!md.getToggleState()); overwrite = (idx==0); // Yes means: overwrite } } if (overwrite) { int idx = indexOfDatabase(exist); removeDatabase(idx); addDatabase(idx, dbcon); } } } /* * Get the log database connection & log table */ String logcon = XMLHandler.getTagValue(jobnode, "logconnection"); logconnection = findDatabase(logcon); logTable = XMLHandler.getTagValue(jobnode, "logtable"); useBatchId = "Y".equalsIgnoreCase(XMLHandler.getTagValue(jobnode, "use_batchid")); batchIdPassed = "Y".equalsIgnoreCase(XMLHandler.getTagValue(jobnode, "pass_batchid")); logfieldUsed = "Y".equalsIgnoreCase(XMLHandler.getTagValue(jobnode, "use_logfield")); /* * read the job entries... */ Node entriesnode = XMLHandler.getSubNode(jobnode, "entries"); int tr = XMLHandler.countNodes(entriesnode, "entry"); for (int i=0;i<tr;i++) { Node entrynode = XMLHandler.getSubNodeByNr(entriesnode, "entry", i); //System.out.println("Reading entry:\n"+entrynode); JobEntryCopy je = new JobEntryCopy(entrynode, databases, rep); JobEntryCopy prev = findJobEntry(je.getName(), 0, true); if (prev!=null) { if (je.getNr()==0) // See if the #0 already exists! { // Replace previous version with this one: remove it first int idx = indexOfJobEntry(prev); removeJobEntry(idx); } else if (je.getNr()>0) // Use previously defined JobEntry info! { je.setEntry(prev.getEntry()); // See if entry.5 already exists... prev = findJobEntry(je.getName(), je.getNr(), true); if (prev!=null) // remove the old one! { int idx = indexOfJobEntry(prev); removeJobEntry(idx); } } } // Add the JobEntryCopy... addJobEntry(je); } Node hopsnode = XMLHandler.getSubNode(jobnode, "hops"); int ho = XMLHandler.countNodes(hopsnode, "hop"); for (int i=0;i<ho;i++) { Node hopnode = XMLHandler.getSubNodeByNr(hopsnode, "hop", i); JobHopMeta hi = new JobHopMeta(hopnode, this); jobhops.add(hi); } // Read the notes... Node notepadsnode = XMLHandler.getSubNode(jobnode, "notepads"); int nrnotes = XMLHandler.countNodes(notepadsnode, "notepad"); for (int i=0;i<nrnotes;i++) { Node notepadnode = XMLHandler.getSubNodeByNr(notepadsnode, "notepad", i); NotePadMeta ni = new NotePadMeta(notepadnode); notes.add(ni); } // Do we have the special entries? if (findJobEntry(STRING_SPECIAL_START, 0, true)==null) addStart(); if (findJobEntry(STRING_SPECIAL_DUMMY, 0, true)==null) addDummy(); clearChanged(); } catch(Exception e) { throw new KettleXMLException("Unable to load job info from XML node", e); } finally { setInternalKettleVariables(); } } /** * Read the database connections in the repository and add them to this job * if they are not yet present. * * @param rep The repository to load the database connections from. */ public void readDatabases(Repository rep) { try { long dbids[] = rep.getDatabaseIDs(); for (int i=0;i<dbids.length;i++) { DatabaseMeta ci = new DatabaseMeta(rep, dbids[i]); if (indexOfDatabase(ci)<0) { addDatabase(ci); ci.setChanged(false); } } } catch(KettleDatabaseException dbe) { log.logError(toString(), "Error reading databases from repository:"+Const.CR+dbe.getMessage()); } catch(KettleException ke) { log.logError(toString(), "Error reading databases from repository:"+Const.CR+ke.getMessage()); } setChanged(false); } /** * Find a database connection by it's name * @param name The database name to look for * @return The database connection or null if nothing was found. */ public DatabaseMeta findDatabase(String name) { for (int i=0;i<nrDatabases();i++) { DatabaseMeta ci = getDatabase(i); if (ci.getName().equalsIgnoreCase(name)) { return ci; } } return null; } public void saveRep(Repository rep) throws KettleException { saveRep(rep, null); } public void saveRep(Repository rep, IProgressMonitor monitor) throws KettleException { try { int nrWorks = 2+nrDatabases()+nrNotes()+nrJobEntries()+nrJobHops(); if (monitor!=null) monitor.beginTask("Saving transformation "+directory+Const.FILE_SEPARATOR+getName(), nrWorks); // Before we start, make sure we have a valid job ID! // Two possibilities: // 1) We have a ID: keep it // 2) We don't have an ID: look it up. // If we find a transformation with the same name: ask! if (monitor!=null) monitor.subTask("Handling previous version of job..."); setID( rep.getJobID(getName(), directory.getID()) ); // If no valid id is available in the database, assign one... if (getID()<=0) { setID( rep.getNextJobID() ); } else { // If we have a valid ID, we need to make sure everything is cleared out // of the database for this id_job, before we put it back in... rep.delAllFromJob(getID()); } if (monitor!=null) monitor.worked(1); // Now, save the job entry in R_JOB // Note, we save this first so that we have an ID in the database. // Everything else depends on this ID, including recursive job entries to the save job. (retry) if (monitor!=null) monitor.subTask("Saving job details..."); log.logDetailed(toString(), "Saving job info to repository..."); saveRepJob(rep); if (monitor!=null) monitor.worked(1); // Save the notes log.logDetailed(toString(), "Saving notes to repository..."); for (int i=0;i<nrNotes();i++) { if (monitor!=null) monitor.subTask("Saving note #"+(i+1)+"/"+nrNotes()); NotePadMeta ni = getNote(i); ni.saveRep(rep, getID()); if (ni.getID()>0) { rep.insertJobNote(getID(), ni.getID()); } if (monitor!=null) monitor.worked(1); } // Save the job entries log.logDetailed(toString(), "Saving "+nrJobEntries()+" ChefGraphEntries to repository..."); for (int i=0;i<nrJobEntries();i++) { if (monitor!=null) monitor.subTask("Saving job entry #"+(i+1)+"/"+nrJobEntries()); JobEntryCopy cge = getJobEntry(i); cge.saveRep(rep, getID()); if (monitor!=null) monitor.worked(1); } log.logDetailed(toString(), "Saving job hops to repository..."); for (int i=0;i<nrJobHops();i++) { if (monitor!=null) monitor.subTask("Saving job hop #"+(i+1)+"/"+nrJobHops()); JobHopMeta hi = getJobHop(i); hi.saveRep(rep, getID()); if (monitor!=null) monitor.worked(1); } // Commit this transaction!! rep.commit(); clearChanged(); if (monitor!=null) monitor.done(); } catch(KettleDatabaseException dbe) { rep.rollback(); throw new KettleException("Unable to save Job in repository, database rollback performed.", dbe); } } /** * Load a job in a directory * @param log the logging channel * @param rep The Repository * @param jobname The name of the job * @param repdir The directory in which the job resides. * @throws KettleException */ public JobMeta(LogWriter log, Repository rep, String jobname, RepositoryDirectory repdir) throws KettleException { this(log, rep, jobname, repdir, null); } /** * Load a job in a directory * @param log the logging channel * @param rep The Repository * @param jobname The name of the job * @param repdir The directory in which the job resides. * @throws KettleException */ public JobMeta(LogWriter log, Repository rep, String jobname, RepositoryDirectory repdir, IProgressMonitor monitor) throws KettleException { this.log = log; try { // Clear everything... clear(); directory = repdir; // Get the transformation id setID( rep.getJobID(jobname, repdir.getID()) ); // If no valid id is available in the database, then give error... if (getID()>0) { // Load the notes... long noteids[] = rep.getJobNoteIDs(getID()); long jecids[] = rep.getJobEntryCopyIDs(getID()); long hopid[] = rep.getJobHopIDs(getID()); int nrWork = 2+noteids.length+jecids.length+hopid.length; if (monitor!=null) monitor.beginTask("Loading job "+repdir+Const.FILE_SEPARATOR+jobname, nrWork); // Load the common database connections if (monitor!=null) monitor.subTask("Reading the available database from the repository"); readDatabases(rep); if (monitor!=null) monitor.worked(1); // get job info: if (monitor!=null) monitor.subTask("Reading the job information"); Row jobrow = rep.getJob(getID()); name = jobrow.searchValue("NAME").getString(); logTable = jobrow.searchValue("TABLE_NAME_LOG").getString(); long id_logdb = jobrow.searchValue("ID_DATABASE_LOG").getInteger(); if (id_logdb>0) { // Get the logconnection logconnection = new DatabaseMeta(rep, id_logdb); } useBatchId = jobrow.getBoolean("USE_BATCH_ID", false); batchIdPassed = jobrow.getBoolean("PASS_BATCH_ID", false); logfieldUsed = jobrow.getBoolean("USE_LOGFIELD", false); if (monitor!=null) monitor.worked(1); log.logDetailed(toString(), "Loading "+noteids.length+" notes"); for (int i=0;i<noteids.length;i++) { if (monitor!=null) monitor.subTask("Reading note #"+(i+1)+"/"+noteids.length); NotePadMeta ni = new NotePadMeta(log, rep, noteids[i]); if (indexOfNote(ni)<0) addNote(ni); if (monitor!=null) monitor.worked(1); } // Load the job entries... log.logDetailed(toString(), "Loading "+jecids.length+" job entries"); for (int i=0;i<jecids.length;i++) { if (monitor!=null) monitor.subTask("Reading job entry #"+(i+1)+"/"+(jecids.length)); JobEntryCopy jec = new JobEntryCopy(log, rep, getID(), jecids[i], jobentries, databases); int idx = indexOfJobEntry(jec); if (idx < 0) { if (jec.getName()!=null && jec.getName().length()>0) addJobEntry(jec); } else { setJobEntry(idx, jec); // replace it! } if (monitor!=null) monitor.worked(1); } // Load the hops... log.logDetailed(toString(), "Loading "+hopid.length+" job hops"); for (int i=0;i<hopid.length;i++) { if (monitor!=null) monitor.subTask("Reading job hop #"+(i+1)+"/"+(jecids.length)); JobHopMeta hi = new JobHopMeta(rep, hopid[i], this, jobcopies); jobhops.add(hi); if (monitor!=null) monitor.worked(1); } // Finally, clear the changed flags... clearChanged(); if (monitor!=null) monitor.subTask("Finishing load"); if (monitor!=null) monitor.done(); } else { throw new KettleException("Can't find job : "+jobname); } } catch(KettleException dbe) { throw new KettleException("An error occurred reading job ["+jobname+"] from the repository", dbe); } finally { setInternalKettleVariables(); } } public JobEntryCopy getChefGraphEntry(int x, int y, int iconsize) { int i, s; s = nrJobEntries(); for (i=s-1;i>=0;i--) // Back to front because drawing goes from start to end { JobEntryCopy je = getJobEntry(i); Point p = je.getLocation(); if (p!=null) { if ( x >= p.x && x <= p.x+iconsize && y >= p.y && y <= p.y+iconsize ) { return je; } } } return null; } public int nrJobEntries() { return jobcopies.size(); } public int nrJobHops() { return jobhops.size(); } public int nrNotes() { return notes.size(); } public int nrDatabases() { return databases.size(); } public JobHopMeta getJobHop(int i) { return (JobHopMeta)jobhops.get(i); } public JobEntryCopy getJobEntry(int i) { return (JobEntryCopy)jobcopies.get(i); } public NotePadMeta getNote(int i) { return (NotePadMeta)notes.get(i); } public DatabaseMeta getDatabase(int i) { return (DatabaseMeta)databases.get(i); } public void addJobEntry(JobEntryCopy je) { jobcopies.add(je); setChanged(); } public void addJobHop(JobHopMeta hi) { jobhops.add(hi); setChanged(); } public void addNote(NotePadMeta ni) { notes.add(ni); setChanged(); } public void addDatabase(DatabaseMeta ci) { databases.add(ci); setChanged(); } public void addJobEntry(int p, JobEntryCopy si) { jobcopies.add(p, si); changed_entries = true; } public void addJobHop(int p, JobHopMeta hi) { jobhops.add(p, hi); changed_hops = true; } public void addNote(int p, NotePadMeta ni) { notes.add(p, ni); changed_notes = true; } public void addDatabase(int p, DatabaseMeta ci) { databases.add(p, ci); setChanged(); } public void removeJobEntry(int i) { jobcopies.remove(i); setChanged(); } public void removeJobHop(int i) { jobhops.remove(i); setChanged(); } public void removeNote(int i) { notes.remove(i); setChanged(); } public void removeDatabase(int i) { if (i<0 || i>=databases.size()) return; databases.remove(i); setChanged(); } public int indexOfJobHop(JobHopMeta he) { return jobhops.indexOf(he); } public int indexOfNote(NotePadMeta ni) { return notes.indexOf(ni); } public int indexOfJobEntry(JobEntryCopy ge) { return jobcopies.indexOf(ge); } public int indexOfDatabase(DatabaseMeta di) { return databases.indexOf(di); } public void setJobEntry(int idx, JobEntryCopy jec) { jobcopies.set(idx, jec); } /** * Find an existing JobEntryCopy by it's name and number * @param name The name of the job entry copy * @param nr The number of the job entry copy * @return The JobEntryCopy or null if nothing was found! */ public JobEntryCopy findJobEntry(String name, int nr, boolean searchHiddenToo) { for (int i=0;i<nrJobEntries();i++) { JobEntryCopy jec = getJobEntry(i); if (jec.getName().equalsIgnoreCase(name) && jec.getNr()==nr) { if (searchHiddenToo || jec.isDrawn()) { return jec; } } } return null; } public JobEntryCopy findJobEntry(String full_name_nr) { int i; for (i=0;i<nrJobEntries();i++) { // log.logDebug("findChefGraphEntry()", "looking at nr: "+i); JobEntryCopy jec = getJobEntry(i); JobEntryInterface je = jec.getEntry(); if (je.toString().equalsIgnoreCase(full_name_nr)) { return jec; } } return null; } public JobHopMeta findJobHop(String name) { int i; for (i=0;i<nrJobHops();i++) { JobHopMeta hi = getJobHop(i); if (hi.toString().equalsIgnoreCase(name)) { return hi; } } return null; } public JobHopMeta findJobHopFrom(JobEntryCopy jge) { int i; for (i=0;i<nrJobHops();i++) { JobHopMeta hi = getJobHop(i); if (hi.from_entry.equals(jge)) // return the first { return hi; } } return null; } public JobHopMeta findJobHop(JobEntryCopy from, JobEntryCopy to) { int i; for (i=0;i<nrJobHops();i++) { JobHopMeta hi = getJobHop(i); if (hi.isEnabled()) { if (hi!=null && hi.from_entry!=null && hi.to_entry!=null && hi.from_entry.equals(from) && hi.to_entry.equals(to) ) { return hi; } } } return null; } public JobHopMeta findJobHopTo(JobEntryCopy jge) { int i; for (i=0;i<nrJobHops();i++) { JobHopMeta hi = getJobHop(i); if (hi!=null && hi.to_entry!=null && hi.to_entry.equals(jge)) // Return the first! { return hi; } } return null; } public int findNrPrevChefGraphEntries(JobEntryCopy from) { return findNrPrevChefGraphEntries(from, false); } public JobEntryCopy findPrevChefGraphEntry(JobEntryCopy to, int nr) { return findPrevChefGraphEntry(to, nr, false); } public int findNrPrevChefGraphEntries(JobEntryCopy to, boolean info) { int count=0; int i; for (i=0;i<nrJobHops();i++) // Look at all the hops; { JobHopMeta hi = getJobHop(i); if (hi.isEnabled() && hi.to_entry.equals(to)) { count++; } } return count; } public JobEntryCopy findPrevChefGraphEntry(JobEntryCopy to, int nr, boolean info) { int count=0; int i; for (i=0;i<nrJobHops();i++) // Look at all the hops; { JobHopMeta hi = getJobHop(i); if (hi.isEnabled() && hi.to_entry.equals(to)) { if (count==nr) { return hi.from_entry; } count++; } } return null; } public int findNrNextChefGraphEntries(JobEntryCopy from) { int count=0; int i; for (i=0;i<nrJobHops();i++) // Look at all the hops; { JobHopMeta hi = getJobHop(i); if (hi.isEnabled() && hi.from_entry.equals(from)) count++; } return count; } public JobEntryCopy findNextChefGraphEntry(JobEntryCopy from, int cnt) { int count=0; int i; for (i=0;i<nrJobHops();i++) // Look at all the hops; { JobHopMeta hi = getJobHop(i); if (hi.isEnabled() && hi.from_entry.equals(from)) { if (count==cnt) { return hi.to_entry; } count++; } } return null; } public boolean hasLoop(JobEntryCopy entry) { return hasLoop(entry, null); } public boolean hasLoop(JobEntryCopy entry, JobEntryCopy lookup) { return false; } public boolean isEntryUsedInHops(JobEntryCopy jge) { JobHopMeta fr = findJobHopFrom(jge); JobHopMeta to = findJobHopTo(jge); if (fr!=null || to!=null) return true; return false; } public int countEntries(String name) { int count=0; int i; for (i=0;i<nrJobEntries();i++) // Look at all the hops; { JobEntryCopy je = getJobEntry(i); if (je.getName().equalsIgnoreCase(name)) count++; } return count; } public int generateJobEntryNameNr(String basename) { int nr=1; JobEntryCopy e = findJobEntry(basename+" "+nr, 0, true); while(e!=null) { nr++; e = findJobEntry(basename+" "+nr, 0, true); } return nr; } public int findUnusedNr(String name) { int nr=1; JobEntryCopy je = findJobEntry(name, nr, true); while (je!=null) { nr++; //log.logDebug("findUnusedNr()", "Trying unused nr: "+nr); je = findJobEntry(name, nr, true); } return nr; } public int findMaxNr(String name) { int max=0; for (int i=0;i<nrJobEntries();i++) { JobEntryCopy je = getJobEntry(i); if (je.getName().equalsIgnoreCase(name)) { if (je.getNr()>max) max=je.getNr(); } } return max; } /** * Proposes an alternative job entry name when the original already exists... * @param entryname The job entry name to find an alternative for.. * @return The alternative stepname. */ public String getAlternativeJobentryName(String entryname) { String newname = entryname; JobEntryCopy jec = findJobEntry(newname); int nr = 1; while (jec!=null) { nr++; newname = entryname + " "+nr; jec = findJobEntry(newname); } return newname; } public JobEntryCopy[] getAllChefGraphEntries(String name) { int count=0; for (int i=0;i<nrJobEntries();i++) { JobEntryCopy je = getJobEntry(i); if (je.getName().equalsIgnoreCase(name)) count++; } JobEntryCopy retval[] = new JobEntryCopy[count]; count=0; for (int i=0;i<nrJobEntries();i++) { JobEntryCopy je = getJobEntry(i); if (je.getName().equalsIgnoreCase(name)) { retval[count]=je; count++; } } return retval; } public JobHopMeta[] getAllJobHopsUsing(String name) { List hops = new ArrayList(); for (int i=0;i<nrJobHops();i++) { JobHopMeta hi = getJobHop(i); if (hi.from_entry!=null && hi.to_entry!=null) { if (hi.from_entry.getName().equalsIgnoreCase(name) || hi.to_entry.getName().equalsIgnoreCase(name) ) { hops.add(hi); } } } return (JobHopMeta[]) hops.toArray(new JobHopMeta[hops.size()]); } public NotePadMeta getNote(int x, int y) { int i, s; s = notes.size(); for (i=s-1;i>=0;i--) // Back to front because drawing goes from start to end { NotePadMeta ni = (NotePadMeta )notes.get(i); Point loc = ni.getLocation(); Point p = new Point(loc.x, loc.y); if ( x >= p.x && x <= p.x+ni.width+2*Const.NOTE_MARGIN && y >= p.y && y <= p.y+ni.height+2*Const.NOTE_MARGIN ) { return ni; } } return null; } public void selectAll() { int i; for (i=0;i<nrJobEntries();i++) { JobEntryCopy ce = getJobEntry(i); ce.setSelected(true); } } public void unselectAll() { int i; for (i=0;i<nrJobEntries();i++) { JobEntryCopy ce = getJobEntry(i); ce.setSelected(false); } } public void selectInRect(Rectangle rect) { int i; for (i = 0; i < nrJobEntries(); i++) { JobEntryCopy je = getJobEntry(i); Point p = je.getLocation(); if (((p.x >= rect.x && p.x <= rect.x + rect.width) || (p.x >= rect.x + rect.width && p.x <= rect.x)) && ((p.y >= rect.y && p.y <= rect.y + rect.height) || (p.y >= rect.y + rect.height && p.y <= rect.y)) ) je.setSelected(true); } } public int getMaxUndo() { return max_undo; } public void setMaxUndo(int mu) { max_undo=mu; while (undo.size()>mu && undo.size()>0) undo.remove(0); } public int getUndoSize() { if (undo==null) return 0; return undo.size(); } public void addUndo(Object from[], Object to[], int pos[], Point prev[], Point curr[], int type_of_change) { // First clean up after the current position. // Example: position at 3, size=5 // 012345 // remove 34 // Add 4 // 01234 while (undo.size()>undo_position+1 && undo.size()>0) { int last = undo.size()-1; undo.remove(last); } TransAction ta = new TransAction(); switch(type_of_change) { case TYPE_UNDO_CHANGE : ta.setChanged(from, to, pos); break; case TYPE_UNDO_DELETE : ta.setDelete(from, pos); break; case TYPE_UNDO_NEW : ta.setNew(from, pos); break; case TYPE_UNDO_POSITION : ta.setPosition(from, pos, prev, curr); break; } undo.add(ta); undo_position++; if (undo.size()>max_undo) { undo.remove(0); undo_position } } // get previous undo, change position public TransAction previousUndo() { if (undo.size()==0 || undo_position<0) return null; // No undo left! TransAction retval = (TransAction)undo.get(undo_position); undo_position return retval; } /** * View current undo, don't change undo position * * @return The current undo transaction */ public TransAction viewThisUndo() { if (undo.size()==0 || undo_position<0) return null; // No undo left! TransAction retval = (TransAction)undo.get(undo_position); return retval; } // View previous undo, don't change position public TransAction viewPreviousUndo() { if (undo.size()==0 || undo_position<0) return null; // No undo left! TransAction retval = (TransAction)undo.get(undo_position); return retval; } public TransAction nextUndo() { int size=undo.size(); if (size==0 || undo_position>=size-1) return null; // no redo left... undo_position++; TransAction retval = (TransAction)undo.get(undo_position); return retval; } public TransAction viewNextUndo() { int size=undo.size(); if (size==0 || undo_position>=size-1) return null; // no redo left... TransAction retval = (TransAction)undo.get(undo_position+1); return retval; } public Point getMaximum() { int maxx = 0, maxy = 0; for (int i = 0; i < nrJobEntries(); i++) { JobEntryCopy entry = getJobEntry(i); Point loc = entry.getLocation(); if (loc.x > maxx) maxx = loc.x; if (loc.y > maxy) maxy = loc.y; } for (int i = 0; i < nrNotes(); i++) { NotePadMeta ni = getNote(i); Point loc = ni.getLocation(); if (loc.x + ni.width > maxx) maxx = loc.x + ni.width; if (loc.y + ni.height > maxy) maxy = loc.y + ni.height; } return new Point(maxx + 100, maxy + 100); } public Point[] getSelectedLocations() { int sels = nrSelected(); Point retval[] = new Point[sels]; for (int i=0;i<sels;i++) { JobEntryCopy si = getSelected(i); Point p = si.getLocation(); retval[i] = new Point(p.x, p.y); // explicit copy of location } return retval; } public JobEntryCopy[] getSelectedEntries() { int sels = nrSelected(); if (sels==0) return null; JobEntryCopy retval[] = new JobEntryCopy[sels]; for (int i=0;i<sels;i++) { JobEntryCopy je = getSelected(i); retval[i] = je; } return retval; } public int nrSelected() { int i, count; count = 0; for (i = 0; i < nrJobEntries(); i++) { JobEntryCopy je = getJobEntry(i); if (je.isSelected() && je.isDrawn()) count++; } return count; } public JobEntryCopy getSelected(int nr) { int i, count; count = 0; for (i = 0; i < nrJobEntries(); i++) { JobEntryCopy je = getJobEntry(i); if (je.isSelected()) { if (nr == count) return je; count++; } } return null; } public int[] getEntryIndexes(JobEntryCopy entries[]) { int retval[] = new int[entries.length]; for (int i=0;i<entries.length;i++) retval[i]=indexOfJobEntry(entries[i]); return retval; } public JobEntryCopy findStart() { for (int i=0;i<nrJobEntries();i++) { if (getJobEntry(i).isStart()) return getJobEntry(i); } return null; } public String toString() { if (getName()!=null) return getName(); else return getClass().getName(); } /** * @return Returns the logfieldUsed. */ public boolean isLogfieldUsed() { return logfieldUsed; } /** * @param logfieldUsed The logfieldUsed to set. */ public void setLogfieldUsed(boolean logfieldUsed) { this.logfieldUsed = logfieldUsed; } /** * @return Returns the useBatchId. */ public boolean isBatchIdUsed() { return useBatchId; } /** * @param useBatchId The useBatchId to set. */ public void setUseBatchId(boolean useBatchId) { this.useBatchId = useBatchId; } /** * @return Returns the batchIdPassed. */ public boolean isBatchIdPassed() { return batchIdPassed; } /** * @param batchIdPassed The batchIdPassed to set. */ public void setBatchIdPassed(boolean batchIdPassed) { this.batchIdPassed = batchIdPassed; } /** * Builds a list of all the SQL statements that this transformation needs in order to work properly. * * @return An ArrayList of SQLStatement objects. */ public ArrayList getSQLStatements(Repository repository, IProgressMonitor monitor) throws KettleException { if (monitor != null) monitor.beginTask("Getting the SQL needed for this job...", nrJobEntries() + 1); ArrayList stats = new ArrayList(); for (int i = 0; i < nrJobEntries(); i++) { JobEntryCopy copy = getJobEntry(i); if (monitor != null) monitor.subTask("Getting SQL statements for job entry copy [" + copy + "]"); ArrayList list = copy.getEntry().getSQLStatements(repository); stats.addAll(list); if (monitor != null) monitor.worked(1); } // Also check the sql for the logtable... if (monitor != null) monitor.subTask("Getting SQL statements for the job (logtable, etc.)"); if (logconnection != null && logTable != null && logTable.length() > 0) { Database db = new Database(logconnection); try { db.connect(); Row fields = Database.getJobLogrecordFields(useBatchId, logfieldUsed); String sql = db.getDDL(logTable, fields); if (sql != null && sql.length() > 0) { SQLStatement stat = new SQLStatement("<this job>", logconnection, sql); stats.add(stat); } } catch (KettleDatabaseException dbe) { SQLStatement stat = new SQLStatement("<this job>", logconnection, null); stat.setError("Error obtaining job log table info: " + dbe.getMessage()); stats.add(stat); } finally { db.disconnect(); } } if (monitor != null) monitor.worked(1); if (monitor != null) monitor.done(); return stats; } /** * @return Returns the logTable. */ public String getLogTable() { return logTable; } /** * @param logTable The logTable to set. */ public void setLogTable(String logTable) { this.logTable = logTable; } /** * @return Returns the arguments. */ public String[] getArguments() { return arguments; } /** * @param arguments The arguments to set. */ public void setArguments(String[] arguments) { this.arguments = arguments; } /** * Get a list of all the strings used in this job. * * @return A list of StringSearchResult with strings used in the job */ public List getStringList(boolean searchSteps, boolean searchDatabases, boolean searchNotes) { ArrayList stringList = new ArrayList(); if (searchSteps) { // Loop over all steps in the transformation and see what the used vars are... for (int i=0;i<nrJobEntries();i++) { JobEntryCopy entryMeta = getJobEntry(i); stringList.add(new StringSearchResult(entryMeta.getName(), entryMeta, "Job entry name")); if (entryMeta.getDescription()!=null) stringList.add(new StringSearchResult(entryMeta.getDescription(), entryMeta, "Job entry description")); JobEntryInterface metaInterface = entryMeta.getEntry(); StringSearcher.findMetaData(metaInterface, 1, stringList, entryMeta); } } // Loop over all steps in the transformation and see what the used vars are... if (searchDatabases) { for (int i=0;i<nrDatabases();i++) { DatabaseMeta meta = getDatabase(i); stringList.add(new StringSearchResult(meta.getName(), meta, "Database connection name")); if (meta.getDatabaseName()!=null) stringList.add(new StringSearchResult(meta.getDatabaseName(), meta, "Database name")); if (meta.getUsername()!=null) stringList.add(new StringSearchResult(meta.getUsername(), meta, "Database Username")); if (meta.getDatabaseTypeDesc()!=null) stringList.add(new StringSearchResult(meta.getDatabaseTypeDesc(), meta, "Database type description")); if (meta.getDatabasePortNumberString()!=null) stringList.add(new StringSearchResult(meta.getDatabasePortNumberString(), meta, "Database port")); } } // Loop over all steps in the transformation and see what the used vars are... if (searchNotes) { for (int i=0;i<nrNotes();i++) { NotePadMeta meta = getNote(i); if (meta.getNote()!=null) stringList.add(new StringSearchResult(meta.getNote(), meta, "Notepad text")); } } return stringList; } public List getUsedVariables() { // Get the list of Strings. List stringList = getStringList(true, true, false); List varList = new ArrayList(); // Look around in the strings, see what we find... for (int i=0;i<stringList.size();i++) { StringSearchResult result = (StringSearchResult) stringList.get(i); StringUtil.getUsedVariables(result.getString(), varList, false); } return varList; } /** * Get an array of all the selected job entries * * @return A list containing all the selected & drawn job entries. */ public List getSelectedDrawnJobEntryList() { List list = new ArrayList(); for (int i = 0; i < nrJobEntries(); i++) { JobEntryCopy jobEntryCopy = getJobEntry(i); if (jobEntryCopy.isDrawn() && jobEntryCopy.isSelected()) { list.add(jobEntryCopy); } } return list; } /** * This method sets various internal kettle variables that can be used by the transformation. */ public void setInternalKettleVariables() { KettleVariables variables = KettleVariables.getInstance(); String prefix = Const.INTERNAL_VARIABLE_PREFIX+"."+"Job."; if (filename!=null) // we have a finename that's defined. { File file = new File(filename); try { file = file.getCanonicalFile(); } catch(IOException e) { file = file.getAbsoluteFile(); } // The directory of the transformation variables.setVariable(prefix+"Filename.Directory", file.getParent()); // The filename of the transformation variables.setVariable(prefix+"Filename.Name", file.getName()); } else { variables.setVariable(prefix+"Filename.Directory", ""); variables.setVariable(prefix+"Filename.Name", ""); } // The name of the job variables.setVariable(prefix+"Name", Const.NVL(name, "")); // The name of the directory in the repository variables.setVariable(prefix+"Repository.Directory", directory!=null?directory.getPath():""); } }
package org.slf4j; import static org.slf4j.event.Level.DEBUG; import static org.slf4j.event.Level.ERROR; import static org.slf4j.event.Level.INFO; import static org.slf4j.event.Level.TRACE; import static org.slf4j.event.Level.WARN; import org.slf4j.event.Level; import org.slf4j.spi.DefaultLoggingEventBuilder; import org.slf4j.spi.LoggingEventBuilder; import org.slf4j.spi.NOPLoggingEventBuilder; /** * The org.slf4j.Logger interface is the main user entry point of SLF4J API. * It is expected that logging takes place through concrete implementations * of this interface. * * <h3>Typical usage pattern:</h3> * <pre> * import org.slf4j.Logger; * import org.slf4j.LoggerFactory; * * public class Wombat { * * <span style="color:green">final static Logger logger = LoggerFactory.getLogger(Wombat.class);</span> * Integer t; * Integer oldT; * * public void setTemperature(Integer temperature) { * oldT = t; * t = temperature; * <span style="color:green">logger.debug("Temperature set to {}. Old temperature was {}.", t, oldT);</span> * if(temperature.intValue() &gt; 50) { * <span style="color:green">logger.info("Temperature has risen above 50 degrees.");</span> * } * } * } * </pre> * * <p>Note that version 2.0 of the SLF4J API introduces a <a href="../../../manual.html#fluent">fluent api</a>, * the most significant API change to occur in the last 20 years. * * <p>Be sure to read the FAQ entry relating to <a href="../../../faq.html#logging_performance">parameterized * logging</a>. Note that logging statements can be parameterized in * <a href="../../../faq.html#paramException">presence of an exception/throwable</a>. * * <p>Once you are comfortable using loggers, i.e. instances of this interface, consider using * <a href="MDC.html">MDC</a> as well as <a href="Marker.html">Markers</a>. * * @author Ceki G&uuml;lc&uuml; */ public interface Logger { /** * Case insensitive String constant used to retrieve the name of the root logger. * * @since 1.3 */ final public String ROOT_LOGGER_NAME = "ROOT"; /** * Return the name of this <code>Logger</code> instance. * @return name of this logger instance */ public String getName(); /** * Make a new {@link LoggingEventBuilder} instance as appropriate for this logger and the * desired {@link Level} passed as parameter. * * @param level desired level for the event builder * @return a new {@link LoggingEventBuilder} instance as appropriate for this logger * @since 2.0 */ default public LoggingEventBuilder makeLoggingEventBuilder(Level level) { return new DefaultLoggingEventBuilder(this, level); } /** * Is the logger instance enabled for the TRACE level? * * @return True if this Logger is enabled for the TRACE level, * false otherwise. * @since 1.4 */ public boolean isTraceEnabled(); /** * Log a message at the TRACE level. * * @param msg the message string to be logged * @since 1.4 */ public void trace(String msg); /** * Log a message at the TRACE level according to the specified format * and argument. * * <p>This form avoids superfluous object creation when the logger * is disabled for the TRACE level. * * @param format the format string * @param arg the argument * @since 1.4 */ public void trace(String format, Object arg); /** * Log a message at the TRACE level according to the specified format * and arguments. * * <p>This form avoids superfluous object creation when the logger * is disabled for the TRACE level. * * @param format the format string * @param arg1 the first argument * @param arg2 the second argument * @since 1.4 */ public void trace(String format, Object arg1, Object arg2); /** * Log a message at the TRACE level according to the specified format * and arguments. * * <p>This form avoids superfluous string concatenation when the logger * is disabled for the TRACE level. However, this variant incurs the hidden * (and relatively small) cost of creating an <code>Object[]</code> before invoking the method, * even if this logger is disabled for TRACE. The variants taking {@link #trace(String, Object) one} and * {@link #trace(String, Object, Object) two} arguments exist solely in order to avoid this hidden cost. * * @param format the format string * @param arguments a list of 3 or more arguments * @since 1.4 */ public void trace(String format, Object... arguments); /** * Log an exception (throwable) at the TRACE level with an * accompanying message. * * @param msg the message accompanying the exception * @param t the exception (throwable) to log * @since 1.4 */ public void trace(String msg, Throwable t); /** * Similar to {@link #isTraceEnabled()} method except that the * marker data is also taken into account. * * @param marker The marker data to take into consideration * @return True if this Logger is enabled for the TRACE level, * false otherwise. * * @since 1.4 */ public boolean isTraceEnabled(Marker marker); /** * Entry point for fluent-logging for {@link org.slf4j.event.Level#TRACE} level. * * @return LoggingEventBuilder instance as appropriate for level TRACE * @since 2.0 */ default public LoggingEventBuilder atTrace() { if(isTraceEnabled()) { return makeLoggingEventBuilder(TRACE); } else { return NOPLoggingEventBuilder.singleton(); } } /** * Log a message with the specific Marker at the TRACE level. * * @param marker the marker data specific to this log statement * @param msg the message string to be logged * @since 1.4 */ public void trace(Marker marker, String msg); /** * This method is similar to {@link #trace(String, Object)} method except that the * marker data is also taken into consideration. * * @param marker the marker data specific to this log statement * @param format the format string * @param arg the argument * @since 1.4 */ public void trace(Marker marker, String format, Object arg); /** * This method is similar to {@link #trace(String, Object, Object)} * method except that the marker data is also taken into * consideration. * * @param marker the marker data specific to this log statement * @param format the format string * @param arg1 the first argument * @param arg2 the second argument * @since 1.4 */ public void trace(Marker marker, String format, Object arg1, Object arg2); /** * This method is similar to {@link #trace(String, Object...)} * method except that the marker data is also taken into * consideration. * * @param marker the marker data specific to this log statement * @param format the format string * @param argArray an array of arguments * @since 1.4 */ public void trace(Marker marker, String format, Object... argArray); /** * This method is similar to {@link #trace(String, Throwable)} method except that the * marker data is also taken into consideration. * * @param marker the marker data specific to this log statement * @param msg the message accompanying the exception * @param t the exception (throwable) to log * @since 1.4 */ public void trace(Marker marker, String msg, Throwable t); /** * Is the logger instance enabled for the DEBUG level? * * @return True if this Logger is enabled for the DEBUG level, * false otherwise. */ public boolean isDebugEnabled(); /** * Log a message at the DEBUG level. * * @param msg the message string to be logged */ public void debug(String msg); /** * Log a message at the DEBUG level according to the specified format * and argument. * * <p>This form avoids superfluous object creation when the logger * is disabled for the DEBUG level. * * @param format the format string * @param arg the argument */ public void debug(String format, Object arg); /** * Log a message at the DEBUG level according to the specified format * and arguments. * * <p>This form avoids superfluous object creation when the logger * is disabled for the DEBUG level. * * @param format the format string * @param arg1 the first argument * @param arg2 the second argument */ public void debug(String format, Object arg1, Object arg2); /** * Log a message at the DEBUG level according to the specified format * and arguments. * * <p>This form avoids superfluous string concatenation when the logger * is disabled for the DEBUG level. However, this variant incurs the hidden * (and relatively small) cost of creating an <code>Object[]</code> before invoking the method, * even if this logger is disabled for DEBUG. The variants taking * {@link #debug(String, Object) one} and {@link #debug(String, Object, Object) two} * arguments exist solely in order to avoid this hidden cost. * * @param format the format string * @param arguments a list of 3 or more arguments */ public void debug(String format, Object... arguments); /** * Log an exception (throwable) at the DEBUG level with an * accompanying message. * * @param msg the message accompanying the exception * @param t the exception (throwable) to log */ public void debug(String msg, Throwable t); /** * Similar to {@link #isDebugEnabled()} method except that the * marker data is also taken into account. * * @param marker The marker data to take into consideration * @return True if this Logger is enabled for the DEBUG level, * false otherwise. */ public boolean isDebugEnabled(Marker marker); /** * Log a message with the specific Marker at the DEBUG level. * * @param marker the marker data specific to this log statement * @param msg the message string to be logged */ public void debug(Marker marker, String msg); /** * This method is similar to {@link #debug(String, Object)} method except that the * marker data is also taken into consideration. * * @param marker the marker data specific to this log statement * @param format the format string * @param arg the argument */ public void debug(Marker marker, String format, Object arg); /** * This method is similar to {@link #debug(String, Object, Object)} * method except that the marker data is also taken into * consideration. * * @param marker the marker data specific to this log statement * @param format the format string * @param arg1 the first argument * @param arg2 the second argument */ public void debug(Marker marker, String format, Object arg1, Object arg2); /** * This method is similar to {@link #debug(String, Object...)} * method except that the marker data is also taken into * consideration. * * @param marker the marker data specific to this log statement * @param format the format string * @param arguments a list of 3 or more arguments */ public void debug(Marker marker, String format, Object... arguments); /** * This method is similar to {@link #debug(String, Throwable)} method except that the * marker data is also taken into consideration. * * @param marker the marker data specific to this log statement * @param msg the message accompanying the exception * @param t the exception (throwable) to log */ public void debug(Marker marker, String msg, Throwable t); /** * Entry point for fluent-logging for {@link org.slf4j.event.Level#DEBUG} level. * * @return LoggingEventBuilder instance as appropriate for level DEBUG * @since 2.0 */ default public LoggingEventBuilder atDebug() { if(isDebugEnabled()) { return makeLoggingEventBuilder(DEBUG); } else { return NOPLoggingEventBuilder.singleton(); } } /** * Is the logger instance enabled for the INFO level? * * @return True if this Logger is enabled for the INFO level, * false otherwise. */ public boolean isInfoEnabled(); /** * Log a message at the INFO level. * * @param msg the message string to be logged */ public void info(String msg); /** * Log a message at the INFO level according to the specified format * and argument. * * <p>This form avoids superfluous object creation when the logger * is disabled for the INFO level. * * @param format the format string * @param arg the argument */ public void info(String format, Object arg); /** * Log a message at the INFO level according to the specified format * and arguments. * * <p>This form avoids superfluous object creation when the logger * is disabled for the INFO level. * * @param format the format string * @param arg1 the first argument * @param arg2 the second argument */ public void info(String format, Object arg1, Object arg2); /** * Log a message at the INFO level according to the specified format * and arguments. * * <p>This form avoids superfluous string concatenation when the logger * is disabled for the INFO level. However, this variant incurs the hidden * (and relatively small) cost of creating an <code>Object[]</code> before invoking the method, * even if this logger is disabled for INFO. The variants taking * {@link #info(String, Object) one} and {@link #info(String, Object, Object) two} * arguments exist solely in order to avoid this hidden cost. * * @param format the format string * @param arguments a list of 3 or more arguments */ public void info(String format, Object... arguments); /** * Log an exception (throwable) at the INFO level with an * accompanying message. * * @param msg the message accompanying the exception * @param t the exception (throwable) to log */ public void info(String msg, Throwable t); /** * Similar to {@link #isInfoEnabled()} method except that the marker * data is also taken into consideration. * * @param marker The marker data to take into consideration * @return true if this logger is warn enabled, false otherwise */ public boolean isInfoEnabled(Marker marker); /** * Log a message with the specific Marker at the INFO level. * * @param marker The marker specific to this log statement * @param msg the message string to be logged */ public void info(Marker marker, String msg); /** * This method is similar to {@link #info(String, Object)} method except that the * marker data is also taken into consideration. * * @param marker the marker data specific to this log statement * @param format the format string * @param arg the argument */ public void info(Marker marker, String format, Object arg); /** * This method is similar to {@link #info(String, Object, Object)} * method except that the marker data is also taken into * consideration. * * @param marker the marker data specific to this log statement * @param format the format string * @param arg1 the first argument * @param arg2 the second argument */ public void info(Marker marker, String format, Object arg1, Object arg2); /** * This method is similar to {@link #info(String, Object...)} * method except that the marker data is also taken into * consideration. * * @param marker the marker data specific to this log statement * @param format the format string * @param arguments a list of 3 or more arguments */ public void info(Marker marker, String format, Object... arguments); /** * This method is similar to {@link #info(String, Throwable)} method * except that the marker data is also taken into consideration. * * @param marker the marker data for this log statement * @param msg the message accompanying the exception * @param t the exception (throwable) to log */ public void info(Marker marker, String msg, Throwable t); /** * Entry point for fluent-logging for {@link org.slf4j.event.Level#INFO} level. * * @return LoggingEventBuilder instance as appropriate for level INFO * @since 2.0 */ default public LoggingEventBuilder atInfo() { if(isInfoEnabled()) { return makeLoggingEventBuilder(INFO); } else { return NOPLoggingEventBuilder.singleton(); } } /** * Is the logger instance enabled for the WARN level? * * @return True if this Logger is enabled for the WARN level, * false otherwise. */ public boolean isWarnEnabled(); /** * Log a message at the WARN level. * * @param msg the message string to be logged */ public void warn(String msg); /** * Log a message at the WARN level according to the specified format * and argument. * * <p>This form avoids superfluous object creation when the logger * is disabled for the WARN level. * * @param format the format string * @param arg the argument */ public void warn(String format, Object arg); /** * Log a message at the WARN level according to the specified format * and arguments. * * <p>This form avoids superfluous string concatenation when the logger * is disabled for the WARN level. However, this variant incurs the hidden * (and relatively small) cost of creating an <code>Object[]</code> before invoking the method, * even if this logger is disabled for WARN. The variants taking * {@link #warn(String, Object) one} and {@link #warn(String, Object, Object) two} * arguments exist solely in order to avoid this hidden cost. * * @param format the format string * @param arguments a list of 3 or more arguments */ public void warn(String format, Object... arguments); /** * Log a message at the WARN level according to the specified format * and arguments. * * <p>This form avoids superfluous object creation when the logger * is disabled for the WARN level. * * @param format the format string * @param arg1 the first argument * @param arg2 the second argument */ public void warn(String format, Object arg1, Object arg2); /** * Log an exception (throwable) at the WARN level with an * accompanying message. * * @param msg the message accompanying the exception * @param t the exception (throwable) to log */ public void warn(String msg, Throwable t); /** * Similar to {@link #isWarnEnabled()} method except that the marker * data is also taken into consideration. * * @param marker The marker data to take into consideration * @return True if this Logger is enabled for the WARN level, * false otherwise. */ public boolean isWarnEnabled(Marker marker); /** * Log a message with the specific Marker at the WARN level. * * @param marker The marker specific to this log statement * @param msg the message string to be logged */ public void warn(Marker marker, String msg); /** * This method is similar to {@link #warn(String, Object)} method except that the * marker data is also taken into consideration. * * @param marker the marker data specific to this log statement * @param format the format string * @param arg the argument */ public void warn(Marker marker, String format, Object arg); /** * This method is similar to {@link #warn(String, Object, Object)} * method except that the marker data is also taken into * consideration. * * @param marker the marker data specific to this log statement * @param format the format string * @param arg1 the first argument * @param arg2 the second argument */ public void warn(Marker marker, String format, Object arg1, Object arg2); /** * This method is similar to {@link #warn(String, Object...)} * method except that the marker data is also taken into * consideration. * * @param marker the marker data specific to this log statement * @param format the format string * @param arguments a list of 3 or more arguments */ public void warn(Marker marker, String format, Object... arguments); /** * This method is similar to {@link #warn(String, Throwable)} method * except that the marker data is also taken into consideration. * * @param marker the marker data for this log statement * @param msg the message accompanying the exception * @param t the exception (throwable) to log */ public void warn(Marker marker, String msg, Throwable t); /** * Entry point for fluent-logging for {@link org.slf4j.event.Level#WARN} level. * * @return LoggingEventBuilder instance as appropriate for level WARN * @since 2.0 */ default public LoggingEventBuilder atWarn() { if(isWarnEnabled()) { return makeLoggingEventBuilder(WARN); } else { return NOPLoggingEventBuilder.singleton(); } } /** * Is the logger instance enabled for the ERROR level? * * @return True if this Logger is enabled for the ERROR level, * false otherwise. */ public boolean isErrorEnabled(); /** * Log a message at the ERROR level. * * @param msg the message string to be logged */ public void error(String msg); /** * Log a message at the ERROR level according to the specified format * and argument. * * <p>This form avoids superfluous object creation when the logger * is disabled for the ERROR level. * * @param format the format string * @param arg the argument */ public void error(String format, Object arg); /** * Log a message at the ERROR level according to the specified format * and arguments. * * <p>This form avoids superfluous object creation when the logger * is disabled for the ERROR level. * * @param format the format string * @param arg1 the first argument * @param arg2 the second argument */ public void error(String format, Object arg1, Object arg2); /** * Log a message at the ERROR level according to the specified format * and arguments. * * <p>This form avoids superfluous string concatenation when the logger * is disabled for the ERROR level. However, this variant incurs the hidden * (and relatively small) cost of creating an <code>Object[]</code> before invoking the method, * even if this logger is disabled for ERROR. The variants taking * {@link #error(String, Object) one} and {@link #error(String, Object, Object) two} * arguments exist solely in order to avoid this hidden cost. * * @param format the format string * @param arguments a list of 3 or more arguments */ public void error(String format, Object... arguments); /** * Log an exception (throwable) at the ERROR level with an * accompanying message. * * @param msg the message accompanying the exception * @param t the exception (throwable) to log */ public void error(String msg, Throwable t); /** * Similar to {@link #isErrorEnabled()} method except that the * marker data is also taken into consideration. * * @param marker The marker data to take into consideration * @return True if this Logger is enabled for the ERROR level, * false otherwise. */ public boolean isErrorEnabled(Marker marker); /** * Log a message with the specific Marker at the ERROR level. * * @param marker The marker specific to this log statement * @param msg the message string to be logged */ public void error(Marker marker, String msg); /** * This method is similar to {@link #error(String, Object)} method except that the * marker data is also taken into consideration. * * @param marker the marker data specific to this log statement * @param format the format string * @param arg the argument */ public void error(Marker marker, String format, Object arg); /** * This method is similar to {@link #error(String, Object, Object)} * method except that the marker data is also taken into * consideration. * * @param marker the marker data specific to this log statement * @param format the format string * @param arg1 the first argument * @param arg2 the second argument */ public void error(Marker marker, String format, Object arg1, Object arg2); /** * This method is similar to {@link #error(String, Object...)} * method except that the marker data is also taken into * consideration. * * @param marker the marker data specific to this log statement * @param format the format string * @param arguments a list of 3 or more arguments */ public void error(Marker marker, String format, Object... arguments); /** * This method is similar to {@link #error(String, Throwable)} * method except that the marker data is also taken into * consideration. * * @param marker the marker data specific to this log statement * @param msg the message accompanying the exception * @param t the exception (throwable) to log */ public void error(Marker marker, String msg, Throwable t); /** * Entry point for fluent-logging for {@link org.slf4j.event.Level#ERROR} level. * * @return LoggingEventBuilder instance as appropriate for level ERROR * @since 2.0 */ default public LoggingEventBuilder atError() { if(isErrorEnabled()) { return makeLoggingEventBuilder(ERROR); } else { return NOPLoggingEventBuilder.singleton(); } } }
package com.sometrik.framework; import android.graphics.Bitmap.Config; import android.graphics.Color; import android.graphics.Typeface; import android.graphics.drawable.GradientDrawable; import android.text.TextUtils.TruncateAt; import android.view.Gravity; import android.view.View; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.TextView; public class FWTextView extends TextView implements NativeCommandHandler { private FrameWork frame; public FWTextView(FrameWork frame) { super(frame); this.frame = frame; // Color color = new Color(); this.setBackground(null); this.setBackgroundColor(Color.rgb(255, 255, 255)); } @Override public void addChild(View view) { System.out.println("FWTextView couldn't handle command"); } @Override public void addOption(int optionId, String text) { System.out.println("FWTextView couldn't handle command"); } @Override public void setValue(String v) { setText(v); } @Override public void setValue(int v) { System.out.println("FWTextView couldn't handle command"); } @Override public void setViewEnabled(Boolean enabled) { setEnabled(enabled); } @Override public void setStyle(String key, String value) { if (key.equals("font-size")) { if (value.equals("small")) { this.setTextSize(9); } else if (value.equals("medium")) { this.setTextSize(12); } else if (value.equals("large")) { this.setTextSize(15); } else { setTextSize(Integer.parseInt(value)); } } else if (key.equals("padding-top")) { setPadding(getPaddingLeft(), Integer.parseInt(value), getPaddingRight(), getPaddingBottom()); } else if (key.equals("padding-bottom")) { setPadding(getPaddingLeft(), getPaddingTop(), getPaddingRight(), Integer.parseInt(value)); } else if (key.equals("padding-left")) { setPadding(Integer.parseInt(value), getPaddingTop(), getPaddingRight(), getPaddingBottom()); } else if (key.equals("padding-right")) { setPadding(getPaddingLeft(), getPaddingTop(), Integer.parseInt(value), getPaddingBottom()); } else if (key.equals("width")) { LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams(); if (value.equals("wrap-content")) { params.width = LinearLayout.LayoutParams.WRAP_CONTENT; } else if (value.equals("match-parent")) { params.width = LinearLayout.LayoutParams.MATCH_PARENT; } else { final float scale = getContext().getResources().getDisplayMetrics().density; int pixels = (int) (Integer.parseInt(value) * scale + 0.5f); params.width = pixels; } setLayoutParams(params); } else if (key.equals("height")) { LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams(); if (value.equals("wrap-content")) { params.height = LinearLayout.LayoutParams.WRAP_CONTENT; } else if (value.equals("match-parent")) { params.height = LinearLayout.LayoutParams.MATCH_PARENT; } else { final float scale = getContext().getResources().getDisplayMetrics().density; int pixels = (int) (Integer.parseInt(value) * scale + 0.5f); params.height = pixels; } setLayoutParams(params); } else if (key.equals("text-overflow")) { if (value.equals("ellipsis")) { setEllipsize(TruncateAt.END); } } else if (key.equals("font-weight")) { if (value.equals("bold")) { setTypeface(null, Typeface.BOLD); } else if (value.equals("normal")) { setTypeface(null, Typeface.NORMAL); } } else if (key.equals("font-style")) { if (value.equals("italic") || value.equals("oblique")) { setTypeface(null, Typeface.ITALIC); } else if (value.equals("normal")) { setTypeface(null, Typeface.NORMAL); } } else if (key.equals("border")) { if (value.equals("none")) { // TODO: clear border } else { GradientDrawable gd = new GradientDrawable(); gd.setColor(Color.parseColor("#ffffff")); // Changes this drawbale to use a single color instead of a gradient gd.setCornerRadius(5); gd.setStroke(1, Color.parseColor(value)); setBackgroundDrawable(gd); } } else if (key.equals("weight")) { LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams(); params.weight = Integer.parseInt(value); setLayoutParams(params); } else if (key.equals("align-text")) { if (value.equals("left")) { setTextAlignment(TEXT_ALIGNMENT_TEXT_START); } else if (value.equals("center")) { setTextAlignment(TEXT_ALIGNMENT_CENTER); } } else if (key.equals("single-line")) { setSingleLine(); } else if (key.equals("color")) { this.setTextColor(Color.parseColor(value)); } else if (key.equals("gravity")) { LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams(); if (value.equals("bottom")) { setGravity(Gravity.BOTTOM); } else if (value.equals("top")) { setGravity(Gravity.TOP); } else if (value.equals("left")) { setGravity(Gravity.LEFT); } else if (value.equals("right")) { setGravity(Gravity.RIGHT); } else if (value.equals("center")) { setGravity(Gravity.CENTER); } else if (value.equals("center-vertical")) { setGravity(Gravity.CENTER_VERTICAL); } else if (value.equals("center-horizontal")) { setGravity(Gravity.CENTER_HORIZONTAL); } setLayoutParams(params); } else if (key.equals("ellipsis")) { if (value.equals("end")) { setEllipsize(TruncateAt.END); } else if (value.equals("start")) { setEllipsize(TruncateAt.START); } else if (value.equals("middle")) { setEllipsize(TruncateAt.MIDDLE); } else if (value.equals("marquee")) { setEllipsize(TruncateAt.MARQUEE); } } else if (key.equals("max-lines")) { setMaxLines(Integer.parseInt(value)); } } @Override public void setError(boolean hasError, String errorText) { //TODO System.out.println("FWTextView couldn't handle command"); } @Override public int getElementId() { return getId(); } @Override public void onScreenOrientationChange(boolean isLandscape) { // TODO Auto-generated method stub } @Override public void addData(String text, int row, int column, int sheet) { System.out.println("FWTextView couldn't handle command"); } @Override public void setViewVisibility(boolean visibility) { if (visibility){ this.setVisibility(VISIBLE); } else { this.setVisibility(INVISIBLE); } } @Override public void clear() { System.out.println("couldn't handle command"); } @Override public void flush() { // TODO Auto-generated method stub } @Override public void addColumn(String text, int columnType) { // TODO Auto-generated method stub } @Override public void reshape(int value, int size) { // TODO Auto-generated method stub } @Override public void setImage(byte[] bytes, int width, int height, Config config) { // TODO Auto-generated method stub } @Override public void reshape(int size) { // TODO Auto-generated method stub } }
package jmini3d.android; import android.app.ActivityManager; import android.content.Context; import android.graphics.PixelFormat; import android.opengl.GLES10; import android.opengl.GLES11; import android.opengl.GLSurfaceView; import android.os.Build; import android.util.Log; import java.nio.FloatBuffer; import java.nio.ShortBuffer; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLDisplay; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL11; import jmini3d.Blending; import jmini3d.Light; import jmini3d.MatrixUtils; import jmini3d.Object3d; import jmini3d.Scene; import jmini3d.Texture; import jmini3d.android.compat.CompatibilityWrapper5; import jmini3d.android.input.TouchController; import jmini3d.input.TouchListener; public class Renderer implements GLSurfaceView.Renderer { public static final String TAG = "Renderer"; public static boolean needsRedraw = true; private GL10 gl; // stats-related public static final int FRAMERATE_SAMPLEINTERVAL_MS = 10000; private boolean logFps = false; private long frameCount = 0; private float fps = 0; private long timeLastSample; Scene scene; private ResourceLoader resourceLoader; private GpuUploader gpuUploader; private TouchController touchController; public float[] ortho = new float[16]; int width; int height; public GLSurfaceView glSurfaceView; private ActivityManager activityManager; private ActivityManager.MemoryInfo memoryInfo; Blending blending; float openGlVersion = 1.0f; public Renderer(Context context, Scene scene, ResourceLoader resourceLoader, boolean traslucent) { this.scene = scene; this.resourceLoader = resourceLoader; activityManager = (ActivityManager) resourceLoader.getContext().getSystemService(Context.ACTIVITY_SERVICE); memoryInfo = new ActivityManager.MemoryInfo(); MatrixUtils.ortho(ortho, 0, 1, 0, 1, -5, 1); gpuUploader = new GpuUploader(resourceLoader); glSurfaceView = new GLSurfaceView(context); if (traslucent) { if (Build.VERSION.SDK_INT >= 5) { CompatibilityWrapper5.setZOrderOnTop(glSurfaceView); } glSurfaceView.setEGLConfigChooser(8, 8, 8, 8, 16, 0); glSurfaceView.getHolder().setFormat(PixelFormat.TRANSLUCENT); } else { // glSurfaceView.setEGLConfigChooser(8, 8, 8, 8, 16, 0); // FAILS with EGL_BAD_MATCH in some devices (Galaxy Mini, Xperia X) glSurfaceView.setEGLConfigChooser(new GLSurfaceView.EGLConfigChooser() { public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display) { int[] attributes = new int[]{EGL10.EGL_DEPTH_SIZE, 16, EGL10.EGL_NONE}; EGLConfig[] configs = new EGLConfig[1]; int[] result = new int[1]; egl.eglChooseConfig(display, attributes, configs, 1, result); return configs[0]; } }); } glSurfaceView.setRenderer(this); glSurfaceView.setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY); } public void onSurfaceCreated(GL10 gl, EGLConfig eglConfig) { Log.i(TAG, "onSurfaceCreated()"); gpuUploader.setGl(gl); setGl(gl); width = -1; height = -1; } public void onSurfaceChanged(GL10 unused, int w, int h) { Log.i(TAG, "onSurfaceChanged() w=" + w + " h= " + h); if (w != width || h != height) { setSize(w, h); width = w; height = h; } } public void onPause() { glSurfaceView.onPause(); } public void onResume() { glSurfaceView.onResume(); } public void setSize(int width, int height) { scene.camera.setWidth(width); scene.camera.setHeight(height); GLES10.glViewport(0, 0, scene.camera.getWidth(), scene.camera.getHeight()); // Scene reload on size changed, needed to keep aspect ratios reset(); gpuUploader.reset(); scene.reset(); scene.sceneController.initScene(); } private void reset() { GLES10.glMatrixMode(GLES10.GL_PROJECTION); GLES10.glLoadIdentity(); GLES10.glEnable(GLES10.GL_DEPTH_TEST); GLES10.glClearDepthf(1f); GLES10.glDepthFunc(GLES10.GL_LEQUAL); GLES10.glDepthRangef(0, 1f); GLES10.glDepthMask(true); GLES10.glDisable(GLES10.GL_DITHER); // For performance // Without this looks horrible in the emulator GLES10.glHint(GLES10.GL_PERSPECTIVE_CORRECTION_HINT, GLES10.GL_NICEST); // For transparency GLES10.glDisable(GLES10.GL_BLEND); blending = Blending.NoBlending; // CCW frontfaces only, by default GLES10.glFrontFace(GLES10.GL_CCW); GLES10.glCullFace(GLES10.GL_BACK); GLES10.glEnable(GLES10.GL_CULL_FACE); GLES10.glEnableClientState(GLES10.GL_VERTEX_ARRAY); GLES10.glDisableClientState(GLES10.GL_COLOR_ARRAY); // Optimizations GLES10.glDisable(GLES10.GL_LIGHTING); GLES10.glDisable(GLES10.GL_COLOR_MATERIAL); // Disable lights by default for (int i = GLES10.GL_LIGHT0; i <= GLES10.GL_LIGHT7; i++) { GLES10.glDisable(i); } } public void onDrawFrame(GL10 gl) { boolean sceneUpdated = scene.sceneController.updateScene(); boolean cameraChanged = scene.getCamera().updateMatrices(); if (!needsRedraw && !sceneUpdated && !cameraChanged) { return; } for (Object o : scene.unload) { gpuUploader.unload(o); } scene.unload.clear(); GLES10.glMatrixMode(GLES10.GL_PROJECTION); GLES10.glLoadIdentity(); GLES10.glMultMatrixf(scene.camera.perspectiveMatrix, 0); // Camera GLES10.glMatrixMode(GLES10.GL_MODELVIEW); GLES10.glLoadIdentity(); GLES10.glMultMatrixf(scene.camera.modelViewMatrix, 0); drawSetupLights(); // Background color GLES10.glClearColor(scene.getBackgroundColor().r, scene.getBackgroundColor().g, scene.getBackgroundColor().b, scene.getBackgroundColor().a); GLES10.glClear(GLES10.GL_COLOR_BUFFER_BIT | GLES10.GL_DEPTH_BUFFER_BIT); for (Object3d o3d : scene.children) { if (o3d.visible) { o3d.updateMatrices(MatrixUtils.IDENTITY4, false); GLES10.glPushMatrix(); GLES10.glMultMatrixf(o3d.modelViewMatrix, 0); drawObject(o3d, cameraChanged); GLES10.glPopMatrix(); if (o3d.clearDepthAfterDraw) { GLES10.glClear(GLES10.GL_DEPTH_BUFFER_BIT); } } } GLES10.glMatrixMode(GLES10.GL_PROJECTION); GLES10.glLoadIdentity(); GLES10.glMultMatrixf(ortho, 0); GLES10.glMatrixMode(GLES10.GL_MODELVIEW); GLES10.glLoadIdentity(); GLES10.glDisable(GLES10.GL_LIGHTING); GLES10.glClear(GLES10.GL_DEPTH_BUFFER_BIT); for (Object3d o3d : scene.hud) { if (o3d.visible) { o3d.updateMatrices(MatrixUtils.IDENTITY4, false); GLES10.glPushMatrix(); GLES10.glMultMatrixf(o3d.modelViewMatrix, 0); drawObject(o3d, false); GLES10.glPopMatrix(); } } if (logFps) { doFps(); } } protected void drawSetupLights() { boolean hasLights = false; int lightIndex = GLES10.GL_LIGHT0; for (Light light : scene.lights) { hasLights = true; GLES10.glEnable(GLES10.GL_LIGHTING); GLES10.glEnable(lightIndex); GLES10.glLightfv(lightIndex, GLES10.GL_POSITION, light.position, 0); GLES10.glLightfv(lightIndex, GLES10.GL_AMBIENT, light.ambient, 0); GLES10.glLightfv(lightIndex, GLES10.GL_DIFFUSE, light.diffuse, 0); GLES10.glLightfv(lightIndex, GLES10.GL_SPECULAR, light.specular, 0); GLES10.glLightfv(lightIndex, GLES10.GL_EMISSION, light.emission, 0); GLES10.glLightfv(lightIndex, GLES10.GL_SPOT_DIRECTION, light.direction, 0); GLES10.glLightf(lightIndex, GLES10.GL_SPOT_CUTOFF, light.spotCutoffAngle); GLES10.glLightf(lightIndex, GLES10.GL_SPOT_EXPONENT, light.spotExponent); GLES10.glLightf(lightIndex, GLES10.GL_CONSTANT_ATTENUATION, light.attenuation[0]); GLES10.glLightf(lightIndex, GLES10.GL_LINEAR_ATTENUATION, light.attenuation[1]); GLES10.glLightf(lightIndex, GLES10.GL_QUADRATIC_ATTENUATION, light.attenuation[2]); lightIndex++; } if (hasLights) { GLES10.glShadeModel(GLES10.GL_SMOOTH); } } protected void drawObject(Object3d o3d, boolean cameraChanged) { GeometryBuffers geometryBuffers = gpuUploader.upload(o3d.geometry3d); if (blending != o3d.material.blending) { setBlending(o3d.material.blending); } Texture texture = o3d.material.texture; if (texture != null) { gpuUploader.upload(texture); } // if (o3d.material.envMapTexture != null) { // gpuUploader.upload(o3d.material.envMapTexture); // Normals if (openGlVersion >= 1.1) { GLES11.glBindBuffer(GLES11.GL_ARRAY_BUFFER, geometryBuffers.normalsBufferId); GLES11.glNormalPointer(GLES10.GL_FLOAT, 0, 0); } else { geometryBuffers.normalsBuffer.position(0); GLES10.glNormalPointer(GLES10.GL_FLOAT, 0, geometryBuffers.normalsBuffer); } GLES10.glEnableClientState(GLES10.GL_NORMAL_ARRAY); // } else { // GLES10.glDisableClientState(GLES10.GL_NORMAL_ARRAY); // boolean useLighting = (scene.getLightingEnabled() && o.hasNormals() // && o.normalsEnabled() && o.lightingEnabled()); // if (useLighting) { // GLES10.glEnable(GLES10.GL_LIGHTING); // } else { // GLES10.glDisable(GLES10.GL_LIGHTING); if (texture != null) { GLES10.glActiveTexture(GLES10.GL_TEXTURE0); GLES10.glClientActiveTexture(GLES10.GL_TEXTURE0); if (openGlVersion >= 1.1) { ((GL11) gl).glBindBuffer(GLES11.GL_ARRAY_BUFFER, geometryBuffers.uvsBufferId); ((GL11) gl).glTexCoordPointer(2, GLES10.GL_FLOAT, 0, 0); ((GL11) gl).glBindBuffer(GLES11.GL_ARRAY_BUFFER, 0); } else { FloatBuffer uvsBuffer = geometryBuffers.uvsBuffer; uvsBuffer.position(0); GLES10.glTexCoordPointer(2, GLES10.GL_FLOAT, 0, uvsBuffer); } int glId = gpuUploader.textures.get(texture); GLES10.glBindTexture(GLES10.GL_TEXTURE_2D, glId); GLES10.glEnable(GLES10.GL_TEXTURE_2D); GLES10.glEnableClientState(GLES10.GL_TEXTURE_COORD_ARRAY); } else { GLES10.glBindTexture(GLES10.GL_TEXTURE_2D, 0); GLES10.glDisable(GLES10.GL_TEXTURE_2D); GLES10.glDisableClientState(GLES10.GL_TEXTURE_COORD_ARRAY); } if (scene.lights.size() > 0) { if (o3d.material.color != null && o3d.material.color.a != 0) { float params[] = {o3d.material.color.r, o3d.material.color.g, o3d.material.color.b, 1}; float materialShininess = 50f; GLES10.glMaterialfv(GLES10.GL_FRONT_AND_BACK, GLES10.GL_AMBIENT_AND_DIFFUSE, params, 0); GLES10.glMaterialfv(GLES10.GL_FRONT_AND_BACK, GLES10.GL_SPECULAR, params, 0); GLES10.glMaterialf(GLES10.GL_FRONT_AND_BACK, GLES10.GL_SHININESS, materialShininess); } else { float materialAmbientAndDiffuse[] = {1f, 1f, 1f, 1f}; float materialSpecular[] = {1f, 1f, 1f, 1f}; float materialShininess = 50f; GLES10.glMaterialfv(GLES10.GL_FRONT_AND_BACK, GLES10.GL_AMBIENT_AND_DIFFUSE, materialAmbientAndDiffuse, 0); GLES10.glMaterialfv(GLES10.GL_FRONT_AND_BACK, GLES10.GL_SPECULAR, materialSpecular, 0); GLES10.glMaterialf(GLES10.GL_FRONT_AND_BACK, GLES10.GL_SHININESS, materialShininess); } } // Draw if (openGlVersion >= 1.1) { ((GL11) gl).glBindBuffer(GLES11.GL_ARRAY_BUFFER, geometryBuffers.vertexBufferId); ((GL11) gl).glVertexPointer(3, GLES10.GL_FLOAT, 0, 0); ((GL11) gl).glBindBuffer(GLES11.GL_ELEMENT_ARRAY_BUFFER, geometryBuffers.facesBufferId); ((GL11) gl).glDrawElements(GLES10.GL_TRIANGLES, o3d.geometry3d.facesLength, GLES10.GL_UNSIGNED_SHORT, 0); ((GL11) gl).glBindBuffer(GLES11.GL_ARRAY_BUFFER, 0); ((GL11) gl).glBindBuffer(GLES11.GL_ELEMENT_ARRAY_BUFFER, 0); } else { FloatBuffer vertexBuffer = geometryBuffers.vertexBuffer; vertexBuffer.position(0); GLES10.glVertexPointer(3, GLES10.GL_FLOAT, 0, vertexBuffer); ShortBuffer facesBuffer = geometryBuffers.facesBuffer; facesBuffer.position(0); GLES10.glDrawElements(GLES10.GL_TRIANGLES, o3d.geometry3d.facesLength, GLES10.GL_UNSIGNED_SHORT, facesBuffer); } } private void setBlending(Blending blending) { this.blending = blending; switch(blending) { case NoBlending: GLES10.glDisable(GLES10.GL_BLEND); break; case NormalBlending: GLES10.glEnable(GLES10.GL_BLEND); GLES10.glBlendFunc(GLES10.GL_SRC_ALPHA, GLES10.GL_ONE_MINUS_SRC_ALPHA); break; case AdditiveBlending: GLES10.glEnable(GLES10.GL_BLEND); GLES10.glBlendFunc(GLES10.GL_SRC_ALPHA, GLES10.GL_ONE); break; case SubtractiveBlending: GLES10.glEnable(GLES10.GL_BLEND); GLES10.glBlendFunc(GLES10.GL_ZERO, GLES10.GL_ONE_MINUS_SRC_COLOR); break; case MultiplyBlending: GLES10.glEnable(GLES10.GL_BLEND); GLES10.glBlendFunc(GLES10.GL_ZERO, GLES10.GL_SRC_COLOR); break; } } private void setGl(GL10 gl) { this.gl = gl; // OpenGL ES version if (gl instanceof GL11) { openGlVersion = 1.1f; } else { openGlVersion = 1.0f; } } public GL10 getGl() { return gl; } public GpuUploader getGpuUploader() { return gpuUploader; } /** * If true, framerate and memory is periodically calculated and Log'ed, and * gettable thru fps() */ public void setLogFps(boolean b) { logFps = b; if (logFps) { // init timeLastSample = System.currentTimeMillis(); frameCount = 0; } } private void doFps() { frameCount++; long now = System.currentTimeMillis(); long delta = now - timeLastSample; if (delta >= FRAMERATE_SAMPLEINTERVAL_MS) { fps = frameCount / (delta / 1000f); activityManager.getMemoryInfo(memoryInfo); Log.v(TAG, "FPS: " + fps + ", availMem: " + Math.round(memoryInfo.availMem / 1048576) + "MB"); timeLastSample = now; frameCount = 0; } } /** * Returns last sampled framerate (logFps must be set to true) */ public float getFps() { return fps; } public ResourceLoader getResourceLoader() { return resourceLoader; } public GLSurfaceView getView() { return glSurfaceView; } public void setTouchListener(TouchListener listener) { if (touchController == null) { touchController = new TouchController(glSurfaceView); } touchController.setListener(listener); } }
package me.vanpan.rctqqsdk; import android.app.Activity; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.text.TextUtils; import android.util.Base64; import android.util.Log; import android.webkit.URLUtil; import com.facebook.react.bridge.ActivityEventListener; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.BaseActivityEventListener; import com.facebook.react.bridge.Promise; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.UiThreadUtil; import com.facebook.react.bridge.WritableMap; import com.facebook.react.views.imagehelper.ResourceDrawableIdHelper; import com.tencent.connect.common.Constants; import com.tencent.connect.share.QQShare; import com.tencent.connect.share.QzonePublish; import com.tencent.connect.share.QzoneShare; import com.tencent.open.GameAppOperation; import com.tencent.tauth.IUiListener; import com.tencent.tauth.Tencent; import com.tencent.tauth.UiError; import org.json.JSONObject; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Map; import javax.annotation.Nullable; import static android.content.ContentValues.TAG; class ShareScene { public static final int QQ = 0; public static final int QQZone = 1; public static final int Favorite = 2; } public class QQSDK extends ReactContextBaseJavaModule { private static Tencent mTencent; private String appId; private String appName; private Promise mPromise; private static final String ACTIVITY_DOES_NOT_EXIST = "activity not found"; private static final String QQ_Client_NOT_INSYALLED_ERROR = "QQ client is not installed"; private static final String QQ_RESPONSE_ERROR = "QQ response is error"; private static final String QQ_CANCEL_BY_USER = "cancelled by user"; private static final String QZONE_SHARE_CANCEL = "QZone share is cancelled"; private static final String QQFAVORITES_CANCEL = "QQ Favorites is cancelled"; private final ActivityEventListener mActivityEventListener = new BaseActivityEventListener() { @Override public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent intent) { if (resultCode == Constants.ACTIVITY_OK) { if (requestCode == Constants.REQUEST_LOGIN) { Tencent.onActivityResultData(requestCode, resultCode, intent, loginListener); } if (requestCode == Constants.REQUEST_QQ_SHARE) { Tencent.onActivityResultData(requestCode, resultCode, intent, qqShareListener); } if (requestCode == Constants.REQUEST_QQ_FAVORITES) { Tencent.onActivityResultData(requestCode, resultCode, intent, addToQQFavoritesListener); } } } }; public QQSDK(ReactApplicationContext reactContext) { super(reactContext); reactContext.addActivityEventListener(mActivityEventListener); appId = this.getAppID(reactContext); appName = this.getAppName(reactContext); if (null == mTencent) { mTencent = Tencent.createInstance(appId, reactContext); } } @Override public void initialize() { super.initialize(); } @Override public String getName() { return "QQSDK"; } @Override public void onCatalystInstanceDestroy() { super.onCatalystInstanceDestroy(); if (mTencent != null) { mTencent.releaseResource(); mTencent = null; } appId = null; appName = null; mPromise = null; } @ReactMethod public void checkClientInstalled(Promise promise) { Activity currentActivity = getCurrentActivity(); if (null == currentActivity) { promise.reject("405",ACTIVITY_DOES_NOT_EXIST); return; } Boolean installed = mTencent.isSupportSSOLogin(currentActivity); if (installed) { promise.resolve(true); } else { promise.reject("404", QQ_Client_NOT_INSYALLED_ERROR); } } @ReactMethod public void logout(Promise promise) { Activity currentActivity = getCurrentActivity(); if (null == currentActivity) { promise.reject("405",ACTIVITY_DOES_NOT_EXIST); return; } mTencent.logout(currentActivity); promise.resolve(true); } @ReactMethod public void ssoLogin(final Promise promise) { final Activity currentActivity = getCurrentActivity(); if (null == currentActivity) { promise.reject("405",ACTIVITY_DOES_NOT_EXIST); return; } Runnable runnable = new Runnable() { @Override public void run() { mPromise = promise; mTencent.login(currentActivity, "all", loginListener); } }; UiThreadUtil.runOnUiThread(runnable); } @ReactMethod public void shareText(String text,int shareScene, final Promise promise) { final Activity currentActivity = getCurrentActivity(); if (null == currentActivity) { promise.reject("405",ACTIVITY_DOES_NOT_EXIST); return; } mPromise = promise; final Bundle params = new Bundle(); switch (shareScene) { case ShareScene.QQ: promise.reject("500","Android QQ"); break; case ShareScene.Favorite: params.putInt(GameAppOperation.QQFAV_DATALINE_REQTYPE, GameAppOperation.QQFAV_DATALINE_TYPE_TEXT); params.putString(GameAppOperation.QQFAV_DATALINE_TITLE, appName); params.putString(GameAppOperation.QQFAV_DATALINE_DESCRIPTION, text); params.putString(GameAppOperation.QQFAV_DATALINE_APPNAME, appName); Runnable favoritesRunnable = new Runnable() { @Override public void run() { mTencent.addToQQFavorites(currentActivity, params, addToQQFavoritesListener); } }; UiThreadUtil.runOnUiThread(favoritesRunnable); break; case ShareScene.QQZone: params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzonePublish.PUBLISH_TO_QZONE_TYPE_PUBLISHMOOD); params.putString(QzoneShare.SHARE_TO_QQ_TITLE, text); Runnable zoneRunnable = new Runnable() { @Override public void run() { mTencent.publishToQzone(currentActivity,params,qZoneShareListener); } }; UiThreadUtil.runOnUiThread(zoneRunnable); break; default: break; } } @ReactMethod public void shareImage(String image,String title, String description,int shareScene, final Promise promise) { final Activity currentActivity = getCurrentActivity(); Log.d("",image); if (null == currentActivity) { promise.reject("405",ACTIVITY_DOES_NOT_EXIST); return; } image = processImage(image); final Bundle params = new Bundle(); switch (shareScene) { case ShareScene.QQ: params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_IMAGE); params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL,image); params.putString(QQShare.SHARE_TO_QQ_TITLE, title); params.putString(QQShare.SHARE_TO_QQ_SUMMARY, description); Runnable qqRunnable = new Runnable() { @Override public void run() { mTencent.shareToQQ(currentActivity,params,qqShareListener); } }; UiThreadUtil.runOnUiThread(qqRunnable); break; case ShareScene.Favorite: ArrayList<String> imageUrls = new ArrayList<String>(); imageUrls.add(image); params.putInt(GameAppOperation.QQFAV_DATALINE_REQTYPE, GameAppOperation.QQFAV_DATALINE_TYPE_IMAGE_TEXT); params.putString(GameAppOperation.QQFAV_DATALINE_TITLE, title); params.putString(GameAppOperation.QQFAV_DATALINE_DESCRIPTION, description); params.putString(GameAppOperation.QQFAV_DATALINE_IMAGEURL,image); params.putString(GameAppOperation.QQFAV_DATALINE_APPNAME, appName); params.putStringArrayList(GameAppOperation.QQFAV_DATALINE_FILEDATA,imageUrls); Runnable favoritesRunnable = new Runnable() { @Override public void run() { mTencent.addToQQFavorites(currentActivity, params, addToQQFavoritesListener); } }; UiThreadUtil.runOnUiThread(favoritesRunnable); break; case ShareScene.QQZone: params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_IMAGE); params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL,image); params.putString(QQShare.SHARE_TO_QQ_TITLE, title); params.putString(QQShare.SHARE_TO_QQ_SUMMARY, description); params.putInt(QQShare.SHARE_TO_QQ_EXT_INT,QQShare.SHARE_TO_QQ_FLAG_QZONE_AUTO_OPEN); Runnable zoneRunnable = new Runnable() { @Override public void run() { mTencent.shareToQQ(currentActivity,params,qqShareListener); } }; UiThreadUtil.runOnUiThread(zoneRunnable); break; default: break; } } @ReactMethod public void shareNews(String url,String image,String title, String description,int shareScene, final Promise promise) { final Activity currentActivity = getCurrentActivity(); if (null == currentActivity) { promise.reject("405",ACTIVITY_DOES_NOT_EXIST); return; } mPromise = promise; final Bundle params = new Bundle(); switch (shareScene) { case ShareScene.QQ: params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT); if(URLUtil.isNetworkUrl(image)) { params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL,image); } else { params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL,processImage(image)); } params.putString(QQShare.SHARE_TO_QQ_TITLE, title); params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, url); params.putString(QQShare.SHARE_TO_QQ_SUMMARY, description); Runnable qqRunnable = new Runnable() { @Override public void run() { mTencent.shareToQQ(currentActivity,params,qqShareListener); } }; UiThreadUtil.runOnUiThread(qqRunnable); break; case ShareScene.Favorite: image = processImage(image); params.putInt(GameAppOperation.QQFAV_DATALINE_REQTYPE, GameAppOperation.QQFAV_DATALINE_TYPE_DEFAULT); params.putString(GameAppOperation.QQFAV_DATALINE_TITLE, title); params.putString(GameAppOperation.QQFAV_DATALINE_DESCRIPTION,description); params.putString(GameAppOperation.QQFAV_DATALINE_IMAGEURL,image); params.putString(GameAppOperation.QQFAV_DATALINE_URL,url); params.putString(GameAppOperation.QQFAV_DATALINE_APPNAME, appName); Runnable favoritesRunnable = new Runnable() { @Override public void run() { mTencent.addToQQFavorites(currentActivity, params, addToQQFavoritesListener); } }; UiThreadUtil.runOnUiThread(favoritesRunnable); break; case ShareScene.QQZone: image = processImage(image); ArrayList<String> imageUrls = new ArrayList<String>(); imageUrls.add(image); params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT); params.putString(QzoneShare.SHARE_TO_QQ_TITLE, title); params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY,description); params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL,url); params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL,imageUrls); Runnable zoneRunnable = new Runnable() { @Override public void run() { mTencent.shareToQzone(currentActivity,params,qZoneShareListener); } }; UiThreadUtil.runOnUiThread(zoneRunnable); break; default: break; } } @ReactMethod public void shareAudio(String url,String flashUrl,String image,String title, String description,int shareScene, final Promise promise) { final Activity currentActivity = getCurrentActivity(); if (null == currentActivity) { promise.reject("405",ACTIVITY_DOES_NOT_EXIST); return; } mPromise = promise; final Bundle params = new Bundle(); switch (shareScene) { case ShareScene.QQ: params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT); if(URLUtil.isNetworkUrl(image)) { params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL,image); } else { params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL,processImage(image)); } params.putString(QQShare.SHARE_TO_QQ_AUDIO_URL, flashUrl); params.putString(QQShare.SHARE_TO_QQ_TITLE, title); params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, url); params.putString(QQShare.SHARE_TO_QQ_SUMMARY, description); Runnable qqRunnable = new Runnable() { @Override public void run() { mTencent.shareToQQ(currentActivity,params,qqShareListener); } }; UiThreadUtil.runOnUiThread(qqRunnable); break; case ShareScene.Favorite: image = processImage(image); params.putInt(GameAppOperation.QQFAV_DATALINE_REQTYPE, GameAppOperation.QQFAV_DATALINE_TYPE_DEFAULT); params.putString(GameAppOperation.QQFAV_DATALINE_TITLE, title); params.putString(GameAppOperation.QQFAV_DATALINE_DESCRIPTION,description); params.putString(GameAppOperation.QQFAV_DATALINE_IMAGEURL,image); params.putString(GameAppOperation.QQFAV_DATALINE_URL,url); params.putString(GameAppOperation.QQFAV_DATALINE_APPNAME, appName); params.putString(GameAppOperation.QQFAV_DATALINE_AUDIOURL,flashUrl); Runnable favoritesRunnable = new Runnable() { @Override public void run() { mTencent.addToQQFavorites(currentActivity, params, addToQQFavoritesListener); } }; UiThreadUtil.runOnUiThread(favoritesRunnable); break; case ShareScene.QQZone: image = processImage(image); ArrayList<String> imageUrls = new ArrayList<String>(); imageUrls.add(image); params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT); params.putString(QzoneShare.SHARE_TO_QQ_TITLE, title); params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY,description); params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL,url); params.putString(QzoneShare.SHARE_TO_QQ_AUDIO_URL,flashUrl); params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL,imageUrls); Runnable zoneRunnable = new Runnable() { @Override public void run() { mTencent.shareToQzone(currentActivity,params,qZoneShareListener); } }; UiThreadUtil.runOnUiThread(zoneRunnable); break; default: break; } } @ReactMethod public void shareVideo(String url,String flashUrl,String image,String title, String description,int shareScene, final Promise promise) { final Activity currentActivity = getCurrentActivity(); if (null == currentActivity) { promise.reject("405",ACTIVITY_DOES_NOT_EXIST); return; } mPromise = promise; final Bundle params = new Bundle(); switch (shareScene) { case ShareScene.QQ: promise.reject("500","Android QQ"); break; case ShareScene.Favorite: promise.reject("500","Android QQ"); break; case ShareScene.QQZone: ArrayList<String> imageUrls = new ArrayList<String>(); imageUrls.add(image); params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzonePublish.PUBLISH_TO_QZONE_TYPE_PUBLISHVIDEO); params.putString(QzonePublish.PUBLISH_TO_QZONE_IMAGE_URL, image); params.putString(QzonePublish.PUBLISH_TO_QZONE_SUMMARY,description); params.putString(QzonePublish.PUBLISH_TO_QZONE_VIDEO_PATH,flashUrl); Runnable zoneRunnable = new Runnable() { @Override public void run() { mTencent.shareToQzone(currentActivity,params,qZoneShareListener); } }; UiThreadUtil.runOnUiThread(zoneRunnable); break; default: break; } } @Nullable @Override public Map<String, Object> getConstants() { final Map<String, Object> constants = new HashMap<>(); constants.put("QQ", ShareScene.QQ); constants.put("QQZone", ShareScene.QQZone); constants.put("Favorite", ShareScene.Favorite); return constants; } /** * Tencent SDK App ID * @param reactContext * @return */ private String getAppID(ReactApplicationContext reactContext) { try { ApplicationInfo appInfo = reactContext.getPackageManager() .getApplicationInfo(reactContext.getPackageName(), PackageManager.GET_META_DATA); String key = appInfo.metaData.get("QQ_APP_ID").toString(); return key; } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } return null; } /** * * @param reactContext * @return */ private String getAppName(ReactApplicationContext reactContext) { PackageManager packageManager = reactContext.getPackageManager(); ApplicationInfo applicationInfo = null; try { applicationInfo = packageManager.getApplicationInfo(reactContext.getPackageName(), 0); } catch (final PackageManager.NameNotFoundException e) {} final String AppName = (String)((applicationInfo != null) ? packageManager.getApplicationLabel(applicationInfo) : "AppName"); return AppName; } /** * * @param image * @return */ private String processImage(String image) { if(URLUtil.isHttpUrl(image) || URLUtil.isHttpsUrl(image)) { return saveBytesToFile(getBytesFromURL(image), image.contains(".gif") ? "gif" : "jpg"); } else if (isBase64(image)) { return saveBitmapToFile(decodeBase64ToBitmap(image)); } else if (URLUtil.isFileUrl(image) || image.startsWith("/") ){ File file = new File(image); return file.getAbsolutePath(); } else if(URLUtil.isContentUrl(image)) { return saveBitmapToFile(getBitmapFromUri(Uri.parse(image))); } else { return saveBitmapToFile(BitmapFactory.decodeResource(getReactApplicationContext().getResources(),getDrawableFileID(image))); } } /** * Base64 * @param image * @return */ private boolean isBase64(String image) { try { byte[] decodedString = Base64.decode(image, Base64.DEFAULT); Bitmap bitmap = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); if (bitmap == null) { return false; } return true; } catch (Exception e) { return false; } } /** * DrawbleID * @param imageName * @return */ private int getDrawableFileID(String imageName) { ResourceDrawableIdHelper sResourceDrawableIdHelper = ResourceDrawableIdHelper.getInstance(); int id = sResourceDrawableIdHelper.getResourceDrawableId(getReactApplicationContext(),imageName); return id; } /** * URLBitmap * @param src * @return */ private static Bitmap getBitmapFromURL(String src) { try { URL url = new URL(src); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.connect(); InputStream input = connection.getInputStream(); Bitmap bitmap = BitmapFactory.decodeStream(input); return bitmap; } catch (IOException e) { return null; } } /** * URL byte[] * @param src * @return */ private static byte[] getBytesFromURL(String src) { try { URL url = new URL(src); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.connect(); InputStream input = connection.getInputStream(); byte[] b = getBytes(input); return b; } catch (Exception e) { e.printStackTrace(); return null; } } /** * Base64Bitmap * @param Base64String * @return */ private Bitmap decodeBase64ToBitmap(String Base64String) { byte[] decode = Base64.decode(Base64String,Base64.DEFAULT); Bitmap bitmap = BitmapFactory.decodeByteArray(decode, 0, decode.length); return bitmap; } /** * uriBitmap * @param uri * @return */ private Bitmap getBitmapFromUri(Uri uri) { try{ InputStream inStream = this.getCurrentActivity().getContentResolver().openInputStream(uri); Bitmap bitmap = BitmapFactory.decodeStream(inStream); return bitmap; }catch (FileNotFoundException e) { Log.d(TAG, "File not found: " + e.getMessage()); } return null; } /** * bitmap * @param bitmap * @return */ private String saveBitmapToFile(Bitmap bitmap) { File pictureFile = getOutputMediaFile(); if (pictureFile == null) { return null; } try { FileOutputStream fos = new FileOutputStream(pictureFile); bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos); fos.close(); } catch (FileNotFoundException e) { Log.d(TAG, "File not found: " + e.getMessage()); } catch (IOException e) { Log.d(TAG, "Error accessing file: " + e.getMessage()); } return pictureFile.getAbsolutePath(); } /** * byte[] * @param bytes * @return */ private String saveBytesToFile(byte[] bytes) { return saveBytesToFile(bytes, "jpg"); } /** * byte[] * @param bytes * @param ext * @return */ private String saveBytesToFile(byte[] bytes, String ext) { File pictureFile = getOutputMediaFile(ext); if (pictureFile == null) { return null; } try { FileOutputStream fos = new FileOutputStream(pictureFile); fos.write(bytes); fos.close(); } catch (FileNotFoundException e) { Log.d(TAG, "File not found: " + e.getMessage()); } catch (IOException e) { Log.d(TAG, "Error accessing file: " + e.getMessage()); } return pictureFile.getAbsolutePath(); } /** * * @return */ private File getOutputMediaFile(){ return getOutputMediaFile("jpg"); } private File getOutputMediaFile(String ext){ ext = ext != null ? ext : "jpg"; File mediaStorageDir = getCurrentActivity().getExternalCacheDir(); if (! mediaStorageDir.exists()){ if (! mediaStorageDir.mkdirs()){ return null; } } String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date()); File mediaFile; String mImageName="RN_"+ timeStamp +"." + ext; mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName); Log.d("path is",mediaFile.getPath()); return mediaFile; } /** * token openid * * @param jsonObject */ public static void initOpenidAndToken(JSONObject jsonObject) { try { String token = jsonObject.getString(Constants.PARAM_ACCESS_TOKEN); String expires = jsonObject.getString(Constants.PARAM_EXPIRES_IN); String openId = jsonObject.getString(Constants.PARAM_OPEN_ID); if (!TextUtils.isEmpty(token) && !TextUtils.isEmpty(expires) && !TextUtils.isEmpty(openId)) { mTencent.setAccessToken(token, expires); mTencent.setOpenId(openId); } } catch (Exception e) { } } IUiListener loginListener = new IUiListener() { @Override public void onComplete(Object response) { if (null == response) { mPromise.reject("600",QQ_RESPONSE_ERROR); return; } JSONObject jsonResponse = (JSONObject) response; if (null != jsonResponse && jsonResponse.length() == 0) { mPromise.reject("600",QQ_RESPONSE_ERROR); return; } initOpenidAndToken(jsonResponse); WritableMap map = Arguments.createMap(); map.putString("userid", mTencent.getOpenId()); map.putString("access_token", mTencent.getAccessToken()); map.putDouble("expires_time", mTencent.getExpiresIn()); mPromise.resolve(map); } @Override public void onError(UiError e) { mPromise.reject("600",e.errorMessage); } @Override public void onCancel() { mPromise.reject("603",QQ_CANCEL_BY_USER); } }; IUiListener qqShareListener = new IUiListener() { @Override public void onCancel() { mPromise.reject("503",QQ_CANCEL_BY_USER); } @Override public void onComplete(Object response) { mPromise.resolve(true); } @Override public void onError(UiError e) { mPromise.reject("500",e.errorMessage); } }; /** * QQZONE */ IUiListener qZoneShareListener = new IUiListener() { @Override public void onCancel() { mPromise.reject("503",QZONE_SHARE_CANCEL); } @Override public void onError(UiError e) { mPromise.reject("500",e.errorMessage); } @Override public void onComplete(Object response) { mPromise.resolve(true); } }; IUiListener addToQQFavoritesListener = new IUiListener() { @Override public void onCancel() { mPromise.reject("503",QQFAVORITES_CANCEL); } @Override public void onComplete(Object response) { mPromise.resolve(true); } @Override public void onError(UiError e) { mPromise.reject("500",e.errorMessage); } }; private static byte[] getBytes(InputStream inputStream) throws Exception { byte[] b = new byte[1024]; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); int len = -1; while ((len = inputStream.read(b)) != -1) { byteArrayOutputStream.write(b, 0, len); } byteArrayOutputStream.close(); inputStream.close(); return byteArrayOutputStream.toByteArray(); } }
package algorithms.dp; public class LongestCommonSubsequence { public int lcs(String s1, String s2) { return lcs(s1, s2, s1.length(), s2.length()); } private int lcs(String s1, String s2, int i, int j) { if (i == 0 || j == 0) { return 0; } else if (s1.charAt(i - 1) == s2.charAt(j - 1)) { return lcs(s1, s2, i - 1, j - 1) + 1; } else { return Math.max(lcs(s1, s2, i, j - 1), lcs(s1, s2, i - 1, j)); } } public int lcsTabulated(String s1, String s2) { int[][] table = new int[s1.length() + 1][s2.length() + 1]; for (int i = 1; i < table.length; i++) { for (int j = 1; j < table[0].length; j++) { if (s1.charAt(i - 1) == s2.charAt(j - 1)) { table[i][j] = table[i - 1][j - 1] + 1; } else { table[i][j] = Math.max(table[i][j - 1], table[i - 1][j]); } } } return table[s1.length()][s2.length()]; } public int lcsMemoized(String s1, String s2) { return lcsMemoized(s1, s2, s1.length(), s2.length(), new int[s1.length()][s2.length()]); } private int lcsMemoized(String s1, String s2, int i, int j, int[][] results) { if (i == 0 || j == 0) { return 0; } if (results[i - 1][j - 1] == 0) { if (s1.charAt(i - 1) == s2.charAt(j - 1)) { results[i - 1][j - 1] = lcsMemoized(s1, s2, i - 1, j - 1, results) + 1; } else { results[i - 1][j - 1] = Math.max(lcsMemoized(s1, s2, i, j - 1, results), lcsMemoized(s1, s2, i - 1, j, results)); } } return results[i - 1][j - 1]; } public static void main(String[] args) { LongestCommonSubsequence lcs = new LongestCommonSubsequence(); System.out.println(lcs.lcsTabulated("AerodroneAerodroneAerodrone", "AirpodAiAirpodrpod")); //System.out.println(lcs.lcsTabulated("AGGRTAB", "GXTXAYB")); System.out.println(lcs.lcsMemoized("AerodroneAerodroneAerodrone", "AirpodAiAirpodrpod")); } }
package liquibase.diff; import liquibase.change.Change; import liquibase.change.ColumnConfig; import liquibase.change.ConstraintsConfig; import liquibase.change.core.*; import liquibase.changelog.ChangeSet; import liquibase.database.Database; import liquibase.database.structure.*; import liquibase.database.typeconversion.TypeConverter; import liquibase.database.typeconversion.TypeConverterFactory; import liquibase.exception.DatabaseException; import liquibase.executor.ExecutorService; import liquibase.logging.LogFactory; import liquibase.parser.core.xml.LiquibaseEntityResolver; import liquibase.parser.core.xml.XMLChangeLogSAXParser; import liquibase.serializer.core.xml.XMLChangeLogSerializer; import liquibase.snapshot.DatabaseSnapshot; import liquibase.statement.DatabaseFunction; import liquibase.statement.core.RawSqlStatement; import liquibase.util.ISODateFormat; import liquibase.util.StringUtils; import liquibase.util.csv.CSVWriter; import liquibase.util.xml.DefaultXmlWriter; import liquibase.util.xml.XmlWriter; import org.w3c.dom.Document; import org.w3c.dom.Element; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.*; import java.util.*; public class DiffResult { private Long idRoot = new Date().getTime(); private int changeNumber = 1; private DatabaseSnapshot referenceSnapshot; private DatabaseSnapshot targetSnapshot; private DiffComparison productName; private DiffComparison productVersion; private SortedSet<Table> missingTables = new TreeSet<Table>(); private SortedSet<Table> unexpectedTables = new TreeSet<Table>(); private SortedSet<View> missingViews = new TreeSet<View>(); private SortedSet<View> unexpectedViews = new TreeSet<View>(); private SortedSet<View> changedViews = new TreeSet<View>(); private SortedSet<Column> missingColumns = new TreeSet<Column>(); private SortedSet<Column> unexpectedColumns = new TreeSet<Column>(); private SortedSet<Column> changedColumns = new TreeSet<Column>(); private SortedSet<ForeignKey> missingForeignKeys = new TreeSet<ForeignKey>(); private SortedSet<ForeignKey> unexpectedForeignKeys = new TreeSet<ForeignKey>(); private SortedSet<Index> missingIndexes = new TreeSet<Index>(); private SortedSet<Index> unexpectedIndexes = new TreeSet<Index>(); private SortedSet<PrimaryKey> missingPrimaryKeys = new TreeSet<PrimaryKey>(); private SortedSet<PrimaryKey> unexpectedPrimaryKeys = new TreeSet<PrimaryKey>(); private SortedSet<UniqueConstraint> missingUniqueConstraints = new TreeSet<UniqueConstraint>(); private SortedSet<UniqueConstraint> unexpectedUniqueConstraints = new TreeSet<UniqueConstraint>(); private SortedSet<Sequence> missingSequences = new TreeSet<Sequence>(); private SortedSet<Sequence> unexpectedSequences = new TreeSet<Sequence>(); private boolean diffData = false; private String dataDir = null; private String changeSetContext; private String changeSetAuthor; public DiffResult(DatabaseSnapshot referenceDatabaseSnapshot, DatabaseSnapshot targetDatabaseSnapshot) { this.referenceSnapshot = referenceDatabaseSnapshot; if (targetDatabaseSnapshot == null) { targetDatabaseSnapshot = new DatabaseSnapshot( referenceDatabaseSnapshot.getDatabase(), null); } this.targetSnapshot = targetDatabaseSnapshot; } public DiffComparison getProductName() { return productName; } public void setProductName(DiffComparison productName) { this.productName = productName; } public DiffComparison getProductVersion() { return productVersion; } public void setProductVersion(DiffComparison product) { this.productVersion = product; } public void addMissingTable(Table table) { missingTables.add(table); } public SortedSet<Table> getMissingTables() { return missingTables; } public void addUnexpectedTable(Table table) { unexpectedTables.add(table); } public SortedSet<Table> getUnexpectedTables() { return unexpectedTables; } public void addMissingView(View viewName) { missingViews.add(viewName); } public SortedSet<View> getMissingViews() { return missingViews; } public void addUnexpectedView(View viewName) { unexpectedViews.add(viewName); } public SortedSet<View> getUnexpectedViews() { return unexpectedViews; } public void addChangedView(View viewName) { changedViews.add(viewName); } public SortedSet<View> getChangedViews() { return changedViews; } public void addMissingColumn(Column columnName) { missingColumns.add(columnName); } public SortedSet<Column> getMissingColumns() { return missingColumns; } public void addUnexpectedColumn(Column columnName) { unexpectedColumns.add(columnName); } public SortedSet<Column> getUnexpectedColumns() { return unexpectedColumns; } public void addChangedColumn(Column columnName) { changedColumns.add(columnName); } public SortedSet<Column> getChangedColumns() { return changedColumns; } public void addMissingForeignKey(ForeignKey fkName) { missingForeignKeys.add(fkName); } public SortedSet<ForeignKey> getMissingForeignKeys() { return missingForeignKeys; } public void addUnexpectedForeignKey(ForeignKey fkName) { unexpectedForeignKeys.add(fkName); } public SortedSet<ForeignKey> getUnexpectedForeignKeys() { return unexpectedForeignKeys; } public void addMissingIndex(Index fkName) { missingIndexes.add(fkName); } public SortedSet<Index> getMissingIndexes() { return missingIndexes; } public void addUnexpectedIndex(Index fkName) { unexpectedIndexes.add(fkName); } public SortedSet<Index> getUnexpectedIndexes() { return unexpectedIndexes; } public void addMissingPrimaryKey(PrimaryKey primaryKey) { missingPrimaryKeys.add(primaryKey); } public SortedSet<PrimaryKey> getMissingPrimaryKeys() { return missingPrimaryKeys; } public void addUnexpectedPrimaryKey(PrimaryKey primaryKey) { unexpectedPrimaryKeys.add(primaryKey); } public SortedSet<PrimaryKey> getUnexpectedPrimaryKeys() { return unexpectedPrimaryKeys; } public void addMissingSequence(Sequence sequence) { missingSequences.add(sequence); } public SortedSet<Sequence> getMissingSequences() { return missingSequences; } public void addUnexpectedSequence(Sequence sequence) { unexpectedSequences.add(sequence); } public SortedSet<Sequence> getUnexpectedSequences() { return unexpectedSequences; } public void addMissingUniqueConstraint(UniqueConstraint uniqueConstraint) { missingUniqueConstraints.add(uniqueConstraint); } public SortedSet<UniqueConstraint> getMissingUniqueConstraints() { return this.missingUniqueConstraints; } public void addUnexpectedUniqueConstraint(UniqueConstraint uniqueConstraint) { unexpectedUniqueConstraints.add(uniqueConstraint); } public SortedSet<UniqueConstraint> getUnexpectedUniqueConstraints() { return unexpectedUniqueConstraints; } public boolean shouldDiffData() { return diffData; } public void setDiffData(boolean diffData) { this.diffData = diffData; } public String getDataDir() { return dataDir; } public void setDataDir(String dataDir) { this.dataDir = dataDir; } public String getChangeSetContext() { return changeSetContext; } public void setChangeSetContext(String changeSetContext) { this.changeSetContext = changeSetContext; } public boolean differencesFound() throws DatabaseException,IOException{ boolean differencesInData=false; if(shouldDiffData()) { List<ChangeSet> changeSets = new ArrayList<ChangeSet>(); addInsertDataChanges(changeSets, dataDir); differencesInData=!changeSets.isEmpty(); } return getMissingColumns().size()>0 || getMissingForeignKeys().size()>0 || getMissingIndexes().size()>0 || getMissingPrimaryKeys().size()>0 || getMissingSequences().size()>0 || getMissingTables().size()>0 || getMissingUniqueConstraints().size()>0 || getMissingViews().size()>0 || getUnexpectedColumns().size()>0 || getUnexpectedForeignKeys().size()>0 || getUnexpectedIndexes().size()>0 || getUnexpectedPrimaryKeys().size()>0 || getUnexpectedSequences().size()>0 || getUnexpectedTables().size()>0 || getUnexpectedUniqueConstraints().size()>0 || getUnexpectedViews().size()>0 || differencesInData; } public void printResult(PrintStream out) throws DatabaseException { out.println("Reference Database: " + referenceSnapshot.getDatabase()); out.println("Target Database: " + targetSnapshot.getDatabase()); printComparision("Product Name", productName, out); printComparision("Product Version", productVersion, out); printSetComparison("Missing Tables", getMissingTables(), out); printSetComparison("Unexpected Tables", getUnexpectedTables(), out); printSetComparison("Missing Views", getMissingViews(), out); printSetComparison("Unexpected Views", getUnexpectedViews(), out); printSetComparison("Changed Views", getChangedViews(), out); printSetComparison("Missing Columns", getMissingColumns(), out); printSetComparison("Unexpected Columns", getUnexpectedColumns(), out); printColumnComparison(getChangedColumns(), out); printSetComparison("Missing Foreign Keys", getMissingForeignKeys(), out); printSetComparison("Unexpected Foreign Keys", getUnexpectedForeignKeys(), out); printSetComparison("Missing Primary Keys", getMissingPrimaryKeys(), out); printSetComparison("Unexpected Primary Keys", getUnexpectedPrimaryKeys(), out); printSetComparison("Missing Unique Constraints", getMissingUniqueConstraints(), out); printSetComparison("Unexpected Unique Constraints", getUnexpectedUniqueConstraints(), out); printSetComparison("Missing Indexes", getMissingIndexes(), out); printSetComparison("Unexpected Indexes", getUnexpectedIndexes(), out); printSetComparison("Missing Sequences", getMissingSequences(), out); printSetComparison("Unexpected Sequences", getUnexpectedSequences(), out); } private void printSetComparison(String title, SortedSet<?> objects, PrintStream out) { out.print(title + ": "); if (objects.size() == 0) { out.println("NONE"); } else { out.println(); for (Object object : objects) { out.println(" " + object); } } } private void printColumnComparison(SortedSet<Column> changedColumns, PrintStream out) { out.print("Changed Columns: "); if (changedColumns.size() == 0) { out.println("NONE"); } else { out.println(); for (Column column : changedColumns) { out.println(" " + column); Column baseColumn = referenceSnapshot.getColumn(column .getTable().getName(), column.getName()); if (baseColumn != null) { if (baseColumn.isDataTypeDifferent(column)) { out.println(" from " + TypeConverterFactory.getInstance().findTypeConverter(referenceSnapshot.getDatabase()).convertToDatabaseTypeString(baseColumn, referenceSnapshot.getDatabase()) + " to " + TypeConverterFactory.getInstance().findTypeConverter(targetSnapshot.getDatabase()).convertToDatabaseTypeString(targetSnapshot.getColumn(column.getTable().getName(), column.getName()), targetSnapshot.getDatabase())); } if (baseColumn.isNullabilityDifferent(column)) { Boolean nowNullable = targetSnapshot.getColumn( column.getTable().getName(), column.getName()) .isNullable(); if (nowNullable == null) { nowNullable = Boolean.TRUE; } if (nowNullable) { out.println(" now nullable"); } else { out.println(" now not null"); } } } } } } private void printComparision(String title, DiffComparison comparison, PrintStream out) { out.print(title + ":"); if (comparison == null) { out.print("NULL"); return; } if (comparison.areTheSame()) { out.println(" EQUAL"); } else { out.println(); out.println(" Reference: '" + comparison.getReferenceVersion() + "'"); out.println(" Target: '" + comparison.getTargetVersion() + "'"); } } public void printChangeLog(String changeLogFile, Database targetDatabase) throws ParserConfigurationException, IOException, DatabaseException { this.printChangeLog(changeLogFile, targetDatabase, new DefaultXmlWriter()); } public void printChangeLog(PrintStream out, Database targetDatabase) throws ParserConfigurationException, IOException, DatabaseException { this.printChangeLog(out, targetDatabase, new DefaultXmlWriter()); } public void printChangeLog(String changeLogFile, Database targetDatabase, XmlWriter xmlWriter) throws ParserConfigurationException, IOException, DatabaseException { File file = new File(changeLogFile); if (!file.exists()) { LogFactory.getLogger().info(file + " does not exist, creating"); FileOutputStream stream = new FileOutputStream(file); printChangeLog(new PrintStream(stream), targetDatabase, xmlWriter); stream.close(); } else { LogFactory.getLogger().info(file + " exists, appending"); ByteArrayOutputStream out = new ByteArrayOutputStream(); printChangeLog(new PrintStream(out), targetDatabase, xmlWriter); String xml = new String(out.toByteArray()); xml = xml.replaceFirst("(?ms).*<databaseChangeLog[^>]*>", ""); xml = xml.replaceFirst("</databaseChangeLog>", ""); xml = xml.trim(); String lineSeparator = System.getProperty("line.separator"); BufferedReader fileReader = new BufferedReader(new FileReader(file)); String line; long offset = 0; while ((line = fileReader.readLine()) != null) { int index = line.indexOf("</databaseChangeLog>"); if (index >= 0) { offset += index; } else { offset += line.getBytes().length; offset += lineSeparator.getBytes().length; } } fileReader.close(); fileReader = new BufferedReader(new FileReader(file)); fileReader.skip(offset); fileReader.close(); // System.out.println("resulting XML: " + xml.trim()); RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw"); randomAccessFile.seek(offset); randomAccessFile.writeBytes(" " + xml + lineSeparator); randomAccessFile.writeBytes("</databaseChangeLog>" + lineSeparator); randomAccessFile.close(); // BufferedWriter fileWriter = new BufferedWriter(new // FileWriter(file)); // fileWriter.append(xml); // fileWriter.close(); } } /** * Prints changeLog that would bring the target database to be the same as * the reference database */ public void printChangeLog(PrintStream out, Database targetDatabase, XmlWriter xmlWriter) throws ParserConfigurationException, IOException, DatabaseException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = factory.newDocumentBuilder(); documentBuilder.setEntityResolver(new LiquibaseEntityResolver()); Document doc = documentBuilder.newDocument(); Element changeLogElement = doc.createElement("databaseChangeLog"); changeLogElement.setAttribute("xmlns", "http: changeLogElement.setAttribute("xmlns:xsi", "http: changeLogElement .setAttribute( "xsi:schemaLocation", "http: + XMLChangeLogSAXParser.getSchemaVersion() + ".xsd"); doc.appendChild(changeLogElement); List<ChangeSet> changeSets = new ArrayList<ChangeSet>(); addMissingTableChanges(changeSets, targetDatabase); addMissingColumnChanges(changeSets, targetDatabase); addChangedColumnChanges(changeSets); addMissingPrimaryKeyChanges(changeSets); addUnexpectedPrimaryKeyChanges(changeSets); addMissingUniqueConstraintChanges(changeSets); addUnexpectedUniqueConstraintChanges(changeSets); if (diffData) { addInsertDataChanges(changeSets, dataDir); } addMissingForeignKeyChanges(changeSets); addUnexpectedForeignKeyChanges(changeSets); addMissingIndexChanges(changeSets); addUnexpectedIndexChanges(changeSets); addUnexpectedColumnChanges(changeSets); addMissingSequenceChanges(changeSets); addUnexpectedSequenceChanges(changeSets); addMissingViewChanges(changeSets); addUnexpectedViewChanges(changeSets); addChangedViewChanges(changeSets); addUnexpectedTableChanges(changeSets); XMLChangeLogSerializer changeLogSerializer = new XMLChangeLogSerializer(); changeLogSerializer.setCurrentChangeLogFileDOM(doc); for (ChangeSet changeSet : changeSets) { doc.getDocumentElement().appendChild( changeLogSerializer.createNode(changeSet)); } xmlWriter.write(doc, out); out.flush(); } private ChangeSet generateChangeSet(Change change) { ChangeSet changeSet = generateChangeSet(); changeSet.addChange(change); return changeSet; } private ChangeSet generateChangeSet() { return new ChangeSet(generateId(), getChangeSetAuthor(), false, false, null, null, getChangeSetContext(), null); } private String getChangeSetAuthor() { if (changeSetAuthor != null) { return changeSetAuthor; } String author = System.getProperty("user.name"); if (StringUtils.trimToNull(author) == null) { return "diff-generated"; } else { return author + " (generated)"; } } public void setChangeSetAuthor(String changeSetAuthor) { this.changeSetAuthor = changeSetAuthor; } private String generateId() { return idRoot.toString() + "-" + changeNumber++; } private void addUnexpectedIndexChanges(List<ChangeSet> changes) { for (Index index : getUnexpectedIndexes()) { DropIndexChange change = new DropIndexChange(); change.setTableName(index.getTable().getName()); change.setSchemaName(index.getTable().getSchema()); change.setIndexName(index.getName()); change.setAssociatedWith(index.getAssociatedWithAsString()); changes.add(generateChangeSet(change)); } } private void addMissingIndexChanges(List<ChangeSet> changes) { for (Index index : getMissingIndexes()) { CreateIndexChange change = new CreateIndexChange(); change.setTableName(index.getTable().getName()); change.setTablespace(index.getTablespace()); change.setSchemaName(index.getTable().getSchema()); change.setIndexName(index.getName()); change.setUnique(index.isUnique()); change.setAssociatedWith(index.getAssociatedWithAsString()); for (String columnName : index.getColumns()) { ColumnConfig column = new ColumnConfig(); column.setName(columnName); change.addColumn(column); } changes.add(generateChangeSet(change)); } } private void addUnexpectedPrimaryKeyChanges(List<ChangeSet> changes) { for (PrimaryKey pk : getUnexpectedPrimaryKeys()) { if (!getUnexpectedTables().contains(pk.getTable())) { DropPrimaryKeyChange change = new DropPrimaryKeyChange(); change.setTableName(pk.getTable().getName()); change.setSchemaName(pk.getTable().getSchema()); change.setConstraintName(pk.getName()); changes.add(generateChangeSet(change)); } } } private void addMissingPrimaryKeyChanges(List<ChangeSet> changes) { for (PrimaryKey pk : getMissingPrimaryKeys()) { AddPrimaryKeyChange change = new AddPrimaryKeyChange(); change.setTableName(pk.getTable().getName()); change.setSchemaName(pk.getTable().getSchema()); change.setConstraintName(pk.getName()); change.setColumnNames(pk.getColumnNames()); change.setTablespace(pk.getTablespace()); changes.add(generateChangeSet(change)); } } private void addUnexpectedUniqueConstraintChanges(List<ChangeSet> changes) { for (UniqueConstraint uc : getUnexpectedUniqueConstraints()) { // Need check for nulls here due to NullPointerException using Postgres if (null != uc) { if (null != uc.getTable()) { DropUniqueConstraintChange change = new DropUniqueConstraintChange(); change.setTableName(uc.getTable().getName()); change.setSchemaName(uc.getTable().getSchema()); change.setConstraintName(uc.getName()); changes.add(generateChangeSet(change)); } } } } private void addMissingUniqueConstraintChanges(List<ChangeSet> changes) { for (UniqueConstraint uc : getMissingUniqueConstraints()) { // Need check for nulls here due to NullPointerException using Postgres if (null != uc) if (null != uc.getTable()) { AddUniqueConstraintChange change = new AddUniqueConstraintChange(); change.setTableName(uc.getTable().getName()); change.setTablespace(uc.getTablespace()); change.setSchemaName(uc.getTable().getSchema()); change.setConstraintName(uc.getName()); change.setColumnNames(uc.getColumnNames()); change.setDeferrable(uc.isDeferrable()); change.setInitiallyDeferred(uc.isInitiallyDeferred()); change.setDisabled(uc.isDisabled()); changes.add(generateChangeSet(change)); } } } private void addUnexpectedForeignKeyChanges(List<ChangeSet> changes) { for (ForeignKey fk : getUnexpectedForeignKeys()) { DropForeignKeyConstraintChange change = new DropForeignKeyConstraintChange(); change.setConstraintName(fk.getName()); change.setBaseTableName(fk.getForeignKeyTable().getName()); change.setBaseTableSchemaName(fk.getForeignKeyTable().getSchema()); changes.add(generateChangeSet(change)); } } private void addMissingForeignKeyChanges(List<ChangeSet> changes) { for (ForeignKey fk : getMissingForeignKeys()) { AddForeignKeyConstraintChange change = new AddForeignKeyConstraintChange(); change.setConstraintName(fk.getName()); change.setReferencedTableName(fk.getPrimaryKeyTable().getName()); change.setReferencedTableSchemaName(fk.getPrimaryKeyTable() .getSchema()); change.setReferencedColumnNames(fk.getPrimaryKeyColumns()); change.setBaseTableName(fk.getForeignKeyTable().getName()); change.setBaseTableSchemaName(fk.getForeignKeyTable().getSchema()); change.setBaseColumnNames(fk.getForeignKeyColumns()); change.setDeferrable(fk.isDeferrable()); change.setInitiallyDeferred(fk.isInitiallyDeferred()); change.setOnUpdate(fk.getUpdateRule()); change.setOnDelete(fk.getDeleteRule()); change.setReferencesUniqueColumn(fk.getReferencesUniqueColumn()); changes.add(generateChangeSet(change)); } } private void addUnexpectedSequenceChanges(List<ChangeSet> changes) { for (Sequence sequence : getUnexpectedSequences()) { DropSequenceChange change = new DropSequenceChange(); change.setSequenceName(sequence.getName()); change.setSchemaName(sequence.getSchema()); changes.add(generateChangeSet(change)); } } private void addMissingSequenceChanges(List<ChangeSet> changes) { for (Sequence sequence : getMissingSequences()) { CreateSequenceChange change = new CreateSequenceChange(); change.setSequenceName(sequence.getName()); change.setSchemaName(sequence.getSchema()); changes.add(generateChangeSet(change)); } } private void addUnexpectedColumnChanges(List<ChangeSet> changes) { for (Column column : getUnexpectedColumns()) { if (!shouldModifyColumn(column)) { continue; } DropColumnChange change = new DropColumnChange(); change.setTableName(column.getTable().getName()); change.setSchemaName(column.getTable().getSchema()); change.setColumnName(column.getName()); changes.add(generateChangeSet(change)); } } private void addMissingViewChanges(List<ChangeSet> changes) { for (View view : getMissingViews()) { CreateViewChange change = new CreateViewChange(); change.setViewName(view.getName()); change.setSchemaName(view.getSchema()); String selectQuery = view.getDefinition(); if (selectQuery == null) { selectQuery = "COULD NOT DETERMINE VIEW QUERY"; } change.setSelectQuery(selectQuery); changes.add(generateChangeSet(change)); } } private void addChangedViewChanges(List<ChangeSet> changes) { for (View view : getChangedViews()) { CreateViewChange change = new CreateViewChange(); change.setViewName(view.getName()); change.setSchemaName(view.getSchema()); String selectQuery = view.getDefinition(); if (selectQuery == null) { selectQuery = "COULD NOT DETERMINE VIEW QUERY"; } change.setSelectQuery(selectQuery); change.setReplaceIfExists(true); changes.add(generateChangeSet(change)); } } private void addChangedColumnChanges(List<ChangeSet> changes) { for (Column column : getChangedColumns()) { if (!shouldModifyColumn(column)) { continue; } TypeConverter targetTypeConverter = TypeConverterFactory.getInstance().findTypeConverter(targetSnapshot.getDatabase()); boolean foundDifference = false; Column referenceColumn = referenceSnapshot.getColumn(column.getTable().getName(), column.getName()); if (column.isDataTypeDifferent(referenceColumn)) { ModifyDataTypeChange change = new ModifyDataTypeChange(); change.setTableName(column.getTable().getName()); change.setSchemaName(column.getTable().getSchema()); change.setColumnName(column.getName()); change.setNewDataType(targetTypeConverter.convertToDatabaseTypeString(referenceColumn, targetSnapshot.getDatabase())); changes.add(generateChangeSet(change)); foundDifference = true; } if (column.isNullabilityDifferent(referenceColumn)) { if (referenceColumn.isNullable() == null || referenceColumn.isNullable()) { DropNotNullConstraintChange change = new DropNotNullConstraintChange(); change.setTableName(column.getTable().getName()); change.setSchemaName(column.getTable().getSchema()); change.setColumnName(column.getName()); change.setColumnDataType(targetTypeConverter.convertToDatabaseTypeString(referenceColumn, targetSnapshot.getDatabase())); changes.add(generateChangeSet(change)); foundDifference = true; } else { AddNotNullConstraintChange change = new AddNotNullConstraintChange(); change.setTableName(column.getTable().getName()); change.setSchemaName(column.getTable().getSchema()); change.setColumnName(column.getName()); change.setColumnDataType(targetTypeConverter.convertToDatabaseTypeString(referenceColumn, targetSnapshot.getDatabase())); changes.add(generateChangeSet(change)); foundDifference = true; } } if (!foundDifference) { throw new RuntimeException("Unknown difference"); } } } private boolean shouldModifyColumn(Column column) { return column.getView() == null && !referenceSnapshot.getDatabase().isLiquibaseTable( column.getTable().getName()); } private void addUnexpectedViewChanges(List<ChangeSet> changes) { for (View view : getUnexpectedViews()) { DropViewChange change = new DropViewChange(); change.setViewName(view.getName()); change.setSchemaName(view.getSchema()); changes.add(generateChangeSet(change)); } } private void addMissingColumnChanges(List<ChangeSet> changes, Database database) { for (Column column : getMissingColumns()) { if (!shouldModifyColumn(column)) { continue; } AddColumnChange change = new AddColumnChange(); change.setTableName(column.getTable().getName()); change.setSchemaName(column.getTable().getSchema()); ColumnConfig columnConfig = new ColumnConfig(); columnConfig.setName(column.getName()); String dataType = TypeConverterFactory.getInstance().findTypeConverter(database).convertToDatabaseTypeString(column, database); columnConfig.setType(dataType); Object defaultValue = column.getDefaultValue(); if (defaultValue != null) { String defaultValueString = TypeConverterFactory.getInstance() .findTypeConverter(database).getDataType(defaultValue) .convertObjectToString(defaultValue, database); if (defaultValueString != null) { defaultValueString = defaultValueString.replaceFirst("'", "").replaceAll("'$", ""); } columnConfig.setDefaultValue(defaultValueString); } if (column.getRemarks() != null) { columnConfig.setRemarks(column.getRemarks()); } if (column.isNullable() != null && !column.isNullable()) { ConstraintsConfig constraintsConfig = columnConfig .getConstraints(); if (constraintsConfig == null) { constraintsConfig = new ConstraintsConfig(); columnConfig.setConstraints(constraintsConfig); } constraintsConfig.setNullable(false); } change.addColumn(columnConfig); changes.add(generateChangeSet(change)); } } private void addMissingTableChanges(List<ChangeSet> changes, Database database) { for (Table missingTable : getMissingTables()) { if (referenceSnapshot.getDatabase().isLiquibaseTable( missingTable.getName())) { continue; } CreateTableChange change = new CreateTableChange(); change.setTableName(missingTable.getName()); change.setSchemaName(missingTable.getSchema()); if (missingTable.getRemarks() != null) { change.setRemarks(missingTable.getRemarks()); } for (Column column : missingTable.getColumns()) { ColumnConfig columnConfig = new ColumnConfig(); columnConfig.setName(column.getName()); columnConfig.setType(TypeConverterFactory.getInstance().findTypeConverter(database).convertToDatabaseTypeString(column, database)); ConstraintsConfig constraintsConfig = null; if (column.isPrimaryKey()) { PrimaryKey primaryKey = null; for (PrimaryKey pk : getMissingPrimaryKeys()) { if (pk.getTable().getName().equalsIgnoreCase(missingTable.getName())) { primaryKey = pk; } } if (primaryKey == null || primaryKey.getColumnNamesAsList().size() == 1) { constraintsConfig = new ConstraintsConfig(); constraintsConfig.setPrimaryKey(true); constraintsConfig.setPrimaryKeyTablespace(column.getTablespace()); if (primaryKey != null) { constraintsConfig.setPrimaryKeyName(primaryKey.getName()); getMissingPrimaryKeys().remove(primaryKey); } } } if (column.isAutoIncrement()) { columnConfig.setAutoIncrement(true); } if (column.isNullable() != null && !column.isNullable()) { if (constraintsConfig == null) { constraintsConfig = new ConstraintsConfig(); } constraintsConfig.setNullable(false); } if (constraintsConfig != null) { columnConfig.setConstraints(constraintsConfig); } Object defaultValue = column.getDefaultValue(); if (defaultValue == null) { // do nothing } else if (column.isAutoIncrement()) { // do nothing } else if (defaultValue instanceof Date) { columnConfig.setDefaultValueDate((Date) defaultValue); } else if (defaultValue instanceof Boolean) { columnConfig.setDefaultValueBoolean(((Boolean) defaultValue)); } else if (defaultValue instanceof Number) { columnConfig.setDefaultValueNumeric(((Number) defaultValue)); } else if (defaultValue instanceof DatabaseFunction) { columnConfig.setDefaultValueComputed((DatabaseFunction) defaultValue); } else { columnConfig.setDefaultValue(defaultValue.toString()); } if (column.getRemarks() != null) { columnConfig.setRemarks(column.getRemarks()); } change.addColumn(columnConfig); } changes.add(generateChangeSet(change)); } } private void addUnexpectedTableChanges(List<ChangeSet> changes) { for (Table unexpectedTable : getUnexpectedTables()) { DropTableChange change = new DropTableChange(); change.setTableName(unexpectedTable.getName()); change.setSchemaName(unexpectedTable.getSchema()); changes.add(generateChangeSet(change)); } } private void addInsertDataChanges(List<ChangeSet> changeSets, String dataDir) throws DatabaseException, IOException { try { String schema = referenceSnapshot.getSchema(); for (Table table : referenceSnapshot.getTables()) { List<Change> changes = new ArrayList<Change>(); List<Map> rs = ExecutorService.getInstance().getExecutor(referenceSnapshot.getDatabase()).queryForList(new RawSqlStatement("SELECT * FROM "+ referenceSnapshot.getDatabase().escapeTableName(schema,table.getName()))); if (rs.size() == 0) { continue; } List<String> columnNames = new ArrayList<String>(); for (Column column : table.getColumns()) { columnNames.add(column.getName()); } // if dataDir is not null, print out a csv file and use loadData // tag if (dataDir != null) { String fileName = table.getName().toLowerCase() + ".csv"; if (dataDir != null) { fileName = dataDir + "/" + fileName; } File parentDir = new File(dataDir); if (!parentDir.exists()) { parentDir.mkdirs(); } if (!parentDir.isDirectory()) { throw new RuntimeException(parentDir + " is not a directory"); } CSVWriter outputFile = new CSVWriter(new FileWriter( fileName)); String[] dataTypes = new String[columnNames.size()]; String[] line = new String[columnNames.size()]; for (int i = 0; i < columnNames.size(); i++) { line[i] = columnNames.get(i); } outputFile.writeNext(line); for (Map row : rs) { line = new String[columnNames.size()]; for (int i = 0; i < columnNames.size(); i++) { Object value = row.get(columnNames.get(i).toUpperCase()); if (dataTypes[i] == null && value != null) { if (value instanceof Number) { dataTypes[i] = "NUMERIC"; } else if (value instanceof Boolean) { dataTypes[i] = "BOOLEAN"; } else if (value instanceof Date) { dataTypes[i] = "DATE"; } else { dataTypes[i] = "STRING"; } } if (value == null) { line[i] = "NULL"; } else { if (value instanceof Date) { line[i] = new ISODateFormat().format(((Date) value)); } else { line[i] = value.toString(); } } } outputFile.writeNext(line); } outputFile.flush(); outputFile.close(); LoadDataChange change = new LoadDataChange(); change.setFile(fileName); change.setEncoding("UTF-8"); change.setSchemaName(schema); change.setTableName(table.getName()); for (int i = 0; i < columnNames.size(); i++) { String colName = columnNames.get(i); LoadDataColumnConfig columnConfig = new LoadDataColumnConfig(); columnConfig.setHeader(colName); columnConfig.setName(colName); columnConfig.setType(dataTypes[i]); change.addColumn(columnConfig); } changes.add(change); } else { // if dataDir is null, build and use insert tags for (Map row : rs) { InsertDataChange change = new InsertDataChange(); change.setSchemaName(schema); change.setTableName(table.getName()); // loop over all columns for this row for (int i = 0; i < columnNames.size(); i++) { ColumnConfig column = new ColumnConfig(); column.setName(columnNames.get(i)); Object value = row.get(columnNames.get(i).toUpperCase()); if (value == null) { column.setValue(null); } else if (value instanceof Number) { column.setValueNumeric((Number) value); } else if (value instanceof Boolean) { column.setValueBoolean((Boolean) value); } else if (value instanceof Date) { column.setValueDate((Date) value); } else { // string column.setValue(value.toString()); } change.addColumn(column); } // for each row, add a new change // (there will be one group per table) changes.add(change); } } if (changes.size() > 0) { ChangeSet changeSet = generateChangeSet(); for (Change change : changes) { changeSet.addChange(change); } changeSets.add(changeSet); } } } catch (Exception e) { throw new RuntimeException(e); } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package qa.qcri.aidr.predictui.facade.imp; import qa.qcri.aidr.predictui.dto.ItemToLabelDTO; import qa.qcri.aidr.predictui.dto.NominalAttributeDTO; import qa.qcri.aidr.predictui.dto.NominalLabelDTO; import qa.qcri.aidr.predictui.dto.TrainingDataDTO; import qa.qcri.aidr.predictui.facade.MiscResourceFacade; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.PersistenceContext; import javax.persistence.Query; import java.math.BigInteger; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.List; /** * * @author Imran */ @Stateless public class MiscResourceImp implements MiscResourceFacade { @PersistenceContext(unitName = "qa.qcri.aidr.predictui-EJBS") private EntityManager em; @Override public List<TrainingDataDTO> getTraningDataByCrisisAndAttribute(int crisisID, int modelFamilyID, int fromRecord, int limit, String sortColumn, String sortDirection) { List<TrainingDataDTO> trainingDataList = new ArrayList<TrainingDataDTO>(); String orderSQLPart = ""; if (sortColumn != null && !sortColumn.isEmpty()){ if (sortDirection != null && !sortDirection.isEmpty()) { if ("ASC".equals(sortDirection)) { sortDirection = "ASC"; } else { sortDirection = "DESC"; } } else { sortDirection = "DESC"; } orderSQLPart += " ORDER BY " + sortColumn + " " + sortDirection + " "; } else{ orderSQLPart += " ORDER BY dnl.timestamp DESC"; } String sql = " SELECT distinct lbl.nominalLabelID, lbl.name labelName, d.data tweetJSON, u.userID, u.name labelerName, dnl.timestamp, d.documentID " + " FROM document_nominal_label dnl " + " JOIN nominal_label lbl on lbl.nominalLabelID=dnl.nominalLabelID " + " JOIN model_family mf on mf.nominalAttributeID=lbl.nominalAttributeID " //+ " JOIN model m on m.modelFamilyID= mf.modelFamilyID " + " JOIN document d on d.documentID = dnl.documentID " // + " JOIN task_answer ta on ta.documentID = d.documentID " + " JOIN users u on u.userID = dnl.userID " + " WHERE mf.modelFamilyID = :modelFamilyID AND d.crisisID = :crisisID " + orderSQLPart + " LIMIT :fromRecord, :limit"; String sqlCount = " SELECT count(distinct lbl.nominalLabelID, lbl.name, d.data, u.userID, u.name, dnl.timestamp, d.documentID) " + " FROM document_nominal_label dnl " + " JOIN nominal_label lbl on lbl.nominalLabelID=dnl.nominalLabelID " + " JOIN model_family mf on mf.nominalAttributeID=lbl.nominalAttributeID " //+ " JOIN model m on m.modelFamilyID= mf.modelFamilyID " + " JOIN document d on d.documentID = dnl.documentID " // + " JOIN task_answer ta on ta.documentID = d.documentID " + " JOIN users u on u.userID = dnl.userID " + " WHERE mf.modelFamilyID = :modelFamilyID AND d.crisisID = :crisisID "; System.out.println("getTraningDataByCrisisAndAttribute : " + sql); try { Integer totalRows; Query queryCount = em.createNativeQuery(sqlCount); queryCount.setParameter("crisisID", crisisID); queryCount.setParameter("modelFamilyID", modelFamilyID); Object res = queryCount.getSingleResult(); totalRows = Integer.parseInt(res.toString()); if (totalRows > 0){ Query query = em.createNativeQuery(sql); query.setParameter("crisisID", crisisID); query.setParameter("modelFamilyID", modelFamilyID); query.setParameter("fromRecord", fromRecord); query.setParameter("limit", limit); List<Object[]> rows = query.getResultList(); TrainingDataDTO trainingDataRow; for (Object[] row : rows) { trainingDataRow = new TrainingDataDTO(); // Removed .intValue() as we already cast to Integer trainingDataRow.setLabelID((Integer) row[0]); trainingDataRow.setLabelName((String) row[1]); trainingDataRow.setTweetJSON((String) row[2]); trainingDataRow.setLabelerID((Integer) row[3]); trainingDataRow.setLabelerName((String) row[4]); trainingDataRow.setLabeledTime(((Date) row[5])); trainingDataRow.setDocumentID(((BigInteger) row[6]).longValue()); trainingDataRow.setTotalRows(totalRows); trainingDataList.add(trainingDataRow); } } return trainingDataList; } catch (NoResultException e) { return null; } } @Override public ItemToLabelDTO getItemToLabel(int crisisID, int modelFamilyID) { // with attributeID get attribute and labels details // with crisisID get an item from document table for which hasHumanLabel is FALSE // packup both info into one class DTO and return NominalAttributeDTO attributeDTO = new NominalAttributeDTO(); ItemToLabelDTO itemToLabel = new ItemToLabelDTO(); try{ String sqlToGetAttribute = "SELECT na.nominalAttributeID, na.code, na.name, na.description FROM nominal_attribute na" + " JOIN model_family mf on mf.nominalAttributeID = na.nominalAttributeID WHERE mf.modelFamilyID = :modelFamilyID"; Query attributeQuery = em.createNativeQuery(sqlToGetAttribute); attributeQuery.setParameter("modelFamilyID", modelFamilyID); List<Object[]> attributeResults = attributeQuery.getResultList(); attributeDTO.setNominalAttributeID(((Integer)attributeResults.get(0)[0]).intValue()); attributeDTO.setCode((String) attributeResults.get(0)[1]); attributeDTO.setName((String) attributeResults.get(0)[2]); attributeDTO.setDescription((String) attributeResults.get(0)[3]); String sqlToGetLabel = "SELECT nominalLabelCode, name, description FROM nominal_label WHERE nominalAttributeID = :attributeID"; Query labelQuery = em.createNativeQuery(sqlToGetLabel); labelQuery.setParameter("attributeID", attributeDTO.getNominalAttributeID()); List<Object[]> labelsResults = labelQuery.getResultList(); Collection<NominalLabelDTO> labelDTOList = new ArrayList<NominalLabelDTO>(); for (Object[] label: labelsResults){ NominalLabelDTO labelDTO = new NominalLabelDTO(); labelDTO.setNominalLabelCode((String)label[0]); labelDTO.setName((String) label[1]); labelDTO.setDescription((String) label[2]); labelDTOList.add(labelDTO); } attributeDTO.setNominalLabelCollection(labelDTOList); //here retrieve data from document table String sqlToGetItem = "SELECT documentID, data FROM document WHERE crisisID = :crisisID AND hasHumanLabels = 0 ORDER BY RAND() LIMIT 0, 1"; Query documentQuery = em.createNativeQuery(sqlToGetItem); documentQuery.setParameter("crisisID", crisisID); List<Object[]> documentResult = documentQuery.getResultList(); itemToLabel.setItemID(((BigInteger) documentResult.get(0)[0])); itemToLabel.setItemText(documentResult.get(0)[1].toString()); itemToLabel.setAttribute(attributeDTO); }catch(NoResultException e) { return null; } return itemToLabel; } }
/* * Honor Code: I pledge that this program represents my own * program code. I received help from (enter the names of * others that helped with the assignment, write no one if * you received no help) in designing and debugging my program. */ package baseattack; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.logging.Level; import java.util.logging.Logger; import javafx.animation.AnimationTimer; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.control.Button; import javafx.scene.image.Image; import javafx.scene.layout.GridPane; import javafx.scene.layout.StackPane; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.scene.text.Text; import javafx.stage.Stage; /** * * @author Michael Hodges * * @todo * This is really in no particular order, feel free to add * Add rotation to rendering * Add AI * Add more buttons, 4 to each base * Add main button functionality * Add Minion logic * ranged * melee * Add functionality to pause menu * ability to access it * write current game state to file * audio settings * buttons for all the above * Add sound effects * explosions * pew pew laser sounds * space melee sound? * music * Add VFX * hit indicator (smallExplosion) * minion death explosions * minion death pieces that fly out * Add very light third cloud effect over everything? * @bugs * None yet */ public class BaseAttack extends Application { @Override public void start(Stage primaryStage) { Player p1 = new Player(false, 100, 0); //user player Player p2 = new Player(true, 100, 0);//AI player Image spaceBase720 = new Image("Assets/spaceBase720.png");//background stars Image spaceClouds720v1 = new Image("Assets/spaceClouds720.png");//clouds right side up Image spaceClouds720v2 = new Image("Assets/spaceClouds720v2.png");//clouds upside down //Added all buttons we needed Button btn = new Button(); btn.setText("Start Game"); btn.setFont(Font.font("Impact", 50)); btn.setStyle("-fx-text-fill: black; -fx-background-color: red;"); btn.setTranslateY(40); Button mbtn = new Button(); mbtn.setText("Ranged Ship"); mbtn.setFont(Font.font("Impact")); mbtn.setTranslateX(200); mbtn.setTranslateY(-330); Button mbtn2 = new Button(); mbtn2.setText("Tank Ship"); mbtn2.setFont(Font.font("Impact")); mbtn2.setTranslateX(300); mbtn2.setTranslateY(-330); Button mbtn3 = new Button(); mbtn3.setText("Normal Ship"); mbtn3.setFont(Font.font("Impact")); mbtn3.setTranslateX(400); mbtn3.setTranslateY(-330); Button ubtn = new Button(); ubtn.setText("Upgrade Base"); ubtn.setFont(Font.font("Impact")); ubtn.setTranslateX(540); ubtn.setTranslateY(-330); Button pbtn = new Button(); pbtn.setText("Pause Game"); pbtn.setFont(Font.font("Impact")); pbtn.setTranslateX(400); pbtn.setTranslateY(330); //Added title to main menu and added style Text title = new Text(); title.setText("Base Attack!"); title.setFont(Font.font("Impact", 80)); title.setStroke(Color.RED); title.setFill(Color.BLACK); title.setTranslateY(-80); //money bar for gameplay Text money = new Text(); money.setText("0"); money.setFont(Font.font("Impact", 80)); money.setStroke(Color.RED); money.setFill(Color.BLACK); money.setTranslateY(-320); //turns out each scene needs its own root StackPane root1 = new StackPane();//for title screen StackPane root2 = new StackPane();//for gameplay StackPane root3 = new StackPane();//for pause menu root1.getChildren().add(btn); root1.getChildren().add(title); root2.getChildren().add(mbtn); root2.getChildren().add(mbtn2); root2.getChildren().add(mbtn3); root2.getChildren().add(pbtn); root2.getChildren().add(ubtn); root2.getChildren().add(money); Scene scene1 = new Scene(root1, 1280, 720);//title screen Scene scene2 = new Scene(root2, 1280, 720);//gameplay Scene scene3 = new Scene(root3, 1280, 720);//pause menu primaryStage.setTitle("Base Attack"); primaryStage.setScene(scene1); //children can only have 1 parent, so multiple canvasses for multiple clouds //there's probablly a much better way to do this without making 1 of each thing for every scene Canvas canvas1 = new Canvas(1280, 720); root1.getChildren().add(canvas1); Canvas canvas2 = new Canvas(1280, 720); root2.getChildren().add(canvas2); Canvas canvas3 = new Canvas(1280, 720); root3.getChildren().add(canvas3); canvas1.toBack(); canvas2.toBack(); GraphicsContext gc = canvas1.getGraphicsContext2D(); GraphicsContext gc2 = canvas2.getGraphicsContext2D(); GraphicsContext gc3 = canvas3.getGraphicsContext2D(); //start button btn.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { primaryStage.setScene(scene2); try { FileWriter gameLog = new FileWriter("game_log.txt"); Date date = new Date(); SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yy hh:mm:ss"); String myDate = dateFormat.format(date); try (BufferedWriter out = new BufferedWriter(gameLog)) { out.write("Game started: " + myDate); } } catch (IOException ex) { Logger.getLogger(BaseAttack.class.getName()).log(Level.SEVERE, null, ex); } } }); //pause button pbtn.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { primaryStage.setScene(scene3); } }); new AnimationTimer() { int tick = 0; int cloudTimer = 0; public void handle(long currentNanoTime) { //actual gameloop code goes here tick++; //money update money.setText(Integer.toString(p1.getMoney())); //not strictly necessary to check scene, but should be more efficient than drawing 2x more than needed if (primaryStage.getScene() == scene1) { gc.drawImage(spaceBase720, 0, 0); gc.drawImage(spaceClouds720v1, cloudTimer % 2560, 0); gc.drawImage(spaceClouds720v1, (cloudTimer % 2560) - 2560, 0); gc.drawImage(spaceClouds720v2, cloudTimer / 2, 0); gc.drawImage(spaceClouds720v2, (cloudTimer / 2) - 2560, 0); } else if (primaryStage.getScene() == scene2) { p1.update(); gc2.drawImage(spaceBase720, 0, 0); gc2.drawImage(spaceClouds720v1, cloudTimer % 2560, 0); gc2.drawImage(spaceClouds720v1, (cloudTimer % 2560) - 2560, 0); gc2.drawImage(spaceClouds720v2, cloudTimer / 2, 0); gc2.drawImage(spaceClouds720v2, (cloudTimer / 2) - 2560, 0); p1.render(gc2); p2.render(gc2); } else { gc3.drawImage(spaceBase720, 0, 0); gc3.drawImage(spaceClouds720v1, cloudTimer % 2560, 0); gc3.drawImage(spaceClouds720v1, (cloudTimer % 2560) - 2560, 0); gc3.drawImage(spaceClouds720v2, cloudTimer / 2, 0); gc3.drawImage(spaceClouds720v2, (cloudTimer / 2) - 2560, 0); } if (cloudTimer == 2560 * 2) { cloudTimer = 0; } else { cloudTimer++; } } }.start(); primaryStage.show(); } /** * @param args the command line arguments */ public static void main(String[] args) { launch(args); } }
package ti.modules.titanium.database; import java.util.HashMap; import org.appcelerator.kroll.KrollProxy; import org.appcelerator.kroll.annotations.Kroll; import org.appcelerator.kroll.common.Log; import org.appcelerator.titanium.TiBlob; import org.appcelerator.titanium.TiContext; import org.appcelerator.titanium.util.TiConvert; import android.database.AbstractWindowedCursor; import android.database.Cursor; import android.database.SQLException; import android.os.Build; @Kroll.proxy(parentModule=DatabaseModule.class) public class TiResultSetProxy extends KrollProxy { private static final String TAG = "TiResultSet"; protected Cursor rs; protected String lastException; protected HashMap<String, Integer> columnNames; // workaround case-sensitive matching in Google's implementation public TiResultSetProxy(Cursor rs) { super(); this.rs = rs; String[] names = rs.getColumnNames(); this.columnNames = new HashMap<String, Integer>(names.length); for(int i=0; i < names.length; i++) { columnNames.put(names[i].toLowerCase(), i); } } public TiResultSetProxy(TiContext tiContext, Cursor rs) { this(rs); } @Kroll.method public void close() { if (rs != null && !rs.isClosed()) { Log.d(TAG, "Closing database cursor", Log.DEBUG_MODE); rs.close(); } else { Log.w(TAG, "Calling close on a closed cursor.", Log.DEBUG_MODE); } } @Kroll.method public Object field(Object[] args) { return internalGetField(args); } @Kroll.method public Object getField(Object[] args) { return internalGetField(args); } private Object internalGetField(Object[] args) { int index = -1; int type = DatabaseModule.FIELD_TYPE_UNKNOWN; if (args.length >= 1) { if(args[0] instanceof Number) { index = TiConvert.toInt(args[0]); } else { (new IllegalArgumentException("Expected int column index as first parameter was " + args[0].getClass().getSimpleName())).printStackTrace(); throw new IllegalArgumentException("Expected int column index as first parameter was " + args[0].getClass().getSimpleName()); } } if (args.length == 2) { if (args[1] instanceof Number) { type = TiConvert.toInt(args[1]); } else { throw new IllegalArgumentException("Expected int field type as second parameter was " + args[1].getClass().getSimpleName()); } } return internalGetField(index, type); } private Object internalGetField(int index, int type) { if (rs == null) { Log.w(TAG, "Attempted to get field value when no result set is available."); return null; } boolean outOfBounds = (index >= rs.getColumnCount()); Object result = null; boolean fromString = false; try { if (rs instanceof AbstractWindowedCursor) { AbstractWindowedCursor cursor = (AbstractWindowedCursor) rs; if (cursor.isFloat(index)) { result = cursor.getDouble(index); } else if (cursor.isLong(index)) { result = cursor.getLong(index); } else if (cursor.isNull(index)) { result = null; } else if (cursor.isBlob(index)) { result = TiBlob.blobFromData(cursor.getBlob(index)); } else { fromString = true; } } else { fromString = true; } if (fromString) { result = rs.getString(index); } if (outOfBounds && Build.VERSION.SDK_INT >= 11) { // TIMOB-4515: Column number doesn't exist, yet no exception // occurred. This is known to happen in Honeycomb. So // we'll throw instead. We throw the same exception type that // Android would. throw new IllegalStateException("Requested column number " + index + " does not exist"); } } catch (RuntimeException e) { // in this block) are RuntimeExceptions and since we anyway re-throw // and log the same error message, we're just catching all RuntimeExceptions. Log.e(TAG, "Exception getting value for column " + index + ": " + e.getMessage(), e); throw e; } switch(type) { case DatabaseModule.FIELD_TYPE_STRING : if (!(result instanceof String)) { result = TiConvert.toString(result); } break; case DatabaseModule.FIELD_TYPE_INT : if (!(result instanceof Integer) && !(result instanceof Long)) { result = TiConvert.toInt(result); } break; case DatabaseModule.FIELD_TYPE_FLOAT : if (!(result instanceof Float)) { result = TiConvert.toFloat(result); } break; case DatabaseModule.FIELD_TYPE_DOUBLE : if (!(result instanceof Double)) { result = TiConvert.toDouble(result); } break; } return result; } @Kroll.method public Object fieldByName(Object[] args) { return internalGetFieldByName(args); } @Kroll.method public Object getFieldByName(Object[] args) { return internalGetFieldByName(args); } private Object internalGetFieldByName(Object[] args) { String name = null; int type = DatabaseModule.FIELD_TYPE_UNKNOWN; if (args.length >= 1) { if(args[0] instanceof String) { name = (String) args[0]; } else { throw new IllegalArgumentException("Expected string column name as first parameter" + args[0].getClass().getSimpleName()); } } if (args.length == 2) { if (args[1] instanceof Number) { type = TiConvert.toInt(args[1]); } else { throw new IllegalArgumentException("Expected int field type as second parameter" + args[1].getClass().getSimpleName()); } } return internalGetFieldByName(name, type); } private Object internalGetFieldByName(String fieldName, int type) { Object result = null; if (rs != null) { try { Integer ndx = columnNames.get(fieldName.toLowerCase()); if (ndx != null) result = internalGetField(ndx.intValue(), type); } catch (SQLException e) { String msg = "Field name " + fieldName + " not found. msg=" + e.getMessage(); Log.e(TAG, msg); throw e; } } return result; } @Kroll.getProperty @Kroll.method public int getFieldCount() { if (rs != null) { try { return rs.getColumnCount(); } catch (SQLException e) { Log.e(TAG, "No fields exist"); throw e; } } return 0; } @Kroll.method public String fieldName(int index) { return getFieldName(index); } @Kroll.method public String getFieldName(int index) { if (rs != null) { try { return rs.getColumnName(index); } catch (SQLException e) { Log.e(TAG, "No column at index: " + index); throw e; } } return null; } @Kroll.getProperty @Kroll.method public int getRowCount() { if (rs != null) { return rs.getCount(); } return 0; } @Kroll.getProperty @Kroll.method public boolean isValidRow() { boolean valid = false; if (rs != null && !rs.isClosed() && !rs.isAfterLast()) { valid = true; } return valid; } @Kroll.method public boolean next() { if (isValidRow()) { return rs.moveToNext(); } else { Log.w(TAG, "Ignoring next, current row is invalid."); } return false; } @Override public String getApiName() { return "Ti.Database.ResultSet"; } }
package com.github.reactnativecommunity.location; import android.app.Activity; import android.content.Intent; import com.facebook.react.bridge.ActivityEventListener; import com.facebook.react.bridge.BaseActivityEventListener; import com.facebook.react.bridge.Promise; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.module.annotations.ReactModule; @ReactModule(name = RNLocationModule.NAME) public class RNLocationModule extends ReactContextBaseJavaModule { public static final String NAME = "RNLocation"; private RNLocationProvider locationProvider; public RNLocationModule(ReactApplicationContext reactContext) { super(reactContext); reactContext.addActivityEventListener(activityEventListener); } @Override public String getName() { return NAME; } // React interface @ReactMethod @SuppressWarnings("unused") public void configure(ReadableMap options, final Promise promise) { // Update the location provider if we are given one if (options.hasKey("androidProvider")) { String providerName = options.getString("androidProvider"); switch (providerName) { case "auto": locationProvider = createDefaultLocationProvider(); break; case "playServices": locationProvider = createPlayServicesLocationProvider(); break; case "standard": locationProvider = createStandardLocationProvider(); break; default: Utils.emitWarning(getReactApplicationContext(), "androidProvider was passed an unknown value: " + providerName, "401"); } } else if (locationProvider == null) { // Otherwise ensure we have a provider and create a default if not locationProvider = createDefaultLocationProvider(); } // Pass the options to the location provider locationProvider.configure(getCurrentActivity(), options, promise); } @ReactMethod @SuppressWarnings("unused") public void startUpdatingLocation() { // Ensure we have a provider if (locationProvider == null) { locationProvider = createDefaultLocationProvider(); } // Call the provider locationProvider.startUpdatingLocation(); } @ReactMethod @SuppressWarnings("unused") public void stopUpdatingLocation() { // Ensure we have a provider if (locationProvider == null) { locationProvider = createDefaultLocationProvider(); } // Call the provider locationProvider.stopUpdatingLocation(); } // Helpers private ActivityEventListener activityEventListener = new BaseActivityEventListener() { public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) { if (locationProvider instanceof RNPlayServicesLocationProvider) { ((RNPlayServicesLocationProvider) locationProvider).onActivityResult(requestCode, resultCode, data); } } }; private RNLocationProvider createDefaultLocationProvider() { // If we have the correct classes for the fused location provider, we default to that. Otherwise, we default to the built-in methods if (Utils.hasFusedLocationProvider()) { return createPlayServicesLocationProvider(); } else { return createStandardLocationProvider(); } } private RNPlayServicesLocationProvider createPlayServicesLocationProvider() { return new RNPlayServicesLocationProvider(getCurrentActivity(), getReactApplicationContext()); } private RNStandardLocationProvider createStandardLocationProvider() { return new RNStandardLocationProvider(getReactApplicationContext()); } }
package com.teachonmars.module.autoContext.annotation; public class Constant { public static String basePackageName = "com.teachonmars.module"; public static String baseBuiltClassName = "ContextNeedy"; public static String builtClassName = basePackageName + "." + baseBuiltClassName; public static String builtClassMain = "main"; public static String contextParameter = "context"; public static String baseNameCommonMethod = "priority"; }
package com.microsoft.office365.connectmicrosoftgraph; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.microsoft.aad.adal.AuthenticationCallback; import com.microsoft.aad.adal.AuthenticationCancelError; import com.microsoft.aad.adal.AuthenticationResult; import com.microsoft.aad.adal.UserInfo; import java.net.URI; import java.util.UUID; /** * Starting Activity of the app. Handles the connection to Office 365. * When it first starts it only displays a button to Connect to Office 365. * If there are no cached tokens, the user is required to sign in to Office 365. * If there are cached tokens, the app tries to reuse them. * The activity redirects the user to the SendMailActivity upon successful connection. */ public class ConnectActivity extends AppCompatActivity { private static final String TAG = "ConnectActivity"; // the connect button private Button mConnectButton; // greeting private TextView mTitleTextView; // progress spinner private ProgressBar mConnectProgressBar; // instructions private TextView mDescriptionTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_connect); // set up our views mConnectButton = (Button) findViewById(R.id.connectButton); mConnectProgressBar = (ProgressBar) findViewById(R.id.connectProgressBar); mTitleTextView = (TextView) findViewById(R.id.titleTextView); mDescriptionTextView = (TextView) findViewById(R.id.descriptionTextView); // add click listener mConnectButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showConnectingInProgressUI(); //check that client id and redirect have been configured if (!hasAzureConfiguration()) { Toast.makeText( ConnectActivity.this, getString(R.string.warning_clientid_redirecturi_incorrect), Toast.LENGTH_LONG).show(); resetUIForConnect(); return; } connect(); } }); } private void connect() { AuthenticationManager mgr = AuthenticationManager.getInstance(); mgr.setContextActivity(this); mgr.connect( new AuthenticationCallback<AuthenticationResult>() { @Override public void onSuccess(AuthenticationResult result) { // get the UserInfo from the auth response UserInfo user = result.getUserInfo(); // get the user's given name String givenName = user.getGivenName(); // get the user's displayable Id String displayableId = user.getDisplayableId(); // start the SendMailActivity Intent sendMailActivity = new Intent(ConnectActivity.this, SendMailActivity.class); // take the user's info along sendMailActivity.putExtra("givenName", givenName); sendMailActivity.putExtra("displayableId", displayableId); // actually start the Activity startActivity(sendMailActivity); finish(); } @Override public void onError(final Exception e) { if (userCancelledConnect(e)) { resetUIForConnect(); } else { showConnectErrorUI(); } } }); } /** * This activity gets notified about the completion of the ADAL activity through this method. * * @param requestCode The integer request code originally supplied to startActivityForResult(), * allowing you to identify who this result came from. * @param resultCode The integer result code returned by the child activity through its * setResult(). * @param data An Intent, which can return result data to the caller (various data * can be attached to Intent "extras"). */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { Log.i(TAG, "onActivityResult - AuthenticationActivity has come back with results"); super.onActivityResult(requestCode, resultCode, data); AuthenticationManager .getInstance() .getAuthenticationContext() .onActivityResult(requestCode, resultCode, data); } private void resetUIForConnect() { mConnectButton.setVisibility(View.VISIBLE); mTitleTextView.setVisibility(View.GONE); mDescriptionTextView.setVisibility(View.GONE); mConnectProgressBar.setVisibility(View.GONE); } private void showConnectingInProgressUI() { mConnectButton.setVisibility(View.GONE); mTitleTextView.setVisibility(View.GONE); mDescriptionTextView.setVisibility(View.GONE); mConnectProgressBar.setVisibility(View.VISIBLE); } private void showConnectErrorUI() { mConnectButton.setVisibility(View.VISIBLE); mConnectProgressBar.setVisibility(View.GONE); mTitleTextView.setText(R.string.title_text_error); mTitleTextView.setVisibility(View.VISIBLE); mDescriptionTextView.setText(R.string.connect_text_error); mDescriptionTextView.setVisibility(View.VISIBLE); Toast.makeText( ConnectActivity.this, R.string.connect_toast_text_error, Toast.LENGTH_LONG).show(); } private static boolean userCancelledConnect(Exception e) { return e instanceof AuthenticationCancelError; } private static boolean hasAzureConfiguration() { try { UUID.fromString(Constants.CLIENT_ID); URI.create(Constants.REDIRECT_URI); return true; } catch (IllegalArgumentException e) { return false; } } }
package replicant; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotation use to mark code as incompatible with GWT. * The Name of the annotation is all that matters. */ @Retention( RetentionPolicy.CLASS ) @Target( { ElementType.TYPE, ElementType.METHOD } ) @Documented @interface GwtIncompatible { }
package com.sine_x.material_wecenter.controller.activity; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import com.github.florent37.materialviewpager.MaterialViewPager; import com.github.florent37.materialviewpager.header.HeaderDesign; import com.sine_x.material_wecenter.models.Response; import com.squareup.picasso.Picasso; import com.sine_x.material_wecenter.Client; import com.sine_x.material_wecenter.R; import com.sine_x.material_wecenter.controller.fragment.UserActonFragment; import com.sine_x.material_wecenter.controller.fragment.UserInfoFragment; import com.sine_x.material_wecenter.models.Result2; import com.sine_x.material_wecenter.models.UserInfo; import butterknife.Bind; import butterknife.ButterKnife; import de.hdodenhof.circleimageview.CircleImageView; public class UserActivity extends AppCompatActivity { @Bind(R.id.view_pager) MaterialViewPager mViewPager; @Bind(R.id.logo_white) CircleImageView imgAvatar; private Menu menu; private String uid; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_user); ButterKnife.bind(this); uid = getIntent().getStringExtra("uid"); setTitle(""); Toolbar toolbar = mViewPager.getToolbar(); if (toolbar != null) { setSupportActionBar(toolbar); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); final ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setDisplayShowHomeEnabled(true); actionBar.setDisplayShowTitleEnabled(true); actionBar.setDisplayUseLogoEnabled(false); actionBar.setHomeButtonEnabled(true); } } mViewPager.getViewPager().setAdapter(new FragmentStatePagerAdapter(getSupportFragmentManager()) { @Override public Fragment getItem(int position) { switch (position % 4) { case 0: return UserInfoFragment.newInstance(uid); case 1: return UserActonFragment.newInstance(uid, UserActonFragment.PUBLISH); default: return UserActonFragment.newInstance(uid, UserActonFragment.ANSWER); } } @Override public int getCount() { return 3; } @Override public CharSequence getPageTitle(int position) { switch (position % 4) { case 0: return ""; case 1: return ""; case 2: return ""; } return ""; } }); mViewPager.setMaterialViewPagerListener(new MaterialViewPager.Listener() { @Override public HeaderDesign getHeaderDesign(int page) { return HeaderDesign.fromColorResAndUrl( R.color.nliveo_blue_colorPrimary, "file:///android_asset/background.jpg"); } }); mViewPager.getViewPager().setOffscreenPageLimit(mViewPager.getViewPager().getAdapter().getCount()); mViewPager.getPagerTitleStrip().setViewPager(mViewPager.getViewPager()); new LoadUserInfo().execute(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_user, menu); this.menu = menu; return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_focus) { return true; } return super.onOptionsItemSelected(item); } class LoadUserInfo extends AsyncTask<Void, Void, Void> { Response<UserInfo> response; @Override protected Void doInBackground(Void... params) { Client client = Client.getInstance(); response = client.getUserInfo(uid); return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); if (response.getRsm() != null) { UserInfo info = response.getRsm(); setTitle(info.getUser_name() + ""); Picasso.with(UserActivity.this).load(info.getAvatar_file()).into(imgAvatar); MenuItem item = menu.findItem(R.id.action_focus); if (info.getHas_focus() == 1) { item.setTitle(""); } else { item.setTitle(""); } } } } }
package com.slothnull.android.medox.viewholder; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.TextView; import com.slothnull.android.medox.model.AbstractNotification; import com.slothnull.android.medox.R; public class NotificationViewHolder extends RecyclerView.ViewHolder { private static final String TAG = "NotificationViewHolder"; public TextView titleView; public TextView timeView; public TextView messageView; public TextView levelView; public NotificationViewHolder(View itemView) { super(itemView); titleView = (TextView) itemView.findViewById(R.id.titleView); timeView = (TextView) itemView.findViewById(R.id.timeView); messageView = (TextView) itemView.findViewById(R.id.messageView); levelView = (TextView) itemView.findViewById(R.id.levelView); } public void bindToNotification(AbstractNotification notification) { titleView.setText(notification.title); timeView.setText(notification.time); if(notification.level.equals("1")) levelView.setText("E"); messageView.setText(notification.message); } }
package com.weather.yogurt.lifequery.activity; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.widget.TextView; import android.widget.Toast; import com.weather.yogurt.lifequery.R; import com.weather.yogurt.lifequery.database.QueryDataBase; import com.weather.yogurt.lifequery.model.TelephoneNumberOwnership; import com.weather.yogurt.lifequery.util.HttpCallbackListener; import com.weather.yogurt.lifequery.util.HttpUtil; import com.weather.yogurt.lifequery.util.Utilty; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.text.SimpleDateFormat; import java.util.Date; public class ShowInformationActivity extends Activity { private String chooseItem; private String inputContent; private TextView showInformationText; private boolean isCancelDialog=false; private Dialog dialog; Context context=ShowInformationActivity.this; private final SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); QueryDataBase dataBase=QueryDataBase.getInstance(context); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.show_information_activity_layout); showInformationText= (TextView) findViewById(R.id.showInformationText); Intent intentFromMainInterface=getIntent(); if (intentFromMainInterface!=null){ boolean isFromMainInterface=intentFromMainInterface.getBooleanExtra("isFromMainInterface",true); if (isFromMainInterface){ chooseItem=intentFromMainInterface.getStringExtra("chooseItem"); inputContent=intentFromMainInterface.getStringExtra("inputContent"); showDialog(); requestInformation(); } } } private void requestInformation() { String searchAddress=""; switch (chooseItem){ case "": searchAddress="http://apis.baidu.com/apistore/mobilenumber/mobilenumber?"+inputContent; break; case "IP": searchAddress="http://apis.baidu.com/apistore/iplookupservice/iplookup?"+inputContent; break; case "": searchAddress="http://api.avatardata.cn/PostNumber/QueryPostnumber?key=[APPKEY]&postnumber=" +inputContent+"&page=1&rows=15?"; break; case "": searchAddress="http://apis.baidu.com/datatiny/cardinfo/cardinfo"+inputContent; break; case "": searchAddress="http://apis.baidu.com/apistore/mobilenumber/mobilenumber?"+inputContent; break; case "IMEI": searchAddress="http://apis.baidu.com/apistore/mobilenumber/mobilenumber?"+inputContent; break; case "": searchAddress="http://apis.baidu.com/apistore/currencyservice/currency?"+"fromCurrency=CNY&toCurrency=USD&amount=2"; break; case "": searchAddress="http://apis.baidu.com/apistore/mobilenumber/mobilenumber?"+inputContent; break; case "": searchAddress="http://apis.baidu.com/apistore/stockservice/hkstock?"+inputContent+"&list=1"; break; case "": searchAddress="http://apis.baidu.com/qunar/qunar_train_service/traindetail?"+inputContent; String httpArg = "version=1.0&train=G101&from=%E5%8C%97%E4%BA%AC%E5%8D%97&" + "to=%E4%B8%8A%E6%B5%B7%E8%99%B9%E6%A1%A5&date=2015-09-01"; break; case "": searchAddress="http://apis.baidu.com/apistore/mobilenumber/mobilenumber?"+inputContent; break; case "": searchAddress="http://apis.baidu.com/apistore/qunaerticket/querydetail?id="+inputContent; break; case ""://api searchAddress="http://apis.baidu.com/apistore/mobilenumber/mobilenumber?"+inputContent; break; } HttpUtil.sendHttpRequest(searchAddress,listener); } //Dialog private void showDialog(){ if (dialog!=null){ dialog=new Dialog(this); } } //Dialog private void cancelDialog(){ if (dialog!=null&&isCancelDialog){ dialog.dismiss(); } } HttpCallbackListener listener=new HttpCallbackListener() { @Override public void onFinish(String result) throws JSONException { JSONArray jsonArray=new JSONArray(result); JSONObject object=jsonArray.getJSONObject(0); boolean isSuccessful; switch (chooseItem){ case "": TelephoneNumberOwnership ownership=new TelephoneNumberOwnership(); ownership.setTelephoneNumber(inputContent); ownership.setSearchDate(format.format(new Date())); dataBase.saveTelephoneNumberOwnershipInformation(ownership); cancelDialog(); isSuccessful=Utilty.parsePhoneNumberOwnership(context,object); dismissDialogAndShowInformation(isSuccessful); break; case "IP": isSuccessful=Utilty.parseIpAddress(context,object); dismissDialogAndShowInformation(isSuccessful); break; case "": isSuccessful=Utilty.parseZipCode(context,object); dismissDialogAndShowInformation(isSuccessful); break; case "": isSuccessful=Utilty.parseBankCard(context,object); dismissDialogAndShowInformation(isSuccessful); break; case "": isSuccessful=Utilty.parseAppleSerialNumber(context,object); dismissDialogAndShowInformation(isSuccessful); break; case "IMEI": isSuccessful=Utilty.parseAppleIMEINumber(context,object); dismissDialogAndShowInformation(isSuccessful); break; case "": isSuccessful=Utilty.parseExchangeRate(context,object); dismissDialogAndShowInformation(isSuccessful); break; case "": isSuccessful=Utilty.parseExpress(context,object); dismissDialogAndShowInformation(isSuccessful); break; case "": isSuccessful=Utilty.parseShares(context,object); dismissDialogAndShowInformation(isSuccessful); break; case "": isSuccessful=Utilty.parseTrainTickets(context,object); dismissDialogAndShowInformation(isSuccessful); break; case "": isSuccessful=Utilty.parseTrademark(context,object); dismissDialogAndShowInformation(isSuccessful); break; case "": isSuccessful=Utilty.parseAttractionsTicketsPrice(context,object); dismissDialogAndShowInformation(isSuccessful); break; case "": isSuccessful=Utilty.parsePerpetualCalendar(context,object); dismissDialogAndShowInformation(isSuccessful); break; } } @Override public void onError(Exception e) { } }; private void dismissDialogAndShowInformation(boolean isSuccessful) { cancelDialog(); if (isSuccessful){ showInformattion(); }else { makeToast(); } } private void showInformattion() { runOnUiThread(new Runnable() { @Override public void run() { SharedPreferences prefs= PreferenceManager.getDefaultSharedPreferences(context); String result=prefs.getString("result",""); showInformationText.setText(result); } }); } private void makeToast() { Toast.makeText(ShowInformationActivity.this,"",Toast.LENGTH_SHORT).show(); onBackPressed(); } @Override public void onBackPressed() { super.onBackPressed(); finish(); } }
package com.wkovacs64.mtorch; 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.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.content.LocalBroadcastManager; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.WindowManager; import android.widget.ImageButton; import android.widget.Toast; import java.util.Set; import timber.log.Timber; public class MainActivity extends BaseActivity implements View.OnClickListener, SharedPreferences.OnSharedPreferenceChangeListener { public static final String INTERNAL_INTENT = MainActivity.class.getPackage().getName() + "INTERNAL_INTENT"; private static final String DEATH_THREAT = "die"; private static final String SETTINGS_AUTO_ON_KEY = "auto_on"; private static final String SETTINGS_PERSISTENCE_KEY = "persistence"; private boolean mAutoOn; private boolean mPersist; private boolean mTorchEnabled; private AboutDialog mAboutDialog; private ImageButton mImageButton; private BroadcastReceiver mBroadcastReceiver; private SharedPreferences mPrefs; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Timber.d("********** onCreate **********"); setContentView(R.layout.activity_main); // Read preferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this); mAutoOn = mPrefs.getBoolean(SETTINGS_AUTO_ON_KEY, false); mPersist = mPrefs.getBoolean(SETTINGS_PERSISTENCE_KEY, false); // Assume flash off on launch (certainly true the first time) mTorchEnabled = false; // Set up the About dialog box mAboutDialog = new AboutDialog(this); // Check for flash capability if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) { Timber.e(getString(R.string.error_no_flash)); Toast.makeText(this, R.string.error_no_flash, Toast.LENGTH_LONG).show(); finish(); return; } Timber.d("DEBUG: flash capability detected!"); // Set up the clickable toggle image mImageButton = (ImageButton) findViewById(R.id.torch_image_button); if (mImageButton == null) Timber.e("ERROR: mImageButton was NULL"); else { mImageButton.setImageResource(R.drawable.torch_off); mImageButton.setOnClickListener(this); mImageButton.setEnabled(true); // Keep the screen on while the app is open getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } // Register to receive broadcasts from the service mBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Timber.d("DEBUG: broadcast received..."); Bundle extras = intent.getExtras(); if (extras != null) { Set<String> ks = extras.keySet(); if (ks.contains(SETTINGS_AUTO_ON_KEY)) { Timber.d("DEBUG: intent included Auto On extra, toggling torch..."); toggleTorch(); } else if (ks.contains(DEATH_THREAT)) { Timber.d("DEBUG: received death threat from service... shutting down!"); Toast.makeText(MainActivity.this, intent.getStringExtra(DEATH_THREAT), Toast.LENGTH_LONG).show(); finish(); } } } }; } @Override protected void onStart() { super.onStart(); Timber.d("********** onStart **********"); Intent startItUp = new Intent(this, TorchService.class); IntentFilter toggleIntent = new IntentFilter(INTERNAL_INTENT); // Listen for intents from the service LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, toggleIntent); // Listen for preference changes so we can react if necessary mPrefs.registerOnSharedPreferenceChangeListener(this); // Pass the service our preferences as extras on the startup intent startItUp.putExtra(SETTINGS_AUTO_ON_KEY, mAutoOn); startItUp.putExtra(SETTINGS_PERSISTENCE_KEY, mPersist); // Start the service that will handle the camera startService(startItUp); } @Override protected void onResume() { super.onResume(); Timber.d("********** onResume **********"); mTorchEnabled = TorchService.isTorchOn(); updateImageButton(); } @Override protected void onStop() { super.onStop(); Timber.d("********** onStop **********"); // Stop listening for broadcasts from the service LocalBroadcastManager.getInstance(this).unregisterReceiver(mBroadcastReceiver); // Stop listening for preference changes mPrefs.unregisterOnSharedPreferenceChangeListener(this); // Close the About dialog if we're stopping anyway if (mAboutDialog.isShowing()) mAboutDialog.dismiss(); // If no persistence or if the torch is off, stop the service if (!mPersist || !mTorchEnabled) { stopService(new Intent(this, TorchService.class)); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. switch (item.getItemId()) { case R.id.menu_about: // show About dialog mAboutDialog.show(); return true; case R.id.menu_settings: // show Settings startActivity(new Intent(this, SettingsActivity.class)); return true; } return super.onOptionsItemSelected(item); } @Override public void onClick(View v) { Timber.d("********** onClick **********"); toggleTorch(); } private void toggleTorch() { Timber.d("DEBUG: toggleTorch | mTorchEnabled was " + mTorchEnabled + " when image was " + "pressed; changing to " + !mTorchEnabled); // Use the service to start/stop the torch (start = on, stop = off) Intent toggleIntent = new Intent(this, TorchService.class); if (mTorchEnabled) toggleIntent.putExtra("stop_torch", true); else toggleIntent.putExtra("start_torch", true); startService(toggleIntent); mTorchEnabled = !mTorchEnabled; updateImageButton(); } private void updateImageButton() { Timber.d("DEBUG: updateImageButton | mTorchEnabled = " + mTorchEnabled + "; setting " + "image accordingly"); if (mTorchEnabled) mImageButton.setImageResource(R.drawable.torch_on); else mImageButton.setImageResource(R.drawable.torch_off); } @Override public void onSharedPreferenceChanged(SharedPreferences prefs, String key) { Timber.d("DEBUG: SharedPreferences: " + key + " has changed"); Intent settingsChangedIntent = new Intent(this, TorchService.class); // Settings have changed, observe the new value if (key.equals(SETTINGS_AUTO_ON_KEY)) { mAutoOn = prefs.getBoolean(key, false); settingsChangedIntent.putExtra(key, mAutoOn); } else if (key.equals(SETTINGS_PERSISTENCE_KEY)) { mPersist = prefs.getBoolean(key, false); settingsChangedIntent.putExtra(key, mPersist); } // Notify the service startService(settingsChangedIntent); } }
package io.github.izzyleung.zhihudailypurify.ui.widget; import android.content.Context; import android.content.res.Configuration; import android.graphics.Rect; import android.os.ResultReceiver; import android.text.Editable; import android.text.Spannable; import android.text.SpannableString; import android.text.TextUtils; import android.text.TextWatcher; import android.text.style.ForegroundColorSpan; import android.util.AttributeSet; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.AutoCompleteTextView; import android.widget.ImageView; import android.widget.LinearLayout; import java.lang.reflect.Method; import io.github.izzyleung.zhihudailypurify.R; /** * Simplified version of SearchView, only EditText and a clear text button is supported * Thanks to code of SearchView in AppCompat */ public class IzzySearchView extends LinearLayout { static final AutoCompleteTextViewReflector HIDDEN_METHOD_INVOKER = new AutoCompleteTextViewReflector(); private boolean mClearingFocus; private SearchAutoComplete mQueryTextView; private View mSearchPlate; private ImageView mClearTextButton; private OnQueryTextListener mOnQueryChangeListener; private CharSequence mQueryHint; private Runnable mShowImeRunnable = () -> { InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE); if (imm != null) { HIDDEN_METHOD_INVOKER.showSoftInputUnchecked(imm, IzzySearchView.this, 0); } }; private Runnable mUpdateDrawableStateRunnable = this::updateFocusedState; public IzzySearchView(Context context) { this(context, null); } public IzzySearchView(Context context, AttributeSet attrs) { super(context, attrs); LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); inflater.inflate(R.layout.izzy_search_view, this, true); mQueryTextView = (SearchAutoComplete) findViewById(R.id.search_src_text); mQueryTextView.setSearchView(this); mSearchPlate = findViewById(R.id.search_plate); mClearTextButton = (ImageView) findViewById(R.id.search_close_btn); mClearTextButton.setOnClickListener(v -> { if (!TextUtils.isEmpty(mQueryTextView.getText())) { mQueryTextView.setText(""); mQueryTextView.requestFocus(); setImeVisibility(true); } }); mQueryTextView.addTextChangedListener(new TextWatcher() { public void beforeTextChanged(CharSequence s, int start, int before, int after) { } public void onTextChanged(CharSequence s, int start, int before, int after) { } public void afterTextChanged(Editable s) { updateCloseButton(); } }); mQueryTextView.setOnEditorActionListener((v, actionId, event) -> { onSubmitQuery(); return true; }); setFocusable(true); updateViewsVisibility(); } static boolean isLandscapeMode(Context context) { return context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE; } @Override public boolean requestFocus(int direction, Rect previouslyFocusedRect) { if (mClearingFocus) return false; if (!isFocusable()) return false; boolean result = mQueryTextView.requestFocus(direction, previouslyFocusedRect); if (result) { updateViewsVisibility(); } return result; } @Override public void clearFocus() { mClearingFocus = true; setImeVisibility(false); super.clearFocus(); mQueryTextView.clearFocus(); mClearingFocus = false; } @Override public void onWindowFocusChanged(boolean hasWindowFocus) { super.onWindowFocusChanged(hasWindowFocus); postUpdateFocusedState(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int widthMode = MeasureSpec.getMode(widthMeasureSpec); int width = MeasureSpec.getSize(widthMeasureSpec); switch (widthMode) { case MeasureSpec.AT_MOST: width = Math.min(getPreferredWidth(), width); break; case MeasureSpec.EXACTLY: break; case MeasureSpec.UNSPECIFIED: width = getPreferredWidth(); break; } widthMode = MeasureSpec.EXACTLY; super.onMeasure(MeasureSpec.makeMeasureSpec(width, widthMode), heightMeasureSpec); } @Override protected void onDetachedFromWindow() { removeCallbacks(mUpdateDrawableStateRunnable); super.onDetachedFromWindow(); } private int getPreferredWidth() { return (int) (320 * getContext().getResources().getDisplayMetrics().density + 0.5f); } public void setOnQueryTextListener(OnQueryTextListener listener) { mOnQueryChangeListener = listener; } private void forceSuggestionQuery() { HIDDEN_METHOD_INVOKER.doBeforeTextChanged(mQueryTextView); HIDDEN_METHOD_INVOKER.doAfterTextChanged(mQueryTextView); } void onTextFocusChanged() { updateViewsVisibility(); postUpdateFocusedState(); if (mQueryTextView.hasFocus()) { forceSuggestionQuery(); } } private void updateViewsVisibility() { updateCloseButton(); } private void updateCloseButton() { final boolean hasText = !TextUtils.isEmpty(mQueryTextView.getText()); mClearTextButton.setVisibility(hasText ? VISIBLE : GONE); mClearTextButton.getDrawable().setState(hasText ? ENABLED_STATE_SET : EMPTY_STATE_SET); } private void postUpdateFocusedState() { post(mUpdateDrawableStateRunnable); } private void updateFocusedState() { boolean focused = mQueryTextView.hasFocus(); mSearchPlate.getBackground().setState(focused ? FOCUSED_STATE_SET : EMPTY_STATE_SET); invalidate(); } private void setImeVisibility(final boolean visible) { if (visible) { post(mShowImeRunnable); } else { removeCallbacks(mShowImeRunnable); InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE); if (imm != null) { imm.hideSoftInputFromWindow(getWindowToken(), 0); } } } public void setQueryHint(CharSequence hint) { mQueryHint = hint; updateQueryHint(); } private CharSequence getDecoratedHint(CharSequence hintText) { Spannable ssb = new SpannableString(hintText); //noinspection deprecation ssb.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.search_view_hint_color)), 0, hintText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); return ssb; } private void updateQueryHint() { if (mQueryHint != null) { mQueryTextView.setHint(getDecoratedHint(mQueryHint)); } else { mQueryTextView.setHint(getDecoratedHint("")); } } private void onSubmitQuery() { CharSequence query = mQueryTextView.getText(); if (query != null && TextUtils.getTrimmedLength(query) > 0) { if (mOnQueryChangeListener != null) { mOnQueryChangeListener.onQueryTextSubmit(query.toString()); } } } public interface OnQueryTextListener { boolean onQueryTextSubmit(String query); } public static class SearchAutoComplete extends AutoCompleteTextView { private int mThreshold; private IzzySearchView mSearchView; public SearchAutoComplete(Context context, AttributeSet attrs) { super(context, attrs); mThreshold = getThreshold(); } void setSearchView(IzzySearchView searchView) { mSearchView = searchView; } @Override public void setThreshold(int threshold) { super.setThreshold(threshold); mThreshold = threshold; } @Override protected void replaceText(CharSequence text) { } @Override public void performCompletion() { } @Override public void onWindowFocusChanged(boolean hasWindowFocus) { super.onWindowFocusChanged(hasWindowFocus); if (hasWindowFocus && mSearchView.hasFocus() && getVisibility() == VISIBLE) { InputMethodManager inputManager = (InputMethodManager) getContext() .getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.showSoftInput(this, 0); if (isLandscapeMode(getContext())) { HIDDEN_METHOD_INVOKER.ensureImeVisible(this, true); } } } @Override protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { super.onFocusChanged(focused, direction, previouslyFocusedRect); mSearchView.onTextFocusChanged(); } @Override public boolean enoughToFilter() { return mThreshold <= 0 || super.enoughToFilter(); } @Override public boolean onKeyPreIme(int keyCode, @SuppressWarnings("NullableProblems") KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) { KeyEvent.DispatcherState state = getKeyDispatcherState(); if (state != null) { state.startTracking(event, this); } return true; } else if (event.getAction() == KeyEvent.ACTION_UP) { KeyEvent.DispatcherState state = getKeyDispatcherState(); if (state != null) { state.handleUpEvent(event); } if (event.isTracking() && !event.isCanceled()) { mSearchView.clearFocus(); mSearchView.setImeVisibility(false); return true; } } } return super.onKeyPreIme(keyCode, event); } } private static class AutoCompleteTextViewReflector { private Method doBeforeTextChanged, doAfterTextChanged; private Method ensureImeVisible; private Method showSoftInputUnchecked; AutoCompleteTextViewReflector() { try { doBeforeTextChanged = AutoCompleteTextView.class .getDeclaredMethod("doBeforeTextChanged"); doBeforeTextChanged.setAccessible(true); } catch (NoSuchMethodException ignored) { } try { doAfterTextChanged = AutoCompleteTextView.class .getDeclaredMethod("doAfterTextChanged"); doAfterTextChanged.setAccessible(true); } catch (NoSuchMethodException ignored) { } try { ensureImeVisible = AutoCompleteTextView.class .getMethod("ensureImeVisible", boolean.class); ensureImeVisible.setAccessible(true); } catch (NoSuchMethodException ignored) { } try { showSoftInputUnchecked = InputMethodManager.class.getMethod( "showSoftInputUnchecked", int.class, ResultReceiver.class); showSoftInputUnchecked.setAccessible(true); } catch (NoSuchMethodException ignored) { } } void doBeforeTextChanged(AutoCompleteTextView view) { if (doBeforeTextChanged != null) { try { doBeforeTextChanged.invoke(view); } catch (Exception ignored) { } } } void doAfterTextChanged(AutoCompleteTextView view) { if (doAfterTextChanged != null) { try { doAfterTextChanged.invoke(view); } catch (Exception ignored) { } } } void ensureImeVisible(AutoCompleteTextView view, boolean visible) { if (ensureImeVisible != null) { try { ensureImeVisible.invoke(view, visible); } catch (Exception ignored) { } } } void showSoftInputUnchecked(InputMethodManager imm, View view, int flags) { if (showSoftInputUnchecked != null) { try { showSoftInputUnchecked.invoke(imm, flags, null); return; } catch (Exception ignored) { } } imm.showSoftInput(view, flags); } } }
package me.devsaki.hentoid.views.ssiv; import android.content.ContentResolver; import android.content.Context; import android.content.res.TypedArray; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.Point; import android.graphics.PointF; import android.graphics.Rect; import android.graphics.RectF; import android.net.Uri; import android.os.AsyncTask; import android.os.Handler; import android.os.Message; import android.provider.MediaStore; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.util.TypedValue; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.View; import android.view.ViewParent; import androidx.annotation.AnyThread; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.exifinterface.media.ExifInterface; import com.davemorrissey.labs.subscaleview.ImageViewState; import com.davemorrissey.labs.subscaleview.R.styleable; import com.davemorrissey.labs.subscaleview.decoder.CompatDecoderFactory; import com.davemorrissey.labs.subscaleview.decoder.DecoderFactory; import com.davemorrissey.labs.subscaleview.decoder.ImageDecoder; import com.davemorrissey.labs.subscaleview.decoder.ImageRegionDecoder; import com.davemorrissey.labs.subscaleview.decoder.SkiaImageDecoder; import com.davemorrissey.labs.subscaleview.decoder.SkiaImageRegionDecoder; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.concurrent.Executor; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import me.devsaki.hentoid.R; import timber.log.Timber; @SuppressWarnings("unused") public class CustomSubsamplingScaleImageView extends View { private static final String TAG = CustomSubsamplingScaleImageView.class.getSimpleName(); /** * Attempt to use EXIF information on the image to rotate it. Works for external files only. */ public static final int ORIENTATION_USE_EXIF = -1; /** * Display the image file in its native orientation. */ public static final int ORIENTATION_0 = 0; /** * Rotate the image 90 degrees clockwise. */ public static final int ORIENTATION_90 = 90; /** * Rotate the image 180 degrees. */ public static final int ORIENTATION_180 = 180; /** * Rotate the image 270 degrees clockwise. */ public static final int ORIENTATION_270 = 270; private static final List<Integer> VALID_ORIENTATIONS = Arrays.asList(ORIENTATION_0, ORIENTATION_90, ORIENTATION_180, ORIENTATION_270, ORIENTATION_USE_EXIF); /** * During zoom animation, keep the point of the image that was tapped in the same place, and scale the image around it. */ public static final int ZOOM_FOCUS_FIXED = 1; /** * During zoom animation, move the point of the image that was tapped to the center of the screen. */ public static final int ZOOM_FOCUS_CENTER = 2; /** * Zoom in to and center the tapped point immediately without animating. */ public static final int ZOOM_FOCUS_CENTER_IMMEDIATE = 3; private static final List<Integer> VALID_ZOOM_STYLES = Arrays.asList(ZOOM_FOCUS_FIXED, ZOOM_FOCUS_CENTER, ZOOM_FOCUS_CENTER_IMMEDIATE); /** * Quadratic ease out. Not recommended for scale animation, but good for panning. */ public static final int EASE_OUT_QUAD = 1; /** * Quadratic ease in and out. */ public static final int EASE_IN_OUT_QUAD = 2; private static final List<Integer> VALID_EASING_STYLES = Arrays.asList(EASE_IN_OUT_QUAD, EASE_OUT_QUAD); /** * Don't allow the image to be panned off screen. As much of the image as possible is always displayed, centered in the view when it is smaller. This is the best option for galleries. */ public static final int PAN_LIMIT_INSIDE = 1; /** * Allows the image to be panned until it is just off screen, but no further. The edge of the image will stop when it is flush with the screen edge. */ public static final int PAN_LIMIT_OUTSIDE = 2; /** * Allows the image to be panned until a corner reaches the center of the screen but no further. Useful when you want to pan any spot on the image to the exact center of the screen. */ public static final int PAN_LIMIT_CENTER = 3; private static final List<Integer> VALID_PAN_LIMITS = Arrays.asList(PAN_LIMIT_INSIDE, PAN_LIMIT_OUTSIDE, PAN_LIMIT_CENTER); /** * Scale the image so that both dimensions of the image will be equal to or less than the corresponding dimension of the view. The image is then centered in the view. This is the default behaviour and best for galleries. */ public static final int SCALE_TYPE_CENTER_INSIDE = 1; /** * Scale the image uniformly so that both dimensions of the image will be equal to or larger than the corresponding dimension of the view. The image is then centered in the view. */ public static final int SCALE_TYPE_CENTER_CROP = 2; /** * Scale the image so that both dimensions of the image will be equal to or less than the maxScale and equal to or larger than minScale. The image is then centered in the view. */ public static final int SCALE_TYPE_CUSTOM = 3; /** * Scale the image so that both dimensions of the image will be equal to or larger than the corresponding dimension of the view. The top left is shown. */ public static final int SCALE_TYPE_START = 4; private static final List<Integer> VALID_SCALE_TYPES = Arrays.asList(SCALE_TYPE_CENTER_CROP, SCALE_TYPE_CENTER_INSIDE, SCALE_TYPE_CUSTOM, SCALE_TYPE_START); /** * State change originated from animation. */ public static final int ORIGIN_ANIM = 1; /** * State change originated from touch gesture. */ public static final int ORIGIN_TOUCH = 2; /** * State change originated from a fling momentum anim. */ public static final int ORIGIN_FLING = 3; /** * State change originated from a double tap zoom anim. */ public static final int ORIGIN_DOUBLE_TAP_ZOOM = 4; /** * State change originated from a long tap zoom anim. */ public static final int ORIGIN_LONG_TAP_ZOOM = 5; private static final String ANIMATION_LISTENER_ERROR = "Error thrown by animation listener"; // Bitmap (preview or full image) private Bitmap bitmap; // Whether the bitmap is a preview image private boolean bitmapIsPreview; // Specifies if a cache handler is also referencing the bitmap. Do not recycle if so. private boolean bitmapIsCached; // Uri of full size image private Uri uri; // Sample size used to display the whole image when fully zoomed out private int fullImageSampleSize; // Map of zoom level to tile grid private Map<Integer, List<Tile>> tileMap; // Overlay tile boundaries and other info private boolean debug; // Image orientation setting private int orientation = ORIENTATION_0; // Max scale allowed (prevent infinite zoom) private float maxScale = 2F; // Min scale allowed (prevent infinite zoom) private float minScale = minScale(); // Density to reach before loading higher resolution tiles private int minimumTileDpi = -1; // Pan limiting style private int panLimit = PAN_LIMIT_INSIDE; // Minimum scale type private int minimumScaleType = SCALE_TYPE_CENTER_INSIDE; // overrides for the dimensions of the generated tiles public static final int TILE_SIZE_AUTO = Integer.MAX_VALUE; private int maxTileWidth = TILE_SIZE_AUTO; private int maxTileHeight = TILE_SIZE_AUTO; // An executor service for loading of images private Executor executor = AsyncTask.THREAD_POOL_EXECUTOR; // Whether tiles should be loaded while gestures and animations are still in progress private boolean eagerLoadingEnabled = true; // Gesture detection settings private boolean panEnabled = true; private boolean zoomEnabled = true; private boolean quickScaleEnabled = true; private boolean longTapZoomEnabled = true; // Double tap zoom behaviour private float doubleTapZoomScale = 1F; private int doubleTapZoomStyle = ZOOM_FOCUS_FIXED; private int doubleTapZoomDuration = 500; // Current scale and scale at start of zoom private float scale; private float scaleStart; // Screen coordinate of top-left corner of source image private PointF vTranslate; private PointF vTranslateStart; private PointF vTranslateBefore; // Source coordinate to center on, used when new position is set externally before view is ready private Float pendingScale; private PointF sPendingCenter; private PointF sRequestedCenter; // Source image dimensions and orientation - dimensions relate to the unrotated image private int sWidth; private int sHeight; private int sOrientation; private Rect sRegion; private Rect pRegion; // Is two-finger zooming in progress private boolean isZooming; // Is one-finger panning in progress private boolean isPanning; // Is quick-scale gesture in progress private boolean isQuickScaling; // Is long tap zoom in progress private boolean isLongTapZooming; // Max touches used in current gesture private int maxTouchCount; // Fling detector private GestureDetector detector; private GestureDetector singleDetector; // Tile and image decoding private ImageRegionDecoder decoder; private final ReadWriteLock decoderLock = new ReentrantReadWriteLock(true); private DecoderFactory<? extends ImageDecoder> bitmapDecoderFactory = new CompatDecoderFactory<>(SkiaImageDecoder.class); private DecoderFactory<? extends ImageRegionDecoder> regionDecoderFactory = new CompatDecoderFactory<>(SkiaImageRegionDecoder.class); // Debug values private PointF vCenterStart; private float vDistStart; // Current quickscale state private final float quickScaleThreshold; private float quickScaleLastDistance; private boolean quickScaleMoved; private PointF quickScaleVLastPoint; private PointF quickScaleSCenter; private PointF quickScaleVStart; // Scale and center animation tracking private Anim anim; // Whether a ready notification has been sent to subclasses private boolean readySent; // Whether a base layer loaded notification has been sent to subclasses private boolean imageLoadedSent; // Event listener private OnImageEventListener onImageEventListener; // Scale and center listener private OnStateChangedListener onStateChangedListener; // Long click listener private OnLongClickListener onLongClickListener; // Long click handler private final Handler handler; private static final int MESSAGE_LONG_CLICK = 1; private Paint bitmapPaint; private Paint debugTextPaint; private Paint debugLinePaint; private Paint tileBgPaint; // Volatile fields used to reduce object creation private ScaleAndTranslate satTemp; private Matrix matrix; private RectF sRect; private final float[] srcArray = new float[8]; private final float[] dstArray = new float[8]; //The logical density of the display private final float density; // A global preference for bitmap format, available to decoder classes that respect it private static Bitmap.Config preferredBitmapConfig; // Switch to ignore all touch events (used in vertical mode when the container view is the one handling touch events) private boolean ignoreTouchEvents = false; // Dimensions used to preload the image before the view actually appears on screen / gets its display dimensions private Point preloadDimensions = null; public CustomSubsamplingScaleImageView(Context context, AttributeSet attr) { super(context, attr); density = getResources().getDisplayMetrics().density; setMinimumDpi(160); setDoubleTapZoomDpi(160); setMinimumTileDpi(320); setGestureDetector(context); this.handler = new Handler(message -> { if (message.what == MESSAGE_LONG_CLICK) { if (onLongClickListener != null) { maxTouchCount = 0; CustomSubsamplingScaleImageView.super.setOnLongClickListener(onLongClickListener); performLongClick(); CustomSubsamplingScaleImageView.super.setOnLongClickListener(null); } if (longTapZoomEnabled) longTapZoom(message.arg1, message.arg2); } return true; }); // Handle XML attributes if (attr != null) { TypedArray typedAttr = getContext().obtainStyledAttributes(attr, R.styleable.CustomSubsamplingScaleImageView); if (typedAttr.hasValue(styleable.SubsamplingScaleImageView_assetName)) { String assetName = typedAttr.getString(styleable.SubsamplingScaleImageView_assetName); if (assetName != null && assetName.length() > 0) { setImage(ImageSource.asset(assetName).tilingEnabled()); } } if (typedAttr.hasValue(styleable.SubsamplingScaleImageView_src)) { int resId = typedAttr.getResourceId(styleable.SubsamplingScaleImageView_src, 0); if (resId > 0) { setImage(ImageSource.resource(resId).tilingEnabled()); } } if (typedAttr.hasValue(styleable.SubsamplingScaleImageView_panEnabled)) { setPanEnabled(typedAttr.getBoolean(styleable.SubsamplingScaleImageView_panEnabled, true)); } if (typedAttr.hasValue(styleable.SubsamplingScaleImageView_zoomEnabled)) { setZoomEnabled(typedAttr.getBoolean(styleable.SubsamplingScaleImageView_zoomEnabled, true)); } if (typedAttr.hasValue(styleable.SubsamplingScaleImageView_quickScaleEnabled)) { setQuickScaleEnabled(typedAttr.getBoolean(styleable.SubsamplingScaleImageView_quickScaleEnabled, true)); } if (typedAttr.hasValue(styleable.SubsamplingScaleImageView_tileBackgroundColor)) { setTileBackgroundColor(typedAttr.getColor(styleable.SubsamplingScaleImageView_tileBackgroundColor, Color.argb(0, 0, 0, 0))); } typedAttr.recycle(); } quickScaleThreshold = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, context.getResources().getDisplayMetrics()); } public CustomSubsamplingScaleImageView(Context context) { this(context, null); } /** * Get the current preferred configuration for decoding bitmaps. {@link ImageDecoder} and {@link ImageRegionDecoder} * instances can read this and use it when decoding images. * * @return the preferred bitmap configuration, or null if none has been set. */ public static Bitmap.Config getPreferredBitmapConfig() { return preferredBitmapConfig; } /** * Set a global preferred bitmap config shared by all view instance and applied to new instances * initialised after the call is made. This is a hint only; the bundled {@link ImageDecoder} and * {@link ImageRegionDecoder} classes all respect this (except when they were constructed with * an instance-specific config) but custom decoder classes will not. * * @param preferredBitmapConfig the bitmap configuration to be used by future instances of the view. Pass null to restore the default. */ public static void setPreferredBitmapConfig(Bitmap.Config preferredBitmapConfig) { CustomSubsamplingScaleImageView.preferredBitmapConfig = preferredBitmapConfig; } /** * Sets the image orientation. It's best to call this before setting the image file or asset, because it may waste * loading of tiles. However, this can be freely called at any time. * * @param orientation orientation to be set. See ORIENTATION_ static fields for valid values. */ public final void setOrientation(int orientation) { if (!VALID_ORIENTATIONS.contains(orientation)) { throw new IllegalArgumentException("Invalid orientation: " + orientation); } this.orientation = orientation; reset(false); invalidate(); requestLayout(); } /** * Set the image source from a bitmap, resource, asset, file or other URI. * * @param imageSource Image source. */ public final void setImage(@NonNull ImageSource imageSource) { setImage(imageSource, null, null); } /** * Set the image source from a bitmap, resource, asset, file or other URI, starting with a given orientation * setting, scale and center. This is the best method to use when you want scale and center to be restored * after screen orientation change; it avoids any redundant loading of tiles in the wrong orientation. * * @param imageSource Image source. * @param state State to be restored. Nullable. */ public final void setImage(@NonNull ImageSource imageSource, ImageViewState state) { setImage(imageSource, null, state); } /** * Set the image source from a bitmap, resource, asset, file or other URI, providing a preview image to be * displayed until the full size image is loaded. * <p> * You must declare the dimensions of the full size image by calling {@link ImageSource#dimensions(int, int)} * on the imageSource object. The preview source will be ignored if you don't provide dimensions, * and if you provide a bitmap for the full size image. * * @param imageSource Image source. Dimensions must be declared. * @param previewSource Optional source for a preview image to be displayed and allow interaction while the full size image loads. */ public final void setImage(@NonNull ImageSource imageSource, ImageSource previewSource) { setImage(imageSource, previewSource, null); } /** * Set the image source from a bitmap, resource, asset, file or other URI, providing a preview image to be * displayed until the full size image is loaded, starting with a given orientation setting, scale and center. * This is the best method to use when you want scale and center to be restored after screen orientation change; * it avoids any redundant loading of tiles in the wrong orientation. * <p> * You must declare the dimensions of the full size image by calling {@link ImageSource#dimensions(int, int)} * on the imageSource object. The preview source will be ignored if you don't provide dimensions, * and if you provide a bitmap for the full size image. * * @param imageSource Image source. Dimensions must be declared. * @param previewSource Optional source for a preview image to be displayed and allow interaction while the full size image loads. * @param state State to be restored. Nullable. */ public final void setImage(@NonNull ImageSource imageSource, ImageSource previewSource, ImageViewState state) { reset(true); if (state != null) { restoreState(state); } if (previewSource != null) { if (imageSource.getBitmap() != null) { throw new IllegalArgumentException("Preview image cannot be used when a bitmap is provided for the main image"); } if (imageSource.getSWidth() <= 0 || imageSource.getSHeight() <= 0) { throw new IllegalArgumentException("Preview image cannot be used unless dimensions are provided for the main image"); } this.sWidth = imageSource.getSWidth(); this.sHeight = imageSource.getSHeight(); this.pRegion = previewSource.getSRegion(); if (previewSource.getBitmap() != null) { this.bitmapIsCached = previewSource.isCached(); onPreviewLoaded(previewSource.getBitmap()); } else { Uri uri = previewSource.getUri(); if (uri == null && previewSource.getResource() != null) { uri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getContext().getPackageName() + "/" + previewSource.getResource()); } BitmapLoadTask task = new BitmapLoadTask(this, getContext(), bitmapDecoderFactory, uri, true); execute(task); } } if (imageSource.getBitmap() != null && imageSource.getSRegion() != null) { onImageLoaded(Bitmap.createBitmap(imageSource.getBitmap(), imageSource.getSRegion().left, imageSource.getSRegion().top, imageSource.getSRegion().width(), imageSource.getSRegion().height()), ORIENTATION_0, false); } else if (imageSource.getBitmap() != null) { onImageLoaded(imageSource.getBitmap(), ORIENTATION_0, imageSource.isCached()); } else { sRegion = imageSource.getSRegion(); uri = imageSource.getUri(); if (uri == null && imageSource.getResource() != null) { uri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getContext().getPackageName() + "/" + imageSource.getResource()); } if (imageSource.getTile() || sRegion != null) { // Load the bitmap using tile decoding. TilesInitTask task = new TilesInitTask(this, getContext(), regionDecoderFactory, uri); execute(task); } else { // Load the bitmap as a single image. BitmapLoadTask task = new BitmapLoadTask(this, getContext(), bitmapDecoderFactory, uri, false); execute(task); } } } /** * Reset all state before setting/changing image or setting new rotation. */ private void reset(boolean newImage) { debug("reset newImage=" + newImage); scale = 0f; scaleStart = 0f; vTranslate = null; vTranslateStart = null; vTranslateBefore = null; pendingScale = 0f; sPendingCenter = null; sRequestedCenter = null; isZooming = false; isPanning = false; isQuickScaling = false; isLongTapZooming = false; maxTouchCount = 0; fullImageSampleSize = 0; vCenterStart = null; vDistStart = 0; quickScaleLastDistance = 0f; quickScaleMoved = false; quickScaleSCenter = null; quickScaleVLastPoint = null; quickScaleVStart = null; anim = null; satTemp = null; matrix = null; sRect = null; if (newImage) { uri = null; decoderLock.writeLock().lock(); try { if (decoder != null) { decoder.recycle(); decoder = null; } } finally { decoderLock.writeLock().unlock(); } if (bitmap != null && !bitmapIsCached) { bitmap.recycle(); } if (bitmap != null && bitmapIsCached && onImageEventListener != null) { onImageEventListener.onPreviewReleased(); } sWidth = 0; sHeight = 0; sOrientation = 0; sRegion = null; pRegion = null; readySent = false; imageLoadedSent = false; bitmap = null; bitmapIsPreview = false; bitmapIsCached = false; } if (tileMap != null) { for (Map.Entry<Integer, List<Tile>> tileMapEntry : tileMap.entrySet()) { for (Tile tile : tileMapEntry.getValue()) { tile.visible = false; if (tile.bitmap != null) { tile.bitmap.recycle(); tile.bitmap = null; } } } tileMap = null; } setGestureDetector(getContext()); } private void setGestureDetector(final Context context) { this.detector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() { @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { if (panEnabled && readySent && vTranslate != null && e1 != null && e2 != null && (Math.abs(e1.getX() - e2.getX()) > 50 || Math.abs(e1.getY() - e2.getY()) > 50) && (Math.abs(velocityX) > 500 || Math.abs(velocityY) > 500) && !isZooming) { PointF vTranslateEnd = new PointF(vTranslate.x + (velocityX * 0.25f), vTranslate.y + (velocityY * 0.25f)); float sCenterXEnd = ((getWidthInternal() / 2f) - vTranslateEnd.x) / scale; float sCenterYEnd = ((getHeightInternal() / 2f) - vTranslateEnd.y) / scale; new AnimationBuilder(new PointF(sCenterXEnd, sCenterYEnd)).withEasing(EASE_OUT_QUAD).withPanLimited(false).withOrigin(ORIGIN_FLING).start(); return true; } return super.onFling(e1, e2, velocityX, velocityY); } @Override public boolean onSingleTapConfirmed(MotionEvent e) { performClick(); return true; } @Override public boolean onDoubleTap(MotionEvent e) { if (zoomEnabled && readySent && vTranslate != null) { // Hacky solution for #15 - after a double tap the GestureDetector gets in a state // where the next fling is ignored, so here we replace it with a new one. setGestureDetector(context); if (quickScaleEnabled) { // Store quick scale params. This will become either a double tap zoom or a // quick scale depending on whether the user swipes. vCenterStart = new PointF(e.getX(), e.getY()); vTranslateStart = new PointF(vTranslate.x, vTranslate.y); scaleStart = scale; isQuickScaling = true; isZooming = true; quickScaleLastDistance = -1F; quickScaleSCenter = viewToSourceCoord(vCenterStart); if (null == quickScaleSCenter) throw new IllegalStateException("vTranslate is null; aborting"); quickScaleVStart = new PointF(e.getX(), e.getY()); quickScaleVLastPoint = new PointF(quickScaleSCenter.x, quickScaleSCenter.y); quickScaleMoved = false; // We need to get events in onTouchEvent after this. return false; } else { // Start double tap zoom animation. PointF sCenter = viewToSourceCoord(new PointF(e.getX(), e.getY())); if (null == sCenter) throw new IllegalStateException("vTranslate is null; aborting"); doubleTapZoom(sCenter, new PointF(e.getX(), e.getY())); return true; } } return super.onDoubleTapEvent(e); } }); singleDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() { @Override public boolean onSingleTapConfirmed(MotionEvent e) { performClick(); return true; } }); } public void longTapZoom(int x, int y) { if (zoomEnabled && longTapZoomEnabled && readySent && vTranslate != null) { isPanning = true; vCenterStart = new PointF(x, y); vTranslateStart = new PointF(vTranslate.x, vTranslate.y); PointF sCenter = viewToSourceCoord(new PointF(x, y)); if (null == sCenter) throw new IllegalStateException("vTranslate is null; aborting"); float doubleTapZoomScale = Math.min(maxScale, this.doubleTapZoomScale); // TODO factorize new AnimationBuilder(doubleTapZoomScale, vCenterStart).withInterruptible(false).withDuration(doubleTapZoomDuration).withOrigin(ORIGIN_LONG_TAP_ZOOM).start(); isLongTapZooming = true; float vLeftStart = vCenterStart.x - vTranslateStart.x; float vTopStart = vCenterStart.y - vTranslateStart.y; float vLeftNow = vLeftStart * doubleTapZoomScale; float vTopNow = vTopStart * doubleTapZoomScale; vTranslate.x = vCenterStart.x - vLeftNow; vTranslate.y = vCenterStart.y - vTopNow; vTranslateStart.set(vTranslate); } } /** * On resize, preserve center and scale. Various behaviours are possible, override this method to use another. */ @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { debug("onSizeChanged %dx%d -> %dx%d", oldw, oldh, w, h); PointF sCenter = getCenter(); if (readySent && sCenter != null) { this.anim = null; this.pendingScale = scale; this.sPendingCenter = sCenter; } } /** * Measures the width and height of the view, preserving the aspect ratio of the image displayed if wrap_content is * used. The image will scale within this box, not resizing the view as it is zoomed. */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec); int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec); int parentWidth = MeasureSpec.getSize(widthMeasureSpec); int parentHeight = MeasureSpec.getSize(heightMeasureSpec); boolean resizeWidth = widthSpecMode != MeasureSpec.EXACTLY; boolean resizeHeight = heightSpecMode != MeasureSpec.EXACTLY; int width = parentWidth; int height = parentHeight; if (sWidth > 0 && sHeight > 0) { if (resizeWidth && resizeHeight) { width = sWidth(); height = sHeight(); } else if (resizeHeight) { height = (int) (((double) sHeight() / (double) sWidth()) * width); } else if (resizeWidth) { width = (int) (((double) sWidth() / (double) sHeight()) * height); } } width = Math.max(width, getSuggestedMinimumWidth()); height = Math.max(height, getSuggestedMinimumHeight()); setMeasuredDimension(width, height); } public void setIgnoreTouchEvents(boolean ignoreTouchEvents) { this.ignoreTouchEvents = ignoreTouchEvents; } /** * Handle touch events. One finger pans, and two finger pinch and zoom plus panning. */ @Override public boolean onTouchEvent(@NonNull MotionEvent event) { if (ignoreTouchEvents) return false; // During non-interruptible anims, ignore all touch events if (anim != null && !anim.interruptible) { requestDisallowInterceptTouchEvent(true); return true; } else { if (anim != null && anim.listener != null) { try { anim.listener.onInterruptedByUser(); } catch (Exception e) { Timber.tag(TAG).w(e, ANIMATION_LISTENER_ERROR); } } anim = null; } // Abort if not ready if (vTranslate == null) { if (singleDetector != null) { singleDetector.onTouchEvent(event); } return true; } // Detect flings, taps and double taps if (!isQuickScaling && (detector == null || detector.onTouchEvent(event))) { isZooming = false; isPanning = false; maxTouchCount = 0; return true; } if (vTranslateStart == null) { vTranslateStart = new PointF(0, 0); } if (vTranslateBefore == null) { vTranslateBefore = new PointF(0, 0); } if (vCenterStart == null) { vCenterStart = new PointF(0, 0); } // Store current values so we can send an event if they change float scaleBefore = scale; vTranslateBefore.set(vTranslate); boolean handled = onTouchEventInternal(event); sendStateChanged(scaleBefore, vTranslateBefore, ORIGIN_TOUCH); return handled || super.onTouchEvent(event); } @SuppressWarnings({"deprecation", "squid:CallToDeprecatedMethod"}) private boolean onTouchEventInternal(@NonNull MotionEvent event) { int touchCount = event.getPointerCount(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_POINTER_1_DOWN: case MotionEvent.ACTION_POINTER_2_DOWN: anim = null; requestDisallowInterceptTouchEvent(true); maxTouchCount = Math.max(maxTouchCount, touchCount); if (touchCount >= 2) { if (zoomEnabled) { // Start pinch to zoom. Calculate distance between touch points and center point of the pinch. float distance = distance(event.getX(0), event.getX(1), event.getY(0), event.getY(1)); scaleStart = scale; vDistStart = distance; vTranslateStart.set(vTranslate.x, vTranslate.y); vCenterStart.set((event.getX(0) + event.getX(1)) / 2, (event.getY(0) + event.getY(1)) / 2); } else { // Abort all gestures on second touch maxTouchCount = 0; } // Cancel long click timer handler.removeMessages(MESSAGE_LONG_CLICK); } else if (!isQuickScaling) { // Start one-finger pan vTranslateStart.set(vTranslate.x, vTranslate.y); vCenterStart.set(event.getX(), event.getY()); // Start long click timer Message m = new Message(); m.what = MESSAGE_LONG_CLICK; m.arg1 = Math.round(event.getX()); m.arg2 = Math.round(event.getY()); handler.sendMessageDelayed(m, 500); } return true; case MotionEvent.ACTION_MOVE: boolean consumed = false; if (maxTouchCount > 0) { if (touchCount >= 2) { // Calculate new distance between touch points, to scale and pan relative to start values. float vDistEnd = distance(event.getX(0), event.getX(1), event.getY(0), event.getY(1)); float vCenterEndX = (event.getX(0) + event.getX(1)) / 2; float vCenterEndY = (event.getY(0) + event.getY(1)) / 2; if (zoomEnabled && (distance(vCenterStart.x, vCenterEndX, vCenterStart.y, vCenterEndY) > 5 || Math.abs(vDistEnd - vDistStart) > 5 || isPanning)) { isZooming = true; isPanning = true; consumed = true; double previousScale = scale; scale = Math.min(maxScale, (vDistEnd / vDistStart) * scaleStart); if (scale <= minScale()) { // Minimum scale reached so don't pan. Adjust start settings so any expand will zoom in. vDistStart = vDistEnd; scaleStart = minScale(); vCenterStart.set(vCenterEndX, vCenterEndY); vTranslateStart.set(vTranslate); } else if (panEnabled) { // Translate to place the source image coordinate that was at the center of the pinch at the start // at the center of the pinch now, to give simultaneous pan + zoom. float vLeftStart = vCenterStart.x - vTranslateStart.x; float vTopStart = vCenterStart.y - vTranslateStart.y; float vLeftNow = vLeftStart * (scale / scaleStart); float vTopNow = vTopStart * (scale / scaleStart); vTranslate.x = vCenterEndX - vLeftNow; vTranslate.y = vCenterEndY - vTopNow; if ((previousScale * sHeight() < getHeightInternal() && scale * sHeight() >= getHeightInternal()) || (previousScale * sWidth() < getWidthInternal() && scale * sWidth() >= getWidthInternal())) { fitToBounds(true); vCenterStart.set(vCenterEndX, vCenterEndY); vTranslateStart.set(vTranslate); scaleStart = scale; vDistStart = vDistEnd; } } else if (sRequestedCenter != null) { // With a center specified from code, zoom around that point. vTranslate.x = (getWidthInternal() / 2f) - (scale * sRequestedCenter.x); vTranslate.y = (getHeightInternal() / 2f) - (scale * sRequestedCenter.y); } else { // With no requested center, scale around the image center. vTranslate.x = (getWidthInternal() / 2f) - (scale * (sWidth() / 2f)); vTranslate.y = (getHeightInternal() / 2f) - (scale * (sHeight() / 2f)); } fitToBounds(true); refreshRequiredTiles(eagerLoadingEnabled); } } else if (isQuickScaling) { // One finger zoom float dist = Math.abs(quickScaleVStart.y - event.getY()) * 2 + quickScaleThreshold; if (quickScaleLastDistance == -1f) { quickScaleLastDistance = dist; } boolean isUpwards = event.getY() > quickScaleVLastPoint.y; quickScaleVLastPoint.set(0, event.getY()); float spanDiff = Math.abs(1 - (dist / quickScaleLastDistance)) * 0.5f; if (spanDiff > 0.03f || quickScaleMoved) { quickScaleMoved = true; float multiplier = 1; if (quickScaleLastDistance > 0) { multiplier = isUpwards ? (1 + spanDiff) : (1 - spanDiff); } double previousScale = scale; scale = Math.max(minScale(), Math.min(maxScale, scale * multiplier)); if (panEnabled) { float vLeftStart = vCenterStart.x - vTranslateStart.x; float vTopStart = vCenterStart.y - vTranslateStart.y; float vLeftNow = vLeftStart * (scale / scaleStart); float vTopNow = vTopStart * (scale / scaleStart); vTranslate.x = vCenterStart.x - vLeftNow; vTranslate.y = vCenterStart.y - vTopNow; if ((previousScale * sHeight() < getHeightInternal() && scale * sHeight() >= getHeightInternal()) || (previousScale * sWidth() < getWidthInternal() && scale * sWidth() >= getWidthInternal())) { fitToBounds(true); vCenterStart.set(sourceToViewCoord(quickScaleSCenter)); vTranslateStart.set(vTranslate); scaleStart = scale; dist = 0; } } else if (sRequestedCenter != null) { // With a center specified from code, zoom around that point. vTranslate.x = (getWidthInternal() / 2f) - (scale * sRequestedCenter.x); vTranslate.y = (getHeightInternal() / 2f) - (scale * sRequestedCenter.y); } else { // With no requested center, scale around the image center. vTranslate.x = (getWidthInternal() / 2f) - (scale * (sWidth() / 2f)); vTranslate.y = (getHeightInternal() / 2f) - (scale * (sHeight() / 2f)); } } quickScaleLastDistance = dist; fitToBounds(true); refreshRequiredTiles(eagerLoadingEnabled); consumed = true; } else if (!isZooming) { // One finger pan - translate the image. We do this calculation even with pan disabled so click // and long click behaviour is preserved. float dx = Math.abs(event.getX() - vCenterStart.x); float dy = Math.abs(event.getY() - vCenterStart.y); //On the Samsung S6 long click event does not work, because the dx > 5 usually true float offset = density * 5; if (dx > offset || dy > offset || isPanning) { consumed = true; vTranslate.x = vTranslateStart.x + (event.getX() - vCenterStart.x); vTranslate.y = vTranslateStart.y + (event.getY() - vCenterStart.y); float lastX = vTranslate.x; float lastY = vTranslate.y; fitToBounds(true); boolean atXEdge = lastX != vTranslate.x; boolean atYEdge = lastY != vTranslate.y; boolean edgeXSwipe = atXEdge && dx > dy && !isPanning; boolean edgeYSwipe = atYEdge && dy > dx && !isPanning; boolean yPan = lastY == vTranslate.y && dy > offset * 3; if (!edgeXSwipe && !edgeYSwipe && (!atXEdge || !atYEdge || yPan || isPanning)) { isPanning = true; } else if (dx > offset || dy > offset) { // Haven't panned the image, and we're at the left or right edge. Switch to page swipe. maxTouchCount = 0; handler.removeMessages(MESSAGE_LONG_CLICK); requestDisallowInterceptTouchEvent(false); } if (!panEnabled) { vTranslate.x = vTranslateStart.x; vTranslate.y = vTranslateStart.y; requestDisallowInterceptTouchEvent(false); } refreshRequiredTiles(eagerLoadingEnabled); } } } if (consumed) { handler.removeMessages(MESSAGE_LONG_CLICK); invalidate(); return true; } break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: case MotionEvent.ACTION_POINTER_2_UP: handler.removeMessages(MESSAGE_LONG_CLICK); if (isQuickScaling) { isQuickScaling = false; if (!quickScaleMoved) { doubleTapZoom(quickScaleSCenter, vCenterStart); } } if (maxTouchCount > 0 && (isZooming || isPanning)) { if (isZooming && touchCount == 2) { // Convert from zoom to pan with remaining touch isPanning = true; vTranslateStart.set(vTranslate.x, vTranslate.y); if (event.getActionIndex() == 1) { vCenterStart.set(event.getX(0), event.getY(0)); } else { vCenterStart.set(event.getX(1), event.getY(1)); } } if (touchCount < 3) { // End zooming when only one touch point isZooming = false; } if (touchCount < 2) { // End panning when no touch points isPanning = false; maxTouchCount = 0; } if (isLongTapZooming) { isLongTapZooming = false; resetScaleAndCenter(); } // Trigger load of tiles now required refreshRequiredTiles(true); return true; } if (touchCount == 1) { isZooming = false; isPanning = false; maxTouchCount = 0; if (isLongTapZooming) { isLongTapZooming = false; resetScaleAndCenter(); } } return true; } return false; } private void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { ViewParent parent = getParent(); if (parent != null) { parent.requestDisallowInterceptTouchEvent(disallowIntercept); } } /** * Double tap zoom handler triggered from gesture detector or on touch, depending on whether * quick scale is enabled. */ private void doubleTapZoom(PointF sCenter, PointF vFocus) { if (!panEnabled) { if (sRequestedCenter != null) { // With a center specified from code, zoom around that point. sCenter.x = sRequestedCenter.x; sCenter.y = sRequestedCenter.y; } else { // With no requested center, scale around the image center. sCenter.x = sWidth() / 2f; sCenter.y = sHeight() / 2f; } } float doubleTapZoomScale = Math.min(maxScale, this.doubleTapZoomScale); boolean zoomIn = (scale <= doubleTapZoomScale * 0.9) || scale == minScale; float targetScale = zoomIn ? doubleTapZoomScale : minScale(); if (doubleTapZoomStyle == ZOOM_FOCUS_CENTER_IMMEDIATE) { setScaleAndCenter(targetScale, sCenter); } else if (doubleTapZoomStyle == ZOOM_FOCUS_CENTER || !zoomIn || !panEnabled) { new AnimationBuilder(targetScale, sCenter).withInterruptible(false).withDuration(doubleTapZoomDuration).withOrigin(ORIGIN_DOUBLE_TAP_ZOOM).start(); } else if (doubleTapZoomStyle == ZOOM_FOCUS_FIXED) { new AnimationBuilder(targetScale, sCenter, vFocus).withInterruptible(false).withDuration(doubleTapZoomDuration).withOrigin(ORIGIN_DOUBLE_TAP_ZOOM).start(); } invalidate(); } /** * Draw method should not be called until the view has dimensions so the first calls are used as triggers to calculate * the scaling and tiling required. Once the view is setup, tiles are displayed as they are loaded. */ @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); createPaints(); // If image or view dimensions are not known yet, abort. if (sWidth == 0 || sHeight == 0 || getWidthInternal() == 0 || getHeightInternal() == 0) { return; } // When using tiles, on first render with no tile map ready, initialise it and kick off async base image loading. if (tileMap == null && decoder != null) { initialiseBaseLayer(getMaxBitmapDimensions(canvas)); } // If image has been loaded or supplied as a bitmap, onDraw may be the first time the view has // dimensions and therefore the first opportunity to set scale and translate. If this call returns // false there is nothing to be drawn so return immediately. if (!checkReady()) { return; } // Set scale and translate before draw. preDraw(); // If animating scale, calculate current scale and center with easing equations if (anim != null && anim.vFocusStart != null) { // Store current values so we can send an event if they change float scaleBefore = scale; if (vTranslateBefore == null) { vTranslateBefore = new PointF(0, 0); } vTranslateBefore.set(vTranslate); long scaleElapsed = System.currentTimeMillis() - anim.time; boolean finished = scaleElapsed > anim.duration; scaleElapsed = Math.min(scaleElapsed, anim.duration); scale = ease(anim.easing, scaleElapsed, anim.scaleStart, anim.scaleEnd - anim.scaleStart, anim.duration); // Apply required animation to the focal point float vFocusNowX = ease(anim.easing, scaleElapsed, anim.vFocusStart.x, anim.vFocusEnd.x - anim.vFocusStart.x, anim.duration); float vFocusNowY = ease(anim.easing, scaleElapsed, anim.vFocusStart.y, anim.vFocusEnd.y - anim.vFocusStart.y, anim.duration); // Find out where the focal point is at this scale and adjust its position to follow the animation path vTranslate.x -= sourceToViewX(anim.sCenterEnd.x) - vFocusNowX; vTranslate.y -= sourceToViewY(anim.sCenterEnd.y) - vFocusNowY; // For translate anims, showing the image non-centered is never allowed, for scaling anims it is during the animation. fitToBounds(finished || (anim.scaleStart == anim.scaleEnd)); sendStateChanged(scaleBefore, vTranslateBefore, anim.origin); refreshRequiredTiles(finished); if (finished) { if (anim.listener != null) { try { anim.listener.onComplete(); } catch (Exception e) { Timber.tag(TAG).w(e, ANIMATION_LISTENER_ERROR); } } anim = null; } invalidate(); } if (tileMap != null && isBaseLayerReady()) { // Optimum sample size for current scale int sampleSize = Math.min(fullImageSampleSize, calculateInSampleSize(scale)); // First check for missing tiles - if there are any we need the base layer underneath to avoid gaps boolean hasMissingTiles = false; for (Map.Entry<Integer, List<Tile>> tileMapEntry : tileMap.entrySet()) { if (tileMapEntry.getKey() == sampleSize) { for (Tile tile : tileMapEntry.getValue()) { if (tile.visible && (tile.loading || tile.bitmap == null)) { hasMissingTiles = true; } } } } // Render all loaded tiles. LinkedHashMap used for bottom up rendering - lower res tiles underneath. for (Map.Entry<Integer, List<Tile>> tileMapEntry : tileMap.entrySet()) { if (tileMapEntry.getKey() == sampleSize || hasMissingTiles) { for (Tile tile : tileMapEntry.getValue()) { sourceToViewRect(tile.sRect, tile.vRect); if (!tile.loading && tile.bitmap != null) { if (tileBgPaint != null) { canvas.drawRect(tile.vRect, tileBgPaint); } if (matrix == null) { matrix = new Matrix(); } matrix.reset(); setMatrixArray(srcArray, 0, 0, tile.bitmap.getWidth(), 0, tile.bitmap.getWidth(), tile.bitmap.getHeight(), 0, tile.bitmap.getHeight()); if (getRequiredRotation() == ORIENTATION_0) { setMatrixArray(dstArray, tile.vRect.left, tile.vRect.top, tile.vRect.right, tile.vRect.top, tile.vRect.right, tile.vRect.bottom, tile.vRect.left, tile.vRect.bottom); } else if (getRequiredRotation() == ORIENTATION_90) { setMatrixArray(dstArray, tile.vRect.right, tile.vRect.top, tile.vRect.right, tile.vRect.bottom, tile.vRect.left, tile.vRect.bottom, tile.vRect.left, tile.vRect.top); } else if (getRequiredRotation() == ORIENTATION_180) { setMatrixArray(dstArray, tile.vRect.right, tile.vRect.bottom, tile.vRect.left, tile.vRect.bottom, tile.vRect.left, tile.vRect.top, tile.vRect.right, tile.vRect.top); } else if (getRequiredRotation() == ORIENTATION_270) { setMatrixArray(dstArray, tile.vRect.left, tile.vRect.bottom, tile.vRect.left, tile.vRect.top, tile.vRect.right, tile.vRect.top, tile.vRect.right, tile.vRect.bottom); } matrix.setPolyToPoly(srcArray, 0, dstArray, 0, 4); canvas.drawBitmap(tile.bitmap, matrix, bitmapPaint); if (debug) { canvas.drawRect(tile.vRect, debugLinePaint); } } else if (tile.loading && debug) { canvas.drawText("LOADING", (float) tile.vRect.left + px(5), (float) tile.vRect.top + px(35), debugTextPaint); } if (tile.visible && debug) { canvas.drawText("ISS " + tile.sampleSize + " RECT " + tile.sRect.top + "," + tile.sRect.left + "," + tile.sRect.bottom + "," + tile.sRect.right, (float) tile.vRect.left + px(5), (float) tile.vRect.top + px(15), debugTextPaint); } } } } } else if (bitmap != null) { float xScale = scale; float yScale = scale; if (bitmapIsPreview) { xScale = scale * ((float) sWidth / bitmap.getWidth()); yScale = scale * ((float) sHeight / bitmap.getHeight()); } if (matrix == null) { matrix = new Matrix(); } matrix.reset(); matrix.postScale(xScale, yScale); matrix.postRotate(getRequiredRotation()); matrix.postTranslate(vTranslate.x, vTranslate.y); if (getRequiredRotation() == ORIENTATION_180) { matrix.postTranslate(scale * sWidth, scale * sHeight); } else if (getRequiredRotation() == ORIENTATION_90) { matrix.postTranslate(scale * sHeight, 0); } else if (getRequiredRotation() == ORIENTATION_270) { matrix.postTranslate(0, scale * sWidth); } if (tileBgPaint != null) { if (sRect == null) { sRect = new RectF(); } sRect.set(0f, 0f, bitmapIsPreview ? bitmap.getWidth() : sWidth, bitmapIsPreview ? bitmap.getHeight() : sHeight); matrix.mapRect(sRect); canvas.drawRect(sRect, tileBgPaint); } canvas.drawBitmap(bitmap, matrix, bitmapPaint); } if (debug) { canvas.drawText("Scale: " + String.format(Locale.ENGLISH, "%.2f", scale) + " (" + String.format(Locale.ENGLISH, "%.2f", minScale()) + " - " + String.format(Locale.ENGLISH, "%.2f", maxScale) + ")", px(5), px(15), debugTextPaint); canvas.drawText("Translate: " + String.format(Locale.ENGLISH, "%.2f", vTranslate.x) + ":" + String.format(Locale.ENGLISH, "%.2f", vTranslate.y), px(5), px(30), debugTextPaint); PointF center = getCenter(); if (null != center) canvas.drawText("Source center: " + String.format(Locale.ENGLISH, "%.2f", center.x) + ":" + String.format(Locale.ENGLISH, "%.2f", center.y), px(5), px(45), debugTextPaint); if (anim != null) { PointF vCenterStart = sourceToViewCoord(anim.sCenterStart); PointF vCenterEndRequested = sourceToViewCoord(anim.sCenterEndRequested); PointF vCenterEnd = sourceToViewCoord(anim.sCenterEnd); if (vCenterStart != null) { canvas.drawCircle(vCenterStart.x, vCenterStart.y, px(10), debugLinePaint); debugLinePaint.setColor(Color.RED); } if (vCenterEndRequested != null) { canvas.drawCircle(vCenterEndRequested.x, vCenterEndRequested.y, px(20), debugLinePaint); debugLinePaint.setColor(Color.BLUE); } if (vCenterEnd != null) { canvas.drawCircle(vCenterEnd.x, vCenterEnd.y, px(25), debugLinePaint); debugLinePaint.setColor(Color.CYAN); } canvas.drawCircle(getWidthInternal() / 2f, getHeightInternal() / 2f, px(30), debugLinePaint); } if (vCenterStart != null) { debugLinePaint.setColor(Color.RED); canvas.drawCircle(vCenterStart.x, vCenterStart.y, px(20), debugLinePaint); } if (quickScaleSCenter != null) { debugLinePaint.setColor(Color.BLUE); canvas.drawCircle(sourceToViewX(quickScaleSCenter.x), sourceToViewY(quickScaleSCenter.y), px(35), debugLinePaint); } if (quickScaleVStart != null && isQuickScaling) { debugLinePaint.setColor(Color.CYAN); canvas.drawCircle(quickScaleVStart.x, quickScaleVStart.y, px(30), debugLinePaint); } debugLinePaint.setColor(Color.MAGENTA); } } /** * Helper method for setting the values of a tile matrix array. */ private void setMatrixArray(float[] array, float f0, float f1, float f2, float f3, float f4, float f5, float f6, float f7) { array[0] = f0; array[1] = f1; array[2] = f2; array[3] = f3; array[4] = f4; array[5] = f5; array[6] = f6; array[7] = f7; } /** * Checks whether the base layer of tiles or full size bitmap is ready. */ private boolean isBaseLayerReady() { if (bitmap != null && !bitmapIsPreview) { return true; } else if (tileMap != null) { boolean baseLayerReady = true; for (Map.Entry<Integer, List<Tile>> tileMapEntry : tileMap.entrySet()) { if (tileMapEntry.getKey() == fullImageSampleSize) { for (Tile tile : tileMapEntry.getValue()) { if (tile.loading || tile.bitmap == null) { baseLayerReady = false; } } } } return baseLayerReady; } return false; } /** * Check whether view and image dimensions are known and either a preview, full size image or * base layer tiles are loaded. First time, send ready event to listener. The next draw will * display an image. */ private boolean checkReady() { boolean ready = getWidthInternal() > 0 && getHeightInternal() > 0 && sWidth > 0 && sHeight > 0 && (bitmap != null || isBaseLayerReady()); if (!readySent && ready) { preDraw(); readySent = true; onReady(); if (onImageEventListener != null) { onImageEventListener.onReady(); } } return ready; } /** * Check whether either the full size bitmap or base layer tiles are loaded. First time, send image * loaded event to listener. */ private boolean checkImageLoaded() { boolean imageLoaded = isBaseLayerReady(); if (!imageLoadedSent && imageLoaded) { preDraw(); imageLoadedSent = true; onImageLoaded(); if (onImageEventListener != null) { onImageEventListener.onImageLoaded(); } } return imageLoaded; } /** * Creates Paint objects once when first needed. */ private void createPaints() { if (bitmapPaint == null) { bitmapPaint = new Paint(); bitmapPaint.setAntiAlias(true); bitmapPaint.setFilterBitmap(true); bitmapPaint.setDither(true); } if ((debugTextPaint == null || debugLinePaint == null) && debug) { debugTextPaint = new Paint(); debugTextPaint.setTextSize(px(12)); debugTextPaint.setColor(Color.MAGENTA); debugTextPaint.setStyle(Style.FILL); debugLinePaint = new Paint(); debugLinePaint.setColor(Color.MAGENTA); debugLinePaint.setStyle(Style.STROKE); debugLinePaint.setStrokeWidth(px(1)); } } /** * Called on first draw when the view has dimensions. Calculates the initial sample size and starts async loading of * the base layer image - the whole source subsampled as necessary. */ private synchronized void initialiseBaseLayer(@NonNull Point maxTileDimensions) { debug("initialiseBaseLayer maxTileDimensions=%dx%d", maxTileDimensions.x, maxTileDimensions.y); satTemp = new ScaleAndTranslate(0f, new PointF(0, 0)); fitToBounds(true, satTemp); // Load double resolution - next level will be split into four tiles and at the center all four are required, // so don't bother with tiling until the next level 16 tiles are needed. fullImageSampleSize = calculateInSampleSize(satTemp.scale); if (fullImageSampleSize > 1) { fullImageSampleSize /= 2; } if (fullImageSampleSize == 1 && sRegion == null && sWidth() < maxTileDimensions.x && sHeight() < maxTileDimensions.y) { // Whole image is required at native resolution, and is smaller than the canvas max bitmap size. // Use BitmapDecoder for better image support. decoder.recycle(); decoder = null; BitmapLoadTask task = new BitmapLoadTask(this, getContext(), bitmapDecoderFactory, uri, false); execute(task); } else { initialiseTileMap(maxTileDimensions); List<Tile> baseGrid = tileMap.get(fullImageSampleSize); if (baseGrid != null) { for (Tile baseTile : baseGrid) { TileLoadTask task = new TileLoadTask(this, decoder, baseTile); execute(task); } refreshRequiredTiles(true); } } } /** * Loads the optimum tiles for display at the current scale and translate, so the screen can be filled with tiles * that are at least as high resolution as the screen. Frees up bitmaps that are now off the screen. * * @param load Whether to load the new tiles needed. Use false while scrolling/panning for performance. */ private void refreshRequiredTiles(boolean load) { if (decoder == null || tileMap == null) { return; } int sampleSize = Math.min(fullImageSampleSize, calculateInSampleSize(scale)); // Load tiles of the correct sample size that are on screen. Discard tiles off screen, and those that are higher // resolution than required, or lower res than required but not the base layer, so the base layer is always present. for (Map.Entry<Integer, List<Tile>> tileMapEntry : tileMap.entrySet()) { for (Tile tile : tileMapEntry.getValue()) { if (tile.sampleSize < sampleSize || (tile.sampleSize > sampleSize && tile.sampleSize != fullImageSampleSize)) { tile.visible = false; if (tile.bitmap != null) { tile.bitmap.recycle(); tile.bitmap = null; } } if (tile.sampleSize == sampleSize) { if (tileVisible(tile)) { tile.visible = true; if (!tile.loading && tile.bitmap == null && load) { TileLoadTask task = new TileLoadTask(this, decoder, tile); execute(task); } } else if (tile.sampleSize != fullImageSampleSize) { tile.visible = false; if (tile.bitmap != null) { tile.bitmap.recycle(); tile.bitmap = null; } } } else if (tile.sampleSize == fullImageSampleSize) { tile.visible = true; } } } } /** * Determine whether tile is visible. */ private boolean tileVisible(Tile tile) { float sVisLeft = viewToSourceX(0); float sVisRight = viewToSourceX(getWidthInternal()); float sVisTop = viewToSourceY(0); float sVisBottom = viewToSourceY(getHeightInternal()); return !(sVisLeft > tile.sRect.right || tile.sRect.left > sVisRight || sVisTop > tile.sRect.bottom || tile.sRect.top > sVisBottom); } /** * Sets scale and translate ready for the next draw. */ private void preDraw() { if (getWidthInternal() == 0 || getHeightInternal() == 0 || sWidth <= 0 || sHeight <= 0) { return; } // If waiting to translate to new center position, set translate now if (sPendingCenter != null && pendingScale != null) { scale = pendingScale; if (vTranslate == null) { vTranslate = new PointF(); } vTranslate.x = (getWidthInternal() / 2f) - (scale * sPendingCenter.x); vTranslate.y = (getHeightInternal() / 2f) - (scale * sPendingCenter.y); sPendingCenter = null; pendingScale = null; fitToBounds(true); refreshRequiredTiles(true); } // On first display of base image set up position, and in other cases make sure scale is correct. fitToBounds(false); } /** * Calculates sample size to fit the source image in given bounds. */ private int calculateInSampleSize(float scale) { if (minimumTileDpi > 0) { DisplayMetrics metrics = getResources().getDisplayMetrics(); float averageDpi = (metrics.xdpi + metrics.ydpi) / 2; scale = (minimumTileDpi / averageDpi) * scale; } int reqWidth = (int) (sWidth() * scale); int reqHeight = (int) (sHeight() * scale); // Raw height and width of image int inSampleSize = 1; if (reqWidth == 0 || reqHeight == 0) { return 32; } if (sHeight() > reqHeight || sWidth() > reqWidth) { // Calculate ratios of height and width to requested height and width final int heightRatio = Math.round((float) sHeight() / (float) reqHeight); final int widthRatio = Math.round((float) sWidth() / (float) reqWidth); // Choose the smallest ratio as inSampleSize value, this will guarantee // a final image with both dimensions larger than or equal to the // requested height and width. inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; } // We want the actual sample size that will be used, so round down to nearest power of 2. int power = 1; while (power * 2 < inSampleSize) { power = power * 2; } return power; } /** * Adjusts hypothetical future scale and translate values to keep scale within the allowed range and the image on screen. Minimum scale * is set so one dimension fills the view and the image is centered on the other dimension. Used to calculate what the target of an * animation should be. * * @param center Whether the image should be centered in the dimension it's too small to fill. While animating this can be false to avoid changes in direction as bounds are reached. * @param sat The scale we want and the translation we're aiming for. The values are adjusted to be valid. */ private void fitToBounds(boolean center, ScaleAndTranslate sat) { if (panLimit == PAN_LIMIT_OUTSIDE && isReady()) { center = false; } PointF vTranslate = sat.vTranslate; float scale = limitedScale(sat.scale); float scaleWidth = scale * sWidth(); float scaleHeight = scale * sHeight(); if (panLimit == PAN_LIMIT_CENTER && isReady()) { vTranslate.x = Math.max(vTranslate.x, getWidthInternal() / 2f - scaleWidth); vTranslate.y = Math.max(vTranslate.y, getHeightInternal() / 2f - scaleHeight); } else if (center) { vTranslate.x = Math.max(vTranslate.x, getWidthInternal() - scaleWidth); vTranslate.y = Math.max(vTranslate.y, getHeightInternal() - scaleHeight); } else { vTranslate.x = Math.max(vTranslate.x, -scaleWidth); vTranslate.y = Math.max(vTranslate.y, -scaleHeight); } // Asymmetric padding adjustments float xPaddingRatio = getPaddingLeft() > 0 || getPaddingRight() > 0 ? getPaddingLeft() / (float) (getPaddingLeft() + getPaddingRight()) : 0.5f; float yPaddingRatio = getPaddingTop() > 0 || getPaddingBottom() > 0 ? getPaddingTop() / (float) (getPaddingTop() + getPaddingBottom()) : 0.5f; float maxTx; float maxTy; if (panLimit == PAN_LIMIT_CENTER && isReady()) { maxTx = Math.max(0, getWidthInternal() / 2); maxTy = Math.max(0, getHeightInternal() / 2); } else if (center) { maxTx = Math.max(0, (getWidthInternal() - scaleWidth) * xPaddingRatio); maxTy = Math.max(0, (getHeightInternal() - scaleHeight) * yPaddingRatio); } else { maxTx = Math.max(0, getWidthInternal()); maxTy = Math.max(0, getHeightInternal()); } vTranslate.x = Math.min(vTranslate.x, maxTx); vTranslate.y = Math.min(vTranslate.y, maxTy); sat.scale = scale; } /** * Adjusts current scale and translate values to keep scale within the allowed range and the image on screen. Minimum scale * is set so one dimension fills the view and the image is centered on the other dimension. * * @param center Whether the image should be centered in the dimension it's too small to fill. While animating this can be false to avoid changes in direction as bounds are reached. */ private void fitToBounds(boolean center) { boolean init = false; if (vTranslate == null) { init = true; vTranslate = new PointF(0, 0); } if (satTemp == null) { satTemp = new ScaleAndTranslate(0, new PointF(0, 0)); } satTemp.scale = scale; satTemp.vTranslate.set(vTranslate); fitToBounds(center, satTemp); scale = satTemp.scale; vTranslate.set(satTemp.vTranslate); if (init && minimumScaleType != SCALE_TYPE_START) { vTranslate.set(vTranslateForSCenter(sWidth() / 2f, sHeight() / 2f, scale)); } } /** * Once source image and view dimensions are known, creates a map of sample size to tile grid. */ private void initialiseTileMap(Point maxTileDimensions) { debug("initialiseTileMap maxTileDimensions=%dx%d", maxTileDimensions.x, maxTileDimensions.y); this.tileMap = new LinkedHashMap<>(); int sampleSize = fullImageSampleSize; int xTiles = 1; int yTiles = 1; while (true) { int sTileWidth = sWidth() / xTiles; int sTileHeight = sHeight() / yTiles; int subTileWidth = sTileWidth / sampleSize; int subTileHeight = sTileHeight / sampleSize; while (subTileWidth + xTiles + 1 > maxTileDimensions.x || (subTileWidth > getWidthInternal() * 1.25 && sampleSize < fullImageSampleSize)) { xTiles += 1; sTileWidth = sWidth() / xTiles; subTileWidth = sTileWidth / sampleSize; } while (subTileHeight + yTiles + 1 > maxTileDimensions.y || (subTileHeight > getHeightInternal() * 1.25 && sampleSize < fullImageSampleSize)) { yTiles += 1; sTileHeight = sHeight() / yTiles; subTileHeight = sTileHeight / sampleSize; } List<Tile> tileGrid = new ArrayList<>(xTiles * yTiles); for (int x = 0; x < xTiles; x++) { for (int y = 0; y < yTiles; y++) { Tile tile = new Tile(); tile.sampleSize = sampleSize; tile.visible = sampleSize == fullImageSampleSize; tile.sRect = new Rect( x * sTileWidth, y * sTileHeight, x == xTiles - 1 ? sWidth() : (x + 1) * sTileWidth, y == yTiles - 1 ? sHeight() : (y + 1) * sTileHeight ); tile.vRect = new Rect(0, 0, 0, 0); tile.fileSRect = new Rect(tile.sRect); tileGrid.add(tile); } } tileMap.put(sampleSize, tileGrid); if (sampleSize == 1) { break; } else { sampleSize /= 2; } } } /** * Async task used to get image details without blocking the UI thread. */ private static class TilesInitTask extends AsyncTask<Void, Void, int[]> { private final WeakReference<CustomSubsamplingScaleImageView> viewRef; private final WeakReference<Context> contextRef; private final WeakReference<DecoderFactory<? extends ImageRegionDecoder>> decoderFactoryRef; private final Uri source; private ImageRegionDecoder decoder; private Exception exception; TilesInitTask(CustomSubsamplingScaleImageView view, Context context, DecoderFactory<? extends ImageRegionDecoder> decoderFactory, Uri source) { this.viewRef = new WeakReference<>(view); this.contextRef = new WeakReference<>(context); this.decoderFactoryRef = new WeakReference<>(decoderFactory); this.source = source; } @Override protected int[] doInBackground(Void... params) { try { String sourceUri = source.toString(); Context context = contextRef.get(); DecoderFactory<? extends ImageRegionDecoder> decoderFactory = decoderFactoryRef.get(); CustomSubsamplingScaleImageView view = viewRef.get(); if (context != null && decoderFactory != null && view != null) { view.debug("TilesInitTask.doInBackground"); decoder = decoderFactory.make(); Point dimensions = decoder.init(context, source); int sWidth = dimensions.x; int sHeight = dimensions.y; int exifOrientation = view.getExifOrientation(context, sourceUri); if (view.sRegion != null) { view.sRegion.left = Math.max(0, view.sRegion.left); view.sRegion.top = Math.max(0, view.sRegion.top); view.sRegion.right = Math.min(sWidth, view.sRegion.right); view.sRegion.bottom = Math.min(sHeight, view.sRegion.bottom); sWidth = view.sRegion.width(); sHeight = view.sRegion.height(); } return new int[]{sWidth, sHeight, exifOrientation}; } } catch (Exception e) { Timber.tag(TAG).e(e, "Failed to initialise bitmap decoder"); this.exception = e; } return null; } @Override protected void onPostExecute(int[] xyo) { final CustomSubsamplingScaleImageView view = viewRef.get(); if (view != null) { if (decoder != null && xyo != null && xyo.length == 3) { view.onTilesInited(decoder, xyo[0], xyo[1], xyo[2]); } else if (exception != null && view.onImageEventListener != null) { view.onImageEventListener.onImageLoadError(exception); } } } } /** * Called by worker task when decoder is ready and image size and EXIF orientation is known. */ private synchronized void onTilesInited(ImageRegionDecoder decoder, int sWidth, int sHeight, int sOrientation) { debug("onTilesInited sWidth=%d, sHeight=%d, sOrientation=%d", sWidth, sHeight, orientation); // If actual dimensions don't match the declared size, reset everything. if (this.sWidth > 0 && this.sHeight > 0 && (this.sWidth != sWidth || this.sHeight != sHeight)) { reset(false); if (bitmap != null) { if (!bitmapIsCached) { bitmap.recycle(); } bitmap = null; if (onImageEventListener != null && bitmapIsCached) { onImageEventListener.onPreviewReleased(); } bitmapIsPreview = false; bitmapIsCached = false; } } this.decoder = decoder; this.sWidth = sWidth; this.sHeight = sHeight; this.sOrientation = sOrientation; checkReady(); if (!checkImageLoaded() && maxTileWidth > 0 && maxTileWidth != TILE_SIZE_AUTO && maxTileHeight > 0 && maxTileHeight != TILE_SIZE_AUTO && getWidthInternal() > 0 && getHeightInternal() > 0) { initialiseBaseLayer(new Point(maxTileWidth, maxTileHeight)); } invalidate(); requestLayout(); } /** * Async task used to load images without blocking the UI thread. */ private static class TileLoadTask extends AsyncTask<Void, Void, Bitmap> { private final WeakReference<CustomSubsamplingScaleImageView> viewRef; private final WeakReference<ImageRegionDecoder> decoderRef; private final WeakReference<Tile> tileRef; private Exception exception; TileLoadTask(CustomSubsamplingScaleImageView view, ImageRegionDecoder decoder, Tile tile) { this.viewRef = new WeakReference<>(view); this.decoderRef = new WeakReference<>(decoder); this.tileRef = new WeakReference<>(tile); tile.loading = true; } @Override protected Bitmap doInBackground(Void... params) { try { CustomSubsamplingScaleImageView view = viewRef.get(); ImageRegionDecoder decoder = decoderRef.get(); Tile tile = tileRef.get(); if (decoder != null && tile != null && view != null && decoder.isReady() && tile.visible) { view.debug("TileLoadTask.doInBackground, tile.sRect=%s, tile.sampleSize=%d", tile.sRect, tile.sampleSize); view.decoderLock.readLock().lock(); try { if (decoder.isReady()) { // Update tile's file sRect according to rotation view.fileSRect(tile.sRect, tile.fileSRect); if (view.sRegion != null) { tile.fileSRect.offset(view.sRegion.left, view.sRegion.top); } return decoder.decodeRegion(tile.fileSRect, tile.sampleSize); } else { tile.loading = false; } } finally { view.decoderLock.readLock().unlock(); } } else if (tile != null) { tile.loading = false; } } catch (Exception e) { Timber.tag(TAG).e(e, "Failed to decode tile"); this.exception = e; } catch (OutOfMemoryError e) { Timber.tag(TAG).e(e, "Failed to decode tile - OutOfMemoryError"); this.exception = new RuntimeException(e); } return null; } @Override protected void onPostExecute(Bitmap bitmap) { final CustomSubsamplingScaleImageView subsamplingScaleImageView = viewRef.get(); final Tile tile = tileRef.get(); if (subsamplingScaleImageView != null && tile != null) { if (bitmap != null) { tile.bitmap = bitmap; tile.loading = false; subsamplingScaleImageView.onTileLoaded(); } else if (exception != null && subsamplingScaleImageView.onImageEventListener != null) { subsamplingScaleImageView.onImageEventListener.onTileLoadError(exception); } } } } /** * Called by worker task when a tile has loaded. Redraws the view. */ private synchronized void onTileLoaded() { debug("onTileLoaded"); checkReady(); checkImageLoaded(); if (isBaseLayerReady() && bitmap != null) { if (!bitmapIsCached) { bitmap.recycle(); } bitmap = null; if (onImageEventListener != null && bitmapIsCached) { onImageEventListener.onPreviewReleased(); } bitmapIsPreview = false; bitmapIsCached = false; } invalidate(); } /** * Async task used to load bitmap without blocking the UI thread. */ private static class BitmapLoadTask extends AsyncTask<Void, Void, Integer> { private final WeakReference<CustomSubsamplingScaleImageView> viewRef; private final WeakReference<Context> contextRef; private final WeakReference<DecoderFactory<? extends ImageDecoder>> decoderFactoryRef; private final Uri source; private final boolean preview; private Bitmap bitmap; private Exception exception; BitmapLoadTask(CustomSubsamplingScaleImageView view, Context context, DecoderFactory<? extends ImageDecoder> decoderFactory, Uri source, boolean preview) { this.viewRef = new WeakReference<>(view); this.contextRef = new WeakReference<>(context); this.decoderFactoryRef = new WeakReference<>(decoderFactory); this.source = source; this.preview = preview; } @Override protected Integer doInBackground(Void... params) { try { String sourceUri = source.toString(); Context context = contextRef.get(); DecoderFactory<? extends ImageDecoder> decoderFactory = decoderFactoryRef.get(); CustomSubsamplingScaleImageView view = viewRef.get(); if (context != null && decoderFactory != null && view != null) { view.debug("BitmapLoadTask.doInBackground"); bitmap = decoderFactory.make().decode(context, source); return view.getExifOrientation(context, sourceUri); } } catch (Exception e) { Timber.tag(TAG).e(e, "Failed to load bitmap"); this.exception = e; } catch (OutOfMemoryError e) { Timber.tag(TAG).e(e, "Failed to load bitmap - OutOfMemoryError"); this.exception = new RuntimeException(e); } return null; } @Override protected void onPostExecute(Integer orientation) { CustomSubsamplingScaleImageView subsamplingScaleImageView = viewRef.get(); if (subsamplingScaleImageView != null) { if (bitmap != null && orientation != null) { if (preview) { subsamplingScaleImageView.onPreviewLoaded(bitmap); } else { subsamplingScaleImageView.onImageLoaded(bitmap, orientation, false); } } else if (exception != null && subsamplingScaleImageView.onImageEventListener != null) { if (preview) { subsamplingScaleImageView.onImageEventListener.onPreviewLoadError(exception); } else { subsamplingScaleImageView.onImageEventListener.onImageLoadError(exception); } } } } } /** * Called by worker task when preview image is loaded. */ private synchronized void onPreviewLoaded(Bitmap previewBitmap) { debug("onPreviewLoaded"); if (bitmap != null || imageLoadedSent) { previewBitmap.recycle(); return; } if (pRegion != null) { bitmap = Bitmap.createBitmap(previewBitmap, pRegion.left, pRegion.top, pRegion.width(), pRegion.height()); } else { bitmap = previewBitmap; } bitmapIsPreview = true; if (checkReady()) { invalidate(); requestLayout(); } } /** * Called by worker task when full size image bitmap is ready (tiling is disabled). */ private synchronized void onImageLoaded(Bitmap bitmap, int sOrientation, boolean bitmapIsCached) { debug("onImageLoaded"); // If actual dimensions don't match the declared size, reset everything. if (this.sWidth > 0 && this.sHeight > 0 && (this.sWidth != bitmap.getWidth() || this.sHeight != bitmap.getHeight())) { reset(false); } if (this.bitmap != null && !this.bitmapIsCached) { this.bitmap.recycle(); } if (this.bitmap != null && this.bitmapIsCached && onImageEventListener != null) { onImageEventListener.onPreviewReleased(); } this.bitmapIsPreview = false; this.bitmapIsCached = bitmapIsCached; this.bitmap = bitmap; this.sWidth = bitmap.getWidth(); this.sHeight = bitmap.getHeight(); this.sOrientation = sOrientation; boolean ready = checkReady(); boolean imageLoaded = checkImageLoaded(); if (ready || imageLoaded) { invalidate(); requestLayout(); } } /** * Helper method for load tasks. Examines the EXIF info on the image file to determine the orientation. * This will only work for external files, not assets, resources or other URIs. */ @AnyThread private int getExifOrientation(Context context, String sourceUri) { int exifOrientation = ORIENTATION_0; if (sourceUri.startsWith(ContentResolver.SCHEME_CONTENT)) { Cursor cursor = null; try { String[] columns = {MediaStore.Images.ImageColumns.ORIENTATION}; cursor = context.getContentResolver().query(Uri.parse(sourceUri), columns, null, null, null); if (cursor != null && cursor.moveToFirst()) { int orientation = cursor.getInt(0); if (VALID_ORIENTATIONS.contains(orientation) && orientation != ORIENTATION_USE_EXIF) { exifOrientation = orientation; } else { Timber.w(TAG, "Unsupported orientation: %s", orientation); } } } catch (Exception e) { Timber.w(TAG, "Could not get orientation of image from media store"); } finally { if (cursor != null) { cursor.close(); } } } else if (sourceUri.startsWith(ImageSource.FILE_SCHEME) && !sourceUri.startsWith(ImageSource.ASSET_SCHEME)) { try { ExifInterface exifInterface = new ExifInterface(sourceUri.substring(ImageSource.FILE_SCHEME.length() - 1)); int orientationAttr = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); if (orientationAttr == ExifInterface.ORIENTATION_NORMAL || orientationAttr == ExifInterface.ORIENTATION_UNDEFINED) { exifOrientation = ORIENTATION_0; } else if (orientationAttr == ExifInterface.ORIENTATION_ROTATE_90) { exifOrientation = ORIENTATION_90; } else if (orientationAttr == ExifInterface.ORIENTATION_ROTATE_180) { exifOrientation = ORIENTATION_180; } else if (orientationAttr == ExifInterface.ORIENTATION_ROTATE_270) { exifOrientation = ORIENTATION_270; } else { Timber.w(TAG, "Unsupported EXIF orientation: %s", orientationAttr); } } catch (Exception e) { Timber.w(TAG, "Could not get EXIF orientation of image"); } } return exifOrientation; } private void execute(AsyncTask<Void, Void, ?> asyncTask) { asyncTask.executeOnExecutor(executor); } private static class Tile { private Rect sRect; private int sampleSize; private Bitmap bitmap; private boolean loading; private boolean visible; // Volatile fields instantiated once then updated before use to reduce GC. private Rect vRect; private Rect fileSRect; } private static class Anim { private float scaleStart; // Scale at start of anim private float scaleEnd; // Scale at end of anim (target) private PointF sCenterStart; // Source center point at start private PointF sCenterEnd; // Source center point at end, adjusted for pan limits private PointF sCenterEndRequested; // Source center point that was requested, without adjustment private PointF vFocusStart; // View point that was double tapped private PointF vFocusEnd; // Where the view focal point should be moved to during the anim private long duration = 500; // How long the anim takes private boolean interruptible = true; // Whether the anim can be interrupted by a touch private int easing = EASE_IN_OUT_QUAD; // Easing style private int origin = ORIGIN_ANIM; // Animation origin (API, double tap or fling) private long time = System.currentTimeMillis(); // Start time private OnAnimationEventListener listener; // Event listener } private static class ScaleAndTranslate { private ScaleAndTranslate(float scale, PointF vTranslate) { this.scale = scale; this.vTranslate = vTranslate; } private float scale; private final PointF vTranslate; } /** * Set scale, center and orientation from saved state. */ private void restoreState(ImageViewState state) { if (state != null && VALID_ORIENTATIONS.contains(state.getOrientation())) { this.orientation = state.getOrientation(); this.pendingScale = state.getScale(); this.sPendingCenter = state.getCenter(); invalidate(); } } /** * By default the View automatically calculates the optimal tile size. Set this to override this, and force an upper limit to the dimensions of the generated tiles. Passing {@link #TILE_SIZE_AUTO} will re-enable the default behaviour. * * @param maxPixels Maximum tile size X and Y in pixels. */ public void setMaxTileSize(int maxPixels) { this.maxTileWidth = maxPixels; this.maxTileHeight = maxPixels; } /** * By default the View automatically calculates the optimal tile size. Set this to override this, and force an upper limit to the dimensions of the generated tiles. Passing {@link #TILE_SIZE_AUTO} will re-enable the default behaviour. * * @param maxPixelsX Maximum tile width. * @param maxPixelsY Maximum tile height. */ public void setMaxTileSize(int maxPixelsX, int maxPixelsY) { this.maxTileWidth = maxPixelsX; this.maxTileHeight = maxPixelsY; } /** * Use canvas max bitmap width and height instead of the default 2048, to avoid redundant tiling. */ @NonNull private Point getMaxBitmapDimensions(Canvas canvas) { return new Point(Math.min(canvas.getMaximumBitmapWidth(), maxTileWidth), Math.min(canvas.getMaximumBitmapHeight(), maxTileHeight)); } /** * Get source width taking rotation into account. */ @SuppressWarnings("SuspiciousNameCombination") private int sWidth() { int rotation = getRequiredRotation(); if (rotation == 90 || rotation == 270) { return sHeight; } else { return sWidth; } } /** * Get source height taking rotation into account. */ @SuppressWarnings("SuspiciousNameCombination") private int sHeight() { int rotation = getRequiredRotation(); if (rotation == 90 || rotation == 270) { return sWidth; } else { return sHeight; } } /** * Converts source rectangle from tile, which treats the image file as if it were in the correct orientation already, * to the rectangle of the image that needs to be loaded. */ @SuppressWarnings("SuspiciousNameCombination") @AnyThread private void fileSRect(Rect sRect, Rect target) { if (getRequiredRotation() == 0) { target.set(sRect); } else if (getRequiredRotation() == 90) { target.set(sRect.top, sHeight - sRect.right, sRect.bottom, sHeight - sRect.left); } else if (getRequiredRotation() == 180) { target.set(sWidth - sRect.right, sHeight - sRect.bottom, sWidth - sRect.left, sHeight - sRect.top); } else { target.set(sWidth - sRect.bottom, sRect.left, sWidth - sRect.top, sRect.right); } } /** * Determines the rotation to be applied to tiles, based on EXIF orientation or chosen setting. */ @AnyThread private int getRequiredRotation() { if (orientation == ORIENTATION_USE_EXIF) { return sOrientation; } else { return orientation; } } /** * Pythagoras distance between two points. */ private float distance(float x0, float x1, float y0, float y1) { float x = x0 - x1; float y = y0 - y1; return (float) Math.sqrt(x * x + y * y); } /** * Releases all resources the view is using and resets the state, nulling any fields that use significant memory. * After you have called this method, the view can be re-used by setting a new image. Settings are remembered * but state (scale and center) is forgotten. You can restore these yourself if required. */ public void recycle() { reset(true); bitmapPaint = null; debugTextPaint = null; debugLinePaint = null; tileBgPaint = null; } /** * Convert screen to source x coordinate. */ private float viewToSourceX(float vx) { if (vTranslate == null) { return Float.NaN; } return (vx - vTranslate.x) / scale; } /** * Convert screen to source y coordinate. */ private float viewToSourceY(float vy) { if (vTranslate == null) { return Float.NaN; } return (vy - vTranslate.y) / scale; } /** * Converts a rectangle within the view to the corresponding rectangle from the source file, taking * into account the current scale, translation, orientation and clipped region. This can be used * to decode a bitmap from the source file. * <p> * This method will only work when the image has fully initialised, after {@link #isReady()} returns * true. It is not guaranteed to work with preloaded bitmaps. * <p> * The result is written to the fRect argument. Re-use a single instance for efficiency. * * @param vRect rectangle representing the view area to interpret. * @param fRect rectangle instance to which the result will be written. Re-use for efficiency. */ public void viewToFileRect(Rect vRect, Rect fRect) { if (vTranslate == null || !readySent) { return; } fRect.set( (int) viewToSourceX(vRect.left), (int) viewToSourceY(vRect.top), (int) viewToSourceX(vRect.right), (int) viewToSourceY(vRect.bottom)); fileSRect(fRect, fRect); fRect.set( Math.max(0, fRect.left), Math.max(0, fRect.top), Math.min(sWidth, fRect.right), Math.min(sHeight, fRect.bottom) ); if (sRegion != null) { fRect.offset(sRegion.left, sRegion.top); } } /** * Find the area of the source file that is currently visible on screen, taking into account the * current scale, translation, orientation and clipped region. This is a convenience method; see * {@link #viewToFileRect(Rect, Rect)}. * * @param fRect rectangle instance to which the result will be written. Re-use for efficiency. */ public void visibleFileRect(Rect fRect) { if (vTranslate == null || !readySent) { return; } fRect.set(0, 0, getWidthInternal(), getHeightInternal()); viewToFileRect(fRect, fRect); } /** * Convert screen coordinate to source coordinate. * * @param vxy view X/Y coordinate. * @return a coordinate representing the corresponding source coordinate. */ @Nullable public final PointF viewToSourceCoord(PointF vxy) { return viewToSourceCoord(vxy.x, vxy.y, new PointF()); } /** * Convert screen coordinate to source coordinate. * * @param vx view X coordinate. * @param vy view Y coordinate. * @return a coordinate representing the corresponding source coordinate. */ @Nullable public final PointF viewToSourceCoord(float vx, float vy) { return viewToSourceCoord(vx, vy, new PointF()); } /** * Convert screen coordinate to source coordinate. * * @param vxy view coordinates to convert. * @param sTarget target object for result. The same instance is also returned. * @return source coordinates. This is the same instance passed to the sTarget param. */ @Nullable public final PointF viewToSourceCoord(PointF vxy, @NonNull PointF sTarget) { return viewToSourceCoord(vxy.x, vxy.y, sTarget); } /** * Convert screen coordinate to source coordinate. * * @param vx view X coordinate. * @param vy view Y coordinate. * @param sTarget target object for result. The same instance is also returned. * @return source coordinates. This is the same instance passed to the sTarget param. */ @Nullable public final PointF viewToSourceCoord(float vx, float vy, @NonNull PointF sTarget) { if (vTranslate == null) { return null; } sTarget.set(viewToSourceX(vx), viewToSourceY(vy)); return sTarget; } /** * Convert source to view x coordinate. */ private float sourceToViewX(float sx) { if (vTranslate == null) { return Float.NaN; } return (sx * scale) + vTranslate.x; } /** * Convert source to view y coordinate. */ private float sourceToViewY(float sy) { if (vTranslate == null) { return Float.NaN; } return (sy * scale) + vTranslate.y; } /** * Convert source coordinate to view coordinate. * * @param sxy source coordinates to convert. * @return view coordinates. */ @Nullable public final PointF sourceToViewCoord(PointF sxy) { return sourceToViewCoord(sxy.x, sxy.y, new PointF()); } /** * Convert source coordinate to view coordinate. * * @param sx source X coordinate. * @param sy source Y coordinate. * @return view coordinates. */ @Nullable public final PointF sourceToViewCoord(float sx, float sy) { return sourceToViewCoord(sx, sy, new PointF()); } /** * Convert source coordinate to view coordinate. * * @param sxy source coordinates to convert. * @param vTarget target object for result. The same instance is also returned. * @return view coordinates. This is the same instance passed to the vTarget param. */ @SuppressWarnings("UnusedReturnValue") @Nullable public final PointF sourceToViewCoord(PointF sxy, @NonNull PointF vTarget) { return sourceToViewCoord(sxy.x, sxy.y, vTarget); } /** * Convert source coordinate to view coordinate. * * @param sx source X coordinate. * @param sy source Y coordinate. * @param vTarget target object for result. The same instance is also returned. * @return view coordinates. This is the same instance passed to the vTarget param. */ @Nullable public final PointF sourceToViewCoord(float sx, float sy, @NonNull PointF vTarget) { if (vTranslate == null) { return null; } vTarget.set(sourceToViewX(sx), sourceToViewY(sy)); return vTarget; } /** * Convert source rect to screen rect, integer values. */ private void sourceToViewRect(@NonNull Rect sRect, @NonNull Rect vTarget) { vTarget.set( (int) sourceToViewX(sRect.left), (int) sourceToViewY(sRect.top), (int) sourceToViewX(sRect.right), (int) sourceToViewY(sRect.bottom) ); } /** * Get the translation required to place a given source coordinate at the center of the screen, with the center * adjusted for asymmetric padding. Accepts the desired scale as an argument, so this is independent of current * translate and scale. The result is fitted to bounds, putting the image point as near to the screen center as permitted. */ @NonNull private PointF vTranslateForSCenter(float sCenterX, float sCenterY, float scale) { int vxCenter = getPaddingLeft() + (getWidthInternal() - getPaddingRight() - getPaddingLeft()) / 2; int vyCenter = getPaddingTop() + (getHeightInternal() - getPaddingBottom() - getPaddingTop()) / 2; if (satTemp == null) { satTemp = new ScaleAndTranslate(0, new PointF(0, 0)); } satTemp.scale = scale; satTemp.vTranslate.set(vxCenter - (sCenterX * scale), vyCenter - (sCenterY * scale)); fitToBounds(true, satTemp); return satTemp.vTranslate; } /** * Returns the minimum allowed scale. */ private float minScale() { int vPadding = getPaddingBottom() + getPaddingTop(); int hPadding = getPaddingLeft() + getPaddingRight(); if (minimumScaleType == SCALE_TYPE_CENTER_CROP || minimumScaleType == SCALE_TYPE_START) { return Math.max((getWidthInternal() - hPadding) / (float) sWidth(), (getHeightInternal() - vPadding) / (float) sHeight()); } else if (minimumScaleType == SCALE_TYPE_CUSTOM && minScale > 0) { return minScale; } else { return Math.min((getWidthInternal() - hPadding) / (float) sWidth(), (getHeightInternal() - vPadding) / (float) sHeight()); } } /** * Adjust a requested scale to be within the allowed limits. */ private float limitedScale(float targetScale) { targetScale = Math.max(minScale(), targetScale); targetScale = Math.min(maxScale, targetScale); return targetScale; } /** * Apply a selected type of easing. * * @param type Easing type, from static fields * @param time Elapsed time * @param from Start value * @param change Target value * @param duration Anm duration * @return Current value */ private float ease(int type, long time, float from, float change, long duration) { switch (type) { case EASE_IN_OUT_QUAD: return easeInOutQuad(time, from, change, duration); case EASE_OUT_QUAD: return easeOutQuad(time, from, change, duration); default: throw new IllegalStateException("Unexpected easing type: " + type); } } private float easeOutQuad(long time, float from, float change, long duration) { float progress = (float) time / (float) duration; return -change * progress * (progress - 2) + from; } private float easeInOutQuad(long time, float from, float change, long duration) { float timeF = time / (duration / 2f); if (timeF < 1) { return (change / 2f * timeF * timeF) + from; } else { timeF return (-change / 2f) * (timeF * (timeF - 2) - 1) + from; } } /** * Debug logger */ @AnyThread private void debug(String message, Object... args) { if (debug) { Timber.d(message, args); } } /** * For debug overlays. Scale pixel value according to screen density. */ private int px(int px) { return (int) (density * px); } /** * Swap the default region decoder implementation for one of your own. You must do this before setting the image file or * asset, and you cannot use a custom decoder when using layout XML to set an asset name. Your class must have a * public default constructor. * * @param regionDecoderClass The {@link ImageRegionDecoder} implementation to use. */ public final void setRegionDecoderClass(@NonNull Class<? extends ImageRegionDecoder> regionDecoderClass) { this.regionDecoderFactory = new CompatDecoderFactory<>(regionDecoderClass); } /** * Swap the default region decoder implementation for one of your own. You must do this before setting the image file or * asset, and you cannot use a custom decoder when using layout XML to set an asset name. * * @param regionDecoderFactory The {@link DecoderFactory} implementation that produces {@link ImageRegionDecoder} * instances. */ public final void setRegionDecoderFactory(@NonNull DecoderFactory<? extends ImageRegionDecoder> regionDecoderFactory) { this.regionDecoderFactory = regionDecoderFactory; } /** * Swap the default bitmap decoder implementation for one of your own. You must do this before setting the image file or * asset, and you cannot use a custom decoder when using layout XML to set an asset name. Your class must have a * public default constructor. * * @param bitmapDecoderClass The {@link ImageDecoder} implementation to use. */ public final void setBitmapDecoderClass(@NonNull Class<? extends ImageDecoder> bitmapDecoderClass) { this.bitmapDecoderFactory = new CompatDecoderFactory<>(bitmapDecoderClass); } /** * Swap the default bitmap decoder implementation for one of your own. You must do this before setting the image file or * asset, and you cannot use a custom decoder when using layout XML to set an asset name. * * @param bitmapDecoderFactory The {@link DecoderFactory} implementation that produces {@link ImageDecoder} instances. */ public final void setBitmapDecoderFactory(@NonNull DecoderFactory<? extends ImageDecoder> bitmapDecoderFactory) { this.bitmapDecoderFactory = bitmapDecoderFactory; } /** * Calculate how much further the image can be panned in each direction. The results are set on * the supplied {@link RectF} and expressed as screen pixels. For example, if the image cannot be * panned any further towards the left, the value of {@link RectF#left} will be set to 0. * * @param vTarget target object for results. Re-use for efficiency. */ public final void getPanRemaining(RectF vTarget) { if (!isReady()) { return; } float scaleWidth = scale * sWidth(); float scaleHeight = scale * sHeight(); if (panLimit == PAN_LIMIT_CENTER) { vTarget.top = Math.max(0, -(vTranslate.y - (getHeightInternal() / 2f))); vTarget.left = Math.max(0, -(vTranslate.x - (getWidthInternal() / 2f))); vTarget.bottom = Math.max(0, vTranslate.y - ((getHeightInternal() / 2f) - scaleHeight)); vTarget.right = Math.max(0, vTranslate.x - ((getWidthInternal() / 2f) - scaleWidth)); } else if (panLimit == PAN_LIMIT_OUTSIDE) { vTarget.top = Math.max(0, -(vTranslate.y - getHeightInternal())); vTarget.left = Math.max(0, -(vTranslate.x - getWidthInternal())); vTarget.bottom = Math.max(0, vTranslate.y + scaleHeight); vTarget.right = Math.max(0, vTranslate.x + scaleWidth); } else { vTarget.top = Math.max(0, -vTranslate.y); vTarget.left = Math.max(0, -vTranslate.x); vTarget.bottom = Math.max(0, (scaleHeight + vTranslate.y) - getHeightInternal()); vTarget.right = Math.max(0, (scaleWidth + vTranslate.x) - getWidthInternal()); } } /** * Set the pan limiting style. See static fields. Normally {@link #PAN_LIMIT_INSIDE} is best, for image galleries. * * @param panLimit a pan limit constant. See static fields. */ public final void setPanLimit(int panLimit) { if (!VALID_PAN_LIMITS.contains(panLimit)) { throw new IllegalArgumentException("Invalid pan limit: " + panLimit); } this.panLimit = panLimit; if (isReady()) { fitToBounds(true); invalidate(); } } /** * Set the minimum scale type. See static fields. Normally {@link #SCALE_TYPE_CENTER_INSIDE} is best, for image galleries. * * @param scaleType a scale type constant. See static fields. */ public final void setMinimumScaleType(int scaleType) { if (!VALID_SCALE_TYPES.contains(scaleType)) { throw new IllegalArgumentException("Invalid scale type: " + scaleType); } this.minimumScaleType = scaleType; if (isReady()) { fitToBounds(true); invalidate(); } } /** * Set the maximum scale allowed. A value of 1 means 1:1 pixels at maximum scale. You may wish to set this according * to screen density - on a retina screen, 1:1 may still be too small. Consider using {@link #setMinimumDpi(int)}, * which is density aware. * * @param maxScale maximum scale expressed as a source/view pixels ratio. */ public final void setMaxScale(float maxScale) { this.maxScale = maxScale; } /** * Set the minimum scale allowed. A value of 1 means 1:1 pixels at minimum scale. You may wish to set this according * to screen density. Consider using {@link #setMaximumDpi(int)}, which is density aware. * * @param minScale minimum scale expressed as a source/view pixels ratio. */ public final void setMinScale(float minScale) { this.minScale = minScale; } /** * This is a screen density aware alternative to {@link #setMaxScale(float)}; it allows you to express the maximum * allowed scale in terms of the minimum pixel density. This avoids the problem of 1:1 scale still being * too small on a high density screen. A sensible starting point is 160 - the default used by this view. * * @param dpi Source image pixel density at maximum zoom. */ public final void setMinimumDpi(int dpi) { DisplayMetrics metrics = getResources().getDisplayMetrics(); float averageDpi = (metrics.xdpi + metrics.ydpi) / 2; setMaxScale(averageDpi / dpi); } /** * This is a screen density aware alternative to {@link #setMinScale(float)}; it allows you to express the minimum * allowed scale in terms of the maximum pixel density. * * @param dpi Source image pixel density at minimum zoom. */ public final void setMaximumDpi(int dpi) { DisplayMetrics metrics = getResources().getDisplayMetrics(); float averageDpi = (metrics.xdpi + metrics.ydpi) / 2; setMinScale(averageDpi / dpi); } /** * Returns the maximum allowed scale. * * @return the maximum scale as a source/view pixels ratio. */ public float getMaxScale() { return maxScale; } /** * Returns the minimum allowed scale. * * @return the minimum scale as a source/view pixels ratio. */ public final float getMinScale() { return minScale(); } /** * By default, image tiles are at least as high resolution as the screen. For a retina screen this may not be * necessary, and may increase the likelihood of an OutOfMemoryError. This method sets a DPI at which higher * resolution tiles should be loaded. Using a lower number will on average use less memory but result in a lower * quality image. 160-240dpi will usually be enough. This should be called before setting the image source, * because it affects which tiles get loaded. When using an untiled source image this method has no effect. * * @param minimumTileDpi Tile loading threshold. */ public void setMinimumTileDpi(int minimumTileDpi) { DisplayMetrics metrics = getResources().getDisplayMetrics(); float averageDpi = (metrics.xdpi + metrics.ydpi) / 2; this.minimumTileDpi = (int) Math.min(averageDpi, minimumTileDpi); if (isReady()) { reset(false); invalidate(); } } /** * Returns the source point at the center of the view. * * @return the source coordinates current at the center of the view. */ @Nullable public final PointF getCenter() { int mX = getWidthInternal() / 2; int mY = getHeightInternal() / 2; return viewToSourceCoord(mX, mY); } /** * Returns the current scale value. * * @return the current scale as a source/view pixels ratio. */ public final float getScale() { return scale; } /** * Externally change the scale and translation of the source image. This may be used with getCenter() and getScale() * to restore the scale and zoom after a screen rotate. * * @param scale New scale to set. * @param sCenter New source image coordinate to center on the screen, subject to boundaries. */ public final void setScaleAndCenter(float scale, @Nullable PointF sCenter) { this.anim = null; this.pendingScale = scale; this.sPendingCenter = sCenter; this.sRequestedCenter = sCenter; invalidate(); } /** * Fully zoom out and return the image to the middle of the screen. This might be useful if you have a view pager * and want images to be reset when the user has moved to another page. */ public final void resetScaleAndCenter() { this.anim = null; this.pendingScale = limitedScale(0); if (isReady()) { this.sPendingCenter = new PointF(sWidth() / 2f, sHeight() / 2f); } else { this.sPendingCenter = new PointF(0, 0); } invalidate(); } /** * Call to find whether the view is initialised, has dimensions, and will display an image on * the next draw. If a preview has been provided, it may be the preview that will be displayed * and the full size image may still be loading. If no preview was provided, this is called once * the base layer tiles of the full size image are loaded. * * @return true if the view is ready to display an image and accept touch gestures. */ public final boolean isReady() { return readySent; } /** * Called once when the view is initialised, has dimensions, and will display an image on the * next draw. This is triggered at the same time as {@link OnImageEventListener#onReady()} but * allows a subclass to receive this event without using a listener. */ @SuppressWarnings({"EmptyMethod", "squid:S1186"}) protected void onReady() { } /** * Call to find whether the main image (base layer tiles where relevant) have been loaded. Before * this event the view is blank unless a preview was provided. * * @return true if the main image (not the preview) has been loaded and is ready to display. */ public final boolean isImageLoaded() { return imageLoadedSent; } /** * Called once when the full size image or its base layer tiles have been loaded. */ @SuppressWarnings({"EmptyMethod", "squid:S1186"}) protected void onImageLoaded() { } /** * Get source width, ignoring orientation. If {@link #getOrientation()} returns 90 or 270, you can use {@link #getSHeight()} * for the apparent width. * * @return the source image width in pixels. */ public final int getSWidth() { return sWidth; } /** * Get source height, ignoring orientation. If {@link #getOrientation()} returns 90 or 270, you can use {@link #getSWidth()} * for the apparent height. * * @return the source image height in pixels. */ public final int getSHeight() { return sHeight; } /** * Returns the orientation setting. This can return {@link #ORIENTATION_USE_EXIF}, in which case it doesn't tell you * the applied orientation of the image. For that, use {@link #getAppliedOrientation()}. * * @return the orientation setting. See static fields. */ public final int getOrientation() { return orientation; } /** * Returns the actual orientation of the image relative to the source file. This will be based on the source file's * EXIF orientation if you're using ORIENTATION_USE_EXIF. Values are 0, 90, 180, 270. * * @return the orientation applied after EXIF information has been extracted. See static fields. */ public final int getAppliedOrientation() { return getRequiredRotation(); } /** * Get the current state of the view (scale, center, orientation) for restoration after rotate. Will return null if * the view is not ready. * * @return an {@link ImageViewState} instance representing the current position of the image. null if the view isn't ready. */ @Nullable public final ImageViewState getState() { PointF center = getCenter(); if (vTranslate != null && sWidth > 0 && sHeight > 0 && center != null) { return new ImageViewState(getScale(), center, getOrientation()); } return null; } /** * Returns true if zoom gesture detection is enabled. * * @return true if zoom gesture detection is enabled. */ public final boolean isZoomEnabled() { return zoomEnabled; } /** * Enable or disable zoom gesture detection. Disabling zoom locks the the current scale. * * @param zoomEnabled true to enable zoom gestures, false to disable. */ public final void setZoomEnabled(boolean zoomEnabled) { this.zoomEnabled = zoomEnabled; } /** * Returns true if double tap &amp; swipe to zoom is enabled. * * @return true if double tap &amp; swipe to zoom is enabled. */ public final boolean isQuickScaleEnabled() { return quickScaleEnabled; } /** * Enable or disable double tap &amp; swipe to zoom. * * @param quickScaleEnabled true to enable quick scale, false to disable. */ public final void setQuickScaleEnabled(boolean quickScaleEnabled) { this.quickScaleEnabled = quickScaleEnabled; } /** * Returns true if pan gesture detection is enabled. * * @return true if pan gesture detection is enabled. */ public final boolean isPanEnabled() { return panEnabled; } /** * Enable or disable pan gesture detection. Disabling pan causes the image to be centered. Pan * can still be changed from code. * * @param panEnabled true to enable panning, false to disable. */ public final void setPanEnabled(boolean panEnabled) { this.panEnabled = panEnabled; if (!panEnabled && vTranslate != null) { vTranslate.x = (getWidthInternal() / 2f) - (scale * (sWidth() / 2f)); vTranslate.y = (getHeightInternal() / 2f) - (scale * (sHeight() / 2f)); if (isReady()) { refreshRequiredTiles(true); invalidate(); } } } /** * Set a solid color to render behind tiles, useful for displaying transparent PNGs. * * @param tileBgColor Background color for tiles. */ public final void setTileBackgroundColor(int tileBgColor) { if (Color.alpha(tileBgColor) == 0) { tileBgPaint = null; } else { tileBgPaint = new Paint(); tileBgPaint.setStyle(Style.FILL); tileBgPaint.setColor(tileBgColor); } invalidate(); } /** * Set the scale the image will zoom in to when double tapped. This also the scale point where a double tap is interpreted * as a zoom out gesture - if the scale is greater than 90% of this value, a double tap zooms out. Avoid using values * greater than the max zoom. * * @param doubleTapZoomScale New value for double tap gesture zoom scale. */ public final void setDoubleTapZoomScale(float doubleTapZoomScale) { this.doubleTapZoomScale = doubleTapZoomScale; } /** * A density aware alternative to {@link #setDoubleTapZoomScale(float)}; this allows you to express the scale the * image will zoom in to when double tapped in terms of the image pixel density. Values lower than the max scale will * be ignored. A sensible starting point is 160 - the default used by this view. * * @param dpi New value for double tap gesture zoom scale. */ public final void setDoubleTapZoomDpi(int dpi) { DisplayMetrics metrics = getResources().getDisplayMetrics(); float averageDpi = (metrics.xdpi + metrics.ydpi) / 2; setDoubleTapZoomScale(averageDpi / dpi); } /** * Set the type of zoom animation to be used for double taps. See static fields. * * @param doubleTapZoomStyle New value for zoom style. */ public final void setDoubleTapZoomStyle(int doubleTapZoomStyle) { if (!VALID_ZOOM_STYLES.contains(doubleTapZoomStyle)) { throw new IllegalArgumentException("Invalid zoom style: " + doubleTapZoomStyle); } this.doubleTapZoomStyle = doubleTapZoomStyle; } /** * Set the duration of the double tap zoom animation. * * @param durationMs Duration in milliseconds. */ public final void setDoubleTapZoomDuration(int durationMs) { this.doubleTapZoomDuration = Math.max(0, durationMs); } /** * <p> * Provide an {@link Executor} to be used for loading images. By default, {@link AsyncTask#THREAD_POOL_EXECUTOR} * is used to minimise contention with other background work the app is doing. You can also choose * to use {@link AsyncTask#SERIAL_EXECUTOR} if you want to limit concurrent background tasks. * Alternatively you can supply an {@link Executor} of your own to avoid any contention. It is * strongly recommended to use a single executor instance for the life of your application, not * one per view instance. * </p><p> * <b>Warning:</b> If you are using a custom implementation of {@link ImageRegionDecoder}, and you * supply an executor with more than one thread, you must make sure your implementation supports * multi-threaded bitmap decoding or has appropriate internal synchronization. From SDK 21, Android's * {@link android.graphics.BitmapRegionDecoder} uses an internal lock so it is thread safe but * there is no advantage to using multiple threads. * </p> * * @param executor an {@link Executor} for image loading. */ public void setExecutor(@NonNull Executor executor) { this.executor = executor; } /** * Enable or disable eager loading of tiles that appear on screen during gestures or animations, * while the gesture or animation is still in progress. By default this is enabled to improve * responsiveness, but it can result in tiles being loaded and discarded more rapidly than * necessary and reduce the animation frame rate on old/cheap devices. Disable this on older * devices if you see poor performance. Tiles will then be loaded only when gestures and animations * are completed. * * @param eagerLoadingEnabled true to enable loading during gestures, false to delay loading until gestures end */ public void setEagerLoadingEnabled(boolean eagerLoadingEnabled) { this.eagerLoadingEnabled = eagerLoadingEnabled; } /** * Enables visual debugging, showing tile boundaries and sizes. * * @param debug true to enable debugging, false to disable. */ public final void setDebug(boolean debug) { this.debug = debug; } /** * Check if an image has been set. The image may not have been loaded and displayed yet. * * @return If an image is currently set. */ public boolean hasImage() { return uri != null || bitmap != null; } /** * {@inheritDoc} */ @Override public void setOnLongClickListener(OnLongClickListener onLongClickListener) { this.onLongClickListener = onLongClickListener; } /** * Add a listener allowing notification of load and error events. Extend {@link DefaultOnImageEventListener} * to simplify implementation. * * @param onImageEventListener an {@link OnImageEventListener} instance. */ public void setOnImageEventListener(OnImageEventListener onImageEventListener) { this.onImageEventListener = onImageEventListener; } /** * Add a listener for pan and zoom events. Extend {@link DefaultOnStateChangedListener} to simplify * implementation. * * @param onStateChangedListener an {@link OnStateChangedListener} instance. */ public void setOnStateChangedListener(OnStateChangedListener onStateChangedListener) { this.onStateChangedListener = onStateChangedListener; } private void sendStateChanged(float oldScale, PointF oldVTranslate, int origin) { if (onStateChangedListener != null && scale != oldScale) { onStateChangedListener.onScaleChanged(scale, origin); } if (onStateChangedListener != null && !vTranslate.equals(oldVTranslate)) { onStateChangedListener.onCenterChanged(getCenter(), origin); } } /** * Creates a panning animation builder, that when started will animate the image to place the given coordinates of * the image in the center of the screen. If doing this would move the image beyond the edges of the screen, the * image is instead animated to move the center point as near to the center of the screen as is allowed - it's * guaranteed to be on screen. * * @param sCenter Target center point * @return {@link AnimationBuilder} instance. Call {@link CustomSubsamplingScaleImageView.AnimationBuilder#start()} to start the anim. */ @Nullable public AnimationBuilder animateCenter(PointF sCenter) { if (!isReady()) { return null; } return new AnimationBuilder(sCenter); } /** * Creates a scale animation builder, that when started will animate a zoom in or out. If this would move the image * beyond the panning limits, the image is automatically panned during the animation. * * @param scale Target scale. * @return {@link AnimationBuilder} instance. Call {@link CustomSubsamplingScaleImageView.AnimationBuilder#start()} to start the anim. */ @Nullable public AnimationBuilder animateScale(float scale) { if (!isReady()) { return null; } return new AnimationBuilder(scale); } /** * Creates a scale animation builder, that when started will animate a zoom in or out. If this would move the image * beyond the panning limits, the image is automatically panned during the animation. * * @param scale Target scale. * @param sCenter Target source center. * @return {@link AnimationBuilder} instance. Call {@link CustomSubsamplingScaleImageView.AnimationBuilder#start()} to start the anim. */ @Nullable public AnimationBuilder animateScaleAndCenter(float scale, PointF sCenter) { if (!isReady()) { return null; } return new AnimationBuilder(scale, sCenter); } public void setPreloadDimensions(int width, int height) { preloadDimensions = new Point(width, height); } private int getWidthInternal() { if (getWidth() > 0 || null == preloadDimensions) return getWidth(); else return preloadDimensions.x; } private int getHeightInternal() { if (getHeight() > 0 || null == preloadDimensions) return getHeight(); else return preloadDimensions.y; } /** * Builder class used to set additional options for a scale animation. Create an instance using {@link #animateScale(float)}, * then set your options and call {@link #start()}. */ public final class AnimationBuilder { private final float targetScale; private final PointF targetSCenter; private final PointF vFocus; private long duration = 500; private int easing = EASE_IN_OUT_QUAD; private int origin = ORIGIN_ANIM; private boolean interruptible = true; private boolean panLimited = true; private OnAnimationEventListener listener; private AnimationBuilder(PointF sCenter) { this.targetScale = scale; this.targetSCenter = sCenter; this.vFocus = null; } private AnimationBuilder(float scale) { this.targetScale = scale; this.targetSCenter = getCenter(); this.vFocus = null; } private AnimationBuilder(float scale, PointF sCenter) { this.targetScale = scale; this.targetSCenter = sCenter; this.vFocus = null; } private AnimationBuilder(float scale, PointF sCenter, PointF vFocus) { this.targetScale = scale; this.targetSCenter = sCenter; this.vFocus = vFocus; } /** * Desired duration of the anim in milliseconds. Default is 500. * * @param duration duration in milliseconds. * @return this builder for method chaining. */ @NonNull public AnimationBuilder withDuration(long duration) { this.duration = duration; return this; } /** * Whether the animation can be interrupted with a touch. Default is true. * * @param interruptible interruptible flag. * @return this builder for method chaining. */ @NonNull public AnimationBuilder withInterruptible(boolean interruptible) { this.interruptible = interruptible; return this; } /** * Set the easing style. See static fields. {@link #EASE_IN_OUT_QUAD} is recommended, and the default. * * @param easing easing style. * @return this builder for method chaining. */ @NonNull public AnimationBuilder withEasing(int easing) { if (!VALID_EASING_STYLES.contains(easing)) { throw new IllegalArgumentException("Unknown easing type: " + easing); } this.easing = easing; return this; } /** * Add an animation event listener. * * @param listener The listener. * @return this builder for method chaining. */ @NonNull public AnimationBuilder withOnAnimationEventListener(OnAnimationEventListener listener) { this.listener = listener; return this; } /** * Only for internal use. When set to true, the animation proceeds towards the actual end point - the nearest * point to the center allowed by pan limits. When false, animation is in the direction of the requested end * point and is stopped when the limit for each axis is reached. The latter behaviour is used for flings but * nothing else. */ @NonNull private AnimationBuilder withPanLimited(boolean panLimited) { this.panLimited = panLimited; return this; } /** * Only for internal use. Indicates what caused the animation. */ @NonNull private AnimationBuilder withOrigin(int origin) { this.origin = origin; return this; } /** * Starts the animation. */ public void start() { if (anim != null && anim.listener != null) { try { anim.listener.onInterruptedByNewAnim(); } catch (Exception e) { Timber.tag(TAG).w(e, ANIMATION_LISTENER_ERROR); } } int vxCenter = getPaddingLeft() + (getWidthInternal() - getPaddingRight() - getPaddingLeft()) / 2; int vyCenter = getPaddingTop() + (getHeightInternal() - getPaddingBottom() - getPaddingTop()) / 2; float targetScale = limitedScale(this.targetScale); PointF targetSCenter = panLimited ? limitedSCenter(this.targetSCenter.x, this.targetSCenter.y, targetScale, new PointF()) : this.targetSCenter; anim = new Anim(); anim.scaleStart = scale; anim.scaleEnd = targetScale; anim.time = System.currentTimeMillis(); anim.sCenterEndRequested = targetSCenter; anim.sCenterStart = getCenter(); anim.sCenterEnd = targetSCenter; anim.vFocusStart = sourceToViewCoord(targetSCenter); anim.vFocusEnd = new PointF( vxCenter, vyCenter ); anim.duration = duration; anim.interruptible = interruptible; anim.easing = easing; anim.origin = origin; anim.time = System.currentTimeMillis(); anim.listener = listener; if (vFocus != null) { // Calculate where translation will be at the end of the anim float vTranslateXEnd = vFocus.x - (targetScale * anim.sCenterStart.x); float vTranslateYEnd = vFocus.y - (targetScale * anim.sCenterStart.y); ScaleAndTranslate satEnd = new ScaleAndTranslate(targetScale, new PointF(vTranslateXEnd, vTranslateYEnd)); // Fit the end translation into bounds fitToBounds(true, satEnd); // Adjust the position of the focus point at end so image will be in bounds anim.vFocusEnd = new PointF( vFocus.x + (satEnd.vTranslate.x - vTranslateXEnd), vFocus.y + (satEnd.vTranslate.y - vTranslateYEnd) ); } invalidate(); } /** * Given a requested source center and scale, calculate what the actual center will have to be to keep the image in * pan limits, keeping the requested center as near to the middle of the screen as allowed. */ @NonNull private PointF limitedSCenter(float sCenterX, float sCenterY, float scale, @NonNull PointF sTarget) { PointF vTranslate = vTranslateForSCenter(sCenterX, sCenterY, scale); int vxCenter = getPaddingLeft() + (getWidthInternal() - getPaddingRight() - getPaddingLeft()) / 2; int vyCenter = getPaddingTop() + (getHeightInternal() - getPaddingBottom() - getPaddingTop()) / 2; float sx = (vxCenter - vTranslate.x) / scale; float sy = (vyCenter - vTranslate.y) / scale; sTarget.set(sx, sy); return sTarget; } } /** * An event listener for animations, allows events to be triggered when an animation completes, * is aborted by another animation starting, or is aborted by a touch event. Note that none of * these events are triggered if the activity is paused, the image is swapped, or in other cases * where the view's internal state gets wiped or draw events stop. */ @SuppressWarnings({"EmptyMethod", "squid:S1186"}) public interface OnAnimationEventListener { /** * The animation has completed, having reached its endpoint. */ void onComplete(); /** * The animation has been aborted before reaching its endpoint because the user touched the screen. */ void onInterruptedByUser(); /** * The animation has been aborted before reaching its endpoint because a new animation has been started. */ void onInterruptedByNewAnim(); } /** * Default implementation of {@link OnAnimationEventListener} for extension. This does nothing in any method. */ @SuppressWarnings({"EmptyMethod", "squid:S1186"}) public static class DefaultOnAnimationEventListener implements OnAnimationEventListener { @Override public void onComplete() { } @Override public void onInterruptedByUser() { } @Override public void onInterruptedByNewAnim() { } } /** * An event listener, allowing subclasses and activities to be notified of significant events. */ @SuppressWarnings({"EmptyMethod", "squid:S1186"}) public interface OnImageEventListener { /** * Called when the dimensions of the image and view are known, and either a preview image, * the full size image, or base layer tiles are loaded. This indicates the scale and translate * are known and the next draw will display an image. This event can be used to hide a loading * graphic, or inform a subclass that it is safe to draw overlays. */ void onReady(); /** * Called when the full size image is ready. When using tiling, this means the lowest resolution * base layer of tiles are loaded, and when tiling is disabled, the image bitmap is loaded. * This event could be used as a trigger to enable gestures if you wanted interaction disabled * while only a preview is displayed, otherwise for most cases {@link #onReady()} is the best * event to listen to. */ void onImageLoaded(); /** * Called when a preview image could not be loaded. This method cannot be relied upon; certain * encoding types of supported image formats can result in corrupt or blank images being loaded * and displayed with no detectable error. The view will continue to load the full size image. * * @param e The exception thrown. This error is logged by the view. */ void onPreviewLoadError(Exception e); /** * Indicates an error initiliasing the decoder when using a tiling, or when loading the full * size bitmap when tiling is disabled. This method cannot be relied upon; certain encoding * types of supported image formats can result in corrupt or blank images being loaded and * displayed with no detectable error. * * @param e The exception thrown. This error is also logged by the view. */ void onImageLoadError(Exception e); /** * Called when an image tile could not be loaded. This method cannot be relied upon; certain * encoding types of supported image formats can result in corrupt or blank images being loaded * and displayed with no detectable error. Most cases where an unsupported file is used will * result in an error caught by {@link #onImageLoadError(Exception)}. * * @param e The exception thrown. This error is logged by the view. */ void onTileLoadError(Exception e); /** * Called when a bitmap set using ImageSource.cachedBitmap is no longer being used by the View. * This is useful if you wish to manage the bitmap after the preview is shown */ void onPreviewReleased(); } /** * Default implementation of {@link OnImageEventListener} for extension. This does nothing in any method. */ @SuppressWarnings({"EmptyMethod", "squid:S1186"}) public static class DefaultOnImageEventListener implements OnImageEventListener { @Override public void onReady() { } @Override public void onImageLoaded() { } @Override public void onPreviewLoadError(Exception e) { } @Override public void onImageLoadError(Exception e) { } @Override public void onTileLoadError(Exception e) { } @Override public void onPreviewReleased() { } } /** * An event listener, allowing activities to be notified of pan and zoom events. Initialisation * and calls made by your code do not trigger events; touch events and animations do. Methods in * this listener will be called on the UI thread and may be called very frequently - your * implementation should return quickly. */ @SuppressWarnings({"EmptyMethod", "squid:S1186"}) public interface OnStateChangedListener { /** * The scale has changed. Use with {@link #getMaxScale()} and {@link #getMinScale()} to determine * whether the image is fully zoomed in or out. * * @param newScale The new scale. * @param origin Where the event originated from - one of {@link #ORIGIN_ANIM}, {@link #ORIGIN_TOUCH}. */ void onScaleChanged(float newScale, int origin); /** * The source center has been changed. This can be a result of panning or zooming. * * @param newCenter The new source center point. * @param origin Where the event originated from - one of {@link #ORIGIN_ANIM}, {@link #ORIGIN_TOUCH}. */ void onCenterChanged(PointF newCenter, int origin); } /** * Default implementation of {@link OnStateChangedListener}. This does nothing in any method. */ @SuppressWarnings({"EmptyMethod", "squid:S1186"}) public static class DefaultOnStateChangedListener implements OnStateChangedListener { @Override public void onCenterChanged(PointF newCenter, int origin) { } @Override public void onScaleChanged(float newScale, int origin) { } } }
package ae3.restresult; import ae3.util.FilterIterator; import java.lang.reflect.Method; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.AnnotatedElement; import java.util.Map; import java.util.Iterator; import java.util.Collection; /** * REST renderer utility class * @author pashky */ class Util { static String methodToProperty(String name) { if (name.startsWith("get")) { name = name.substring(3); } else if (name.startsWith("is")) { name = name.substring(2); } else { return name; } if (Character.isUpperCase(name.charAt(0))) { if(name.length() > 1) name = name.substring(0, 1).toLowerCase() + name.substring(1); else name = name.toLowerCase(); } return name; } private static RestOut[] getAnnos(AnnotatedElement ae) { RestOuts restOuts = ae.getAnnotation(RestOuts.class); if(restOuts != null) return restOuts.value(); RestOut restOut = ae.getAnnotation(RestOut.class); if(restOut != null) return new RestOut[] { restOut }; return new RestOut[0]; } public static RestOut getAnno(AnnotatedElement ae, Class renderer, Class profile) { for(RestOut a : getAnnos(ae)) { if((a.forProfile() == Object.class || a.forProfile().isAssignableFrom(profile)) && (a.forRenderer() == RestResultRenderer.class || a.forRenderer() == renderer)) return a; } return null; } public static RestOut mergeAnno(RestOut a, AnnotatedElement ae, Class renderer, Class profile) { if(a == null) return Util.getAnno(ae, renderer, profile); return a; } static class Prop { String name; Object value; RestOut outProp; Prop(String name, Object value, RestOut outProp) { this.name = name; this.value = value; this.outProp = outProp; } } static boolean isEmpty(Object o) { if(o instanceof String) return "".equals(o); if(o instanceof Collection) return ((Collection)o).isEmpty(); if(o instanceof Iterable) return ((Iterable)o).iterator().hasNext(); if(o instanceof Iterator) return ((Iterator)o).hasNext(); if(o instanceof Map) return ((Map)o).isEmpty(); return false; } static Iterable<Prop> iterableProperties(final Object o, final Class profile, final RestResultRenderer renderer) { final Class rendererClass = renderer.getClass(); if(o instanceof Map) return new Iterable<Prop>() { public Iterator<Prop> iterator() { @SuppressWarnings("unchecked") Iterator<Map.Entry> fromiter = ((Map) o).entrySet().iterator(); return new FilterIterator<Map.Entry,Prop>(fromiter) { public Prop map(Map.Entry e) { return e.getValue() != null ? new Prop(e.getKey().toString(), e.getValue(), null) : null; } }; } }; return new Iterable<Prop>() { public Iterator<Prop> iterator() { final Method[] methods = o.getClass().getMethods(); boolean noAnnos = true; for(Method m : methods) if(m.isAnnotationPresent(RestOut.class)) noAnnos = false; final boolean checkAnno = !noAnnos; return new Iterator<Prop>() { int i; Object value; RestOut restOut; { i = 0; skip(); } public boolean hasNext() { return i < methods.length; } public Prop next() { Method m = methods[i]; Object value = this.value; RestOut restOut = this.restOut; String name; if(restOut != null && restOut.name().length() != 0) name = restOut.name(); else name = methodToProperty(m.getName()); ++i; skip(); return new Prop(name, value, restOut); } private void skip() { while(i < methods.length) { if(methods[i].getParameterTypes().length == 0) { if(checkAnno) { restOut = getAnno(methods[i], rendererClass, profile); if(restOut != null) { try { value = methods[i].invoke(o, (Object[])null); if(value != null) { if(restOut.exposeEmpty() || !isEmpty(value)) { return; } } } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } } } else if((methods[i].getName().startsWith("get") || methods[i].getName().startsWith("is")) && !methods[i].getName().equals("getClass")) { try { try { value = methods[i].invoke(o, (Object[])null); } catch(IllegalAccessException e) { methods[i].setAccessible(true); value = methods[i].invoke(o, (Object[])null); } if(value != null) { restOut = null; return; } } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } } } ++i; } } public void remove() { } }; } }; } }
package me.thenightmancodeth.classi.views.fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import io.realm.Realm; import io.realm.RealmResults; import me.thenightmancodeth.classi.R; import me.thenightmancodeth.classi.models.Api; import me.thenightmancodeth.classi.models.data.Class; import me.thenightmancodeth.classi.models.data.Grade; import me.thenightmancodeth.classi.models.data.GradeType; import me.thenightmancodeth.classi.views.ClassRecycleAdapter; import me.thenightmancodeth.classi.views.GradeRecycleAdapter; public class GradesListFragment extends Fragment { @BindView(R.id.grades_list_rv) RecyclerView gradesRecycler; Realm realm; String className; Class thisClass; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.grade_list_fragment, container, false); ButterKnife.bind(this, view); Realm.init(getContext()); realm = Realm.getDefaultInstance(); className = getArguments().getString("class_name"); thisClass = realm.where(Class.class).equalTo("name", className).findFirst(); return view; } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { gradesRecycler.setHasFixedSize(true); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext()); gradesRecycler.setLayoutManager(layoutManager); refreshGrades(); } private List<Grade> getFakeGrades() { List<Grade> gradest = new ArrayList<>(); for (int i = 10; i > 0; i Grade newGrade = new Grade(); newGrade.setGrade(10 * i); newGrade.setName("Grade " +i); newGrade.setDueDate("03/03/2017"); newGrade.setDueTime("03:30 PM"); newGrade.setDescription("This is the " +i +" grade"); GradeType type = new GradeType(); type.setPercent(50); type.setType("Type " +i); gradest.add(newGrade); } return gradest; } public List<Grade> getGradesFromRealm() { List<Grade> arrayListGrades = new ArrayList<>(); for (Grade g : thisClass.getGrades()) { arrayListGrades.add(g); } return arrayListGrades; } public void refreshGrades() { GradeRecycleAdapter adapter = new GradeRecycleAdapter(getGradesFromRealm(), getContext()); gradesRecycler.setAdapter(adapter); } }
package com.shuimin.table; import com.shuimin.table.spi.ExpressionEngine; import com.shuimin.table.spi.expr.SimpleExprEngine; import org.apache.poi.hssf.usermodel.*; import pond.common.S; import pond.common.f.Function; import pond.common.f.Tuple; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.*; import static pond.common.f.Tuple.t2; public class XLSTable extends RowBasedModelTable implements Closeable { ExpressionEngine engine = new SimpleExprEngine(); InputStream is = null; //HSSFWorkbook 97-2003 public final HSSFWorkbook workbook; //sheet final HSSFSheet sheet; //Cell private int sheet_cols = 0; private int sheet_rows = 0; private Object[][] _value; //constructor public XLSTable(InputStream is, final Map<Integer, Function<Object, HSSFCell>> parsers) throws IOException { Map<Integer, Function<Object, HSSFCell>> customerParsers = S.avoidNull(parsers, Collections.emptyMap()); //workbook workbook = new HSSFWorkbook(is); this.is = is; sheet = workbook.getSheetAt(workbook.getActiveSheetIndex()); System.out.println(sheet.getSheetName()); sheet_rows = sheet.getLastRowNum() + 1; for (int i = 0; i < sheet_rows; i++) { HSSFRow row = sheet.getRow(i); // in case row is an "empty" row if (row != null) { int _i = row.getPhysicalNumberOfCells(); sheet_cols = S.math.max(sheet_cols, _i); } } _value = new Object[sheet_rows][sheet_cols]; for (int i = 0; i < sheet_rows; i++) { HSSFRow row = sheet.getRow(i); if (row != null) for (int j = 0; j < sheet_cols; j++) { _value[i][j] = cellValue(row.getCell(j), customerParsers.get(j)); } else for (int j = 0; j < sheet_cols; j++) { _value[i][j] = ""; } } } public XLSRow row(int i, final Map<Integer, Function<Object, HSSFCell>> parsers) { Map<Integer, Function<Object, HSSFCell>> customerParsers = S.avoidNull(parsers, Collections.emptyMap()); if (i >= this.rows()) throw new IllegalArgumentException("" + i + "not a valid rowNum"); HSSFRow rowline = sheet.getRow(i); int filledColumns = rowline.getLastCellNum(); XLSRow list = new XLSRow(filledColumns); for (int j = 0; j < filledColumns; j++) { list.add(cellValue(rowline.getCell(j), customerParsers.get(j))); } return list; } public <E> List<E> parse(int r_b, int r_e, Map<Integer, Function<Object, HSSFCell>> customParsers, Function<E, XLSRow> row_mapper){ List<E> ret = new ArrayList<>(); for (int i = r_b; i < r_e; i++) { XLSRow _row = this.row(i, customParsers); E e = row_mapper.apply(_row); ret.add(e); } return ret; } public XLSTable(InputStream is) throws IOException{ this(is, Collections.emptyMap()); } public InputStream source() { return is; } public XLSTable init(Function.F2<Object, Integer, Integer> provider) { for (int i = 0, length = this.rows(); i < length; i++) { for (int j = 0; j < this.row(i).size(); j++) { this.set(i, j, provider.apply(i, j)); } } return this; } @Override public MemoryTable init(int i, int j, Object initVal) throws IOException { throw new UnsupportedOperationException(); } //TODO @Override public int cols() { return sheet_cols; } //sheet @Override public int rows() { return sheet_rows; } @Override public XLSRow row(int i) { return row(i, Collections.emptyMap()); } //TODO ugly private Object cellValue(HSSFCell cell, Function<Object, HSSFCell> customerParser) { if (cell == null) return null; if (customerParser == null) { //default parse int type = cell.getCellType(); switch (type) { case HSSFCell.CELL_TYPE_BLANK: return ""; case HSSFCell.CELL_TYPE_BOOLEAN: return cell.getBooleanCellValue(); case HSSFCell.CELL_TYPE_ERROR: return cell.getErrorCellValue(); case HSSFCell.CELL_TYPE_FORMULA: return cell.getCellFormula(); case HSSFCell.CELL_TYPE_NUMERIC: return HSSFDateUtil.isCellDateFormatted(cell) ? cell.getDateCellValue() : cell.getNumericCellValue(); case HSSFCell.CELL_TYPE_STRING: return cell.getStringCellValue(); default: return cell.getStringCellValue(); } } else { return customerParser.apply(cell); } } private void setCellValue(HSSFCell cell, Object val) { if (cell != null) { if (val == null) { //todo cell.setCellValue(""); return; } Class c = val.getClass(); if (val instanceof Date) { cell.setCellValue((Date) val); } else if (val instanceof Integer) { cell.setCellValue((Integer) val); } else if (val instanceof Float) { cell.setCellValue((Float) val); } else if (val instanceof Double) { cell.setCellValue((Double) val); } else if (c.isPrimitive()) { cell.setCellValue((double) val); } else { cell.setCellValue(val.toString()); } } } @Override public List<Object> col(int i) { List<Object> list = new ArrayList<>(); for (int row = 0; row < sheet_rows; row++) { list.add(_value[row][i]); } return list; } //isheetjk @Override public Object get(int i, int j) { return _value[i][j]; } @Override public void set(int i, int j, Object val) { _value[i][j] = val; } @Override public Object[][] toArray() { return _value.clone(); } public void close() { //isInputStream if (is != null) { try { is.close(); } catch (IOException e) { throw new RuntimeException(e); } } } @Override public String toString() { return S.dump(_value); } @Override protected Tuple<String, Object> resolve(int i, int j, String value) { if (engine.isExpression(value)) return t2(engine.getName(value), null); else return null; } private void _save() { for (int i = 0; i < sheet_rows; i++) { HSSFRow row = sheet.getRow(i); for (int j = 0; j < row.getLastCellNum(); j++) { Object val = _value[i][j]; HSSFCell cell = row.getCell(j); setCellValue(cell, val); } } } public void save(OutputStream out) throws IOException { this.workbook.write(out); } }
package org.dasfoo.rover.android.client.auth; import android.Manifest; import android.accounts.AccountManager; import android.app.Activity; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.util.Log; import com.google.android.gms.common.GoogleApiAvailability; import com.google.android.gms.security.ProviderInstaller; import com.google.api.client.extensions.android.http.AndroidHttp; import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential; import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.services.storage.Storage; import com.google.api.services.storage.StorageScopes; import org.dasfoo.rover.android.client.R; import org.dasfoo.rover.android.client.menu.SharedPreferencesHandler; import org.dasfoo.rover.android.client.util.LogUtil; import org.dasfoo.rover.android.client.util.ResultCallback; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Collections; import butterknife.ButterKnife; public class GetRoverPasswordActivity extends AppCompatActivity implements ProviderInstaller.ProviderInstallListener { private static final String TAG = LogUtil.tagFor(GetRoverPasswordActivity.class); private GoogleAccountCredential mAccountCredential; private Storage mStorage; private ResultCallback mActivityResultCallback; /** * {@inheritDoc} */ @Override public void onRequestPermissionsResult(final int requestCode, @NonNull final String[] permissions, @NonNull final int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); mActivityResultCallback.onRequestPermissionsResult(requestCode, permissions, grantResults); } @Override protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) { super.onActivityResult(requestCode, resultCode, data); mActivityResultCallback.onActivityResult(requestCode, resultCode, data); } @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_get_rover_password); ButterKnife.bind(this); mActivityResultCallback = new ResultCallback(this); mAccountCredential = GoogleAccountCredential.usingOAuth2( this, Collections.singleton(StorageScopes.DEVSTORAGE_READ_ONLY)); mStorage = new Storage.Builder( AndroidHttp.newCompatibleTransport(), new JacksonFactory(), mAccountCredential ).build(); // Android relies on a security Provider to provide secure network communications. // It verifies that the security provider is up-to-date. ProviderInstaller.installIfNeededAsync(this, this); } /** * Callback for successful installation of the security provider. */ @Override public void onProviderInstalled() { mActivityResultCallback.startPermissionRequestWithResultHandler( Manifest.permission.GET_ACCOUNTS, getString(R.string.get_accounts_permission_rationale), new ResultCallback.RequestPermissionListener() { @Override public void handle(final int grantResult) { if (grantResult == PackageManager.PERMISSION_GRANTED) { selectAccount(); } else { setResult(Activity.RESULT_CANCELED); finish(); } } } ); } /** * Callback for the failure to install a security provider. * * @param errorCode error code * @param recoveryIntent an intent that can be used to recover from the failure */ @Override public void onProviderInstallFailed(final int errorCode, final Intent recoveryIntent) { final GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance(); if (googleAPI.isUserResolvableError(errorCode)) { mActivityResultCallback.startActivityWithResultHandler( (Intent) null, new ResultCallback.AbstractActivityResultListener() { @Override public void start(final int requestCode) { googleAPI.getErrorDialog(GetRoverPasswordActivity.this, errorCode, requestCode).show(); } @Override public void handle(final int resultCode, final Intent data) { ProviderInstaller.installIfNeededAsync( GetRoverPasswordActivity.this, GetRoverPasswordActivity.this); } }); } else { buildCancelableAlertDialog() // TODO(dotdoom): get descriptive error message from the code .setMessage(getString(R.string.security_provider_failed_message, errorCode)) .show(); } } private void selectAccount() { final SharedPreferencesHandler sharedPreferences = new SharedPreferencesHandler(this); try { String accountName = sharedPreferences.getAccountName(); mAccountCredential.setSelectedAccountName(accountName); if (mAccountCredential.getSelectedAccountName() != null) { downloadPassword(); return; } } catch (IllegalArgumentException e) { Log.i(TAG, "Can't get pre-saved account name: " + e.getMessage()); } // The account we have in Preferences may no longer exist. Request a new one. mActivityResultCallback.startActivityWithResultHandler( mAccountCredential.newChooseAccountIntent(), new ResultCallback.AbstractActivityResultListener() { @Override public void handle(final int resultCode, final Intent data) { if (resultCode == Activity.RESULT_OK && data != null && data.getExtras() != null) { String accountName = data.getExtras().getString( AccountManager.KEY_ACCOUNT_NAME); if (accountName != null) { sharedPreferences.setAccountName(accountName); mAccountCredential.setSelectedAccountName(accountName); downloadPassword(); } } else { setResult(Activity.RESULT_CANCELED); finish(); } } }); } private void downloadPassword() { Storage.Objects.Get getObject; try { getObject = mStorage.objects().get( // TODO(dotdoom): use preferences to get this value "rover-authentication", // E-mail is the same as account name for GoogleCredential. mAccountCredential.getSelectedAccountName() ); } catch (IOException e) { buildCancelableAlertDialog() .setMessage(e.getMessage()) .setPositiveButton(R.string.retry_button, new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int which) { downloadPassword(); } }) .show(); return; } getObject.getMediaHttpDownloader().setDirectDownloadEnabled(true); new DownloadPasswordTask().execute(getObject); } private AlertDialog.Builder buildCancelableAlertDialog() { return new AlertDialog.Builder(this) .setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(final DialogInterface dialog) { setResult(Activity.RESULT_CANCELED); finish(); } }); } private class DownloadPasswordTask extends AsyncTask<Storage.Objects.Get, Void, String> { private IOException mIOError; @Override protected String doInBackground(final Storage.Objects.Get... params) { ByteArrayOutputStream b = new ByteArrayOutputStream(); try { params[0].executeMediaAndDownloadTo(b); return b.toString(); } catch (IOException e) { mIOError = e; } return null; } @Override protected void onPostExecute(final String password) { if (password != null) { setResult(Activity.RESULT_OK, new Intent( getClass().getCanonicalName(), new Uri.Builder() .authority( mAccountCredential.getSelectedAccountName() + ":" + password) .build())); finish(); return; } if (mIOError instanceof UserRecoverableAuthIOException) { mActivityResultCallback.startActivityWithResultHandler( ((UserRecoverableAuthIOException) mIOError).getIntent(), new ResultCallback.AbstractActivityResultListener() { @Override public void handle(final int resultCode, final Intent data) { if (resultCode == Activity.RESULT_OK) { downloadPassword(); } else { setResult(Activity.RESULT_CANCELED); finish(); } } } ); return; } buildCancelableAlertDialog() .setMessage(mIOError.getMessage()) .setPositiveButton(R.string.retry_button, new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int which) { downloadPassword(); } }) .show(); } } }
package se.chalmers.dat255.sleepfighter.model.challenge; import java.util.Collections; import java.util.Map; import se.chalmers.dat255.sleepfighter.model.IdProvider; import com.google.common.collect.Maps; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; /** * ChallengeConfig models what challenge to produce, and with what settings. * * @author Centril<twingoow@gmail.com> / Mazdak Farrokhzad. * @version 1.0 * @since Oct 3, 2013 */ @DatabaseTable(tableName = "challenge_config") public class ChallengeConfig implements IdProvider { public static final String SET_FOREIGN_COLUMN = "challenge_set_id"; @DatabaseField(canBeNull = false, columnName = SET_FOREIGN_COLUMN) private int challengeSetId; @DatabaseField(generatedId = true) private int id; @DatabaseField private boolean enabled = true; @DatabaseField private ChallengeType type; private Map<String, String> params; /** * Constructs the config object with no parameters. */ public ChallengeConfig() { this.params = Maps.newHashMap(); } /** * Constructs the config object with type. * * @param type the type of the config. * @param enabled true if challenge is to be enabled. See {@link #setEnabled(boolean)} */ public ChallengeConfig( ChallengeType type, boolean enabled ) { this( type, enabled, null ); } /** * Constructs the config object with given its type, parameters and whether or not to enable it. * * @param type the type of the config. * @param enabled true if challenge is to be enabled. See {@link #setEnabled(boolean)} * @param params the initial parameters to use for config. */ public ChallengeConfig( ChallengeType type, boolean enabled, Map<String, String> params ) { this.type = type; this.params = params; this.enabled = enabled; } /** * Returns the id of the owner challenge set. * * @return the id of the set. */ public int getSetId() { return this.challengeSetId; } @Override public int getId() { return this.id; } /** * Returns the type of this config, used to factorize a challenge. * * @return the type. */ public ChallengeType getType() { return this.type; } /** * Returns whether or not the specific challenge given by {@link #getType()} is enabled or not. * * @return true if it is enabled. */ public boolean isEnabled() { return this.enabled; } /** * Returns a settings parameter for this ChallengeConfig. * * @param key the setting key, challenge specific. * @return the value, challenge specific. */ public String getParam( String key ) { return this.params.get( key ); } /** * Returns an unmodifiable view of all parameters for this challenge config. * * @return the parameters. */ public Map<String, String> getParams() { return Collections.unmodifiableMap( this.params ); } /** * Sets whether or not to enable challenge. * * @param enabled if true, challenge is enabled, otherwise it is disabled. * @return true if {@link #isEnabled()} will return the inverse value after calling {@link #setEnabled(boolean)}. */ protected boolean setEnabled( boolean enabled ) { if ( this.enabled == enabled ) { return false; } this.enabled = enabled; return true; } /** * Sets a settings parameter for this ChallengeConfig. * * @param key the setting key, challenge specific. * @param value the value, challenge specific. null is converted to an empty string. * @return the old value, or null if not set before. */ protected String setParam( String key, String value ) { return this.params.put( key, value == null ? "" : null ); } /** * <p><strong>NOTE:</strong> this method is only intended for persistence purposes.<br/> * This method is motivated and needed due to OrmLite not supporting results from joins.<br/> * This is also a better method than reflection which is particularly expensive on android.</p> * * <p>Sets a {@link ChallengeParam}, bypassing any and all checks, and does not send any event to bus.</p> * * @param param the {@link ChallengeParam} to set. */ public void setFetched( ChallengeParam param ) { this.params.put( param.getKey(), param.getValue() ); } /** * <p><strong>NOTE:</strong> this method is only intended for persistence purposes.<br/> * This method is motivated and needed due to OrmLite not supporting results from joins.<br/> * This is also a better method than reflection which is particularly expensive on android.</p> * * <p>Sets the set ID owning this config, bypassing any and all checks.</p> * * @param id the id of the owning set, to use. */ public void setFetchedSetId( int id ) { this.challengeSetId = id; } }
package br.ufsc.lehmann.msm.artigo.problems; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import com.google.common.collect.Multimap; import com.google.common.collect.MultimapBuilder; import br.ufsc.core.trajectory.EqualsDistanceFunction; import br.ufsc.core.trajectory.Semantic; import br.ufsc.core.trajectory.SemanticTrajectory; import br.ufsc.core.trajectory.StopSemantic; import br.ufsc.core.trajectory.TPoint; import br.ufsc.core.trajectory.TemporalDuration; import br.ufsc.core.trajectory.semantic.AttributeDescriptor; import br.ufsc.core.trajectory.semantic.AttributeType; import br.ufsc.core.trajectory.semantic.Move; import br.ufsc.core.trajectory.semantic.Stop; import br.ufsc.db.source.DataRetriever; import br.ufsc.db.source.DataSource; import br.ufsc.db.source.DataSourceType; import br.ufsc.lehmann.AngleDistance; import br.ufsc.lehmann.DTWDistance; import br.ufsc.lehmann.EllipsesDistance; import br.ufsc.lehmann.MoveSemantic; import br.ufsc.lehmann.NumberDistance; import br.ufsc.utils.Angle; import br.ufsc.utils.Distance; import br.ufsc.utils.LatLongDistanceFunction; public class InvolvesDatabaseReader implements IDataReader { private static final LatLongDistanceFunction DISTANCE_FUNCTION = new LatLongDistanceFunction(); public static final BasicSemantic<Integer> DIMENSAO_DATA = new BasicSemantic<>(3); public static final BasicSemantic<Integer> WEEK = new BasicSemantic<>(4); public static final BasicSemantic<Integer> DAY_OF_WEEK = new BasicSemantic<>(5); public static final BasicSemantic<Integer> USER_ID = new BasicSemantic<>(6); public static final StopSemantic STOP_CENTROID_SEMANTIC = new StopSemantic(7, new AttributeDescriptor<Stop, TPoint>(AttributeType.STOP_CENTROID, DISTANCE_FUNCTION)); public static final StopSemantic STOP_STREET_NAME_SEMANTIC = new StopSemantic(7, new AttributeDescriptor<Stop, String>(AttributeType.STOP_STREET_NAME, new EqualsDistanceFunction<String>())); public static final StopSemantic STOP_NAME_SEMANTIC = new StopSemantic(7, new AttributeDescriptor<Stop, String>(AttributeType.STOP_NAME, new EqualsDistanceFunction<String>())); public static final MoveSemantic MOVE_ANGLE_SEMANTIC = new MoveSemantic(8, new AttributeDescriptor<Move, Double>(AttributeType.MOVE_ANGLE, new AngleDistance())); public static final MoveSemantic MOVE_DISTANCE_SEMANTIC = new MoveSemantic(8, new AttributeDescriptor<Move, Double>(AttributeType.MOVE_TRAVELLED_DISTANCE, new NumberDistance())); public static final MoveSemantic MOVE_TEMPORAL_DURATION_SEMANTIC = new MoveSemantic(8, new AttributeDescriptor<Move, Double>(AttributeType.MOVE_DURATION, new NumberDistance())); public static final MoveSemantic MOVE_POINTS_SEMANTIC = new MoveSemantic(8, new AttributeDescriptor<Move, TPoint[]>(AttributeType.MOVE_POINTS, new DTWDistance(DISTANCE_FUNCTION))); public static final MoveSemantic MOVE_ELLIPSES_SEMANTIC = new MoveSemantic(8, new AttributeDescriptor<Move, TPoint[]>(AttributeType.MOVE_POINTS, new EllipsesDistance(DISTANCE_FUNCTION))); public static final BasicSemantic<String> TRAJECTORY_IDENTIFIER = new BasicSemantic<String>(9) { @Override public String getData(SemanticTrajectory p, int i) { return USER_ID.getData(p, i) + "/" + DAY_OF_WEEK.getData(p, i); } }; public static final BasicSemantic<String> WEEKLY_TRAJECTORY_IDENTIFIER = new BasicSemantic<String>(10) { @Override public String getData(SemanticTrajectory p, int i) { return USER_ID.getData(p, i) + "/" + WEEK.getData(p, i); } }; private static final String SCHEMA = "involves"; private boolean onlyStops; private String baseTable; private String stopMove_table; private boolean weekly; public InvolvesDatabaseReader(boolean onlyStops) { this(onlyStops, false, null, null); } public InvolvesDatabaseReader(boolean onlyStops, boolean weekly, String year_month, String stopMove_table) { this.onlyStops = onlyStops; this.weekly = weekly; this.baseTable = year_month == null ? "" : year_month; this.stopMove_table = stopMove_table == null ? "" : stopMove_table; } public List<SemanticTrajectory> read() { try { return internalRead(); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException | SQLException e) { throw new RuntimeException(e); } } private List<SemanticTrajectory> internalRead() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException { DataSource source = new DataSource("postgres", "postgres", "localhost", 5432, "postgis", DataSourceType.PGSQL, "public.amsterdan_park_cbsmot", null, null); DataRetriever retriever = source.getRetriever(); Map<Integer, Stop> stops = new HashMap<>(); Map<Integer, Move> moves = new HashMap<>(); Multimap<String, InvolvesRecord> records = MultimapBuilder.hashKeys().linkedListValues().build(); Connection conn = retriever.getConnection(); try { System.out.println("Executing SQL..."); conn.setAutoCommit(false); Statement st = conn.createStatement(); st.setFetchSize(1000); ResultSet stopsData = st.executeQuery( "SELECT id, start_timestamp, end_timestamp, start_lat, start_lon, end_lat, end_lon, begin, length, longitude, latitude, \"closest_PDV\", \"PDV_distance\", is_home, id_colaborador_unidade, \"closest_colab_PDV\" as closest_colab_pdv, \"colab_PDV_distance\"\r\n" + " FROM " + SCHEMA + ".\"stops_FastCBSMoT" + stopMove_table + "\";"); while (stopsData.next()) { int stopId = stopsData.getInt("id"); Stop stop = stops.get(stopId); if (stop == null) { stop = new Stop(stopId, stopsData.getString("closest_colab_pdv"), stopsData.getTimestamp("start_timestamp").getTime(), stopsData.getTimestamp("end_timestamp").getTime(), new TPoint(stopsData.getDouble("start_lat"), stopsData.getDouble("start_lon")), stopsData.getInt("begin"), new TPoint(stopsData.getDouble("end_lat"), stopsData.getDouble("end_lon")), stopsData.getInt("length"), new TPoint(stopsData.getDouble("latitude"), stopsData.getDouble("longitude")), null, null ); stops.put(stopId, stop); } } stopsData.close(); ResultSet movesData = st .executeQuery("SELECT id, id_colaborador_unidade, start_timestamp, end_timestamp, start_stop_id, end_stop_id\r\n" + " FROM " + SCHEMA + ".\"moves_FastCBSMoT" + stopMove_table + "\""); while (movesData.next()) { int moveId = movesData.getInt("id"); Move move = moves.get(moveId); if (move == null) { int startStopId = movesData.getInt("start_stop_id"); if (movesData.wasNull()) { startStopId = -1; } int endStopId = movesData.getInt("end_stop_id"); if (movesData.wasNull()) { endStopId = -1; } Stop startStop = stops.get(startStopId); Stop endStop = stops.get(endStopId); move = new Move(moveId, startStop, endStop, movesData.getTimestamp("start_timestamp").getTime(), movesData.getTimestamp("end_timestamp").getTime(), -1, -1, null); move.setAttribute(AttributeType.MOVE_USER, movesData.getInt("id_colaborador_unidade")); moves.put(moveId, move); } } movesData.close(); st.close(); String sql = "select (gps.id_usuario::text || gps.id_dimensao_data::text || gps.id_dado_gps::text) as id_dado_gps, " + "gps.id_usuario, col.id_colaborador_unidade, gps.id_dimensao_data, dt.dia_semana, dt.semana, dt_coordenada, " + "st_x(st_transform(st_setsrid(st_makepoint(gps.longitude, gps.latitude), 4326), 900913)) as lat, " + "st_y(st_transform(st_setsrid(st_makepoint(gps.longitude, gps.latitude), 4326), 900913)) as lon, " + "case when map.is_stop = true then map.semantic_id else null end as semantic_stop_id, " + "case when map.is_move = true then map.semantic_id else null end as semantic_move_id " + "from " + SCHEMA + ".\"dadoGps" + baseTable + "\" gps "; sql += "inner join " + SCHEMA + ".dimensao_data dt on dt.id = gps.id_dimensao_data "; sql += "inner join " + SCHEMA + ".colaboradores col on col.id_usuario = gps.id_usuario "; sql += "left join " + SCHEMA + ".\"stops_moves_FastCBSMoT" + stopMove_table + "\" map on (gps.id_usuario::text || gps.id_dimensao_data::text || gps.id_dado_gps::text)::bigint = map.gps_point_id "; sql += "where provedor = 'gps' "; //sql += "and gps.id_dimensao_data= 405 ";// sql += "order by gps.id_usuario, gps.id_dimensao_data, gps.dt_coordenada, gps.id_dado_gps"; PreparedStatement preparedStatement = conn.prepareStatement(sql); ResultSet data = preparedStatement.executeQuery(); System.out.println("Fetching..."); while(data.next()) { Integer stopId = data.getInt("semantic_stop_id"); if(data.wasNull()) { stopId = null; } Integer moveId = data.getInt("semantic_move_id"); if(data.wasNull()) { moveId = null; } InvolvesRecord record = new InvolvesRecord( data.getLong("id_dado_gps"), data.getInt("id_usuario"), data.getInt("id_colaborador_unidade"), data.getInt("id_dimensao_data"), data.getInt("semana"), data.getInt("dia_semana"), data.getTimestamp("dt_coordenada"), data.getDouble("lat"), data.getDouble("lon"), stopId, moveId ); if(weekly) { records.put(record.getId_usuario() + "/" + record.getSemana(), record); } else { records.put(record.getId_usuario() + "/" + record.getId_dimensao_data(), record); } } data.close(); preparedStatement.close(); } finally { conn.close(); } System.out.printf("Loaded %d GPS points from database\n", records.size()); System.out.printf("Loaded %d trajectories from database\n", records.keySet().size()); List<SemanticTrajectory> ret = null; List<Move> usedMoves = new ArrayList<Move>(); if(onlyStops) { ret = readStopsTrajectories(stops, moves, records, usedMoves); } else { ret = readRawPoints(stops, moves, records); } compute(usedMoves); return ret; } private List<SemanticTrajectory> readStopsTrajectories(Map<Integer, Stop> stops, Map<Integer, Move> moves, Multimap<String, InvolvesRecord> records, List<Move> usedMoves) { List<SemanticTrajectory> ret = new ArrayList<>(); Set<String> keys = records.keySet(); DescriptiveStatistics stats = new DescriptiveStatistics(); for (String trajId : keys) { SemanticTrajectory s = new SemanticTrajectory(trajId, 11); Collection<InvolvesRecord> collection = records.get(trajId); int i = 0; for (InvolvesRecord record : collection) { if(record.getSemanticStopId() == null && record.getSemanticMoveId() == null) { continue; } TPoint point = new TPoint(record.getLat(), record.getLon()); if(record.getSemanticStopId() != null) { Stop stop = stops.remove(record.getSemanticStopId()); if(stop == null) { continue; } stop.addPoint(point); if(i > 0) { if(STOP_CENTROID_SEMANTIC.getData(s, i - 1) == stop) { continue; } Stop previousStop = STOP_CENTROID_SEMANTIC.getData(s, i - 1); if(previousStop != null && previousStop.getNextMove() == null) { Move move = new Move(-1, previousStop, stop, previousStop.getEndTime(), stop.getStartTime(), stop.getBegin() - 1, 0, new TPoint[0], Angle.getAngle(previousStop.getEndPoint(), stop.getStartPoint()), Distance.getDistance(new TPoint[] {previousStop.getEndPoint(), stop.getStartPoint()}, DISTANCE_FUNCTION)); previousStop.setNextMove(move); stop.setPreviousMove(move); } } s.addData(i, STOP_CENTROID_SEMANTIC, stop); s.addData(i, Semantic.TEMPORAL, new TemporalDuration(Instant.ofEpochMilli(stop.getStartTime()), Instant.ofEpochMilli(stop.getEndTime()))); s.addData(i, Semantic.GID, record.getId()); s.addData(i, Semantic.SPATIAL_LATLON, stop.getCentroid()); s.addData(i, USER_ID, record.getId_usuario()); s.addData(i, DIMENSAO_DATA, record.getId_dimensao_data()); s.addData(i, WEEK, record.getSemana()); s.addData(i, DAY_OF_WEEK, record.getDiaSemana()); s.addData(i, TRAJECTORY_IDENTIFIER, TRAJECTORY_IDENTIFIER.getData(s, i)); s.addData(i, WEEKLY_TRAJECTORY_IDENTIFIER, WEEKLY_TRAJECTORY_IDENTIFIER.getData(s, i)); i++; } else if(record.getSemanticMoveId() != null) { Move move = moves.get(record.getSemanticMoveId()); if(move == null) { throw new RuntimeException("Move does not found"); } if(!usedMoves.contains(move)) { usedMoves.add(move); } if(move.getStart() != null) { move.getStart().setNextMove(move); } if(move.getEnd() != null) { move.getEnd().setPreviousMove(move); } TPoint[] points = (TPoint[]) move.getAttribute(AttributeType.MOVE_POINTS); List<TPoint> a = new ArrayList<TPoint>(points == null ? Collections.emptyList() : Arrays.asList(points)); a.add(point); move.setAttribute(AttributeType.MOVE_POINTS, a.toArray(new TPoint[a.size()])); move.setAttribute(AttributeType.TRAJECTORY, s); } } if(s.length() > 0) { stats.addValue(s.length()); ret.add(s); } } System.out.printf("Semantic Trajectories statistics: mean - %.2f, min - %.2f, max - %.2f, sd - %.2f\n", stats.getMean(), stats.getMin(), stats.getMax(), stats.getStandardDeviation()); return ret; } private List<SemanticTrajectory> readRawPoints(Map<Integer, Stop> stops, Map<Integer, Move> moves, Multimap<String, InvolvesRecord> records) { List<SemanticTrajectory> ret = new ArrayList<>(); Set<String> keys = records.keySet(); DescriptiveStatistics stats = new DescriptiveStatistics(); for (String trajId : keys) { SemanticTrajectory s = new SemanticTrajectory(trajId, 11); Collection<InvolvesRecord> collection = records.get(trajId); int i = 0; for (InvolvesRecord record : collection) { s.addData(i, Semantic.GID, record.getId()); TPoint point = new TPoint(record.getId(), record.getLat(), record.getLon(), record.getDt_coordenada()); s.addData(i, Semantic.SPATIAL, point); s.addData(i, Semantic.TEMPORAL, new TemporalDuration(Instant.ofEpochMilli(record.getDt_coordenada().getTime()), Instant.ofEpochMilli(record.getDt_coordenada().getTime()))); s.addData(i, USER_ID, record.getId_usuario()); s.addData(i, WEEK, record.getSemana()); s.addData(i, DAY_OF_WEEK, record.getDiaSemana()); s.addData(i, DIMENSAO_DATA, record.getId_dimensao_data()); s.addData(i, TRAJECTORY_IDENTIFIER, TRAJECTORY_IDENTIFIER.getData(s, i)); s.addData(i, WEEKLY_TRAJECTORY_IDENTIFIER, WEEKLY_TRAJECTORY_IDENTIFIER.getData(s, i)); if(record.getSemanticStopId() != null) { Stop stop = stops.get(record.getSemanticStopId()); s.addData(i, STOP_CENTROID_SEMANTIC, stop); } if(record.getSemanticMoveId() != null) { Move move = moves.get(record.getSemanticMoveId()); TPoint[] points = (TPoint[]) move.getAttribute(AttributeType.MOVE_POINTS); List<TPoint> a = new ArrayList<TPoint>(points == null ? Collections.emptyList() : Arrays.asList(points)); a.add(point); move.setAttribute(AttributeType.MOVE_POINTS, a.toArray(new TPoint[a.size()])); s.addData(i, MOVE_ANGLE_SEMANTIC, move); } i++; } stats.addValue(s.length()); ret.add(s); } System.out.printf("Semantic Trajectories statistics: mean - %.2f, min - %.2f, max - %.2f, sd - %.2f\n", stats.getMean(), stats.getMin(), stats.getMax(), stats.getStandardDeviation()); return ret; } private void compute(Collection<Move> moves) { for (Move move : moves) { List<TPoint> points = new ArrayList<>(); if(move.getStart() != null) { points.add(move.getStart().getEndPoint()); } if(move.getPoints() != null) { points.addAll(Arrays.asList(move.getPoints())); } if(move.getEnd() != null) { points.add(move.getEnd().getStartPoint()); } // move.setAttribute(AttributeType.MOVE_ANGLE, Angle.getAngle(points.get(0), points.get(points.size() - 1))); move.setAttribute(AttributeType.MOVE_TRAVELLED_DISTANCE, Distance.getDistance(points.toArray(new TPoint[points.size()]), DISTANCE_FUNCTION)); } } }
package bisq.common.config; import org.bitcoinj.core.NetworkParameters; import joptsimple.AbstractOptionSpec; import joptsimple.ArgumentAcceptingOptionSpec; import joptsimple.HelpFormatter; import joptsimple.OptionException; import joptsimple.OptionParser; import joptsimple.OptionSet; import joptsimple.OptionSpec; import joptsimple.OptionSpecBuilder; import joptsimple.util.PathConverter; import joptsimple.util.PathProperties; import joptsimple.util.RegexMatcher; import java.nio.file.Files; import java.nio.file.Path; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.io.UncheckedIOException; import java.util.List; import java.util.Optional; import ch.qos.logback.classic.Level; import static com.google.common.base.Preconditions.checkNotNull; import static java.lang.String.format; import static java.util.stream.Collectors.toList; /** * Parses and provides access to all Bisq configuration options specified at the command * line and/or via the {@value DEFAULT_CONFIG_FILE_NAME} config file, including any * default values. Constructing a {@link Config} instance is generally side-effect free, * with one key exception being that {@value APP_DATA_DIR} and its subdirectories will * be created if they do not already exist. Care is taken to avoid inadvertent creation or * modification of the actual system user data directory and/or the production Bisq * application data directory. Calling code must explicitly specify these values; they are * never assumed. * <p/> * Note that this class deviates from typical JavaBean conventions in that fields * representing configuration options are public and have no corresponding accessor * ("getter") method. This is because all such fields are final and therefore not subject * to modification by calling code and because eliminating the accessor methods means * eliminating hundreds of lines of boilerplate code and one less touchpoint to deal with * when adding or modifying options. Furthermore, while accessor methods are often useful * when mocking an object in a testing context, this class is designed for testability * without needing to be mocked. See {@code ConfigTests} for examples. * @see #Config(String...) * @see #Config(String, File, String...) */ public class Config { // Option name constants public static final String HELP = "help"; public static final String APP_NAME = "appName"; public static final String USER_DATA_DIR = "userDataDir"; public static final String APP_DATA_DIR = "appDataDir"; public static final String CONFIG_FILE = "configFile"; public static final String MAX_MEMORY = "maxMemory"; public static final String LOG_LEVEL = "logLevel"; public static final String BANNED_BTC_NODES = "bannedBtcNodes"; public static final String BANNED_PRICE_RELAY_NODES = "bannedPriceRelayNodes"; public static final String BANNED_SEED_NODES = "bannedSeedNodes"; public static final String BASE_CURRENCY_NETWORK = "baseCurrencyNetwork"; public static final String REFERRAL_ID = "referralId"; public static final String USE_DEV_MODE = "useDevMode"; public static final String USE_DEV_MODE_HEADER = "useDevModeHeader"; public static final String TOR_DIR = "torDir"; public static final String STORAGE_DIR = "storageDir"; public static final String KEY_STORAGE_DIR = "keyStorageDir"; public static final String WALLET_DIR = "walletDir"; public static final String USE_DEV_PRIVILEGE_KEYS = "useDevPrivilegeKeys"; public static final String DUMP_STATISTICS = "dumpStatistics"; public static final String IGNORE_DEV_MSG = "ignoreDevMsg"; public static final String PROVIDERS = "providers"; public static final String SEED_NODES = "seedNodes"; public static final String BAN_LIST = "banList"; public static final String NODE_PORT = "nodePort"; public static final String USE_LOCALHOST_FOR_P2P = "useLocalhostForP2P"; public static final String MAX_CONNECTIONS = "maxConnections"; public static final String SOCKS_5_PROXY_BTC_ADDRESS = "socks5ProxyBtcAddress"; public static final String SOCKS_5_PROXY_HTTP_ADDRESS = "socks5ProxyHttpAddress"; public static final String USE_TOR_FOR_BTC = "useTorForBtc"; public static final String TORRC_FILE = "torrcFile"; public static final String TORRC_OPTIONS = "torrcOptions"; public static final String TOR_CONTROL_PORT = "torControlPort"; public static final String TOR_CONTROL_PASSWORD = "torControlPassword"; public static final String TOR_CONTROL_COOKIE_FILE = "torControlCookieFile"; public static final String TOR_CONTROL_USE_SAFE_COOKIE_AUTH = "torControlUseSafeCookieAuth"; public static final String TOR_STREAM_ISOLATION = "torStreamIsolation"; public static final String MSG_THROTTLE_PER_SEC = "msgThrottlePerSec"; public static final String MSG_THROTTLE_PER_10_SEC = "msgThrottlePer10Sec"; public static final String SEND_MSG_THROTTLE_TRIGGER = "sendMsgThrottleTrigger"; public static final String SEND_MSG_THROTTLE_SLEEP = "sendMsgThrottleSleep"; public static final String IGNORE_LOCAL_BTC_NODE = "ignoreLocalBtcNode"; public static final String BITCOIN_REGTEST_HOST = "bitcoinRegtestHost"; public static final String BTC_NODES = "btcNodes"; public static final String SOCKS5_DISCOVER_MODE = "socks5DiscoverMode"; public static final String USE_ALL_PROVIDED_NODES = "useAllProvidedNodes"; public static final String USER_AGENT = "userAgent"; public static final String NUM_CONNECTIONS_FOR_BTC = "numConnectionsForBtc"; public static final String RPC_USER = "rpcUser"; public static final String RPC_PASSWORD = "rpcPassword"; public static final String RPC_HOST = "rpcHost"; public static final String RPC_PORT = "rpcPort"; public static final String RPC_BLOCK_NOTIFICATION_PORT = "rpcBlockNotificationPort"; public static final String RPC_BLOCK_NOTIFICATION_HOST = "rpcBlockNotificationHost"; public static final String DUMP_BLOCKCHAIN_DATA = "dumpBlockchainData"; public static final String FULL_DAO_NODE = "fullDaoNode"; public static final String GENESIS_TX_ID = "genesisTxId"; public static final String GENESIS_BLOCK_HEIGHT = "genesisBlockHeight"; public static final String GENESIS_TOTAL_SUPPLY = "genesisTotalSupply"; public static final String DAO_ACTIVATED = "daoActivated"; public static final String DUMP_DELAYED_PAYOUT_TXS = "dumpDelayedPayoutTxs"; public static final String ALLOW_FAULTY_DELAYED_TXS = "allowFaultyDelayedTxs"; public static final String API_PASSWORD = "apiPassword"; public static final String API_PORT = "apiPort"; public static final String PREVENT_PERIODIC_SHUTDOWN_AT_SEED_NODE = "preventPeriodicShutdownAtSeedNode"; public static final String REPUBLISH_MAILBOX_ENTRIES = "republishMailboxEntries"; public static final String BTC_TX_FEE = "btcTxFee"; public static final String BTC_MIN_TX_FEE = "btcMinTxFee"; public static final String BTC_FEES_TS = "bitcoinFeesTs"; public static final String BYPASS_MEMPOOL_VALIDATION = "bypassMempoolValidation"; // Default values for certain options public static final int UNSPECIFIED_PORT = -1; public static final String DEFAULT_REGTEST_HOST = "localhost"; public static final int DEFAULT_NUM_CONNECTIONS_FOR_BTC_PROVIDED = 7; // down from BitcoinJ default of 12 public static final int DEFAULT_NUM_CONNECTIONS_FOR_BTC_PUBLIC = 9; public static final boolean DEFAULT_FULL_DAO_NODE = false; static final String DEFAULT_CONFIG_FILE_NAME = "bisq.properties"; // Static fields that provide access to Config properties in locations where injecting // a Config instance is not feasible. See Javadoc for corresponding static accessors. private static File APP_DATA_DIR_VALUE; private static BaseCurrencyNetwork BASE_CURRENCY_NETWORK_VALUE = BaseCurrencyNetwork.BTC_MAINNET; // Default "data dir properties", i.e. properties that can determine the location of // Bisq's application data directory (appDataDir) public final String defaultAppName; public final File defaultUserDataDir; public final File defaultAppDataDir; public final File defaultConfigFile; // Options supported only at the command-line interface (cli) public final boolean helpRequested; public final File configFile; // Options supported on cmd line and in the config file public final String appName; public final File userDataDir; public final File appDataDir; public final int nodePort; public final int maxMemory; public final String logLevel; public final List<String> bannedBtcNodes; public final List<String> bannedPriceRelayNodes; public final List<String> bannedSeedNodes; public final BaseCurrencyNetwork baseCurrencyNetwork; public final NetworkParameters networkParameters; public final boolean ignoreLocalBtcNode; public final String bitcoinRegtestHost; public final boolean daoActivated; public final String referralId; public final boolean useDevMode; public final boolean useDevModeHeader; public final boolean useDevPrivilegeKeys; public final boolean dumpStatistics; public final boolean ignoreDevMsg; public final List<String> providers; public final List<String> seedNodes; public final List<String> banList; public final boolean useLocalhostForP2P; public final int maxConnections; public final String socks5ProxyBtcAddress; public final String socks5ProxyHttpAddress; public final File torrcFile; public final String torrcOptions; public final int torControlPort; public final String torControlPassword; public final File torControlCookieFile; public final boolean useTorControlSafeCookieAuth; public final boolean torStreamIsolation; public final int msgThrottlePerSec; public final int msgThrottlePer10Sec; public final int sendMsgThrottleTrigger; public final int sendMsgThrottleSleep; public final String btcNodes; public final boolean useTorForBtc; public final boolean useTorForBtcOptionSetExplicitly; public final String socks5DiscoverMode; public final boolean useAllProvidedNodes; public final String userAgent; public final int numConnectionsForBtc; public final String rpcUser; public final String rpcPassword; public final String rpcHost; public final int rpcPort; public final int rpcBlockNotificationPort; public final String rpcBlockNotificationHost; public final boolean dumpBlockchainData; public final boolean fullDaoNode; public final boolean fullDaoNodeOptionSetExplicitly; public final String genesisTxId; public final int genesisBlockHeight; public final long genesisTotalSupply; public final boolean dumpDelayedPayoutTxs; public final boolean allowFaultyDelayedTxs; public final String apiPassword; public final int apiPort; public final boolean preventPeriodicShutdownAtSeedNode; public final boolean republishMailboxEntries; public final boolean bypassMempoolValidation; // Properties derived from options but not exposed as options themselves public final File torDir; public final File walletDir; public final File storageDir; public final File keyStorageDir; // The parser that will be used to parse both cmd line and config file options private final OptionParser parser = new OptionParser(); /** * Create a new {@link Config} instance using a randomly-generated default * {@value APP_NAME} and a newly-created temporary directory as the default * {@value USER_DATA_DIR} along with any command line arguments. This constructor is * primarily useful in test code, where no references or modifications should be made * to the actual system user data directory and/or real Bisq application data * directory. Most production use cases will favor calling the * {@link #Config(String, File, String...)} constructor directly. * @param args zero or more command line arguments in the form "--optName=optValue" * @throws ConfigException if any problems are encountered during option parsing * @see #Config(String, File, String...) */ public Config(String... args) { this(randomAppName(), tempUserDataDir(), args); } /** * Create a new {@link Config} instance with the given default {@value APP_NAME} and * {@value USER_DATA_DIR} values along with any command line arguments, typically * those supplied via a Bisq application's main() method. * <p/> * This constructor performs all parsing of command line options and config file * options, assuming the default config file exists or a custom config file has been * specified via the {@value CONFIG_FILE} option and exists. For any options that * are present both at the command line and in the config file, the command line value * will take precedence. Note that the {@value HELP} and {@value CONFIG_FILE} options * are supported only at the command line and are disallowed within the config file * itself. * @param defaultAppName typically "Bisq" or similar * @param defaultUserDataDir typically the OS-specific user data directory location * @param args zero or more command line arguments in the form "--optName=optValue" * @throws ConfigException if any problems are encountered during option parsing */ public Config(String defaultAppName, File defaultUserDataDir, String... args) { this.defaultAppName = defaultAppName; this.defaultUserDataDir = defaultUserDataDir; this.defaultAppDataDir = new File(defaultUserDataDir, defaultAppName); this.defaultConfigFile = absoluteConfigFile(defaultAppDataDir, DEFAULT_CONFIG_FILE_NAME); AbstractOptionSpec<Void> helpOpt = parser.accepts(HELP, "Print this help text") .forHelp(); ArgumentAcceptingOptionSpec<String> configFileOpt = parser.accepts(CONFIG_FILE, format("Specify configuration file. " + "Relative paths will be prefixed by %s location.", APP_DATA_DIR)) .withRequiredArg() .ofType(String.class) .defaultsTo(DEFAULT_CONFIG_FILE_NAME); ArgumentAcceptingOptionSpec<String> appNameOpt = parser.accepts(APP_NAME, "Application name") .withRequiredArg() .ofType(String.class) .defaultsTo(this.defaultAppName); ArgumentAcceptingOptionSpec<File> userDataDirOpt = parser.accepts(USER_DATA_DIR, "User data directory") .withRequiredArg() .ofType(File.class) .defaultsTo(this.defaultUserDataDir); ArgumentAcceptingOptionSpec<File> appDataDirOpt = parser.accepts(APP_DATA_DIR, "Application data directory") .withRequiredArg() .ofType(File.class) .defaultsTo(defaultAppDataDir); ArgumentAcceptingOptionSpec<Integer> nodePortOpt = parser.accepts(NODE_PORT, "Port to listen on") .withRequiredArg() .ofType(Integer.class) .defaultsTo(9999); ArgumentAcceptingOptionSpec<Integer> maxMemoryOpt = parser.accepts(MAX_MEMORY, "Max. permitted memory (used only by headless versions)") .withRequiredArg() .ofType(int.class) .defaultsTo(1200); ArgumentAcceptingOptionSpec<String> logLevelOpt = parser.accepts(LOG_LEVEL, "Set logging level") .withRequiredArg() .ofType(String.class) .describedAs("OFF|ALL|ERROR|WARN|INFO|DEBUG|TRACE") .defaultsTo(Level.INFO.levelStr); ArgumentAcceptingOptionSpec<String> bannedBtcNodesOpt = parser.accepts(BANNED_BTC_NODES, "List Bitcoin nodes to ban") .withRequiredArg() .ofType(String.class) .withValuesSeparatedBy(',') .describedAs("host:port[,...]"); ArgumentAcceptingOptionSpec<String> bannedPriceRelayNodesOpt = parser.accepts(BANNED_PRICE_RELAY_NODES, "List Bisq price nodes to ban") .withRequiredArg() .ofType(String.class) .withValuesSeparatedBy(',') .describedAs("host:port[,...]"); ArgumentAcceptingOptionSpec<String> bannedSeedNodesOpt = parser.accepts(BANNED_SEED_NODES, "List Bisq seed nodes to ban") .withRequiredArg() .ofType(String.class) .withValuesSeparatedBy(',') .describedAs("host:port[,...]"); //noinspection rawtypes ArgumentAcceptingOptionSpec<Enum> baseCurrencyNetworkOpt = parser.accepts(BASE_CURRENCY_NETWORK, "Base currency network") .withRequiredArg() .ofType(BaseCurrencyNetwork.class) .withValuesConvertedBy(new EnumValueConverter(BaseCurrencyNetwork.class)) .defaultsTo(BaseCurrencyNetwork.BTC_MAINNET); ArgumentAcceptingOptionSpec<Boolean> ignoreLocalBtcNodeOpt = parser.accepts(IGNORE_LOCAL_BTC_NODE, "If set to true a Bitcoin Core node running locally will be ignored") .withRequiredArg() .ofType(Boolean.class) .defaultsTo(false); ArgumentAcceptingOptionSpec<String> bitcoinRegtestHostOpt = parser.accepts(BITCOIN_REGTEST_HOST, "Bitcoin Core node when using BTC_REGTEST network") .withRequiredArg() .ofType(String.class) .describedAs("host[:port]") .defaultsTo(""); ArgumentAcceptingOptionSpec<String> referralIdOpt = parser.accepts(REFERRAL_ID, "Optional Referral ID (e.g. for API users or pro market makers)") .withRequiredArg() .ofType(String.class) .defaultsTo(""); ArgumentAcceptingOptionSpec<Boolean> useDevModeOpt = parser.accepts(USE_DEV_MODE, "Enables dev mode which is used for convenience for developer testing") .withRequiredArg() .ofType(boolean.class) .defaultsTo(false); ArgumentAcceptingOptionSpec<Boolean> useDevModeHeaderOpt = parser.accepts(USE_DEV_MODE_HEADER, "Use dev mode css scheme to distinguish dev instances.") .withRequiredArg() .ofType(boolean.class) .defaultsTo(false); ArgumentAcceptingOptionSpec<Boolean> useDevPrivilegeKeysOpt = parser.accepts(USE_DEV_PRIVILEGE_KEYS, "If set to true all privileged features requiring a private " + "key to be enabled are overridden by a dev key pair (This is for developers only!)") .withRequiredArg() .ofType(boolean.class) .defaultsTo(false); ArgumentAcceptingOptionSpec<Boolean> dumpStatisticsOpt = parser.accepts(DUMP_STATISTICS, "If set to true dump trade statistics to a json file in appDataDir") .withRequiredArg() .ofType(boolean.class) .defaultsTo(false); ArgumentAcceptingOptionSpec<Boolean> ignoreDevMsgOpt = parser.accepts(IGNORE_DEV_MSG, "If set to true all signed " + "network_messages from bisq developers are ignored (Global " + "alert, Version update alert, Filters for offers, nodes or " + "trading account data)") .withRequiredArg() .ofType(boolean.class) .defaultsTo(false); ArgumentAcceptingOptionSpec<String> providersOpt = parser.accepts(PROVIDERS, "List custom pricenodes") .withRequiredArg() .withValuesSeparatedBy(',') .describedAs("host:port[,...]"); ArgumentAcceptingOptionSpec<String> seedNodesOpt = parser.accepts(SEED_NODES, "Override hard coded seed nodes as comma separated list e.g. " + "'rxdkppp3vicnbgqt.onion:8002,mfla72c4igh5ta2t.onion:8002'") .withRequiredArg() .withValuesSeparatedBy(',') .describedAs("host:port[,...]"); ArgumentAcceptingOptionSpec<String> banListOpt = parser.accepts(BAN_LIST, "Nodes to exclude from network connections.") .withRequiredArg() .withValuesSeparatedBy(',') .describedAs("host:port[,...]"); ArgumentAcceptingOptionSpec<Boolean> useLocalhostForP2POpt = parser.accepts(USE_LOCALHOST_FOR_P2P, "Use localhost P2P network for development. Only available for non-BTC_MAINNET configuration.") .availableIf(BASE_CURRENCY_NETWORK) .withRequiredArg() .ofType(boolean.class) .defaultsTo(false); ArgumentAcceptingOptionSpec<Integer> maxConnectionsOpt = parser.accepts(MAX_CONNECTIONS, "Max. connections a peer will try to keep") .withRequiredArg() .ofType(int.class) .defaultsTo(12); ArgumentAcceptingOptionSpec<String> socks5ProxyBtcAddressOpt = parser.accepts(SOCKS_5_PROXY_BTC_ADDRESS, "A proxy address to be used for Bitcoin network.") .withRequiredArg() .describedAs("host:port") .defaultsTo(""); ArgumentAcceptingOptionSpec<String> socks5ProxyHttpAddressOpt = parser.accepts(SOCKS_5_PROXY_HTTP_ADDRESS, "A proxy address to be used for Http requests (should be non-Tor)") .withRequiredArg() .describedAs("host:port") .defaultsTo(""); ArgumentAcceptingOptionSpec<Path> torrcFileOpt = parser.accepts(TORRC_FILE, "An existing torrc-file to be sourced for Tor. Note that torrc-entries, " + "which are critical to Bisq's correct operation, cannot be overwritten.") .withRequiredArg() .describedAs("File") .withValuesConvertedBy(new PathConverter(PathProperties.FILE_EXISTING, PathProperties.READABLE)); ArgumentAcceptingOptionSpec<String> torrcOptionsOpt = parser.accepts(TORRC_OPTIONS, "A list of torrc-entries to amend to Bisq's torrc. Note that " + "torrc-entries, which are critical to Bisq's flawless operation, cannot be overwritten. " + "[torrc options line, torrc option, ...]") .withRequiredArg() .withValuesConvertedBy(RegexMatcher.regex("^([^\\s,]+\\s[^,]+,?\\s*)+$")) .defaultsTo(""); ArgumentAcceptingOptionSpec<Integer> torControlPortOpt = parser.accepts(TOR_CONTROL_PORT, "The control port of an already running Tor service to be used by Bisq.") .availableUnless(TORRC_FILE, TORRC_OPTIONS) .withRequiredArg() .ofType(int.class) .describedAs("port") .defaultsTo(UNSPECIFIED_PORT); ArgumentAcceptingOptionSpec<String> torControlPasswordOpt = parser.accepts(TOR_CONTROL_PASSWORD, "The password for controlling the already running Tor service.") .availableIf(TOR_CONTROL_PORT) .withRequiredArg() .defaultsTo(""); ArgumentAcceptingOptionSpec<Path> torControlCookieFileOpt = parser.accepts(TOR_CONTROL_COOKIE_FILE, "The cookie file for authenticating against the already " + "running Tor service. Use in conjunction with --" + TOR_CONTROL_USE_SAFE_COOKIE_AUTH) .availableIf(TOR_CONTROL_PORT) .availableUnless(TOR_CONTROL_PASSWORD) .withRequiredArg() .describedAs("File") .withValuesConvertedBy(new PathConverter(PathProperties.FILE_EXISTING, PathProperties.READABLE)); OptionSpecBuilder torControlUseSafeCookieAuthOpt = parser.accepts(TOR_CONTROL_USE_SAFE_COOKIE_AUTH, "Use the SafeCookie method when authenticating to the already running Tor service.") .availableIf(TOR_CONTROL_COOKIE_FILE); OptionSpecBuilder torStreamIsolationOpt = parser.accepts(TOR_STREAM_ISOLATION, "Use stream isolation for Tor [experimental!]."); ArgumentAcceptingOptionSpec<Integer> msgThrottlePerSecOpt = parser.accepts(MSG_THROTTLE_PER_SEC, "Message throttle per sec for connection class") .withRequiredArg() .ofType(int.class) // With PERMITTED_MESSAGE_SIZE of 200kb results in bandwidth of 40MB/sec or 5 mbit/sec .defaultsTo(200); ArgumentAcceptingOptionSpec<Integer> msgThrottlePer10SecOpt = parser.accepts(MSG_THROTTLE_PER_10_SEC, "Message throttle per 10 sec for connection class") .withRequiredArg() .ofType(int.class) // With PERMITTED_MESSAGE_SIZE of 200kb results in bandwidth of 20MB/sec or 2.5 mbit/sec .defaultsTo(1000); ArgumentAcceptingOptionSpec<Integer> sendMsgThrottleTriggerOpt = parser.accepts(SEND_MSG_THROTTLE_TRIGGER, "Time in ms when we trigger a sleep if 2 messages are sent") .withRequiredArg() .ofType(int.class) .defaultsTo(20); // Time in ms when we trigger a sleep if 2 messages are sent ArgumentAcceptingOptionSpec<Integer> sendMsgThrottleSleepOpt = parser.accepts(SEND_MSG_THROTTLE_SLEEP, "Pause in ms to sleep if we get too many messages to send") .withRequiredArg() .ofType(int.class) .defaultsTo(50); // Pause in ms to sleep if we get too many messages to send ArgumentAcceptingOptionSpec<String> btcNodesOpt = parser.accepts(BTC_NODES, "Custom nodes used for BitcoinJ as comma separated IP addresses.") .withRequiredArg() .describedAs("ip[,...]") .defaultsTo(""); ArgumentAcceptingOptionSpec<Boolean> useTorForBtcOpt = parser.accepts(USE_TOR_FOR_BTC, "If set to true BitcoinJ is routed over tor (socks 5 proxy).") .withRequiredArg() .ofType(Boolean.class) .defaultsTo(false); ArgumentAcceptingOptionSpec<String> socks5DiscoverModeOpt = parser.accepts(SOCKS5_DISCOVER_MODE, "Specify discovery mode for Bitcoin nodes. " + "One or more of: [ADDR, DNS, ONION, ALL] (comma separated, they get OR'd together).") .withRequiredArg() .describedAs("mode[,...]") .defaultsTo("ALL"); ArgumentAcceptingOptionSpec<Boolean> useAllProvidedNodesOpt = parser.accepts(USE_ALL_PROVIDED_NODES, "Set to true if connection of bitcoin nodes should include clear net nodes") .withRequiredArg() .ofType(boolean.class) .defaultsTo(false); ArgumentAcceptingOptionSpec<String> userAgentOpt = parser.accepts(USER_AGENT, "User agent at btc node connections") .withRequiredArg() .defaultsTo("Bisq"); ArgumentAcceptingOptionSpec<Integer> numConnectionsForBtcOpt = parser.accepts(NUM_CONNECTIONS_FOR_BTC, "Number of connections to the Bitcoin network") .withRequiredArg() .ofType(int.class) .defaultsTo(DEFAULT_NUM_CONNECTIONS_FOR_BTC_PROVIDED); ArgumentAcceptingOptionSpec<String> rpcUserOpt = parser.accepts(RPC_USER, "Bitcoind rpc username") .withRequiredArg() .defaultsTo(""); ArgumentAcceptingOptionSpec<String> rpcPasswordOpt = parser.accepts(RPC_PASSWORD, "Bitcoind rpc password") .withRequiredArg() .defaultsTo(""); ArgumentAcceptingOptionSpec<String> rpcHostOpt = parser.accepts(RPC_HOST, "Bitcoind rpc host") .withRequiredArg() .defaultsTo(""); ArgumentAcceptingOptionSpec<Integer> rpcPortOpt = parser.accepts(RPC_PORT, "Bitcoind rpc port") .withRequiredArg() .ofType(int.class) .defaultsTo(UNSPECIFIED_PORT); ArgumentAcceptingOptionSpec<Integer> rpcBlockNotificationPortOpt = parser.accepts(RPC_BLOCK_NOTIFICATION_PORT, "Bitcoind rpc port for block notifications") .withRequiredArg() .ofType(int.class) .defaultsTo(UNSPECIFIED_PORT); ArgumentAcceptingOptionSpec<String> rpcBlockNotificationHostOpt = parser.accepts(RPC_BLOCK_NOTIFICATION_HOST, "Bitcoind rpc accepted incoming host for block notifications") .withRequiredArg() .defaultsTo(""); ArgumentAcceptingOptionSpec<Boolean> dumpBlockchainDataOpt = parser.accepts(DUMP_BLOCKCHAIN_DATA, "If set to true the blockchain data " + "from RPC requests to Bitcoin Core are stored as json file in the data dir.") .withRequiredArg() .ofType(boolean.class) .defaultsTo(false); ArgumentAcceptingOptionSpec<Boolean> fullDaoNodeOpt = parser.accepts(FULL_DAO_NODE, "If set to true the node requests the blockchain data via RPC requests " + "from Bitcoin Core and provide the validated BSQ txs to the network. It requires that the " + "other RPC properties are set as well.") .withRequiredArg() .ofType(Boolean.class) .defaultsTo(DEFAULT_FULL_DAO_NODE); ArgumentAcceptingOptionSpec<String> genesisTxIdOpt = parser.accepts(GENESIS_TX_ID, "Genesis transaction ID when not using the hard coded one") .withRequiredArg() .defaultsTo(""); ArgumentAcceptingOptionSpec<Integer> genesisBlockHeightOpt = parser.accepts(GENESIS_BLOCK_HEIGHT, "Genesis transaction block height when not using the hard coded one") .withRequiredArg() .ofType(int.class) .defaultsTo(-1); ArgumentAcceptingOptionSpec<Long> genesisTotalSupplyOpt = parser.accepts(GENESIS_TOTAL_SUPPLY, "Genesis total supply when not using the hard coded one") .withRequiredArg() .ofType(long.class) .defaultsTo(-1L); ArgumentAcceptingOptionSpec<Boolean> daoActivatedOpt = parser.accepts(DAO_ACTIVATED, "Developer flag. If true it enables dao phase 2 features.") .withRequiredArg() .ofType(boolean.class) .defaultsTo(true); ArgumentAcceptingOptionSpec<Boolean> dumpDelayedPayoutTxsOpt = parser.accepts(DUMP_DELAYED_PAYOUT_TXS, "Dump delayed payout transactions to file") .withRequiredArg() .ofType(boolean.class) .defaultsTo(false); ArgumentAcceptingOptionSpec<Boolean> allowFaultyDelayedTxsOpt = parser.accepts(ALLOW_FAULTY_DELAYED_TXS, "Allow completion of trades with faulty delayed " + "payout transactions") .withRequiredArg() .ofType(boolean.class) .defaultsTo(false); ArgumentAcceptingOptionSpec<String> apiPasswordOpt = parser.accepts(API_PASSWORD, "gRPC API password") .withRequiredArg() .defaultsTo(""); ArgumentAcceptingOptionSpec<Integer> apiPortOpt = parser.accepts(API_PORT, "gRPC API port") .withRequiredArg() .ofType(Integer.class) .defaultsTo(9998); ArgumentAcceptingOptionSpec<Boolean> preventPeriodicShutdownAtSeedNodeOpt = parser.accepts(PREVENT_PERIODIC_SHUTDOWN_AT_SEED_NODE, "Prevents periodic shutdown at seed nodes") .withRequiredArg() .ofType(boolean.class) .defaultsTo(false); ArgumentAcceptingOptionSpec<Boolean> republishMailboxEntriesOpt = parser.accepts(REPUBLISH_MAILBOX_ENTRIES, "Republish mailbox messages at startup") .withRequiredArg() .ofType(boolean.class) .defaultsTo(false); ArgumentAcceptingOptionSpec<Boolean> bypassMempoolValidationOpt = parser.accepts(BYPASS_MEMPOOL_VALIDATION, "Prevents mempool check of trade parameters") .withRequiredArg() .ofType(boolean.class) .defaultsTo(false); try { CompositeOptionSet options = new CompositeOptionSet(); // Parse command line options OptionSet cliOpts = parser.parse(args); options.addOptionSet(cliOpts); // Option parsing is strict at the command line, but we relax it now for any // subsequent config file processing. This is for compatibility with pre-1.2.6 // versions that allowed unrecognized options in the bisq.properties config // file and because it follows suit with Bitcoin Core's config file behavior. parser.allowsUnrecognizedOptions(); // Parse config file specified at the command line only if it was specified as // an absolute path. Otherwise, the config file will be processed later below. File configFile = null; OptionSpec<?>[] disallowedOpts = new OptionSpec<?>[]{helpOpt, configFileOpt}; final boolean cliHasConfigFileOpt = cliOpts.has(configFileOpt); boolean configFileHasBeenProcessed = false; if (cliHasConfigFileOpt) { configFile = new File(cliOpts.valueOf(configFileOpt)); if (configFile.isAbsolute()) { Optional<OptionSet> configFileOpts = parseOptionsFrom(configFile, disallowedOpts); if (configFileOpts.isPresent()) { options.addOptionSet(configFileOpts.get()); configFileHasBeenProcessed = true; } } } // Assign values to the following "data dir properties". If a // relatively-pathed config file was specified at the command line, any // entries it has for these options will be ignored, as it has not been // processed yet. this.appName = options.valueOf(appNameOpt); this.userDataDir = options.valueOf(userDataDirOpt); this.appDataDir = mkAppDataDir(options.has(appDataDirOpt) ? options.valueOf(appDataDirOpt) : new File(userDataDir, appName)); // If the config file has not yet been processed, either because a relative // path was provided at the command line, or because no value was provided at // the command line, attempt to process the file now, falling back to the // default config file location if none was specified at the command line. if (!configFileHasBeenProcessed) { configFile = cliHasConfigFileOpt && !configFile.isAbsolute() ? absoluteConfigFile(appDataDir, configFile.getPath()) : absoluteConfigFile(appDataDir, DEFAULT_CONFIG_FILE_NAME); Optional<OptionSet> configFileOpts = parseOptionsFrom(configFile, disallowedOpts); configFileOpts.ifPresent(options::addOptionSet); } // Assign all remaining properties, with command line options taking // precedence over those provided in the config file (if any) this.helpRequested = options.has(helpOpt); this.configFile = configFile; this.nodePort = options.valueOf(nodePortOpt); this.maxMemory = options.valueOf(maxMemoryOpt); this.logLevel = options.valueOf(logLevelOpt); this.bannedBtcNodes = options.valuesOf(bannedBtcNodesOpt); this.bannedPriceRelayNodes = options.valuesOf(bannedPriceRelayNodesOpt); this.bannedSeedNodes = options.valuesOf(bannedSeedNodesOpt); this.baseCurrencyNetwork = (BaseCurrencyNetwork) options.valueOf(baseCurrencyNetworkOpt); this.networkParameters = baseCurrencyNetwork.getParameters(); this.ignoreLocalBtcNode = options.valueOf(ignoreLocalBtcNodeOpt); this.bitcoinRegtestHost = options.valueOf(bitcoinRegtestHostOpt); this.torrcFile = options.has(torrcFileOpt) ? options.valueOf(torrcFileOpt).toFile() : null; this.torrcOptions = options.valueOf(torrcOptionsOpt); this.torControlPort = options.valueOf(torControlPortOpt); this.torControlPassword = options.valueOf(torControlPasswordOpt); this.torControlCookieFile = options.has(torControlCookieFileOpt) ? options.valueOf(torControlCookieFileOpt).toFile() : null; this.useTorControlSafeCookieAuth = options.has(torControlUseSafeCookieAuthOpt); this.torStreamIsolation = options.has(torStreamIsolationOpt); this.referralId = options.valueOf(referralIdOpt); this.useDevMode = options.valueOf(useDevModeOpt); this.useDevModeHeader = options.valueOf(useDevModeHeaderOpt); this.useDevPrivilegeKeys = options.valueOf(useDevPrivilegeKeysOpt); this.dumpStatistics = options.valueOf(dumpStatisticsOpt); this.ignoreDevMsg = options.valueOf(ignoreDevMsgOpt); this.providers = options.valuesOf(providersOpt); this.seedNodes = options.valuesOf(seedNodesOpt); this.banList = options.valuesOf(banListOpt); this.useLocalhostForP2P = !this.baseCurrencyNetwork.isMainnet() && options.valueOf(useLocalhostForP2POpt); this.maxConnections = options.valueOf(maxConnectionsOpt); this.socks5ProxyBtcAddress = options.valueOf(socks5ProxyBtcAddressOpt); this.socks5ProxyHttpAddress = options.valueOf(socks5ProxyHttpAddressOpt); this.msgThrottlePerSec = options.valueOf(msgThrottlePerSecOpt); this.msgThrottlePer10Sec = options.valueOf(msgThrottlePer10SecOpt); this.sendMsgThrottleTrigger = options.valueOf(sendMsgThrottleTriggerOpt); this.sendMsgThrottleSleep = options.valueOf(sendMsgThrottleSleepOpt); this.btcNodes = options.valueOf(btcNodesOpt); this.useTorForBtc = options.valueOf(useTorForBtcOpt); this.useTorForBtcOptionSetExplicitly = options.has(useTorForBtcOpt); this.socks5DiscoverMode = options.valueOf(socks5DiscoverModeOpt); this.useAllProvidedNodes = options.valueOf(useAllProvidedNodesOpt); this.userAgent = options.valueOf(userAgentOpt); this.numConnectionsForBtc = options.valueOf(numConnectionsForBtcOpt); this.rpcUser = options.valueOf(rpcUserOpt); this.rpcPassword = options.valueOf(rpcPasswordOpt); this.rpcHost = options.valueOf(rpcHostOpt); this.rpcPort = options.valueOf(rpcPortOpt); this.rpcBlockNotificationPort = options.valueOf(rpcBlockNotificationPortOpt); this.rpcBlockNotificationHost = options.valueOf(rpcBlockNotificationHostOpt); this.dumpBlockchainData = options.valueOf(dumpBlockchainDataOpt); this.fullDaoNode = options.valueOf(fullDaoNodeOpt); this.fullDaoNodeOptionSetExplicitly = options.has(fullDaoNodeOpt); this.genesisTxId = options.valueOf(genesisTxIdOpt); this.genesisBlockHeight = options.valueOf(genesisBlockHeightOpt); this.genesisTotalSupply = options.valueOf(genesisTotalSupplyOpt); this.daoActivated = options.valueOf(daoActivatedOpt); this.dumpDelayedPayoutTxs = options.valueOf(dumpDelayedPayoutTxsOpt); this.allowFaultyDelayedTxs = options.valueOf(allowFaultyDelayedTxsOpt); this.apiPassword = options.valueOf(apiPasswordOpt); this.apiPort = options.valueOf(apiPortOpt); this.preventPeriodicShutdownAtSeedNode = options.valueOf(preventPeriodicShutdownAtSeedNodeOpt); this.republishMailboxEntries = options.valueOf(republishMailboxEntriesOpt); this.bypassMempoolValidation = options.valueOf(bypassMempoolValidationOpt); } catch (OptionException ex) { throw new ConfigException("problem parsing option '%s': %s", ex.options().get(0), ex.getCause() != null ? ex.getCause().getMessage() : ex.getMessage()); } // Create all appDataDir subdirectories and assign to their respective properties File btcNetworkDir = mkdir(appDataDir, baseCurrencyNetwork.name().toLowerCase()); this.keyStorageDir = mkdir(btcNetworkDir, "keys"); this.storageDir = mkdir(btcNetworkDir, "db"); this.torDir = mkdir(btcNetworkDir, "tor"); this.walletDir = mkdir(btcNetworkDir, "wallet"); // Assign values to special-case static fields APP_DATA_DIR_VALUE = appDataDir; BASE_CURRENCY_NETWORK_VALUE = baseCurrencyNetwork; } private static File absoluteConfigFile(File parentDir, String relativeConfigFilePath) { return new File(parentDir, relativeConfigFilePath); } private Optional<OptionSet> parseOptionsFrom(File configFile, OptionSpec<?>[] disallowedOpts) { if (!configFile.exists()) { if (!configFile.equals(absoluteConfigFile(appDataDir, DEFAULT_CONFIG_FILE_NAME))) throw new ConfigException("The specified config file '%s' does not exist.", configFile); return Optional.empty(); } ConfigFileReader configFileReader = new ConfigFileReader(configFile); String[] optionLines = configFileReader.getOptionLines().stream() .map(o -> "--" + o) // prepend dashes expected by jopt parser below .collect(toList()) .toArray(new String[]{}); OptionSet configFileOpts = parser.parse(optionLines); for (OptionSpec<?> disallowedOpt : disallowedOpts) if (configFileOpts.has(disallowedOpt)) throw new ConfigException("The '%s' option is disallowed in config files", disallowedOpt.options().get(0)); return Optional.of(configFileOpts); } public void printHelp(OutputStream sink, HelpFormatter formatter) { try { parser.formatHelpWith(formatter); parser.printHelpOn(sink); } catch (IOException ex) { throw new UncheckedIOException(ex); } } private static String randomAppName() { try { File file = Files.createTempFile("Bisq", "Temp").toFile(); //noinspection ResultOfMethodCallIgnored file.delete(); return file.toPath().getFileName().toString(); } catch (IOException ex) { throw new UncheckedIOException(ex); } } private static File tempUserDataDir() { try { return Files.createTempDirectory("BisqTempUserData").toFile(); } catch (IOException ex) { throw new UncheckedIOException(ex); } } /** * Creates {@value APP_DATA_DIR} including any nonexistent parent directories. Does * nothing if the directory already exists. * @return the given directory, now guaranteed to exist */ private static File mkAppDataDir(File dir) { if (!dir.exists()) { try { Files.createDirectories(dir.toPath()); } catch (IOException ex) { throw new UncheckedIOException(format("Application data directory '%s' could not be created", dir), ex); } } return dir; } /** * Creates child directory assuming parent directories already exist. Does nothing if * the directory already exists. * @return the child directory, now guaranteed to exist */ private static File mkdir(File parent, String child) { File dir = new File(parent, child); if (!dir.exists()) { try { Files.createDirectory(dir.toPath()); } catch (IOException ex) { throw new UncheckedIOException(format("Directory '%s' could not be created", dir), ex); } } return dir; } /** * Static accessor that returns the same value as the non-static * {@link #appDataDir} property. For use only in the {@code Overlay} class, where * because of its large number of subclasses, injecting the Guice-managed * {@link Config} class is not worth the effort. {@link #appDataDir} should be * favored in all other cases. * @throws NullPointerException if the static value has not yet been assigned, i.e. if * the Guice-managed {@link Config} class has not yet been instantiated elsewhere. * This should never be the case, as Guice wiring always happens before any * {@code Overlay} class is instantiated. */ public static File appDataDir() { return checkNotNull(APP_DATA_DIR_VALUE, "The static appDataDir has not yet " + "been assigned. A Config instance must be instantiated (usually by " + "Guice) before calling this method."); } /** * Static accessor that returns either the default base currency network value of * {@link BaseCurrencyNetwork#BTC_MAINNET} or the value assigned via the * {@value BASE_CURRENCY_NETWORK} option. The non-static * {@link #baseCurrencyNetwork} property should be favored whenever possible and * this static accessor should be used only in code locations where it is infeasible * or too cumbersome to inject the normal Guice-managed singleton {@link Config} * instance. */ public static BaseCurrencyNetwork baseCurrencyNetwork() { return BASE_CURRENCY_NETWORK_VALUE; } public static NetworkParameters baseCurrencyNetworkParameters() { return BASE_CURRENCY_NETWORK_VALUE.getParameters(); } }
package thredds.tds.idd; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.Test; import java.util.Collection; /** * _more_ * * @author edavis * @since 4.0 */ @RunWith(Parameterized.class) public class PingTdsAtNsf { private String catalogUrl; public PingTdsAtNsf( String catalogUrl ) { this.catalogUrl = catalogUrl; } @Parameterized.Parameters public static Collection<Object[]> getCatalogUrls() { Collection<Object[]> catUrls = StandardCatalogUtils.getIddMainCatalogUrlArrayCollection(); catUrls.addAll( StandardCatalogUtils.getNsfMainCatalogUrlArrayCollection() ); return catUrls; } @Test public void pingNsfThreddsTds() { String tdsUrl = "http://thredds.cise-nsf.gov:8080/thredds/"; CatalogValidityTestUtils.assertCatalogIsAccessibleValidAndNotExpired( tdsUrl + catalogUrl ); } }
package org.commcare.android.view; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.speech.tts.TextToSpeech; import android.text.Spannable; import android.text.SpannableString; import android.text.Spanned; import android.text.TextUtils; import android.text.style.BackgroundColorSpan; import android.view.View; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import org.commcare.android.models.AsyncEntity; import org.commcare.android.models.Entity; import org.commcare.android.tasks.ExceptionReportTask; import org.commcare.android.util.AndroidUtil; import org.commcare.android.util.InvalidStateException; import org.commcare.android.util.StringUtils; import org.commcare.dalvik.R; import org.commcare.suite.model.Detail; import org.commcare.suite.model.graph.GraphData; import org.javarosa.core.reference.InvalidReferenceException; import org.javarosa.core.reference.ReferenceManager; import org.javarosa.core.services.Logger; import org.odk.collect.android.views.media.AudioButton; import org.odk.collect.android.views.media.ViewId; import java.io.IOException; import java.util.Hashtable; import java.util.Vector; /** * @author ctsims */ public class EntityView extends LinearLayout { private View[] views; private String[] forms; private TextToSpeech tts; private String[] searchTerms; private String[] mHints; private Context context; private Hashtable<Integer, Hashtable<Integer, View>> renderedGraphsCache; // index => { orientation => GraphView } private long rowId; public static final String FORM_AUDIO = "audio"; public static final String FORM_IMAGE = "image"; public static final String FORM_GRAPH = "graph"; public static final String FORM_CALLLOUT = "callout"; private boolean mFuzzySearchEnabled = true; private boolean mIsAsynchronous = false; /* * Constructor for row/column contents */ public EntityView(Context context, Detail d, Entity e, TextToSpeech tts, String[] searchTerms, long rowId, boolean mFuzzySearchEnabled) { super(context); this.context = context; //this is bad :( mIsAsynchronous = e instanceof AsyncEntity; this.searchTerms = searchTerms; this.tts = tts; this.renderedGraphsCache = new Hashtable<Integer, Hashtable<Integer, View>>(); this.rowId = rowId; this.views = new View[e.getNumFields()]; this.forms = d.getTemplateForms(); this.mHints = d.getTemplateSizeHints(); for (int i = 0; i < views.length; ++i) { if (mHints[i] == null || !mHints[i].startsWith("0")) { views[i] = initView(e.getField(i), forms[i], new ViewId(rowId, i, false), e.getSortField(i)); views[i].setId(i); } } refreshViewsForNewEntity(e, false, rowId); for (int i = 0; i < views.length; i++) { LayoutParams l = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); if (views[i] != null) { addView(views[i], l); } } this.mFuzzySearchEnabled = mFuzzySearchEnabled; } /* * Constructor for row/column headers */ public EntityView(Context context, Detail d, String[] headerText) { super(context); this.context = context; this.views = new View[headerText.length]; this.mHints = d.getHeaderSizeHints(); String[] headerForms = d.getHeaderForms(); int[] colors = AndroidUtil.getThemeColorIDs(context, new int[]{R.attr.entity_view_header_background_color, R.attr.entity_view_header_text_color}); if (colors[0] != -1) { this.setBackgroundColor(colors[0]); } for (int i = 0; i < views.length; ++i) { if (mHints[i] == null || !mHints[i].startsWith("0")) { LayoutParams l = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); ViewId uniqueId = new ViewId(rowId, i, false); views[i] = initView(headerText[i], headerForms[i], uniqueId, null); views[i].setId(i); if (colors[1] != -1) { TextView tv = (TextView) views[i].findViewById(R.id.component_audio_text_txt); if (tv != null) tv.setTextColor(colors[1]); } addView(views[i], l); } } } /* * Creates up a new view in the view with ID uniqueid, based upon * the entity's text and form */ private View initView(Object data, String form, ViewId uniqueId, String sortField) { View retVal; if (FORM_IMAGE.equals(form)) { ImageView iv = (ImageView) View.inflate(context, R.layout.entity_item_image, null); retVal = iv; } else if (FORM_AUDIO.equals(form)) { String text = (String) data; AudioButton b; if (text != null & text.length() > 0) { b = new AudioButton(context, text, uniqueId, true); } else { b = new AudioButton(context, text, uniqueId, false); } retVal = b; } else if (FORM_GRAPH.equals(form) && data instanceof GraphData) { View layout = View.inflate(context, R.layout.entity_item_graph, null); retVal = layout; } else if (FORM_CALLLOUT.equals(form)) { View layout = View.inflate(context, R.layout.entity_item_graph, null); retVal = layout; } else { View layout = View.inflate(context, R.layout.component_audio_text, null); setupTextAndTTSLayout(layout, (String) data, sortField); retVal = layout; } return retVal; } public void setSearchTerms(String[] terms) { this.searchTerms = terms; } public void refreshViewsForNewEntity(Entity e, boolean currentlySelected, long rowId) { for (int i = 0; i < e.getNumFields(); ++i) { Object field = e.getField(i); View view = views[i]; String form = forms[i]; if (view == null) { continue; } if (FORM_AUDIO.equals(form)) { ViewId uniqueId = new ViewId(rowId, i, false); setupAudioLayout(view, (String) field, uniqueId); } else if (FORM_IMAGE.equals(form)) { setupImageLayout(view, (String) field); } else if (FORM_GRAPH.equals(form) && field instanceof GraphData) { int orientation = getResources().getConfiguration().orientation; GraphView g = new GraphView(context, ""); View rendered = null; if (renderedGraphsCache.get(i) != null) { rendered = renderedGraphsCache.get(i).get(orientation); } else { renderedGraphsCache.put(i, new Hashtable<Integer, View>()); } if (rendered == null) { try { rendered = g.getView((GraphData) field); } catch (InvalidStateException ise) { rendered = new TextView(context); ((TextView) rendered).setText(ise.getMessage()); } renderedGraphsCache.get(i).put(orientation, rendered); } ((LinearLayout) view).removeAllViews(); ((LinearLayout) view).addView(rendered, g.getLayoutParams()); view.setVisibility(VISIBLE); } else { //text to speech setupTextAndTTSLayout(view, (String) field, e.getSortField(i)); } } if (currentlySelected) { this.setBackgroundResource(R.drawable.grey_bordered_box); } else { this.setBackgroundDrawable(null); } } /* * Updates the AudioButton layout that is passed in, based on the * new id and source */ private void setupAudioLayout(View layout, String source, ViewId uniqueId) { AudioButton b = (AudioButton) layout; if (source != null && source.length() > 0) { b.modifyButtonForNewView(uniqueId, source, true); } else { b.modifyButtonForNewView(uniqueId, source, false); } } /* * Updates the text layout that is passed in, based on the new text */ private void setupTextAndTTSLayout(View layout, final String text, String searchField) { TextView tv = (TextView) layout.findViewById(R.id.component_audio_text_txt); tv.setVisibility(View.VISIBLE); tv.setText(highlightSearches(this.getContext(), searchTerms, new SpannableString(text == null ? "" : text), searchField, mFuzzySearchEnabled, mIsAsynchronous)); ImageButton btn = (ImageButton) layout.findViewById(R.id.component_audio_text_btn_audio); btn.setFocusable(false); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String textToRead = text; tts.speak(textToRead, TextToSpeech.QUEUE_FLUSH, null); } }); if (tts == null || text == null || text.equals("")) { btn.setVisibility(View.INVISIBLE); RelativeLayout.LayoutParams params = (android.widget.RelativeLayout.LayoutParams) btn.getLayoutParams(); params.width = 0; btn.setLayoutParams(params); } else { btn.setVisibility(View.VISIBLE); RelativeLayout.LayoutParams params = (android.widget.RelativeLayout.LayoutParams) btn.getLayoutParams(); params.width = LayoutParams.WRAP_CONTENT; btn.setLayoutParams(params); } } /* * Updates the ImageView layout that is passed in, based on the * new id and source */ public void setupImageLayout(View layout, final String source) { ImageView iv = (ImageView) layout; Bitmap b; if (!source.equals("")) { try { b = BitmapFactory.decodeStream(ReferenceManager._().DeriveReference(source).getStream()); if (b == null) { //Input stream could not be used to derive bitmap, so showing error-indicating image iv.setImageDrawable(getResources().getDrawable(R.drawable.ic_menu_archive)); } else { iv.setImageBitmap(b); } } catch (IOException ex) { ex.printStackTrace(); //Error loading image iv.setImageDrawable(getResources().getDrawable(R.drawable.ic_menu_archive)); } catch (InvalidReferenceException ex) { ex.printStackTrace(); //No image iv.setImageDrawable(getResources().getDrawable(R.drawable.ic_menu_archive)); } } else { iv.setImageDrawable(getResources().getDrawable(R.color.transparent)); } } //TODO: This method now really does two different things and should possibly be different //methods. /** * Based on the search terms provided, highlight the aspects of the spannable provided which * match. A background string can be provided which provides the exact data that is being * matched. */ public static Spannable highlightSearches(Context context, String[] searchTerms, Spannable raw, String backgroundString, boolean fuzzySearchEnabled, boolean strictMode) { if (searchTerms == null) { return raw; } try { //TOOD: Only do this if we're in strict mode if (strictMode) { if (backgroundString == null) { return raw; } //make sure that we have the same consistency for our background match backgroundString = StringUtils.normalize(backgroundString).trim(); } else { //Otherwise we basically want to treat the "Search" string and the display string //the same way. backgroundString = StringUtils.normalize(raw.toString()); } String normalizedDisplayString = StringUtils.normalize(raw.toString()); removeSpans(raw); Vector<int[]> matches = new Vector<int[]>(); //Highlight direct substring matches for (String searchText : searchTerms) { if ("".equals(searchText)) { continue; } //TODO: Assuming here that our background string exists and //isn't null due to the background string check above //check to see where we should start displaying this chunk int offset = TextUtils.indexOf(normalizedDisplayString, backgroundString); if (offset == -1) { //We can't safely highlight any of this, due to this field not actually //containing the same string we're searching by. continue; } int index = backgroundString.indexOf(searchText); //int index = TextUtils.indexOf(normalizedDisplayString, searchText); while (index >= 0) { //grab the display offset for actually displaying things int displayIndex = index + offset; raw.setSpan(new BackgroundColorSpan(context.getResources().getColor(R.color.yellow)), displayIndex, displayIndex + searchText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); matches.add(new int[]{index, index + searchText.length()}); //index=TextUtils.indexOf(raw, searchText, index + searchText.length()); index = backgroundString.indexOf(searchText, index + searchText.length()); //we have a non-fuzzy match, so make sure we don't fuck with it } } //now insert the spans for any fuzzy matches (if enabled) if (fuzzySearchEnabled && backgroundString != null) { backgroundString += " "; for (String searchText : searchTerms) { if ("".equals(searchText)) { continue; } int curStart = 0; int curEnd = backgroundString.indexOf(" ", curStart); while (curEnd != -1) { boolean skip = matches.size() != 0; //See whether the fuzzy match overlaps at all with the concrete matches for (int[] textMatch : matches) { if (curStart < textMatch[0] && curEnd <= textMatch[0]) { skip = false; } else if (curStart >= textMatch[1] && curEnd > textMatch[1]) { skip = false; } else { //We're definitely inside of this span, so //don't do any fuzzy matching! skip = true; break; } } if (!skip) { //Walk the string to find words that are fuzzy matched String currentSpan = backgroundString.substring(curStart, curEnd); //First, figure out where we should be matching (if we don't //have anywhere to match, that means there's nothing to display //anyway) int indexInDisplay = normalizedDisplayString.indexOf(currentSpan); int length = (curEnd - curStart); if (indexInDisplay != -1 && StringUtils.fuzzyMatch(currentSpan, searchText).first) { raw.setSpan(new BackgroundColorSpan(context.getResources().getColor(R.color.green)), indexInDisplay, indexInDisplay + length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } } curStart = curEnd + 1; curEnd = backgroundString.indexOf(" ", curStart); } } } } catch (Exception excp) { removeSpans(raw); Logger.log("search-hl", excp.toString() + " " + ExceptionReportTask.getStackTrace(excp)); } return raw; } /** * Removes all background color spans from the Spannable * * @param raw Spannable to remove background colors from */ private static void removeSpans(Spannable raw) { //Zero out the existing spans BackgroundColorSpan[] spans = raw.getSpans(0, raw.length(), BackgroundColorSpan.class); for (BackgroundColorSpan span : spans) { raw.removeSpan(span); } } /** * Determine width of each child view, based on mHints, the suite's size hints. * mHints contains a width hint for each child view, each one of * - A string like "50%", requesting the field take up 50% of the row * - A string like "200", requesting the field take up 200 pixels * - Null, not specifying a width for the field * This function will parcel out requested widths and divide remaining space among unspecified columns. * * @param fullSize Width, in pixels, of the containing row. * @return Array of integers, each corresponding to a child view, * representing the desired width, in pixels, of that view. */ private int[] calculateDetailWidths(int fullSize) { // Convert any percentages to pixels. Percentage columns are treated as percentage of the entire screen width. int[] widths = new int[mHints.length]; for (int i = 0; i < mHints.length; i++) { if (mHints[i] == null) { widths[i] = -1; } else if (mHints[i].contains("%")) { widths[i] = fullSize * Integer.parseInt(mHints[i].substring(0, mHints[i].indexOf("%"))) / 100; } else { widths[i] = Integer.parseInt(mHints[i]); } } int claimedSpace = 0; int indeterminateColumns = 0; for (int width : widths) { if (width != -1) { claimedSpace += width; } else { indeterminateColumns++; } } if (fullSize < claimedSpace + indeterminateColumns || (fullSize > claimedSpace && indeterminateColumns == 0)) { // Either more space has been claimed than the screen has room for, // or the full width isn't spoken for and there are no indeterminate columns claimedSpace += indeterminateColumns; for (int i = 0; i < widths.length; i++) { if (widths[i] == -1) { // Assign indeterminate columns a real width. // It's arbitrary and tiny, but this is going to look terrible regardless. widths[i] = 1; } else { // Shrink or expand columns proportionally widths[i] = fullSize * widths[i] / claimedSpace; } } } else if (indeterminateColumns > 0) { // Divide remaining space equally among the indeterminate columns int defaultWidth = (fullSize - claimedSpace) / indeterminateColumns; for (int i = 0; i < widths.length; i++) { if (widths[i] == -1) { widths[i] = defaultWidth; } } } return widths; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // calculate the view and its childrens default measurements super.onMeasure(widthMeasureSpec, heightMeasureSpec); // Adjust the children view's widths based on percentage size hints int[] widths = calculateDetailWidths(getMeasuredWidth()); for (int i = 0; i < views.length; i++) { if (views[i] != null) { LayoutParams params = (LinearLayout.LayoutParams) views[i].getLayoutParams(); params.width = widths[i]; views[i].setLayoutParams(params); } } // Re-calculate the view's measurements based on the percentage // adjustments above super.onMeasure(widthMeasureSpec, heightMeasureSpec); } }
package com.valkryst.VTerminal.samples; import com.valkryst.VTerminal.AsciiCharacter; import com.valkryst.VTerminal.AsciiString; import com.valkryst.VTerminal.Panel; import com.valkryst.VTerminal.builder.PanelBuilder; import com.valkryst.VTerminal.font.Font; import com.valkryst.VTerminal.font.FontLoader; import java.awt.Color; import java.io.IOException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.Collectors; public class SampleDrawTime { public static void main(final String[] args) throws IOException, URISyntaxException, InterruptedException { final Font font = FontLoader.loadFontFromJar("Fonts/DejaVu Sans Mono/18pt/bitmap.png", "Fonts/DejaVu Sans Mono/18pt/data.fnt", 1); final PanelBuilder builder = new PanelBuilder(); builder.setFont(font); final Panel panel = builder.build(); List<Long> measurements = new ArrayList<>(); for(int i = 1 ; i != 10_001 ; i++) { final int colorVal = ThreadLocalRandom.current().nextInt(45, 56 + (i / 500)); panel.getScreen().setForegroundColor(new Color(colorVal, 155, 255, 255)); panel.getScreen().setBackgroundColor(new Color(colorVal, colorVal, colorVal, 255)); // Random Characters, Flips, and Underlines: for (final AsciiString string : panel.getScreen().getStrings()) { for (final AsciiCharacter character : string.getCharacters()) { character.setCharacter(((char)ThreadLocalRandom.current().nextInt(45, 126))); character.setFlippedVertically(ThreadLocalRandom.current().nextBoolean()); character.setFlippedHorizontally(ThreadLocalRandom.current().nextBoolean()); character.setUnderlined(ThreadLocalRandom.current().nextBoolean()); character.setHidden(ThreadLocalRandom.current().nextBoolean()); } } // Draw and deal with calculations: final long timeBeforeDraw = System.nanoTime(); panel.draw(); final long timeAfterDraw = System.nanoTime(); final long timeDifference = timeAfterDraw - timeBeforeDraw; measurements.add(timeDifference); if (i % 50 == 0) { double averageDrawTime = measurements.stream().mapToLong(Long::longValue).sum() / (double) i; averageDrawTime /= 1_000_000; System.out.println( String.format("Avg Draw Time: %f ms\t\tAvg FPS: %f\t\tTotal Measurements: %d\t\tCached Images: %d", averageDrawTime, 1000 / averageDrawTime, i, panel.getImageCache().totalCachedImages()) ); } Thread.sleep(16); } // Remove the bottom and top 10% (outliers) of results: Collections.sort(measurements); final long middleElement = measurements.get(measurements.size() / 2); final double lowestElement = middleElement * 0.80; final double highestElement = middleElement + (middleElement * 0.80); measurements = measurements.stream().filter(val -> val >= lowestElement && val <= highestElement).collect(Collectors.toList()); double averageDrawTime = measurements.stream().mapToLong(Long::longValue).sum() / (double) measurements.size(); averageDrawTime /= 1_000_000; System.out.println("\nFINAL RESULTS:"); System.out.println( String.format("Avg Draw Time: %f ms\t\tAvg FPS: %f\t\tTotal Measurements: %d\t\tCached Images: %d", averageDrawTime, 1000 / averageDrawTime, measurements.size(), panel.getImageCache().totalCachedImages()) ); System.exit(0); } }
package org.commcare.views.media; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Point; import android.media.MediaPlayer; import android.net.Uri; import android.os.Build; import android.support.annotation.IdRes; import android.util.DisplayMetrics; import android.util.Log; import android.view.Display; import android.view.View; import android.view.WindowManager; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.MediaController; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import android.widget.VideoView; import org.commcare.dalvik.R; import org.commcare.preferences.CommCarePreferences; import org.commcare.preferences.DeveloperPreferences; import org.commcare.utils.MediaUtil; import org.commcare.utils.QRCodeEncoder; import org.commcare.views.ResizingImageView; import org.javarosa.core.reference.InvalidReferenceException; import org.javarosa.core.reference.ReferenceManager; import org.javarosa.core.services.Logger; import java.io.File; /** * This layout is used anywhere we can have image/audio/video/text. * TODO: Put this in a layout file!!!! * * @author carlhartung */ public class MediaLayout extends RelativeLayout { private static final String TAG = MediaLayout.class.getSimpleName(); @IdRes public static final int INLINE_VIDEO_PANE_ID = 99999; @IdRes private static final int QUESTION_TEXT_PANE_ID = 2342134; @IdRes private static final int AUDIO_BUTTON_ID = 3245345; @IdRes private static final int VIDEO_BUTTON_ID = 234982340; @IdRes private static final int IMAGE_VIEW_ID = 23423534; @IdRes private static final int MISSING_IMAGE_ID = 234873453; private TextView viewText; private AudioButton audioButton; private ImageButton videoButton; private TextView missingImageText; public MediaLayout(Context c) { super(c); viewText = null; audioButton = null; missingImageText = null; videoButton = null; } public void setAVT(TextView text, String audioURI, String imageURI, boolean showImageAboveText) { setAVT(text, audioURI, imageURI, null, null, null, null, showImageAboveText); } public void setAVT(TextView text, String audioURI, String imageURI, final String videoURI, final String bigImageURI) { setAVT(text, audioURI, imageURI, videoURI, bigImageURI, null, null, false); } public void setAVT(TextView text, String audioURI, String imageURI, final String videoURI, final String bigImageURI, final String qrCodeContent, String inlineVideoURI, boolean showImageAboveText) { viewText = text; RelativeLayout.LayoutParams mediaPaneParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); RelativeLayout questionTextPane = new RelativeLayout(this.getContext()); questionTextPane.setId(QUESTION_TEXT_PANE_ID); if (audioURI != null) { audioButton = new AudioButton(getContext(), audioURI, true); // random ID to be used by the relative layout. audioButton.setId(AUDIO_BUTTON_ID); } // Then set up the video button setupVideoButton(videoURI); boolean textVisible = (viewText.getVisibility() != GONE); addAudioVideoButtonsToView(questionTextPane, textVisible); // Now set up the center view, it is either an image, a QR Code, or an inline video View mediaPane = null; if (inlineVideoURI != null) { mediaPane = getInlineVideoView(inlineVideoURI, mediaPaneParams); } else if (qrCodeContent != null) { mediaPane = setupQRView(qrCodeContent); } else if (imageURI != null) { mediaPane = setupImage(imageURI, bigImageURI); } showImageAboveText = showImageAboveText || DeveloperPreferences.imageAboveTextEnabled(); addElementsToView(mediaPane, mediaPaneParams, questionTextPane, textVisible, showImageAboveText); } private void setupVideoButton(final String videoURI) { if (videoURI != null) { videoButton = new ImageButton(getContext()); videoButton.setImageResource(android.R.drawable.ic_media_play); videoButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String videoFilename = ""; try { videoFilename = ReferenceManager._().DeriveReference(videoURI).getLocalURI(); } catch (InvalidReferenceException e) { Log.e(TAG, "Invalid reference exception"); e.printStackTrace(); } File videoFile = new File(videoFilename); if (!videoFile.exists()) { // We should have a video clip, but the file doesn't exist. String errorMsg = getContext().getString(R.string.file_missing, videoFilename); Log.e(TAG, errorMsg); Toast.makeText(getContext(), errorMsg, Toast.LENGTH_LONG).show(); return; } Intent i = new Intent("android.intent.action.VIEW"); /** * Creates a video view for the provided URI or an error view elaborating why the video * couldn't be displayed. * * @param inlineVideoURI JavaRosa Reference URI * @param viewLayoutParams the layout params that will be applied to the view. Expect to be * mutated by this method */ private View getInlineVideoView(String inlineVideoURI, RelativeLayout.LayoutParams viewLayoutParams) { try { final String videoFilename = ReferenceManager._().DeriveReference(inlineVideoURI).getLocalURI(); int[] maxBounds = getMaxCenterViewBounds(); File videoFile = new File(videoFilename); if (!videoFile.exists()) { return getMissingImageView("No video file found at: " + videoFilename); } else { //NOTE: This has odd behavior when you have a text input on the screen //since clicking the video view to bring up controls has weird effects. //since we shotgun grab the focus for the input widget. final MediaController ctrl = new MediaController(this.getContext()); VideoView videoView = new VideoView(this.getContext()); videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mediaPlayer) { ctrl.show(); } }); videoView.setVideoPath(videoFilename); videoView.setMediaController(ctrl); ctrl.setAnchorView(videoView); //These surprisingly get re-jiggered as soon as the video is loaded, so we //just want to give it the _max_ bounds, it'll pick the limiter and shrink //itself when it's ready. viewLayoutParams.width = maxBounds[0]; viewLayoutParams.height = maxBounds[1]; videoView.setId(INLINE_VIDEO_PANE_ID); return videoView; } } catch (InvalidReferenceException ire) { Log.e(TAG, "invalid video reference exception"); ire.printStackTrace(); return getMissingImageView("Invalid reference: " + ire.getReferenceString()); } } private TextView getMissingImageView(String errorMessage) { missingImageText = new TextView(getContext()); missingImageText.setText(errorMessage); missingImageText.setPadding(10, 10, 10, 10); missingImageText.setId(MISSING_IMAGE_ID); return missingImageText; } private boolean useResizingImageView() { // only allow ResizingImageView to be used if not also using smart inflation return !CommCarePreferences.isSmartInflationEnabled() && ("full".equals(ResizingImageView.resizeMethod) || "half".equals(ResizingImageView.resizeMethod) || "width".equals(ResizingImageView.resizeMethod)); } /** * @return The appropriate max size of an image view pane in this widget. returned as an int * array of [width, height] */ private int[] getMaxCenterViewBounds() { DisplayMetrics metrics = this.getContext().getResources().getDisplayMetrics(); int maxWidth = metrics.widthPixels; int maxHeight = metrics.heightPixels; // subtract height for textview and buttons, if present if (viewText != null) { maxHeight = maxHeight - viewText.getHeight(); } if (videoButton != null) { maxHeight = maxHeight - videoButton.getHeight(); } else if (audioButton != null) { maxHeight = maxHeight - audioButton.getHeight(); } // reduce by third for safety return new int[]{maxWidth, (2 * maxHeight) / 3}; } /** * This adds a divider at the bottom of this layout. Used to separate * fields in lists. */ public void addDivider(ImageView v) { RelativeLayout.LayoutParams dividerParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); if (missingImageText != null) { dividerParams.addRule(RelativeLayout.BELOW, missingImageText.getId()); } else if (videoButton != null) { dividerParams.addRule(RelativeLayout.BELOW, videoButton.getId()); } else if (audioButton != null) { dividerParams.addRule(RelativeLayout.BELOW, audioButton.getId()); } else if (viewText != null) { // No picture dividerParams.addRule(RelativeLayout.BELOW, viewText.getId()); } else { Log.e(TAG, "Tried to add divider to uninitialized ATVWidget"); return; } addView(v, dividerParams); } @Override protected void onWindowVisibilityChanged(int visibility) { super.onWindowVisibilityChanged(visibility); if (visibility != View.VISIBLE) { if (audioButton != null) { audioButton.endPlaying(); } } } }
package com.designpatterns; import java.util.LinkedList; import java.util.List; public class TextCaretaker { private List<TextMemento> states = new LinkedList<TextMemento>(); public void setMemenot(TextMemento memento) { states.add(memento); } public TextMemento getState(int previous) { return states.get(states.size() - previous); } public TextMemento getPreviousState() { return getState(1); } }
/* -*- mode: jde; c-basic-offset: 2; indent-tabs-mode: nil -*- */ package processing.app.debug; import processing.app.Base; import processing.app.Preferences; import processing.app.Serial; import processing.app.SerialException; import static processing.app.I18n._; import java.io.*; import java.util.*; import java.util.zip.*; import javax.swing.*; import gnu.io.*; public class AvrdudeUploader extends Uploader { public AvrdudeUploader() { } public boolean uploadUsingPreferences(String buildPath, String className, boolean usingProgrammer) throws RunnerException, SerialException { this.verbose = verbose; Map<String, String> boardPreferences = Base.getBoardPreferences(); // if no protocol is specified for this board, assume it lacks a // bootloader and upload using the selected programmer. if (usingProgrammer || boardPreferences.get("upload.protocol") == null) { String programmer = Preferences.get("programmer"); Target target = Base.getTarget(); if (programmer.indexOf(":") != -1) { target = Base.targetsTable.get(programmer.substring(0, programmer.indexOf(":"))); programmer = programmer.substring(programmer.indexOf(":") + 1); } Collection params = getProgrammerCommands(target, programmer); params.add("-Uflash:w:" + buildPath + File.separator + className + ".hex:i"); return avrdude(params); } return uploadViaBootloader(buildPath, className); } private boolean uploadViaBootloader(String buildPath, String className) throws RunnerException, SerialException { Map<String, String> boardPreferences = Base.getBoardPreferences(); List commandDownloader = new ArrayList(); String protocol = boardPreferences.get("upload.protocol"); // avrdude wants "stk500v1" to distinguish it from stk500v2 if (protocol.equals("stk500")) protocol = "stk500v1"; String uploadPort = Preferences.get("serial.port"); // need to do a little dance for Leonardo and derivatives: // open then close the port at the magic baudrate (usually 1200 bps) first // to signal to the sketch that it should reset into bootloader. after doing // this wait a moment for the bootloader to enumerate. On Windows, also must // deal with the fact that the COM port number changes from bootloader to // sketch. if (boardPreferences.get("bootloader.path").equals("caterina")) { String caterinaUploadPort = null; try { // Toggle 1200 bps on selected serial port to force board reset. List<String> before = Serial.list(); if (before.contains(uploadPort)) { if (verbose) System.out .println(_("Forcing reset using 1200bps open/close on port ") + uploadPort); Serial.touchPort(uploadPort, 1200); // Scanning for available ports seems to open the port or // otherwise assert DTR, which would cancel the WDT reset if // it happened within 250 ms. So we wait until the reset should // have already occured before we start scanning. if (!Base.isMacOS()) Thread.sleep(300); } // Wait for a port to appear on the list int elapsed = 0; while (elapsed < 10000) { List<String> now = Serial.list(); List<String> diff = new ArrayList<String>(now); diff.removeAll(before); System.out.print("{"); for (String p : before) System.out.print(p+","); System.out.print("} / {"); for (String p : now) System.out.print(p+","); System.out.print("} => {"); for (String p : diff) System.out.print(p+","); System.out.println("}"); if (diff.size() > 0) { caterinaUploadPort = diff.get(0); System.out.println("found leo: " + caterinaUploadPort); break; } // Keep track of port that disappears before = now; Thread.sleep(250); elapsed += 250; // On Windows, it can take a long time for the port to disappear and // come back, so use a longer time out before assuming that the selected // port is the bootloader (not the sketch). if (((!Base.isWindows() && elapsed >= 500) || elapsed >= 5000) && now.contains(uploadPort)) { System.out.println("using selected port: " + uploadPort); caterinaUploadPort = uploadPort; break; } } if (caterinaUploadPort == null) // Something happened while detecting port throw new RunnerException( _("Couldn’t find the selected board. Try pressing the reset button after initiating the upload.")); uploadPort = caterinaUploadPort; } catch (SerialException e) { throw new RunnerException(e.getMessage()); } catch (InterruptedException e) { throw new RunnerException(e.getMessage()); } } commandDownloader.add("-c" + protocol); commandDownloader.add("-P" + (Base.isWindows() ? "\\\\.\\" : "") + uploadPort); commandDownloader.add( "-b" + Integer.parseInt(boardPreferences.get("upload.speed"))); commandDownloader.add("-D"); // don't erase if (!Preferences.getBoolean("upload.verify")) commandDownloader.add("-V"); // disable verify commandDownloader.add("-Uflash:w:" + buildPath + File.separator + className + ".hex:i"); if (boardPreferences.get("upload.disable_flushing") == null || boardPreferences.get("upload.disable_flushing").toLowerCase().equals("false")) { flushSerialBuffer(); } return avrdude(commandDownloader); } public boolean burnBootloader() throws RunnerException { String programmer = Preferences.get("programmer"); Target target = Base.getTarget(); if (programmer.indexOf(":") != -1) { target = Base.targetsTable.get(programmer.substring(0, programmer.indexOf(":"))); programmer = programmer.substring(programmer.indexOf(":") + 1); } return burnBootloader(getProgrammerCommands(target, programmer)); } private Collection getProgrammerCommands(Target target, String programmer) { Map<String, String> programmerPreferences = target.getProgrammers().get(programmer); List params = new ArrayList(); params.add("-c" + programmerPreferences.get("protocol")); if ("usb".equals(programmerPreferences.get("communication"))) { params.add("-Pusb"); } else if ("serial".equals(programmerPreferences.get("communication"))) { params.add("-P" + (Base.isWindows() ? "\\\\.\\" : "") + Preferences.get("serial.port")); if (programmerPreferences.get("speed") != null) { params.add("-b" + Integer.parseInt(programmerPreferences.get("speed"))); } } // XXX: add support for specifying the port address for parallel // programmers, although avrdude has a default that works in most cases. if (programmerPreferences.get("force") != null && programmerPreferences.get("force").toLowerCase().equals("true")) params.add("-F"); if (programmerPreferences.get("delay") != null) params.add("-i" + programmerPreferences.get("delay")); return params; } protected boolean burnBootloader(Collection params) throws RunnerException { Map<String, String> boardPreferences = Base.getBoardPreferences(); List fuses = new ArrayList(); fuses.add("-e"); // erase the chip if (boardPreferences.get("bootloader.unlock_bits") != null) fuses.add("-Ulock:w:" + boardPreferences.get("bootloader.unlock_bits") + ":m"); if (boardPreferences.get("bootloader.extended_fuses") != null) fuses.add("-Uefuse:w:" + boardPreferences.get("bootloader.extended_fuses") + ":m"); fuses.add("-Uhfuse:w:" + boardPreferences.get("bootloader.high_fuses") + ":m"); fuses.add("-Ulfuse:w:" + boardPreferences.get("bootloader.low_fuses") + ":m"); if (!avrdude(params, fuses)) return false; try { Thread.sleep(1000); } catch (InterruptedException e) {} Target t; List bootloader = new ArrayList(); String bootloaderPath = boardPreferences.get("bootloader.path"); if (bootloaderPath != null) { if (bootloaderPath.indexOf(':') == -1) { t = Base.getTarget(); // the current target (associated with the board) } else { String targetName = bootloaderPath.substring(0, bootloaderPath.indexOf(':')); t = Base.targetsTable.get(targetName); bootloaderPath = bootloaderPath.substring(bootloaderPath.indexOf(':') + 1); } File bootloadersFile = new File(t.getFolder(), "bootloaders"); File bootloaderFile = new File(bootloadersFile, bootloaderPath); bootloaderPath = bootloaderFile.getAbsolutePath(); bootloader.add("-Uflash:w:" + bootloaderPath + File.separator + boardPreferences.get("bootloader.file") + ":i"); } if (boardPreferences.get("bootloader.lock_bits") != null) bootloader.add("-Ulock:w:" + boardPreferences.get("bootloader.lock_bits") + ":m"); if (bootloader.size() > 0) return avrdude(params, bootloader); return true; } public boolean avrdude(Collection p1, Collection p2) throws RunnerException { ArrayList p = new ArrayList(p1); p.addAll(p2); return avrdude(p); } public boolean avrdude(Collection params) throws RunnerException { List commandDownloader = new ArrayList(); if(Base.isLinux()) { if ((new File(Base.getHardwarePath() + "/tools/" + "avrdude")).exists()) { commandDownloader.add(Base.getHardwarePath() + "/tools/" + "avrdude"); commandDownloader.add("-C" + Base.getHardwarePath() + "/tools/avrdude.conf"); } else { commandDownloader.add("avrdude"); } } else { commandDownloader.add(Base.getHardwarePath() + "/tools/avr/bin/" + "avrdude"); commandDownloader.add("-C" + Base.getHardwarePath() + "/tools/avr/etc/avrdude.conf"); } if (verbose || Preferences.getBoolean("upload.verbose")) { commandDownloader.add("-v"); commandDownloader.add("-v"); commandDownloader.add("-v"); commandDownloader.add("-v"); } else { commandDownloader.add("-q"); commandDownloader.add("-q"); } commandDownloader.add("-p" + Base.getBoardPreferences().get("build.mcu")); commandDownloader.addAll(params); return executeUploadCommand(commandDownloader); } }
package com.facebook.android; import java.util.LinkedList; import org.json.JSONException; import org.json.JSONObject; import android.app.ProgressDialog; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.os.Handler; import android.util.Log; import com.facebook.android.Util.Callback; // TODO(ssoneff): // clean up login / logout interface // make Facebook button // refine callback interface... // error codes? // javadocs // make endpoint URLs set-able // fix null pointer exception in webview // tidy up eclipse config... // size, title of uiActivity // support multiple facebook sessions? provide session manager? // wrapper for data: FacebookObject? // lower pri: auto uiInteraction on session failure? // request queue? request callbacks for loading, cancelled? // Questions: // fix fbconnect://... // oauth redirect not working // oauth does not return expires_in // expires_in is duration or expiration? // for errors: use string (message), error codes, or exceptions? // why callback on both receive response and loaded? public class Facebook { public static final String SUCCESS_URI = "fbconnect://success"; private static final String OAUTH_ENDPOINT = "http://graph.dev.facebook.com/oauth/authorize"; private static final String UI_SERVER = "http: private static final String GRAPH_BASE_URL = "https://graph.facebook.com/"; private static final String RESTSERVER_URL = "http://api.facebook.com/restserver.php"; private static final String TOKEN = "access_token"; private static final String EXPIRES = "expires_in"; private static final String KEY = "facebook-session"; final private Context mContext; final private String mAppId; private static String mAccessToken = null; private static long mAccessExpires = 0; // Initialization // for Facebook requests without a context public Facebook() { this.mContext = null; this.mAppId = null; } public Facebook(Context c, String clientId) { this.mContext = c; this.mAppId = clientId; if (getAccessToken() == null) { restoreSavedSession(); } } public void authorize(String[] permissions, final DialogListener listener) { // check if we have a context to run in... Bundle params = new Bundle(); params.putString("display", "touch"); params.putString("type", "user_agent"); params.putString("client_id", mAppId); params.putString("redirect_uri", SUCCESS_URI); if (permissions != null) { params.putString("scope", Util.join(permissions, ',')); } dialog("login", params, new DialogListener() { @Override public void onDialogSucceed(Bundle values) { setAccessToken(values.getString(TOKEN)); setAccessExpiresIn(values.getString(EXPIRES)); storeSession(); Log.d("Facebook", "Success! access_token=" + getAccessToken() + " expires=" + getAccessExpires()); listener.onDialogSucceed(values); } @Override public void onDialogFail(String error) { Log.d("Facebook-Callback", "Dialog failed: " + error); listener.onDialogFail(error); } @Override public void onDialogCancel() { Log.d("Facebook-Callback", "Dialog cancelled"); listener.onDialogCancel(); } }); } public void logout() { setAccessToken(""); setAccessExpires(0); clearStoredSession(); } // API requests // support old API: method provided as parameter public void request(Bundle parameters, RequestListener listener) { request(null, "GET", parameters, listener); } public void request(String graphPath, RequestListener listener) { request(graphPath, "GET", new Bundle(), listener); } public void request(String graphPath, Bundle parameters, RequestListener listener) { request(graphPath, "GET", parameters, listener); } public void request(String graphPath, String httpMethod, Bundle parameters, final RequestListener listener) { if (isSessionValid()) { parameters.putString(TOKEN, getAccessToken()); } String url = graphPath != null ? GRAPH_BASE_URL + graphPath : RESTSERVER_URL; Util.asyncOpenUrl(url, httpMethod, parameters, new Callback() { public void call(String response) { Log.d("Facebook-SDK", "Got response: " + response); try { JSONObject o = new JSONObject(response); if (o.has("error")) { listener.onRequestFail(o.getString("error")); } else { listener.onRequestSucceed(o); } } catch (JSONException e) { listener.onRequestFail(e.getMessage()); } } }); } // UI Server requests public void dialog(String action, DialogListener listener) { dialog(action, null, listener); } public void dialog(String action, Bundle parameters, final DialogListener listener) { if (mContext == null) { Log.w("Facebook-SDK", "Cannot create a dialog without context"); } // need logic to determine correct endpoint for resource, e.g. "login" --> "oauth/authorize" String endpoint = action.equals("login") ? OAUTH_ENDPOINT : UI_SERVER; final String url = endpoint + "?" + Util.encodeUrl(parameters); // This is buggy: webview dies with null pointer exception (but not in my code)... /* final ProgressDialog spinner = ProgressDialog.show(mContext, "Facebook", "Loading..."); final Handler h = new Handler(); // start async data fetch Util.asyncOpenUrl(url, "GET", null, new Callback() { @Override public void call(final String response) { Log.d("Facebook", "got response: " + response); if (response.length() == 0) listener.onDialogFail("Empty response"); h.post(new Runnable() { @Override public void run() { //callback: close progress dialog spinner.dismiss(); new FbDialog(mContext, url, response, listener).show(); } }); } }); */ new FbDialog(mContext, url, "", listener).show(); } // utilities public boolean isSessionValid() { Log.d("Facebook SDK", "session valid? token=" + getAccessToken() + " duration: " + (getAccessExpires() - System.currentTimeMillis())); return getAccessToken() != null && (getAccessExpires() == 0 || System.currentTimeMillis() < getAccessExpires()); } private void storeSession() { Editor editor = mContext.getSharedPreferences(KEY, Context.MODE_PRIVATE).edit(); editor.putString(TOKEN, getAccessToken()); editor.putLong(EXPIRES, getAccessExpires()); if (editor.commit()) { Log.d("Facebook-WebView", "changes committed"); } else { Log.d("Facebook-WebView", "changes NOT committed"); } // WTF? commit does not work on emulator ... file system problem? SharedPreferences s = mContext.getSharedPreferences(KEY, Context.MODE_PRIVATE); Log.d("Facebook-Callback", "Stored: access_token=" + s.getString(TOKEN, "NONE")); } private void restoreSavedSession() { SharedPreferences savedSession = mContext.getSharedPreferences(KEY, Context.MODE_PRIVATE); setAccessToken(savedSession.getString(TOKEN, null)); setAccessExpires(savedSession.getLong(EXPIRES, 0)); } private void clearStoredSession() { Editor editor = mContext.getSharedPreferences( KEY, Context.MODE_PRIVATE).edit(); editor.clear(); editor.commit(); } // get/set public static synchronized String getAccessToken() { return mAccessToken; } public static synchronized long getAccessExpires() { return mAccessExpires; } public static synchronized void setAccessToken(String token) { mAccessToken = token; } public static synchronized void setAccessExpires(long time) { mAccessExpires = time; } public static void setAccessExpiresIn(String expires_in) { if (expires_in != null) { setAccessExpires(System.currentTimeMillis() + Integer.parseInt(expires_in) * 1000); } } // callback interfaces // Questions: // problem: callbacks are called in background thread, not UI thread: changes to UI need to be done in UI thread // solution 0: make all the interfaces blocking -- but lots of work for developers to get working! // solution 1: let the SDK users handle this -- they write code to post action back to UI thread (current) // solution 2: add extra callback methods -- one for background thread to call, on for UI thread (perhaps simplest?) // solution 3: let developer explicitly provide handler to run the callback // solution 4: run everything in the UI thread public static abstract class LogoutListener { public void onSessionLogoutStart() { } public void onSessionLogoutFinish() { } } public static abstract class RequestListener { public abstract void onRequestSucceed(JSONObject response); public abstract void onRequestFail(String error); } public static abstract class DialogListener { public abstract void onDialogSucceed(Bundle values); public abstract void onDialogFail(String error); public void onDialogCancel() { } } }
package org.ovirt.engine.core.bll; import java.util.ArrayList; import org.ovirt.engine.core.common.businessentities.MigrationSupport; import org.ovirt.engine.core.common.businessentities.VDS; import org.ovirt.engine.core.common.businessentities.VDSStatus; import org.ovirt.engine.core.common.businessentities.VDSType; import org.ovirt.engine.core.common.businessentities.VM; import org.ovirt.engine.core.common.businessentities.VMStatus; import org.ovirt.engine.core.common.businessentities.VdsVersion; import org.ovirt.engine.core.common.config.Config; import org.ovirt.engine.core.common.config.ConfigValues; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.compat.NGuid; import org.ovirt.engine.core.compat.Version; import org.ovirt.engine.core.dal.VdcBllMessages; import org.ovirt.engine.core.dal.dbbroker.DbFacade; import org.ovirt.engine.core.utils.log.Log; import org.ovirt.engine.core.utils.log.LogFactory; public class VdsSelector { private java.util.ArrayList<Guid> privateRunVdssList; public java.util.ArrayList<Guid> getRunVdssList() { return privateRunVdssList; } public void setRunVdssList(java.util.ArrayList<Guid> value) { privateRunVdssList = value; } private boolean privateCheckDestinationFirst; public boolean getCheckDestinationFirst() { return privateCheckDestinationFirst; } public void setCheckDestinationFirst(boolean value) { privateCheckDestinationFirst = value; } private NGuid privateDestinationVdsId; public NGuid getDestinationVdsId() { return privateDestinationVdsId; } public void setDestinationVdsId(NGuid value) { privateDestinationVdsId = value; } private VM privateVm; private VM getVm() { return privateVm; } private void setVm(VM value) { privateVm = value; } public VdsSelector(VM vm, NGuid destinationVdsId, boolean dedicatedFirst) { setVm(vm); setDestinationVdsId(destinationVdsId); setCheckDestinationFirst(dedicatedFirst); setRunVdssList(new java.util.ArrayList<Guid>()); } public Guid GetVdsToRunOn() { Guid result = Guid.Empty; if (getDestinationVdsId() != null) { if (getCheckDestinationFirst()) { result = GetVdsRunOnDestination(); if (result.equals(Guid.Empty) && privateVm.getMigrationSupport() != MigrationSupport.PINNED_TO_HOST) { result = GetAnyVdsToRunOn(); } } else { result = GetAnyVdsToRunOn(); if (result.equals(Guid.Empty)) { result = GetVdsRunOnDestination(); } } } else { result = GetAnyVdsToRunOn(); } return result; } public boolean CanFindVdsToRunOn(java.util.ArrayList<String> messages, boolean isMigrate) { boolean returnValue = false; if (getDestinationVdsId() != null) { returnValue = CanRunOnDestinationVds(messages, isMigrate); } if (!returnValue) { if (privateVm.getMigrationSupport() == MigrationSupport.PINNED_TO_HOST) { if (messages.size() > 0) { messages.set(0, VdcBllMessages.VM_PINNED_TO_HOST_CANNOT_RUN_ON_THE_DEFAULT_VDS.toString()); } else { messages.add(VdcBllMessages.VM_PINNED_TO_HOST_CANNOT_RUN_ON_THE_DEFAULT_VDS.toString()); } return false; } returnValue = CanFindAnyVds(messages, isMigrate); } return returnValue; } private Guid GetVdsRunOnDestination() { Guid result = Guid.Empty; if (getDestinationVdsId() != null) { VDS target_vds = DbFacade.getInstance().getVdsDAO().get(getDestinationVdsId()); log.infoFormat("Checking for a specific VDS only - id:{0}, name:{1}, host_name(ip):{2}", getDestinationVdsId(), target_vds.getvds_name(), target_vds.gethost_name()); VmHandler.UpdateVmGuestAgentVersion(getVm()); if (target_vds.getvds_type() == VDSType.PowerClient && !Config.<Boolean> GetValue(ConfigValues.PowerClientAllowRunningGuestsWithoutTools) && getVm() != null && getVm().getHasAgent()) { log.infoFormat( "VdcBLL.RunVmCommandBase.getVdsToRunOn - VM {0} has no tools - skipping power client check", getVm().getId()); } else { result = getVdsToRunOn(new java.util.ArrayList<VDS>(java.util.Arrays.asList(new VDS[] { target_vds }))); } } return result; } private Guid GetAnyVdsToRunOn() { return getVdsToRunOn(DbFacade.getInstance() .getVdsDAO() .getAllOfTypes(new VDSType[] { VDSType.VDS, VDSType.oVirtNode })); } private boolean CanRunOnDestinationVds(java.util.ArrayList<String> messages, boolean isMigrate) { boolean returnValue = false; if (getDestinationVdsId() != null) { VDS target_vds = DbFacade.getInstance().getVdsDAO().get(getDestinationVdsId()); log.infoFormat("Checking for a specific VDS only - id:{0}, name:{1}, host_name(ip):{2}", getDestinationVdsId(), target_vds.getvds_name(), target_vds.gethost_name()); returnValue = CanFindVdsToRun(messages, isMigrate, new java.util.ArrayList<VDS>(java.util.Arrays.asList(new VDS[] { target_vds }))); } return returnValue; } private boolean CanFindAnyVds(java.util.ArrayList<String> messages, boolean isMigrate) { return CanFindVdsToRun(messages, isMigrate, DbFacade.getInstance().getVdsDAO().getAllOfTypes(new VDSType[] { VDSType.VDS, VDSType.oVirtNode })); } /** * This function used in CanDoAction function. Purpose is to check if there * are Vds avalable to run vm in CanDoAction - before concrete running * action This function goes over all available vdss and check if current * vds can run vm. If vds cannot running vm - reason stored. If there is no * any vds, avalable too run vm - returning reason with highest value. * Reasons sorted in VdcBllMessages by their priorities */ private boolean CanFindVdsToRun(java.util.ArrayList<String> messages, boolean isMigrate, Iterable<VDS> vdss) { VdcBllMessages messageToReturn = VdcBllMessages.Unassigned; /** * save vdsVersion in order to know vds version that was wrong */ VdsVersion vdsVersion = null; boolean noVDSs = true; for (VDS curVds : vdss) { if (isMigrate && getVm().getrun_on_vds() != null && getVm().getrun_on_vds().equals(curVds.getId())) { continue; } noVDSs = false; ValidationResult result = validateHostIsReadyToRun(curVds); if (result.isValid()) { return true; } else { if (messageToReturn.getValue() < result.getMessage().getValue()) { messageToReturn = result.getMessage(); /** * save version of current vds for later use */ vdsVersion = curVds.getVersion(); } } } if (noVDSs) { if (messages != null) { messageToReturn = VdcBllMessages.ACTION_TYPE_FAILED_NO_VDS_AVAILABLE_IN_CLUSTER; } } if (messages != null) { messages.add(messageToReturn.toString()); /** * if error due to versions, add versions information to can do * action message */ if (messageToReturn == VdcBllMessages.ACTION_TYPE_FAILED_VDS_VM_VERSION && vdsVersion != null) { VmHandler.UpdateVmGuestAgentVersion(getVm()); messages.add("$toolsVersion " + getVm().getPartialVersion()); messages.add("$serverVersion " + vdsVersion.getPartialVersion()); } } return false; } private ValidationResult validateHostIsReadyToRun(final VDS vds) { if ((!vds.getvds_group_id().equals(getVm().getvds_group_id())) || (vds.getstatus() != VDSStatus.Up) || isVdsFailedToRunVm(vds.getId())) { return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_VDS_VM_CLUSTER); } // If Vm in Paused mode - no additional memory allocation needed else if (getVm().getstatus() != VMStatus.Paused && !RunVmCommandBase.hasMemoryToRunVM(vds, getVm())) { // not enough memory // In case we are using this function in migration we make sure we // don't allocate the same VDS return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_VDS_VM_MEMORY); } // if vm has more vCpus then vds physical cpus - dont allow to run else if (vds.getcpu_cores() != null && getVm().getnum_of_cpus() > vds.getcpu_cores()) { return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_VDS_VM_CPUS); } else if (!IsVMSwapValueLegal(vds)) { return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_VDS_VM_SWAP); } return new ValidationResult(); } /** * Determine if specific vds already failed to run vm - to prevent * sequentual running of vm on problematic vds * * @param vdsId * @return */ private boolean isVdsFailedToRunVm(Guid vdsId) { boolean retValue = false; if (getRunVdssList() != null && getRunVdssList().contains(vdsId)) { retValue = true; } return retValue; } private static boolean IsVMSwapValueLegal(VDS vds) { Version version = vds.getvds_group_compatibility_version(); if (!Config.<Boolean> GetValue(ConfigValues.EnableSwapCheck)) { return true; } if (vds.getswap_total() == null || vds.getswap_free() == null || vds.getmem_available() == null || vds.getmem_available() <= 0 || vds.getphysical_mem_mb() == null || vds.getphysical_mem_mb() <= 0) { return true; } long swap_total = vds.getswap_total(); long swap_free = vds.getswap_free(); long mem_available = vds.getmem_available(); long physical_mem_mb = vds.getphysical_mem_mb(); return ((swap_total - swap_free - mem_available) * 100 / physical_mem_mb) <= Config .<Integer> GetValue(ConfigValues.BlockMigrationOnSwapUsagePercentage); } private Guid getVdsToRunOn(Iterable<VDS> vdss) { ArrayList<VDS> readyToRun = new ArrayList<VDS>(); for (VDS curVds : vdss) { // vds must be in the correct group if (!curVds.getvds_group_id().equals(getVm().getvds_group_id())) continue; // vds must be up to run a vm if (curVds.getstatus() != VDSStatus.Up) continue; // apply limit on vds memory over commit. if (!RunVmCommandBase.hasMemoryToRunVM(curVds, getVm())) continue; // In case we are using this function in migration we make sure we // don't allocate the same VDS if ((getVm().getrun_on_vds() != null && getVm().getrun_on_vds().equals(curVds.getId())) || isVdsFailedToRunVm(curVds.getId()) || // RunVmCommandBase.isVdsVersionOld(curVds, getVm()) || !RunVmCommandBase.hasCapacityToRunVM(curVds)) continue; // vds must have at least cores as the vm if (curVds.getcpu_cores() != null && getVm().getnum_of_cpus() > curVds.getcpu_cores()) { continue; } if (!IsVMSwapValueLegal(curVds)) continue; readyToRun.add(curVds); } return readyToRun.isEmpty() ? Guid.Empty : getBestVdsToRun(readyToRun); } private Guid getBestVdsToRun(java.util.ArrayList<VDS> list) { VdsComparer comparer = VdsComparer.CreateComparer(list.get(0).getselection_algorithm()); VDS bestVDS = list.get(0); for (int i = 1; i < list.size(); i++) { VDS curVds = list.get(i); if (comparer.IsBetter(bestVDS, curVds, getVm())) // if (((bestVDS.physical_mem_mb - bestVDS.mem_commited) < // (curVds.physical_mem_mb - curVds.mem_commited))) { bestVDS = curVds; } } /** * add chosen vds to running vdss list. */ comparer.BestVdsProcedure(bestVDS); getRunVdssList().add(bestVDS.getId()); return bestVDS.getId(); } private static Log log = LogFactory.getLog(VdsSelector.class); }
package com.github.kubatatami.judonetworking.transports; import com.github.kubatatami.judonetworking.AsyncResult; import java.io.IOException; import okhttp3.Authenticator; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.Route; public abstract class OkHttpOAuth2 { private String tokenType; private String accessToken; private long tokenLifeTime; private AsyncResult asyncResult; private Interceptor oAuthInterceptor = new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { if (asyncResult != null) { await(); } Request request = chain.request(); if (tokenLifeTime != 0 && tokenLifeTime < System.currentTimeMillis()) { callForToken(); } if (accessToken != null && tokenType != null) { request = request.newBuilder() .header("Authorization", tokenType + " " + accessToken).build(); } return chain.proceed(request); } }; private Authenticator oAuthAuthenticator = new Authenticator() { @Override public Request authenticate(Route route, Response response) throws IOException { String prevAccessToken = accessToken; synchronized (this) { if (canDoTokenRequest()) { if (prevAccessToken.equals(accessToken)) { callForToken(); } if (accessToken != null) { return response.request(); } } return null; } } }; private void callForToken() throws IOException { asyncResult = doTokenRequest(); await(); } private void await() throws IOException { try { asyncResult.await(); } catch (InterruptedException e) { throw new IOException(e); } } public void prepareOkHttpToOAuth(OkHttpClient.Builder okHttpClient) { okHttpClient.networkInterceptors().add(oAuthInterceptor); okHttpClient.authenticator(oAuthAuthenticator); } public void setOAuthToken(String tokenType, String accessToken) { this.tokenType = tokenType; this.accessToken = accessToken; } public void setTokenLifeTime(long tokenLifeTime) { this.tokenLifeTime = tokenLifeTime; } public String getTokenType() { return tokenType; } public String getAccessToken() { return accessToken; } public long getTokenLifeTime() { return tokenLifeTime; } protected abstract AsyncResult doTokenRequest(); protected abstract boolean canDoTokenRequest(); }
package org.intermine.bio.dataconversion; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Map.Entry; import org.intermine.dataconversion.ItemWriter; import org.intermine.metadata.ClassDescriptor; import org.intermine.metadata.FieldDescriptor; import org.intermine.metadata.MetaDataException; import org.intermine.metadata.Model; import org.intermine.metadata.ReferenceDescriptor; import org.intermine.objectstore.ObjectStoreException; import org.intermine.sql.Database; import org.intermine.sql.DatabaseUtil; import org.intermine.util.StringUtil; import org.intermine.util.TypeUtil; import org.intermine.util.XmlUtil; import org.intermine.xml.full.Attribute; import org.intermine.xml.full.Item; import org.intermine.xml.full.Reference; import org.intermine.xml.full.ReferenceList; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import org.apache.commons.collections.keyvalue.MultiKey; import org.apache.commons.collections.map.MultiKeyMap; import org.apache.log4j.Logger; /** * DataConverter to read from a Chado database into items * @author Kim Rutherford */ public class ChadoDBConverter extends BioDBConverter { private static class FeatureData { String uniqueName; // the synonyms that have already been created Set<String> existingSynonyms = new HashSet<String>(); String itemIdentifier; String interMineType; Integer intermineObjectId; short flags = 0; static final short EVIDENCE_CREATED_BIT = 0; static final short EVIDENCE_CREATED = 1 << EVIDENCE_CREATED_BIT; } protected static final Logger LOG = Logger.getLogger(ChadoDBConverter.class); private Map<Integer, FeatureData> features = new HashMap<Integer, FeatureData>(); private String dataSourceName; private String dataSetTitle; private int taxonId = -1; private String genus; private String species; private String sequenceFeatureTypesString = "'chromosome', 'chromosome_arm'"; private String featureTypesString = "'gene', 'mRNA', 'transcript', 'CDS', 'intron', 'exon', " + "'regulatory_region', 'enhancer', " // ignore for now: + "'EST', 'cDNA_clone', " + "'miRNA', 'snRNA', 'ncRNA', 'rRNA', 'ncRNA', 'snoRNA', 'tRNA', " + "'chromosome_band', 'transposable_element_insertion_site', " + "'chromosome_structure_variation', 'protein', " + "'five_prime_untranslated_region', " + "'five_prime_UTR', 'three_prime_untranslated_region', 'three_prime_UTR', 'transcript', " + sequenceFeatureTypesString; private int chadoOrganismId; private Model model = Model.getInstanceByName("genomic"); private MultiKeyMap config = null; private static final List<String> PARTOF_RELATIONS = Arrays.asList("partof", "part_of"); private static final List<Item> EMPTY_ITEM_LIST = Collections.emptyList(); /** * A class that represents an action while processing synonyms, dbxrefs, etc. * @author Kim Rutherford */ protected static class ConfigAction { protected ConfigAction() { // empty } } /** * An action that sets an attribute in a new Item. */ protected static class SetFieldConfigAction extends ConfigAction { private String fieldName; SetFieldConfigAction() { fieldName = null; } SetFieldConfigAction(String fieldName) { this.fieldName = fieldName; } } /** * An action that sets a Synonym. */ protected static class CreateSynonymAction extends ConfigAction { private String synonymType; // make a synonym and use the type from chado ("symbol", "identifier" etc.) as the Synonym // type CreateSynonymAction() { synonymType = null; } // make a synonym and use given type as the Synonym type CreateSynonymAction(String synonymType) { this.synonymType = synonymType; } } private static class DoNothingAction extends ConfigAction { // do nothing for this data } /** * An action that make a synonym. */ protected static final ConfigAction CREATE_SYNONYM_ACTION = new CreateSynonymAction(); protected static final ConfigAction DO_NOTHING_ACTION = new DoNothingAction(); /** * Create a new ChadoDBConverter object. * @param database the database to read from * @param tgtModel the Model used by the object store we will write to with the ItemWriter * @param writer an ItemWriter used to handle the resultant Items */ public ChadoDBConverter(Database database, Model tgtModel, ItemWriter writer) { super(database, tgtModel, writer); } @SuppressWarnings("unchecked") protected Map<MultiKey, List<ConfigAction>> getConfig() { if (config == null) { config = new MultiKeyMap(); } return config; } /** * Set the name of the DataSet Item to create for this converter. * @param title the title */ public void setDataSetTitle(String title) { this.dataSetTitle = title; } /** * Set the name of the DataSource Item to create for this converter. * @param name the name */ public void setDataSourceName(String name) { this.dataSourceName = name; } /** * Set the taxonId to use when creating the Organism Item for the new features. * @param taxonId the taxon id */ public void setTaxonId(String taxonId) { this.taxonId = Integer.valueOf(taxonId).intValue(); } /** * Get the taxonId to use when creating the Organism Item for the * @return the taxon id */ public int getTaxonIdInt() { return taxonId; } /** * The genus to use when querying for features. * @param genus the genus */ public void setGenus(String genus) { this.genus = genus; } /** * The species to use when querying for features. * @param species the species */ public void setSpecies(String species) { this.species = species; } /** * Process the data from the Database and write to the ItemWriter. * {@inheritDoc} */ @Override public void process() throws Exception { Connection connection; if (getDatabase() == null) { // no Database when testing and no connectio needed connection = null; } else { connection = getDatabase().getConnection(); } if (dataSetTitle == null) { throw new IllegalArgumentException("dataSetTitle not set in ChadoDBConverter"); } if (dataSourceName == null) { throw new IllegalArgumentException("dataSourceName not set in ChadoDBConverter"); } if (getTaxonIdInt() == -1) { throw new IllegalArgumentException("taxonId not set in ChadoDBConverter"); } if (species == null) { throw new IllegalArgumentException("species not set in ChadoDBConverter"); } if (genus == null) { throw new IllegalArgumentException("genus not set in ChadoDBConverter"); } chadoOrganismId = getChadoOrganismId(connection); processFeatureTable(connection); processPubTable(connection); processLocationTable(connection); processRelationTable(connection); processDbxrefTable(connection); processSynonymTable(connection); processFeaturePropTable(connection); addMissingDataEvidence(); } private void processFeatureTable(Connection connection) throws SQLException, ObjectStoreException { Item dataSet = getDataSetItem(dataSetTitle); // Stores DataSet Item dataSource = getDataSourceItem(dataSourceName); // Stores DataSource Item organismItem = getOrganismItem(getTaxonIdInt()); // Stores Organism ResultSet res = getFeatureResultSet(connection); int count = 0; while (res.next()) { Integer featureId = new Integer(res.getInt("feature_id")); String name = res.getString("name"); String uniqueName = res.getString("uniquename"); String type = res.getString("type"); int seqlen = 0; if (res.getObject("seqlen") != null) { seqlen = res.getInt("seqlen"); } List<String> primaryIds = new ArrayList<String>(); primaryIds.add(uniqueName); String interMineType = TypeUtil.javaiseClassName(fixFeatureType(type)); uniqueName = fixIdentifier(interMineType, uniqueName); Item feature = makeFeature(featureId, type, interMineType, name, uniqueName, seqlen); if (feature != null) { FeatureData fdat = new FeatureData(); fdat.itemIdentifier = feature.getIdentifier(); fdat.uniqueName = uniqueName; fdat.interMineType = XmlUtil.getFragmentFromURI(feature.getClassName()); feature.setReference("organism", organismItem); MultiKey nameKey = new MultiKey("feature", fdat.interMineType, dataSourceName, "name"); List<ConfigAction> nameActionList = getConfig().get(nameKey); MultiKey uniqueNameKey = new MultiKey("feature", fdat.interMineType, dataSourceName, "uniquename"); List<ConfigAction> uniqueNameActionList = getConfig().get(uniqueNameKey); if (name != null) { if (nameActionList == null || nameActionList.size() == 0) { if (feature.checkAttribute("symbol")) { feature.setAttribute("symbol", name); } else { if (feature.checkAttribute("symbol")) { feature.setAttribute("symbol", name); } else { // do nothing, if the name needs to go in a different attribute // it will need to be configured } } } else { for (ConfigAction action: nameActionList) { if (action instanceof SetFieldConfigAction) { SetFieldConfigAction attrAction = (SetFieldConfigAction) action; feature.setAttribute(attrAction.fieldName, name); } } } } if (uniqueNameActionList == null || uniqueNameActionList.size() == 0) { feature.setAttribute("identifier", uniqueName); } else { for (ConfigAction action: uniqueNameActionList) { if (action instanceof SetFieldConfigAction) { SetFieldConfigAction attrAction = (SetFieldConfigAction) action; feature.setAttribute(attrAction.fieldName, uniqueName); } } } // don't set the evidence collection - that's done by processPubTable() fdat.intermineObjectId = store(feature); // Stores Feature // always create a synonym for the uniquename createSynonym(fdat, "identifier", uniqueName, true, dataSet, EMPTY_ITEM_LIST, dataSource); // Stores Synonym if (name != null) { if (nameActionList == null || nameActionList.size() == 0 || nameActionList.contains(CREATE_SYNONYM_ACTION)) { name = fixIdentifier(interMineType, name); if (!fdat.existingSynonyms.contains(name)) { createSynonym(fdat, "name", name, false, dataSet, EMPTY_ITEM_LIST, dataSource); // Stores Synonym } } } features.put(featureId, fdat); count++; } } LOG.info("created " + count + " features"); res.close(); } /** * Make and store a new feature * @param featureId the chado feature id * @param chadoFeatureType the chado feature type (a SO term) * @param interMineType the InterMine type of the feature * @param name the name * @param uniqueName the uniquename * @param seqlen the sequence length (if known) */ protected Item makeFeature(Integer featureId, String chadoFeatureType, String interMineType, String name, String uniqueName, int seqlen) { return createItem(interMineType); } /** * Fix types from the feature table, perhaps by changing non-SO type into their SO equivalent. * Types that don't need fixing will be returned unchanged. * @param type the input type * @return the fixed type */ protected String fixFeatureType(String type) { if (type.equals("five_prime_untranslated_region")) { return "five_prime_UTR"; } else { if (type.equals("three_prime_untranslated_region")) { return "three_prime_UTR"; } else { return type; } } } private void processLocationTable(Connection connection) throws SQLException, ObjectStoreException { Item dataSet = getDataSetItem(dataSetTitle); ResultSet res = getFeatureLocResultSet(connection); int count = 0; int featureWarnings = 0; while (res.next()) { Integer featureLocId = new Integer(res.getInt("featureloc_id")); Integer featureId = new Integer(res.getInt("feature_id")); Integer srcFeatureId = new Integer(res.getInt("srcfeature_id")); int start = res.getInt("fmin") + 1; int end = res.getInt("fmax"); int strand = res.getInt("strand"); if (features.containsKey(srcFeatureId)) { FeatureData srcFeatureData = features.get(srcFeatureId); if (features.containsKey(featureId)) { FeatureData featureData = features.get(featureId); makeLocation(srcFeatureData.itemIdentifier, featureData.itemIdentifier, start, end, strand, getTaxonIdInt(), dataSet); // Stores Location count++; } else { if (featureWarnings <= 20) { if (featureWarnings < 20) { LOG.warn("featureId (" + featureId + ") from location " + featureLocId + " was not found in the feature table"); } else { LOG.warn("further location warnings ignored"); } featureWarnings++; } } } else { throw new RuntimeException("srcfeature_id (" + srcFeatureId + ") from location " + featureLocId + " was not found in the feature table"); } } LOG.info("created " + count + " locations"); res.close(); } private void processRelationTable(Connection connection) throws SQLException, ObjectStoreException { ResultSet res = getFeatureRelationshipResultSet(connection); Integer lastSubjectId = null; // Map from relation type to Map from object type to FeatureData Map<String, Map<String, List<FeatureData>>> relTypeMap = new HashMap<String, Map<String, List<FeatureData>>>(); int featureWarnings = 0; int count = 0; int collectionTotal = 0; while (res.next()) { Integer featRelationshipId = new Integer(res.getInt("feature_relationship_id")); Integer subjectId = new Integer(res.getInt("subject_id")); Integer objectId = new Integer(res.getInt("object_id")); String relationTypeName = res.getString("type_name"); if (lastSubjectId != null && subjectId != lastSubjectId) { processCollectionData(lastSubjectId, relTypeMap); // Stores stuff collectionTotal += relTypeMap.size(); relTypeMap = new HashMap<String, Map<String, List<FeatureData>>>(); } if (features.containsKey(subjectId)) { if (features.containsKey(objectId)) { FeatureData objectFeatureData = features.get(objectId); Map<String, List<FeatureData>> objectClassFeatureDataMap; if (relTypeMap.containsKey(relationTypeName)) { objectClassFeatureDataMap = relTypeMap.get(relationTypeName); } else { objectClassFeatureDataMap = new HashMap<String, List<FeatureData>>(); relTypeMap.put(relationTypeName, objectClassFeatureDataMap); } List<FeatureData> featureDataList; if (objectClassFeatureDataMap.containsKey(objectFeatureData.interMineType)) { featureDataList = objectClassFeatureDataMap.get(objectFeatureData.interMineType); } else { featureDataList = new ArrayList<FeatureData>(); objectClassFeatureDataMap.put(objectFeatureData.interMineType, featureDataList); } featureDataList.add(objectFeatureData); } else { if (featureWarnings <= 20) { if (featureWarnings < 20) { LOG.warn("object_id " + objectId + " from feature_relationship " + featRelationshipId + " was not found in the feature table"); } else { LOG.warn("further feature_relationship warnings ignored"); } featureWarnings++; } } } else { if (featureWarnings <= 20) { if (featureWarnings < 20) { LOG.warn("subject_id " + subjectId + " from feature_relationship " + featRelationshipId + " was not found in the feature table"); } else { LOG.warn("further feature_relationship warnings ignored"); } featureWarnings++; } } count++; lastSubjectId = subjectId; } if (lastSubjectId != null) { processCollectionData(lastSubjectId, relTypeMap); // Stores stuff collectionTotal += relTypeMap.size(); } LOG.info("processed " + count + " relations"); LOG.info("total collection elements created: " + collectionTotal); res.close(); } /** * Create collections and references for the Item given by chadoSubjectId. */ private void processCollectionData(Integer chadoSubjectId, Map<String, Map<String, List<FeatureData>>> relTypeMap) throws ObjectStoreException { FeatureData subjectData = features.get(chadoSubjectId); if (subjectData == null) { LOG.warn("unknown feature " + chadoSubjectId + " passed to processCollectionData - " + "ignoring"); return; } // map from collection name to list of item ids Map<String, List<String>> collectionsToStore = new HashMap<String, List<String>>(); String subjectInterMineType = subjectData.interMineType; Integer intermineItemId = subjectData.intermineObjectId; for (Map.Entry<String, Map<String, List<FeatureData>>> entry: relTypeMap.entrySet()) { String relationType = entry.getKey(); Map<String, List<FeatureData>> objectClassFeatureDataMap = entry.getValue(); Set<Entry<String, List<FeatureData>>> mapEntries = objectClassFeatureDataMap.entrySet(); for (Map.Entry<String, List<FeatureData>> featureDataMap: mapEntries) { String objectClass = featureDataMap.getKey(); List<FeatureData> featureDataCollection = featureDataMap.getValue(); ClassDescriptor cd = model.getClassDescriptorByName(subjectInterMineType); List<FieldDescriptor> fds = null; FeatureData subjectFeatureData = features.get(chadoSubjectId); // key example: ("relationship", "Translation", "producedby", "MRNA") MultiKey key = new MultiKey("relationship", subjectFeatureData.interMineType, relationType, objectClass); List<ConfigAction> actionList = getConfig().get(key); if (actionList != null) { if (actionList.size() == 0 || actionList.size() == 1 && actionList.get(0) instanceof DoNothingAction) { // do nothing continue; } fds = new ArrayList<FieldDescriptor>(); for (ConfigAction action: actionList) { if (action instanceof SetFieldConfigAction) { SetFieldConfigAction setAction = (SetFieldConfigAction) action; String fieldName = setAction.fieldName; FieldDescriptor fd = cd.getFieldDescriptorByName(fieldName); if (fd == null) { throw new RuntimeException("can't find field " + fieldName + " in class " + cd + " configured for " + key); } else { fds.add(fd); } } } if (fds.size() == 0) { throw new RuntimeException("no actions found for " + key); } } else { if (PARTOF_RELATIONS.contains(relationType)) { // special case for part_of relations - try to find a reference or // collection that has a name that looks right for these objects (of class // objectClass). eg. If the subject is a Transcript and the objectClass // is Exon then find collections called "exons", "geneParts" (GenePart is // a superclass of Exon) fds = getReferenceForRelationship(objectClass, cd); } else { continue; } } if (fds.size() == 0) { LOG.error("can't find collection for type " + relationType + " in " + subjectInterMineType + " while processing feature " + chadoSubjectId); continue; } for (FieldDescriptor fd: fds) { if (fd.isReference()) { if (objectClassFeatureDataMap.size() > 1) { throw new RuntimeException("found more than one object for reference " + fd + " in class " + subjectInterMineType + " current subject identifier: " + subjectData.uniqueName); } else { if (objectClassFeatureDataMap.size() == 1) { Reference reference = new Reference(); reference.setName(fd.getName()); FeatureData referencedFeatureData = featureDataCollection.get(0); reference.setRefId(referencedFeatureData.itemIdentifier); store(reference, intermineItemId); // Stores Reference for Feature // special case for 1-1 relations - we need to set the reverse // reference ReferenceDescriptor rd = (ReferenceDescriptor) fd; ReferenceDescriptor reverseRD = rd.getReverseReferenceDescriptor(); if (reverseRD != null && !reverseRD.isCollection()) { Reference revReference = new Reference(); revReference.setName(reverseRD.getName()); revReference.setRefId(subjectData.itemIdentifier); store(revReference, referencedFeatureData.intermineObjectId); } } } } else { List<String> itemIds; if (collectionsToStore.containsKey(fd.getName())) { itemIds = collectionsToStore.get(fd.getName()); } else { itemIds = new ArrayList<String>(); collectionsToStore.put(fd.getName(), itemIds); } for (FeatureData featureData: featureDataCollection) { itemIds.add(featureData.itemIdentifier); } } } } } for (Map.Entry<String, List<String>> entry: collectionsToStore.entrySet()) { ReferenceList referenceList = new ReferenceList(); referenceList.setName(entry.getKey()); referenceList.setRefIds(entry.getValue()); store(referenceList, intermineItemId); // Stores ReferenceList for Feature } } /** * Search ClassDescriptor cd class for refs/collections with the right name for the objectType * eg. find CDSs collection for objectType = CDS and find gene reference for objectType = Gene. */ private List<FieldDescriptor> getReferenceForRelationship(String objectType, ClassDescriptor cd) { List<FieldDescriptor> fds = new ArrayList<FieldDescriptor>(); LinkedHashSet<String> allClasses = new LinkedHashSet<String>(); allClasses.add(objectType); try { Set<String> parentClasses = ClassDescriptor.findSuperClassNames(model, objectType); allClasses.addAll(parentClasses); } catch (MetaDataException e) { throw new RuntimeException("class not found in the model", e); } for (String clsName: allClasses) { List<String> possibleRefNames = new ArrayList<String>(); String unqualifiedClsName = TypeUtil.unqualifiedName(clsName); possibleRefNames.add(unqualifiedClsName); possibleRefNames.add(unqualifiedClsName + 's'); possibleRefNames.add(StringUtil.decapitalise(unqualifiedClsName)); possibleRefNames.add(StringUtil.decapitalise(unqualifiedClsName) + 's'); for (String possibleRefName: possibleRefNames) { FieldDescriptor fd = cd.getFieldDescriptorByName(possibleRefName); if (fd != null) { fds.add(fd); } } } return fds; } private void processDbxrefTable(Connection connection) throws SQLException, ObjectStoreException { Item dataSource = getDataSourceItem(dataSourceName); Item dataSet = getDataSetItem(dataSetTitle); ResultSet res = getDbxrefResultSet(connection); Set<String> existingAttributes = new HashSet<String>(); Integer currentFeatureId = null; int count = 0; while (res.next()) { Integer featureId = new Integer(res.getInt("feature_id")); String accession = res.getString("accession"); String dbName = res.getString("db_name"); Boolean isCurrent = res.getBoolean("is_current"); if (currentFeatureId != null && currentFeatureId != featureId) { existingAttributes = new HashSet<String>(); } if (features.containsKey(featureId)) { FeatureData fdat = features.get(featureId); accession = fixIdentifier(fdat.interMineType, accession); MultiKey key = new MultiKey("dbxref", fdat.interMineType, dbName, isCurrent); List<ConfigAction> actionList = getConfig().get(key); if (actionList == null) { // try ignoring isCurrent MultiKey key2 = new MultiKey("dbxref", fdat.interMineType, dbName, null); actionList = getConfig().get(key2); } if (actionList == null) { // no actions configured for this synonym continue; } for (ConfigAction action: actionList) { if (action instanceof SetFieldConfigAction) { SetFieldConfigAction setAction = (SetFieldConfigAction) action; if (!existingAttributes.contains(setAction.fieldName)) { setAttribute(fdat, setAction.fieldName, accession); // Stores // Attribute for Feature existingAttributes.add(setAction.fieldName); } } else { if (action instanceof CreateSynonymAction) { if (fdat.existingSynonyms.contains(accession)) { continue; } else { createSynonym(fdat, "identifier", accession, false, dataSet, EMPTY_ITEM_LIST, dataSource); // Stores Synonym count++; } } } } } currentFeatureId = featureId; } LOG.info("created " + count + " synonyms from the dbxref table"); res.close(); } private void processFeaturePropTable(Connection connection) throws SQLException, ObjectStoreException { Item dataSource = getDataSourceItem(dataSourceName); Item dataSet = getDataSetItem(dataSetTitle); ResultSet res = getFeaturePropResultSet(connection); int count = 0; while (res.next()) { Integer featureId = new Integer(res.getInt("feature_id")); String identifier = res.getString("value"); String propTypeName = res.getString("type_name"); if (features.containsKey(featureId)) { FeatureData fdat = features.get(featureId); MultiKey key = new MultiKey("prop", fdat.interMineType, propTypeName); List<ConfigAction> actionList = getConfig().get(key); if (actionList == null) { // no actions configured for this prop continue; } for (ConfigAction action: actionList) { if (action instanceof SetFieldConfigAction) { SetFieldConfigAction setAction = (SetFieldConfigAction) action; setAttribute(fdat, setAction.fieldName, identifier); // Stores // Attribute for Feature } else { if (action instanceof CreateSynonymAction) { CreateSynonymAction synonymAction = (CreateSynonymAction) action; Set<String> existingSynonyms = fdat.existingSynonyms; if (existingSynonyms.contains(identifier)) { continue; } else { String synonymType = synonymAction.synonymType; if (synonymType == null) { synonymType = propTypeName; } createSynonym(fdat, synonymType, identifier, false, dataSet, EMPTY_ITEM_LIST, dataSource); // Stores Synonym count++; } } } } } } LOG.info("created " + count + " synonyms from the featureprop table"); res.close(); } private void processSynonymTable(Connection connection) throws SQLException, ObjectStoreException { Item dataSource = getDataSourceItem(dataSourceName); Item dataSet = getDataSetItem(dataSetTitle); ResultSet res = getSynonymResultSet(connection); Set<String> existingAttributes = new HashSet<String>(); Integer currentFeatureId = null; int count = 0; while (res.next()) { Integer featureId = new Integer(res.getInt("feature_id")); String identifier = res.getString("synonym_name"); String synonymTypeName = res.getString("type_name"); Boolean isCurrent = res.getBoolean("is_current"); identifier = fixIdentifier(synonymTypeName, identifier); if (currentFeatureId != null && currentFeatureId != featureId) { existingAttributes = new HashSet<String>(); } if (features.containsKey(featureId)) { FeatureData fdat = features.get(featureId); MultiKey key = new MultiKey("synonym", fdat.interMineType, synonymTypeName, isCurrent); List<ConfigAction> actionList = getConfig().get(key); if (actionList == null) { // try ignoring isCurrent MultiKey key2 = new MultiKey("synonym", fdat.interMineType, synonymTypeName, null); actionList = getConfig().get(key2); } if (actionList == null) { // no actions configured for this synonym continue; } for (ConfigAction action: actionList) { if (action instanceof SetFieldConfigAction) { SetFieldConfigAction setAction = (SetFieldConfigAction) action; if (!existingAttributes.contains(setAction.fieldName)) { setAttribute(fdat, setAction.fieldName, identifier); // Stores // Attribute for Feature existingAttributes.add(setAction.fieldName); } } else { if (action instanceof CreateSynonymAction) { if (fdat.existingSynonyms.contains(identifier)) { continue; } else { createSynonym(fdat, synonymTypeName, identifier, false, dataSet, EMPTY_ITEM_LIST, dataSource); // Stores Synonym count++; } } } } } currentFeatureId = featureId; } LOG.info("created " + count + " synonyms from the synonym table"); res.close(); } /** * Process the identifier and return a "cleaned" version. Implement in sub-classes to fix * data problem. * @param the (SO) type of the feature that this identifier came from * @param identifier the identifier * @return a cleaned identifier */ protected String fixIdentifier(String type, String identifier) { /* * default implementation should be: return identifier */ // XXX FIXME TODO - for wormbase - move to WormBaseDBConverter if (identifier.startsWith(type + ":")) { return identifier.substring(type.length() + 1); } else { return identifier; } } /** * Set an attribute in an Item by creating an Attribute object and storing it. * @param fdat the data about the feature * @param attributeName the attribute name * @param value the value to set */ private void setAttribute(FeatureData fdat, String attributeName, String value) throws ObjectStoreException { Attribute att = new Attribute(); att.setName(attributeName); att.setValue(value); store(att, fdat.intermineObjectId); } private void processPubTable(Connection connection) throws SQLException, ObjectStoreException { ResultSet res = getPubResultSet(connection); List<String> currentEvidenceIds = new ArrayList<String>(); Integer lastPubFeatureId = null; int featureWarnings = 0; int count = 0; Map<String, String> pubs = new HashMap<String, String>(); while (res.next()) { Integer featureId = new Integer(res.getInt("feature_id")); if (!features.containsKey(featureId)) { if (featureWarnings <= 20) { if (featureWarnings < 20) { LOG.warn("feature " + featureId + " not found in features Map while " + "processing publications"); } else { LOG.warn("further feature id warnings ignored in processPubTable()"); } featureWarnings++; } continue; } String pubMedId = res.getString("pub_db_identifier"); if (lastPubFeatureId != null && !featureId.equals(lastPubFeatureId)) { makeFeaturePublications(lastPubFeatureId, currentEvidenceIds); makeFeatureEvidence(lastPubFeatureId, currentEvidenceIds); // Stores ReferenceList currentEvidenceIds = new ArrayList<String>(); } String publicationId; if (pubs.containsKey(pubMedId)) { publicationId = pubs.get(pubMedId); } else { Item publication = createItem("Publication"); publication.setAttribute("pubMedId", pubMedId); store(publication); // Stores Publication publicationId = publication.getIdentifier(); pubs.put(pubMedId, publicationId); } currentEvidenceIds.add(publicationId); lastPubFeatureId = featureId; count++; } if (lastPubFeatureId != null) { makeFeaturePublications(lastPubFeatureId, currentEvidenceIds); makeFeatureEvidence(lastPubFeatureId, currentEvidenceIds); } LOG.info("Created " + count + " publications"); res.close(); } /** * Set the publications collection of the feature with the given (chado) feature id. */ private void makeFeaturePublications(Integer featureId, List<String> argPublicationIds) throws ObjectStoreException { FeatureData fdat = features.get(featureId); if (fdat == null) { throw new RuntimeException("feature " + featureId + " not found in features Map"); } if (!fdat.interMineType.equals("Gene")) { // only Gene has a publications collection return; } List<String> publicationIds = new ArrayList<String>(argPublicationIds); ReferenceList referenceList = new ReferenceList(); referenceList.setName("publications"); referenceList.setRefIds(publicationIds); store(referenceList, fdat.intermineObjectId); } /** * Set the evidence collection of the feature with the given (chado) feature id. */ private void makeFeatureEvidence(Integer featureId, List<String> argEvidenceIds) throws ObjectStoreException { FeatureData fdat = features.get(featureId); if (fdat == null) { throw new RuntimeException("feature " + featureId + " not found in features Map"); } List<String> evidenceIds = new ArrayList<String>(argEvidenceIds); Item dataSet = getDataSetItem(dataSetTitle); evidenceIds.add(0, dataSet.getIdentifier()); ReferenceList referenceList = new ReferenceList(); referenceList.setName("evidence"); referenceList.setRefIds(evidenceIds); store(referenceList, fdat.intermineObjectId); fdat.flags |= FeatureData.EVIDENCE_CREATED; } /** * For those features in the features Map that don't yet have a evidence collection, create one * containing the DataSet. We know if a feature doesn't have an evidence collection if it * doesn't have it's EVIDENCE_CREATED flag set. */ private void addMissingDataEvidence() throws ObjectStoreException { List<String> emptyList = Collections.emptyList(); for (Map.Entry<Integer, FeatureData> entry: features.entrySet()) { Integer featureId = entry.getKey(); FeatureData featureData = entry.getValue(); if ((featureData.flags & FeatureData.EVIDENCE_CREATED) == 0) { makeFeatureEvidence(featureId, emptyList); } } } /** * Return the interesting rows from the features table. * This is a protected method so that it can be overriden for testing * @param connection the db connection * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getFeatureResultSet(Connection connection) throws SQLException { String query = "SELECT feature_id, feature.name, uniquename, cvterm.name as type, seqlen, is_analysis" + " FROM feature, cvterm" + " WHERE feature.type_id = cvterm.cvterm_id" + " AND cvterm.name IN (" + featureTypesString + ")" + " AND organism_id = " + chadoOrganismId + " AND NOT feature.is_obsolete"; LOG.info("executing: " + query); Statement stmt = connection.createStatement(); ResultSet res = stmt.executeQuery(query); return res; } /** * Return the chado organism id for the given genus/species. This is a protected method so * that it can be overriden for testing * @param connection the db connection * @return the internal id (organism_id from the organism table) * @throws SQLException if the is a database problem */ protected int getChadoOrganismId(Connection connection) throws SQLException { String query = "select organism_id from organism where genus = " + DatabaseUtil.objectToString(genus) + " and species = " + DatabaseUtil.objectToString(species); LOG.info("executing: " + query); Statement stmt = connection.createStatement(); ResultSet res = stmt.executeQuery(query); if (res.next()) { return res.getInt(1); } else { throw new RuntimeException("no rows returned when querying organism table for genus \"" + genus + "\" and species \"" + species + "\""); } } /** * Return a SQL query string the gets all non-obsolete interesting features. */ private String getFeatureIdQuery() { return " SELECT feature_id FROM feature, cvterm" + " WHERE cvterm.name IN (" + featureTypesString + ")" + " AND organism_id = " + chadoOrganismId + " AND NOT feature.is_obsolete" + " AND feature.type_id = cvterm.cvterm_id"; } /** * Return the interesting rows from the feature_relationship table. * This is a protected method so that it can be overriden for testing * @param connection the db connection * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getFeatureRelationshipResultSet(Connection connection) throws SQLException { String query = "SELECT feature_relationship_id, subject_id, object_id, cvterm.name AS type_name" + " FROM feature_relationship, cvterm" + " WHERE cvterm.cvterm_id = type_id" + " AND subject_id IN (" + getFeatureIdQuery() + ")" + " AND object_id IN (" + getFeatureIdQuery() + ")" + " ORDER BY subject_id"; LOG.info("executing: " + query); Statement stmt = connection.createStatement(); ResultSet res = stmt.executeQuery(query); return res; } /** * Return the interesting rows from the featureloc table. * This is a protected method so that it can be overriden for testing * @param connection the db connection * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getFeatureLocResultSet(Connection connection) throws SQLException { String query = "SELECT featureloc_id, feature_id, srcfeature_id, fmin, is_fmin_partial," + " fmax, is_fmax_partial, strand" + " FROM featureloc" + " WHERE feature_id IN" + " (" + getFeatureIdQuery() + ")" + " AND srcfeature_id IN" + " (" + getFeatureIdQuery() + ")" + " AND locgroup = 0"; LOG.info("executing: " + query); Statement stmt = connection.createStatement(); ResultSet res = stmt.executeQuery(query); return res; } /** * Return the interesting rows from the dbxref table. * This is a protected method so that it can be overriden for testing * @param connection the db connection * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getDbxrefResultSet(Connection connection) throws SQLException { String query = "SELECT feature.feature_id, accession, db.name AS db_name, is_current" + " FROM dbxref, feature_dbxref, feature, db" + " WHERE feature_dbxref.dbxref_id = dbxref.dbxref_id " + " AND feature_dbxref.feature_id = feature.feature_id " + " AND feature.feature_id IN" + " (" + getFeatureIdQuery() + ")" + " AND dbxref.db_id = db.db_id"; LOG.info("executing: " + query); Statement stmt = connection.createStatement(); ResultSet res = stmt.executeQuery(query); return res; } /** * Return the interesting rows from the featureprop table. * This is a protected method so that it can be overriden for testing * @param connection the db connection * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getFeaturePropResultSet(Connection connection) throws SQLException { String query = "select feature_id, value, cvterm.name AS type_name FROM featureprop, cvterm" + " WHERE featureprop.type_id = cvterm.cvterm_id" + " AND feature_id IN (" + getFeatureIdQuery() + ")"; LOG.info("executing: " + query); Statement stmt = connection.createStatement(); ResultSet res = stmt.executeQuery(query); return res; } /** * Return the interesting rows from the synonym table. * This is a protected method so that it can be overriden for testing * @param connection the db connection * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getSynonymResultSet(Connection connection) throws SQLException { String query = "SELECT DISTINCT feature_id, synonym.name AS synonym_name," + " cvterm.name AS type_name, is_current" + " FROM feature_synonym, synonym, cvterm" + " WHERE feature_synonym.synonym_id = synonym.synonym_id" + " AND synonym.type_id = cvterm.cvterm_id" + " AND feature_id IN (" + getFeatureIdQuery() + ")"; LOG.info("executing: " + query); Statement stmt = connection.createStatement(); ResultSet res = stmt.executeQuery(query); return res; } /** * Return the interesting rows from the pub table. * This is a protected method so that it can be overriden for testing * @param connection the db connection * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getPubResultSet(Connection connection) throws SQLException { String query = "SELECT DISTINCT feature_pub.feature_id, dbxref.accession as pub_db_identifier" + " FROM feature_pub, dbxref, db, pub, pub_dbxref" + " WHERE feature_pub.pub_id = pub.pub_id" + " AND pub_dbxref.dbxref_id = dbxref.dbxref_id" + " AND dbxref.db_id = db.db_id" + " AND pub.pub_id = pub_dbxref.pub_id" + " AND db.name = 'pubmed'" + " AND feature_id IN (" + getFeatureIdQuery() + ")" + " ORDER BY feature_pub.feature_id"; LOG.info("executing: " + query); Statement stmt = connection.createStatement(); ResultSet res = stmt.executeQuery(query); return res; } /** * Call super.createSynonym(), store the Item then record in fdat that we've created it. */ private Item createSynonym(FeatureData fdat, String type, String identifier, boolean isPrimary, Item dataSet, List<Item> otherEvidence, Item dataSource) throws ObjectStoreException { if (fdat.existingSynonyms.contains(identifier)) { throw new IllegalArgumentException("feature identifier " + identifier + " is already a synonym for: " + fdat.existingSynonyms); } List<Item> allEvidence = new ArrayList<Item>(); allEvidence.add(dataSet); allEvidence.addAll(otherEvidence); Item returnItem = createSynonym(fdat.itemIdentifier, type, identifier, isPrimary, allEvidence, dataSource); fdat.existingSynonyms.add(identifier); return returnItem; } }
package org.intermine.bio.dataconversion; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.collections.keyvalue.MultiKey; import org.apache.commons.collections.map.MultiKeyMap; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.intermine.bio.chado.ChadoCV; import org.intermine.bio.chado.ChadoCVFactory; import org.intermine.bio.chado.ChadoCVTerm; import org.intermine.bio.chado.config.ConfigAction; import org.intermine.bio.chado.config.CreateSynonymAction; import org.intermine.bio.chado.config.SetFieldConfigAction; import org.intermine.bio.util.OrganismData; import org.intermine.objectstore.ObjectStoreException; import org.intermine.util.IntPresentSet; import org.intermine.util.XmlUtil; import org.intermine.xml.full.Item; import org.intermine.xml.full.Reference; import org.intermine.xml.full.ReferenceList; /** * A converter for chado that handles FlyBase specific configuration. * @author Kim Rutherford */ public class FlyBaseProcessor extends SequenceProcessor { /** * The cv.name for the wild type class term. For chromosome_structure_variations, used to * identify the "Feature type" from the "Class of aberration" section of a FlyBase aberation * page. */ private static final String WT_CLASS_CVTERM = "wt_class"; private static final String FLYBASE_DB_NAME = "FlyBase"; /** * The cv.name for the FlyBase miscellaneous CV. */ protected static final String FLYBASE_MISCELLANEOUS_CV = FLYBASE_DB_NAME + " miscellaneous CV"; /** * The cv.name for the FlyBase miscellaneous CV. */ protected static final String FLYBASE_SO_CV_NAME = "SO"; private static final String FLYBASE_ANATOMY_TERM_PREFIX = "FBbt"; // a pattern the matches attribute stored in FlyBase properties, eg. "@FBcv0000289:hypomorph@" private static final String FLYBASE_PROP_ATTRIBUTE_PATTERN = "@([^@]+)@"; // interactions use this - UKNOWN private static final String RELATIONSHIP_TYPE = "MI:0499"; private static final String DEFAULT_ROLE = "unspecified"; /** * A ConfigAction that overrides processValue() to change FlyBase attribute tags * (like "@FBcv0000289:hypomorph@") to text like: "hypomorph" * @author Kim Rutherford */ private class AlleleClassSetFieldAction extends SetFieldConfigAction { /** * Create a new AlleleClassSetFieldAction * @param fieldName the fieldName to process with this object. */ AlleleClassSetFieldAction(String fieldName) { super(fieldName); } /** * {@inheritDoc} */ @Override public String processValue(String value) { Pattern p = Pattern.compile(FLYBASE_PROP_ATTRIBUTE_PATTERN); Matcher m = p.matcher(value); StringBuffer sb = new StringBuffer(); while (m.find()) { String field = m.group(1); int colonPos = field.indexOf(':'); if (colonPos == -1) { m.appendReplacement(sb, field); } else { String text = field.substring(colonPos + 1); m.appendReplacement(sb, text); } } m.appendTail(sb); return sb.toString(); } } private static final Logger LOG = Logger.getLogger(FlyBaseProcessor.class); // the configuration for this processor, set when getConfig() is called the first time private final Map<Integer, MultiKeyMap> config = new HashMap<Integer, MultiKeyMap>(); // a set of feature_ids for those genes that have a location in the featureloc table, set by // the constructor private final IntPresentSet locatedGeneIds; // a map from the uniquename of each allele to its item identifier private Map<String, String> alleleIdMap = new HashMap<String, String>(); // a map from the uniquename of each cdna clone to its item identifier private Map<String, FeatureData> cdnaCloneMap = new HashMap<String, FeatureData>(); // an object representing the FlyBase miscellaneous CV private ChadoCV flyBaseMiscCv = null; // an object representing the sequence ontology, as stored in the FlyBase chado database private ChadoCV sequenceOntologyCV = null; // a map from mutagen description to Mutagen Item identifier private Map<String, String> mutagensMap = new HashMap<String, String>(); // a map from featureId to seqlen // private Map<Integer, Integer> cdnaLengths = null; private final Map<Integer, Integer> chromosomeStructureVariationTypes; private Map<String, String> interactionExperiments = new HashMap<String, String>(); private static final String LOCATED_GENES_TEMP_TABLE_NAME = "intermine_located_genes_temp"; private static final String ALLELE_TEMP_TABLE_NAME = "intermine_flybase_allele_temp"; private static final String INSERTION_TEMP_TABLE_NAME = "intermine_flybase_insertion_temp"; // pattern to match the names of Exelixis insertions // - matches "f07705" in "PBac{WH}f07705" // - matches "f07705" in "PBac{WH}tam[f07705]" private static final Pattern PB_INSERTION_PATTERN = Pattern.compile(".*\\{.*\\}(?:.*\\[)?([def]\\d+)(?:\\])?"); private static final Map<String, String> CHROMOSOME_STRUCTURE_VARIATION_SO_MAP = new HashMap<String, String>(); private final Map<String, FeatureData> proteinFeatureDataMap = new HashMap<String, FeatureData>(); static { CHROMOSOME_STRUCTURE_VARIATION_SO_MAP.put("chromosomal_deletion", "ChromosomalDeletion"); CHROMOSOME_STRUCTURE_VARIATION_SO_MAP.put("chromosomal_duplication", "ChromosomalDuplication"); CHROMOSOME_STRUCTURE_VARIATION_SO_MAP.put("chromosomal_inversion", "ChromosomalInversion"); CHROMOSOME_STRUCTURE_VARIATION_SO_MAP.put("chromosomal_translocation", "ChromosomalTranslocation"); CHROMOSOME_STRUCTURE_VARIATION_SO_MAP.put("transposition", "ChromosomalTransposition"); } private static final String CHROMOSOME_STRUCTURE_VARIATION_SO_NAME = "chromosome_structure_variation"; /** * Create a new FlyBaseChadoDBConverter. * @param chadoDBConverter the converter that created this object */ public FlyBaseProcessor(ChadoDBConverter chadoDBConverter) { super(chadoDBConverter); Connection connection = getChadoDBConverter().getConnection(); try { flyBaseMiscCv = getFlyBaseMiscCV(connection); } catch (SQLException e) { throw new RuntimeException("can't execute query for flybase cv terms", e); } try { sequenceOntologyCV = getFlyBaseSequenceOntologyCV(connection); } catch (SQLException e) { throw new RuntimeException("can't execute query for so cv terms", e); } try { createLocatedGenesTempTable(connection); } catch (SQLException e) { throw new RuntimeException("can't execute query for located genes", e); } locatedGeneIds = getLocatedGeneIds(connection); chromosomeStructureVariationTypes = getChromosomeStructureVariationTypes(connection); // try { // cdnaLengths = makeCDNALengthMap(connection); // } catch (SQLException e) { // e.printStackTrace(); } /** * @param connection database connection * @return map of feature_id to seqlen */ // protected Map<Integer, Integer> getLengths(Connection connection) { // if (cdnaLengths == null) { // try { // cdnaLengths = makeCDNALengthMap(connection); // } catch (SQLException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // return cdnaLengths; /** * Return a map from chromosome_structure_variation feature_ids to the cvterm_id of the * associated cvtermprop. This is needed because the exact type of the * chromosome_structure_variation objects is not used as the type_id of the feature, instead * it's stored in the cvtermprop table. */ private Map<Integer, Integer> getChromosomeStructureVariationTypes(Connection connection) { Map<Integer, Integer> retVal = new HashMap<Integer, Integer>(); ResultSet res; try { res = getChromosomeStructureVariationResultSet(connection); } catch (SQLException e) { throw new RuntimeException("can't execute query for chromosome_structure_variation " + "types", e); } try { while (res.next()) { int featureId = res.getInt("feature_id"); int cvtermId = res.getInt("cvterm_id"); retVal.put(new Integer(featureId), new Integer(cvtermId)); } } catch (SQLException e) { throw new RuntimeException("problem while reading chromosome_structure_variation " + "types", e); } return retVal; } /** * Return the results of running a query for the chromosome_structure_variation feature types. * @param connection the connection * @return the results * @throws SQLException if there is a database problem */ protected ResultSet getChromosomeStructureVariationResultSet(Connection connection) throws SQLException { String query = " SELECT feature.feature_id, cvterm.cvterm_id" + " FROM feature, feature_cvterm, cvterm feature_type, cvterm, cv," + " feature_cvtermprop, cvterm prop_term" + " WHERE feature.type_id = feature_type.cvterm_id" + " AND feature_type.name = '" + CHROMOSOME_STRUCTURE_VARIATION_SO_NAME + "' " + " AND feature_cvterm.feature_id = feature.feature_id" + " AND feature_cvterm.cvterm_id = cvterm.cvterm_id AND cvterm.cv_id = cv.cv_id" + " AND cv.name = 'SO' " + " AND feature_cvtermprop.feature_cvterm_id = feature_cvterm.feature_cvterm_id" + " AND feature_cvtermprop.type_id = prop_term.cvterm_id AND prop_term.name = '" + WT_CLASS_CVTERM + "'"; LOG.info("executing getChromosomeStructureVariationResultSet(): " + query); Statement stmt = connection.createStatement(); ResultSet res = stmt.executeQuery(query); return res; } /** * Return a set of ids of those genes that have a location in the featureloc table. */ private IntPresentSet getLocatedGeneIds(Connection connection) { IntPresentSet retVal = new IntPresentSet(); ResultSet res; try { res = getLocatedGenesResultSet(connection); } catch (SQLException e) { throw new RuntimeException("can't execute query for located genes", e); } try { while (res.next()) { int featureId = res.getInt("feature_id"); retVal.set(featureId, true); } } catch (SQLException e) { throw new RuntimeException("problem while reading located genes", e); } return retVal; } /** * Create a temporary table containing the ids of the located genes. This is a protected * method so that it can be overridden for testing * @param connection the Connection * @throws SQLException if there is a database problem */ protected void createLocatedGenesTempTable(Connection connection) throws SQLException { String organismConstraint = getOrganismConstraint(); String orgConstraintForQuery = ""; if (!StringUtils.isEmpty(organismConstraint)) { orgConstraintForQuery = " AND " + organismConstraint; } String query = "CREATE TEMPORARY TABLE " + LOCATED_GENES_TEMP_TABLE_NAME + " AS SELECT feature.feature_id FROM feature, cvterm" + " WHERE feature.type_id = cvterm.cvterm_id" + " AND cvterm.name = 'gene' " + " AND NOT feature.is_obsolete " + " AND feature.feature_id IN " + " (SELECT l.feature_id " + " FROM featureloc l, feature c " + " WHERE l.srcfeature_id = c.feature_id and NOT c.is_obsolete)" + orgConstraintForQuery; Statement stmt = connection.createStatement(); LOG.info("executing createLocatedGenesTempTable(): " + query); stmt.execute(query); String idIndexQuery = "CREATE INDEX " + LOCATED_GENES_TEMP_TABLE_NAME + "_feature_index ON " + LOCATED_GENES_TEMP_TABLE_NAME + "(feature_id)"; LOG.info("executing: " + idIndexQuery); stmt.execute(idIndexQuery); String analyze = "ANALYZE " + LOCATED_GENES_TEMP_TABLE_NAME; LOG.info("executing: " + analyze); stmt.execute(analyze); } /** * Create a temporary table of allele feature_ids. The table will only have allele of genes * with locations. * @param connection the connection * @throws SQLException if there is a database problem */ protected void createAllelesTempTable(Connection connection) throws SQLException { String organismConstraint = getOrganismConstraint(); String orgConstraintForQuery = ""; if (!StringUtils.isEmpty(organismConstraint)) { orgConstraintForQuery = " AND " + organismConstraint; } String query = " CREATE TEMPORARY TABLE " + ALLELE_TEMP_TABLE_NAME + " AS SELECT feature_id" + " FROM feature, cvterm feature_type " + " WHERE feature_type.name = 'gene'" + " AND type_id = feature_type.cvterm_id" + " AND uniquename LIKE 'FBal%'" + " AND NOT feature.is_obsolete" + " AND feature_id IN (SELECT feature_id FROM feature WHERE " + getLocatedGeneAllesSql() + ")" + orgConstraintForQuery; Statement stmt = connection.createStatement(); LOG.info("executing createAllelesTempTable(): " + query); stmt.execute(query); String idIndexQuery = "CREATE INDEX " + ALLELE_TEMP_TABLE_NAME + "_feature_index ON " + ALLELE_TEMP_TABLE_NAME + "(feature_id)"; LOG.info("executing: " + idIndexQuery); stmt.execute(idIndexQuery); String analyze = "ANALYZE " + ALLELE_TEMP_TABLE_NAME; LOG.info("executing: " + analyze); stmt.execute(analyze); } /** * Create a temporary table from pairs of insertions (eg. "FBti0027974" => "FBti0023081") * containing the feature_ids of the pair (the object_id, subject_id in the relation table) * and the fmin and fmax of the first insertion in the pair (ie. the progenitor / object from * the feature_relationship table). * The second in the pair is the "Modified descendant of" the first. The pairs are found using * the 'modified_descendant_of' relation type. All insertions are from DrosDel. * @param connection the connection * @throws SQLException if there is a database problem */ protected void createInsertionTempTable(Connection connection) throws SQLException { String query = " CREATE TEMPORARY TABLE " + INSERTION_TEMP_TABLE_NAME + " AS SELECT obj.feature_id AS obj_id, sub.feature_id AS sub_id," + " obj_loc.fmin, obj_loc.fmax," + " obj_loc.srcfeature_id as chr_feature_id" + " FROM feature sub, cvterm sub_type, feature_relationship rel, cvterm rel_type, " + " feature obj, cvterm obj_type, featureloc obj_loc" + " WHERE sub.feature_id = rel.subject_id AND rel.object_id = obj.feature_id" + " AND sub_type.cvterm_id = sub.type_id AND obj_type.cvterm_id = obj.type_id" + " AND sub_type.name = 'transposable_element_insertion_site' " + " AND obj_type.name = 'transposable_element_insertion_site' " + " AND rel.type_id = rel_type.cvterm_id" + " AND rel_type.name = 'modified_descendant_of'" + " AND sub.feature_id in (select feature_id from feature_pub where pub_id =" + " (SELECT pub_id FROM pub" + " WHERE title = " + "'The DrosDel collection: a set of P-element insertions for " + "generating custom chromosomal aberrations in Drosophila melanogaster.')) " + " AND obj.feature_id = obj_loc.feature_id"; Statement stmt = connection.createStatement(); LOG.info("executing createInsertionTempTable(): " + query); stmt.execute(query); String idIndexQuery = "CREATE INDEX " + INSERTION_TEMP_TABLE_NAME + "index ON " + INSERTION_TEMP_TABLE_NAME + "(sub_id)"; LOG.info("executing: " + idIndexQuery); stmt.execute(idIndexQuery); String analyze = "ANALYZE " + INSERTION_TEMP_TABLE_NAME; LOG.info("executing: " + analyze); stmt.execute(analyze); } /** * Get ChadoCV object representing the FlyBase misc cv. * This is a protected method so that it can be overriden for testing * @param connection the database Connection * @return the cv * @throws SQLException if there is a database problem */ protected ChadoCV getFlyBaseMiscCV(Connection connection) throws SQLException { ChadoCVFactory cvFactory = new ChadoCVFactory(connection); return cvFactory.getChadoCV(FLYBASE_MISCELLANEOUS_CV); } /** * Get ChadoCV object representing SO from FlyBase. * This is a protected method so that it can be overriden for testing * @param connection the database Connection * @return the cv * @throws SQLException if there is a database problem */ protected ChadoCV getFlyBaseSequenceOntologyCV(Connection connection) throws SQLException { ChadoCVFactory cvFactory = new ChadoCVFactory(connection); return cvFactory.getChadoCV(FLYBASE_SO_CV_NAME); } /** * {@inheritDoc} */ @Override protected Integer store(Item feature, int taxonId) throws ObjectStoreException { processItem(feature, new Integer(taxonId)); Integer itemId = super.store(feature, taxonId); return itemId; } /** * note: featureId is needed only by modMine * {@inheritDoc} */ @Override protected Item makeLocation(int start, int end, int strand, FeatureData srcFeatureData, FeatureData featureData, int taxonId, int featureId) throws ObjectStoreException { Item location = super.makeLocation(start, end, strand, srcFeatureData, featureData, taxonId, 0); processItem(location, new Integer(taxonId)); return location; } /** * {@inheritDoc} */ @Override protected Item createSynonym(FeatureData fdat, String identifier) throws ObjectStoreException { Item synonym = super.createSynonym(fdat, identifier); /* synonym can be null if it's been created earlier. this would happen only if * the synonym was created when another protein was created in favour of this one. */ if (synonym != null) { OrganismData od = fdat.getOrganismData(); processItem(synonym, new Integer(od.getTaxonId())); } return synonym; } /** * Return from chado the feature_ids of the genes with entries in the featureloc table. * @param connection the db connection * @return the SQL result set * @throws SQLException if a database problem occurs */ protected ResultSet getLocatedGenesResultSet(Connection connection) throws SQLException { String query = getLocatedGenesSql(); LOG.info("executing getLocatedGenesResultSet(): " + query); Statement stmt = connection.createStatement(); ResultSet res = stmt.executeQuery(query); return res; } /** * Return a query that gets the feature_ids of genes that have locations. */ private static String getLocatedGenesSql() { return "SELECT feature_id FROM " + LOCATED_GENES_TEMP_TABLE_NAME; } /** * {@inheritDoc} */ @Override protected Map<MultiKey, List<ConfigAction>> getConfig(int taxonId) { MultiKeyMap map = config.get(new Integer(taxonId)); if (map == null) { map = new MultiKeyMap(); config.put(new Integer(taxonId), map); // synomym configuration example: for features of class "Gene", if the type name of // the synonym is "fullname" and "is_current" is true, set the "name" attribute of // the new Gene to be this synonym and then make a Synonym object map.put(new MultiKey("synonym", "Gene", "fullname", Boolean.TRUE), Arrays.asList(new SetFieldConfigAction("name"))); map.put(new MultiKey("synonym", "Gene", "fullname", Boolean.FALSE), Arrays.asList(CREATE_SYNONYM_ACTION)); map.put(new MultiKey("synonym", "Gene", "symbol", Boolean.TRUE), Arrays.asList(new SetFieldConfigAction("symbol"))); map.put(new MultiKey("synonym", "Gene", "symbol", Boolean.FALSE), Arrays.asList(CREATE_SYNONYM_ACTION)); // dbxref table configuration example: for features of class "Gene", where the // db.name is "FlyBase Annotation IDs" and "is_current" is true, set the // "secondaryIdentifier" attribute of the new Gene to be this dbxref and then make a // Synonym object map.put(new MultiKey("dbxref", "Gene", FLYBASE_DB_NAME + " Annotation IDs", Boolean.TRUE), Arrays.asList(new SetFieldConfigAction("secondaryIdentifier"))); map.put(new MultiKey("dbxref", "Gene", FLYBASE_DB_NAME + " Annotation IDs", Boolean.FALSE), Arrays.asList(CREATE_SYNONYM_ACTION)); // null for the "is_current" means either TRUE or FALSE is OK. map.put(new MultiKey("dbxref", "Gene", FLYBASE_DB_NAME, null), Arrays.asList(CREATE_SYNONYM_ACTION)); map.put(new MultiKey("dbxref", "MRNA", FLYBASE_DB_NAME + " Annotation IDs", Boolean.TRUE), Arrays.asList(new SetFieldConfigAction("secondaryIdentifier"))); map.put(new MultiKey("dbxref", "TransposableElementInsertionSite", "drosdel", null), Arrays.asList(new SetFieldConfigAction("symbol"))); map.put(new MultiKey("synonym", "ChromosomeStructureVariation", "fullname", Boolean.TRUE), Arrays.asList(new SetFieldConfigAction("name"))); map.put(new MultiKey("synonym", "ChromosomalDeletion", "fullname", Boolean.TRUE), Arrays.asList(new SetFieldConfigAction("name"))); map.put(new MultiKey("synonym", "ChromosomalDuplication", "fullname", Boolean.TRUE), Arrays.asList(new SetFieldConfigAction("name"))); map.put(new MultiKey("synonym", "ChromosomalInversion", "fullname", Boolean.TRUE), Arrays.asList(new SetFieldConfigAction("name"))); map.put(new MultiKey("synonym", "ChromosomalTranslocation", "fullname", Boolean.TRUE), Arrays.asList(new SetFieldConfigAction("name"))); map.put(new MultiKey("synonym", "ChromosomalTransposition", "fullname", Boolean.TRUE), Arrays.asList(new SetFieldConfigAction("name"))); map.put(new MultiKey("synonym", "MRNA", "symbol", Boolean.TRUE), Arrays.asList(new SetFieldConfigAction("symbol"))); map.put(new MultiKey("synonym", "MRNA", "symbol", Boolean.FALSE), Arrays.asList(CREATE_SYNONYM_ACTION)); map.put(new MultiKey("dbxref", "MRNA", FLYBASE_DB_NAME + " Annotation IDs", null), Arrays.asList(CREATE_SYNONYM_ACTION)); map.put(new MultiKey("dbxref", "MRNA", FLYBASE_DB_NAME, null), Arrays.asList(CREATE_SYNONYM_ACTION)); // set the Allele.gene when there is an alleleof relationship between Allele and Gene map.put(new MultiKey("relationship", "Allele", "alleleof", "Gene"), Arrays.asList(new SetFieldConfigAction("gene"))); // Set the protein reference in the MRNA - "rev_relationship" means that the // relationship table actually has Protein, producedby, MRNA. We configure like // this so we can set a reference in MRNA rather than protein map.put(new MultiKey("rev_relationship", "MRNA", "producedby", "Protein"), Arrays.asList(new SetFieldConfigAction("protein"))); map.put(new MultiKey("relationship", "CDNAClone", "derived_assoc_cdna_clone", "Gene"), Arrays.asList(new SetFieldConfigAction("gene"))); map.put(new MultiKey("relationship", "Gene", "producedby", "Protein"), Arrays.asList(new SetFieldConfigAction("proteins"))); // featureprop configuration example: for features of class "Gene", if the type name // of the prop is "cyto_range", set the "cytoLocation" attribute of the // new Gene to be this property map.put(new MultiKey("prop", "Gene", "cyto_range"), Arrays.asList(new SetFieldConfigAction("cytoLocation"))); map.put(new MultiKey("prop", "Gene", "symbol"), Arrays.asList(CREATE_SYNONYM_ACTION)); map.put(new MultiKey("prop", "TransposableElementInsertionSite", "curated_cytological_location"), Arrays.asList(new SetFieldConfigAction("cytoLocation"))); ConfigAction alleleClassConfigAction = new AlleleClassSetFieldAction("alleleClass"); map.put(new MultiKey("prop", "Allele", "promoted_allele_class"), Arrays.asList(alleleClassConfigAction)); // library config example: for features of class "CDNAClone", if the type name // of the library is "stage", set the "stage" attribute of the // new CDNAClone to be this property map.put(new MultiKey("library", "CDNAClone", "stage"), Arrays.asList(new SetFieldConfigAction("stage"))); // anatomy term config example: for features of class "CDNAClone" if there is an // anatomy term, set a reference in CDNAClone.tissueSource // See #2173 // map.put(new MultiKey("anatomyterm", "CDNAClone", null), // Arrays.asList(new SetFieldConfigAction("tissueSource"))); // feature_cvterm example for Transposition: we create a featureTerms collection in the // Transposition objects containing SequenceOntologyTerm objects. For the current // feature we create one SequenceOntologyTerm object for each associated "SO" cvterm. // We set the "name" field of the SequenceOntologyTerm to be the name from the cvterm // table. // TODO fixme // List<String> chromosomeStructureVariationClassNames = // Arrays.asList("ChromosomeStructureVariation", "ChromosomalDeletion", // "ChromosomalDuplication", "ChromosomalInversion", // "ChromosomalTranslocation", "ChromosomalTransposition"); // for (String className: chromosomeStructureVariationClassNames) { // map.put(new MultiKey("cvterm", className, "SO"), // Arrays.asList(new CreateCollectionAction("SOTerm", "abberationSOTerms", // "name", true))); // feature configuration example: for features of class "Exon", from "FlyBase", // set the Gene.symbol to be the "name" field from the chado feature map.put(new MultiKey("feature", "Exon", FLYBASE_DB_NAME, "name"), Arrays.asList(new SetFieldConfigAction("symbol"))); map.put(new MultiKey("feature", "Allele", FLYBASE_DB_NAME, "name"), Arrays.asList(new SetFieldConfigAction("symbol"))); // DO_NOTHING_ACTION means skip the name from this feature map.put(new MultiKey("feature", "Chromosome", FLYBASE_DB_NAME, "name"), Arrays.asList(DO_NOTHING_ACTION)); map.put(new MultiKey("feature", "ChromosomeBand", FLYBASE_DB_NAME, "name"), Arrays.asList(DO_NOTHING_ACTION)); map.put(new MultiKey("feature", "TransposableElementInsertionSite", FLYBASE_DB_NAME, "name"), Arrays.asList(new SetFieldConfigAction("symbol", PB_INSERTION_PATTERN), new SetFieldConfigAction("secondaryIdentifier"))); map.put(new MultiKey("feature", "Gene", FLYBASE_DB_NAME, "uniquename"), Arrays.asList(new SetFieldConfigAction("primaryIdentifier"))); map.put(new MultiKey("feature", "Gene", FLYBASE_DB_NAME, "name"), Arrays.asList(DO_NOTHING_ACTION)); map.put(new MultiKey("feature", "ChromosomeStructureVariation", FLYBASE_DB_NAME, "name"), Arrays.asList(new SetFieldConfigAction("secondaryIdentifier"))); // just make a Synonym because the secondaryIdentifier and the symbol are set from the // dbxref and synonym tables map.put(new MultiKey("feature", "MRNA", FLYBASE_DB_NAME, "name"), Arrays.asList(new CreateSynonymAction())); map.put(new MultiKey("feature", "PointMutation", FLYBASE_DB_NAME, "uniquename"), Arrays.asList(new SetFieldConfigAction("name"), new SetFieldConfigAction("primaryIdentifier"))); // name isn't set in flybase: map.put(new MultiKey("feature", "PointMutation", FLYBASE_DB_NAME, "name"), Arrays.asList(DO_NOTHING_ACTION)); map.put(new MultiKey("dbxref", "Protein", FLYBASE_DB_NAME + " Annotation IDs", Boolean.TRUE), Arrays.asList(CREATE_SYNONYM_ACTION)); map.put(new MultiKey("feature", "Protein", FLYBASE_DB_NAME, "name"), Arrays.asList(CREATE_SYNONYM_ACTION)); map.put(new MultiKey("feature", "Protein", FLYBASE_DB_NAME, "uniquename"), Arrays.asList(new SetFieldConfigAction("secondaryIdentifier"))); map.put(new MultiKey("dbxref", "Protein", "GB_protein", Boolean.TRUE), Arrays.asList(new SetFieldConfigAction("genbankIdentifier"), CREATE_SYNONYM_ACTION)); // transposable_element and natural_transposable_element map.put(new MultiKey("feature", "TransposableElement", FLYBASE_DB_NAME, "name"), Arrays.asList(new SetFieldConfigAction("secondaryIdentifier"), new SetFieldConfigAction("symbol"))); map.put(new MultiKey("feature", "NaturalTransposableElement", FLYBASE_DB_NAME, "name"), Arrays.asList(new SetFieldConfigAction("secondaryIdentifier"), new SetFieldConfigAction("symbol"))); map.put(new MultiKey("relationship", "TransposableElement", "producedby", "NaturalTransposableElement"), Arrays.asList(new SetFieldConfigAction("insertedElement"))); map.put(new MultiKey("synonym", "NaturalTransposableElement", "fullname", Boolean.TRUE), Arrays.asList(new SetFieldConfigAction("name"))); } return map; } /** * {@inheritDoc} */ @Override protected String getExtraFeatureConstraint() { return "NOT ((cvterm.name = 'golden_path_region'" + " OR cvterm.name = 'unassigned_supercontig'" + " OR cvterm.name = 'ultra_scaffold')" + " AND (uniquename LIKE 'Unknown_%' OR uniquename LIKE '%_groupMISC'))" + " AND " + getLocatedGeneAllesSql(); } /** * Query that returns only allele of located genes. */ private static String getLocatedGeneAllesSql() { return "(NOT (uniquename LIKE 'FBal%') OR feature_id IN" + " (SELECT subject_id" + " FROM feature_relationship, cvterm" + " WHERE type_id = cvterm.cvterm_id" + " AND cvterm.name = 'alleleof'" + " AND object_id IN (" + getLocatedGenesSql() + ")))"; } /** * {@inheritDoc} */ @Override protected Item makeFeature(Integer featureId, String chadoFeatureType, String interMineType, String name, String uniqueName, int seqlen, int taxonId) { String realInterMineType = interMineType; if ("protein".equals(chadoFeatureType) && !uniqueName.startsWith("FBpp")) { return null; } if ("gene".equals(chadoFeatureType)) { if (uniqueName.startsWith("FBal")) { // fix type of allele "gene" features realInterMineType = "Allele"; } else { if (!locatedGeneIds.contains(featureId.intValue())) { // ignore genes with no location return null; } } } // ignore unknown chromosome from dpse if (uniqueName.startsWith("Unknown_")) { return null; } if (taxonId != 7227 && "chromosome_arm".equals(chadoFeatureType)) { // nothing is located on a chromosome_arm return null; } if ("chromosome".equals(chadoFeatureType) && !"dmel_mitochondrion_genome".equals(uniqueName)) { // ignore Chromosomes from flybase - features are located on ChromosomeArms except // for mitochondrial features return null; } if ("chromosome_arm".equals(chadoFeatureType) || "ultra_scaffold".equals(chadoFeatureType)) { if ("dmel_mitochondrion_genome".equals(uniqueName)) { // ignore - all features are on the Chromosome object with uniqueName // "dmel_mitochondrion_genome" return null; } realInterMineType = "Chromosome"; } if ("golden_path_region".equals(chadoFeatureType)) { realInterMineType = "Chromosome"; } if (chadoFeatureType.equals(CHROMOSOME_STRUCTURE_VARIATION_SO_NAME)) { Integer cvtermId = chromosomeStructureVariationTypes.get(featureId); if (cvtermId != null) { ChadoCVTerm term = sequenceOntologyCV.getByChadoId(cvtermId); for (String soName: CHROMOSOME_STRUCTURE_VARIATION_SO_MAP.keySet()) { if (termOrChildrenNameMatches(term, soName)) { realInterMineType = CHROMOSOME_STRUCTURE_VARIATION_SO_MAP.get(soName); break; } } } } if ("transposable_element_insertion_site".equals(chadoFeatureType) && name == null && !uniqueName.startsWith("FBti")) { // ignore this feature as it doesn't have an FBti identifier and there will be // another feature for the same transposable_element_insertion_site that does have // the FBti identifier return null; } if ("mRNA".equals(chadoFeatureType) && (seqlen == 0 || !uniqueName.startsWith("FBtr"))) { // flybase has > 7000 mRNA features that have no sequence and don't appear in their // webapp so we filter them out. See #1086 return null; } if ("protein".equals(chadoFeatureType) && seqlen == 0) { // flybase has ~ 2100 protein features that don't appear in their webapp so we // filter them out return null; } Item feature = getChadoDBConverter().createItem(realInterMineType); if ("Allele".equals(realInterMineType)) { alleleIdMap.put(uniqueName, feature.getIdentifier()); } return feature; } /** * Return true iff the given term or one of its children is named termName. */ private static boolean termOrChildrenNameMatches(ChadoCVTerm term, String termName) { if (term.getName().equals(termName)) { return true; } Set<ChadoCVTerm> children = term.getAllChildren(); for (ChadoCVTerm childTerm: children) { if (childTerm.getName().equals(termName)) { return true; } } return false; } private static final List<String> FEATURES = Arrays.asList( "gene", "mRNA", "transcript", "protein", "intron", "exon", "regulatory_region", "enhancer", "EST", "cDNA_clone", "miRNA", "snRNA", "ncRNA", "rRNA", "ncRNA", "snoRNA", "tRNA", "chromosome_band", "transposable_element_insertion_site", CHROMOSOME_STRUCTURE_VARIATION_SO_NAME, "point_mutation", "natural_transposable_element", "transposable_element" ); /** * Get a list of the chado/so types of the LocatedSequenceFeatures we wish to load. The list * will not include chromosome-like features. * @return the list of features */ @Override protected List<String> getFeatures() { return FEATURES; } /** * For objects that have primaryIdentifier == null, set the primaryIdentifier to be the * uniquename column from chado. * {@inheritDoc} */ @Override protected void extraProcessing(Connection connection, Map<Integer, FeatureData> features) throws ObjectStoreException, SQLException { createAllelesTempTable(connection); createInsertionTempTable(connection); for (FeatureData featureData: features.values()) { if (!featureData.getFlag(FeatureData.IDENTIFIER_SET)) { setAttribute(featureData.getIntermineObjectId(), "primaryIdentifier", featureData.getChadoFeatureUniqueName()); } } if (FEATURES.contains("gene")) { processAlleleProps(connection, features); Map<Integer, List<String>> mutagenMap = makeMutagenMap(connection); for (Integer alleleFeatureId: mutagenMap.keySet()) { FeatureData alleleDat = features.get(alleleFeatureId); List<String> mutagenRefIds = new ArrayList<String>(); for (String mutagenDescription: mutagenMap.get(alleleFeatureId)) { String mutagenIdentifier = getMutagen(mutagenDescription); mutagenRefIds.add(mutagenIdentifier); } ReferenceList referenceList = new ReferenceList(); referenceList.setName("mutagens"); referenceList.setRefIds(mutagenRefIds); getChadoDBConverter().store(referenceList, alleleDat.getIntermineObjectId()); } createIndelReferences(connection); createDeletionLocations(connection); copyInsertionLocations(connection); createInteractions(connection); } } private Item getInteraction(Map<MultiKey, Item> interactions, String refId, String gene2RefId) { MultiKey key = new MultiKey(refId, gene2RefId); Item item = interactions.get(key); if (item == null) { item = getChadoDBConverter().createItem("Interaction"); item.setReference("participant1", refId); item.setReference("participant2", gene2RefId); interactions.put(key, item); } return item; } /** * Create Interaction objects. */ private void createInteractions(Connection connection) throws SQLException, ObjectStoreException { Map<MultiKey, Item> seenInteractions = new HashMap<MultiKey, Item>(); ResultSet res = getInteractionResultSet(connection); while (res.next()) { Integer featureId = new Integer(res.getInt("feature_id")); Integer otherFeatureId = new Integer(res.getInt("other_feature_id")); String pubTitle = res.getString("pub_title"); Integer pubmedId = new Integer(res.getInt("pubmed_id")); FeatureData featureData = getFeatureMap().get(featureId); FeatureData otherFeatureData = getFeatureMap().get(otherFeatureId); OrganismData od = otherFeatureData.getOrganismData(); Item dataSetItem = getChadoDBConverter().getDataSetItem(od.getTaxonId()); String publicationItemId = makePublication(pubmedId); String name = "FlyBase:" + featureData.getChadoFeatureUniqueName() + "_" + otherFeatureData.getChadoFeatureUniqueName(); Item interaction = getInteraction(seenInteractions, featureData.getItemIdentifier(), otherFeatureData.getItemIdentifier()); createDetail(dataSetItem, pubTitle, publicationItemId, interaction, name); name = "FlyBase:" + otherFeatureData.getChadoFeatureUniqueName() + "_" + featureData.getChadoFeatureUniqueName(); interaction = getInteraction(seenInteractions, otherFeatureData.getItemIdentifier(), featureData.getItemIdentifier()); createDetail(dataSetItem, pubTitle, publicationItemId, interaction, name); } for (Item item : seenInteractions.values()) { getChadoDBConverter().store(item); } } private void createDetail(Item dataSetItem, String pubTitle, String publicationItemId, Item interaction, String name) throws ObjectStoreException { Item detail = getChadoDBConverter().createItem("InteractionDetail"); detail.setAttribute("name", name); detail.setAttribute("type", "genetic"); detail.setAttribute("role1", DEFAULT_ROLE); detail.setAttribute("role2", DEFAULT_ROLE); String experimentItemIdentifier = makeInteractionExperiment(pubTitle, publicationItemId); detail.setReference("experiment", experimentItemIdentifier); detail.setReference("interaction", interaction); detail.setAttribute("relationshipType", RELATIONSHIP_TYPE); detail.addToCollection("dataSets", dataSetItem); getChadoDBConverter().store(detail); } /** * Return the item identifier of the Interaction Item for the given pubmed id, creating the * Item if necessary. * @param experimentTitle the new title * @param publicationItemIdentifier the item identifier of the publication for this experiment * @return the interaction item identifier * @throws ObjectStoreException if the item can't be stored */ protected String makeInteractionExperiment(String experimentTitle, String publicationItemIdentifier) throws ObjectStoreException { if (interactionExperiments.containsKey(experimentTitle)) { return interactionExperiments.get(experimentTitle); } Item experiment = getChadoDBConverter().createItem("InteractionExperiment"); experiment.setAttribute("name", experimentTitle); experiment.setReference("publication", publicationItemIdentifier); getChadoDBConverter().store(experiment); String experimentId = experiment.getIdentifier(); interactionExperiments.put(experimentTitle, experimentId); return experimentId; } /** * Create Location objects for deletions (chromosome_structure_variation) as they don't have * locations in the featureloc table. * @throws ObjectStoreException */ private void createDeletionLocations(Connection connection) throws SQLException, ObjectStoreException { ResultSet res = getDeletionLocationResultSet(connection); while (res.next()) { Integer delId = new Integer(res.getInt("deletion_feature_id")); FeatureData delFeatureData = getFeatureMap().get(delId); if (delFeatureData == null) { LOG.info("can't find deletion " + delId + " in feature map"); continue; } String chromosomeName = res.getString("chromosome_name"); String startString = res.getString("fmin"); String endString = res.getString("fmax"); String strandString = res.getString("strand"); // Df(3L)ZN47/FBab0000006 and some others don't have a strand // I don't know why, but for now we'll just give them a default if (StringUtils.isEmpty(strandString)) { strandString = "1"; } if (StringUtils.isEmpty(startString) || StringUtils.isEmpty(endString)) { continue; } Integer organismId = new Integer(res.getInt("deletion_organism_id")); int start = Integer.parseInt(startString); int end = Integer.parseInt(endString); int strand = Integer.parseInt(strandString); if (start > end) { int tmp = start; start = end; end = tmp; } int taxonId = delFeatureData.getOrganismData().getTaxonId(); Integer chrFeatureId = getChromosomeFeatureMap(organismId).get(chromosomeName); if (chrFeatureId == null) { String msg = "Can't find chromosome " + chromosomeName + " in feature map"; LOG.warn(msg); continue; } FeatureData chrFeatureData = getFeatureMap().get(chrFeatureId); if (chrFeatureData == null) { String msg = "chrFeatureData is null " + chrFeatureId + " for feature " + delId; LOG.warn(msg); continue; } makeAndStoreLocation(chrFeatureId, delFeatureData, start, end, strand, taxonId); } } private void makeAndStoreLocation(Integer chrFeatureId, FeatureData subjectFeatureData, int start, int end, int strand, int taxonId) throws ObjectStoreException { if ("protein".equalsIgnoreCase(subjectFeatureData.getInterMineType())) { // don't make locations for proteins return; } FeatureData chrFeatureData = getFeatureMap().get(chrFeatureId); if (chrFeatureData == null) { // chromosome might be empty if we ignored it earlier, e.g. golden path region return; } Item location = getChadoDBConverter().makeLocation(chrFeatureData.getItemIdentifier(), subjectFeatureData.getItemIdentifier(), start, end, strand, taxonId); Item dataSetItem = getChadoDBConverter().getDataSetItem(taxonId); location.addToCollection("dataSets", dataSetItem); Reference chrLocReference = new Reference(); chrLocReference.setName("chromosomeLocation"); chrLocReference.setRefId(location.getIdentifier()); getChadoDBConverter().store(chrLocReference, subjectFeatureData.getIntermineObjectId()); getChadoDBConverter().store(location); } /** * Create the ChromosomalDeletion.element1 and element2 references (to * TransposableElementInsertionSite objects) */ private void createIndelReferences(Connection connection) throws ObjectStoreException, SQLException { ResultSet res = getIndelResultSet(connection); int featureWarnings = 0; while (res.next()) { Integer delId = new Integer(res.getInt("deletion_feature_id")); Integer insId = new Integer(res.getInt("insertion_feature_id")); String breakType = res.getString("breakpoint_type"); Reference reference = new Reference(); if ("bk1".equals(breakType)) { reference.setName("element1"); } else { reference.setName("element2"); } FeatureData insFeatureData = getFeatureMap().get(insId); if (insFeatureData == null) { if (featureWarnings <= 20) { if (featureWarnings < 20) { LOG.warn("insertion " + insId + " was not found in the feature table"); } else { LOG.warn("further warnings ignored"); } featureWarnings++; } continue; } reference.setRefId(insFeatureData.getItemIdentifier()); FeatureData delFeatureData = getFeatureMap().get(delId); if (delFeatureData == null) { if (featureWarnings <= 20) { if (featureWarnings < 20) { LOG.warn("deletion " + delId + " was not found in the feature table"); } else { LOG.warn("further warnings ignored"); } featureWarnings++; } continue; } getChadoDBConverter().store(reference, delFeatureData.getIntermineObjectId()); } } private String getMutagen(String description) throws ObjectStoreException { if (mutagensMap.containsKey(description)) { return mutagensMap.get(description); } Item mutagen = getChadoDBConverter().createItem("Mutagen"); mutagen.setAttribute("description", description); mutagensMap.put(description, mutagen.getIdentifier()); store(mutagen); return mutagen.getIdentifier(); } /** * @param connection */ private void copyInsertionLocations(Connection connection) throws ObjectStoreException, SQLException { ResultSet res = getInsertionLocationsResultSet(connection); while (res.next()) { int subId = res.getInt("sub_id"); int chrId = res.getInt("chr_feature_id"); int fmin = res.getInt("fmin"); int fmax = res.getInt("fmax"); int start = fmin + 1; int end = fmax; // make sure both are relevant features. e.g. we do not load golden paths // but they have insertions. See #1052 FeatureData subFeatureData = getFeatureMap().get(new Integer(subId)); if (subFeatureData != null) { // this is a hack - we should make sure that we only query for features that are in // the feature map, ie. those for the current organism int taxonId = subFeatureData.getOrganismData().getTaxonId(); makeAndStoreLocation(new Integer(chrId), subFeatureData, start, end, 1, taxonId); } } } private void store(Item item) throws ObjectStoreException { getChadoDBConverter().store(item); } // map from anatomy identifier (eg. "FBbt0001234") to Item identifier private Map<String, String> anatomyTermMap = new HashMap<String, String>(); // map from development term identifier (eg. "FBdv0001234") to Item identifier private Map<String, String> developmentTermMap = new HashMap<String, String>(); // map from FlyBase cv identifier (eg. "FBcv0001234") to Item identifier private Map<String, String> cvTermMap = new HashMap<String, String>(); private void processAlleleProps(Connection connection, Map<Integer, FeatureData> features) throws SQLException, ObjectStoreException { Map<Integer, List<String>> annotationPubMap = makeAnnotationPubMap(connection); ResultSet res = getAllelePropResultSet(connection); while (res.next()) { Integer featureId = new Integer(res.getInt("feature_id")); String value = res.getString("value"); String propType = res.getString("type_name"); Integer featurePropId = new Integer(res.getInt("featureprop_id")); FeatureData alleleFeatureData = features.get(featureId); OrganismData od = alleleFeatureData.getOrganismData(); Item dataSetItem = getChadoDBConverter().getDataSetItem(od.getTaxonId()); String alleleItemIdentifier = alleleFeatureData.getItemIdentifier(); Item phenotypeAnnotation = null; if ("derived_pheno_manifest".equals(propType)) { phenotypeAnnotation = makePhenotypeAnnotation(alleleItemIdentifier, value, dataSetItem, annotationPubMap.get(featurePropId)); phenotypeAnnotation.setAttribute("annotationType", "manifest in"); } else { if ("derived_pheno_class".equals(propType)) { phenotypeAnnotation = makePhenotypeAnnotation(alleleItemIdentifier, value, dataSetItem, annotationPubMap.get(featurePropId)); phenotypeAnnotation.setAttribute("annotationType", "phenotype class"); } } if (phenotypeAnnotation != null) { getChadoDBConverter().store(phenotypeAnnotation); } } } /** * Return a Map from allele feature_id to mutagen. The mutagen is found be looking at cvterms * that are associated with each feature and saving those terms that have "origin of mutation" * as a parent term. */ private Map<Integer, List<String>> makeMutagenMap(Connection connection) throws SQLException { Map<Integer, List<String>> retMap = new HashMap<Integer, List<String>>(); ResultSet res = getAlleleCVTermsResultSet(connection); RESULTS: while (res.next()) { Integer featureId = new Integer(res.getInt("feature_id")); Integer cvtermId = new Integer(res.getInt("cvterm_id")); ChadoCVTerm cvterm = flyBaseMiscCv.getByChadoId(cvtermId); if (cvterm == null) { LOG.error("cvterm not found for " + res.getInt("cvterm_id") + " for feature " + res.getInt("feature_id")); continue; } Set<ChadoCVTerm> parents = cvterm.getAllParents(); for (ChadoCVTerm parent: parents) { if ("origin of mutation".equals(parent.getName())) { String fixedName = XmlUtil.fixEntityNames(cvterm.getName()); List<String> mutagens; if (retMap.containsKey(featureId)) { mutagens = retMap.get(featureId); } else { mutagens = new ArrayList<String>(); retMap.put(featureId, mutagens); } mutagens.add(fixedName); continue RESULTS; } } } return retMap; } /** * Get result set of feature_id, cvterm_id pairs for the alleles in flybase chado. * @param connection the Connectio * @return the cvterms * @throws SQLException if there is a database problem */ protected ResultSet getAlleleCVTermsResultSet(Connection connection) throws SQLException { String query = "SELECT DISTINCT feature.feature_id, cvterm.cvterm_id" + " FROM feature, feature_cvterm, cvterm" + " WHERE feature.feature_id = feature_cvterm.feature_id" + " AND feature.feature_id IN (" + getAlleleFeaturesSql() + ")" + " AND feature_cvterm.cvterm_id = cvterm.cvterm_id"; LOG.info("executing getAlleleCVTermsResultSet(): " + query); Statement stmt = connection.createStatement(); ResultSet res = stmt.executeQuery(query); return res; } /** * Return a map from featureprop_id for alleles to publication item identifier */ private Map<Integer, List<String>> makeAnnotationPubMap(Connection connection) throws SQLException, ObjectStoreException { Map<Integer, List<String>> retMap = new HashMap<Integer, List<String>>(); ResultSet res = getAllelePropPubResultSet(connection); while (res.next()) { Integer featurePropId = new Integer(res.getInt("featureprop_id")); String pubDbId = res.getString("pub_db_identifier"); Integer n = new Integer(Integer.parseInt(pubDbId)); String pubicationItemIdentifier = makePublication(n); if (!retMap.containsKey(featurePropId)) { retMap.put(featurePropId, new ArrayList<String>()); } retMap.get(featurePropId).add(pubicationItemIdentifier); } return retMap; } /** * Return a map from feature_id to seqlen * @throws SQLException if somethign goes wrong */ // private Map<Integer, Integer> makeCDNALengthMap(Connection connection) // throws SQLException { // Map<Integer, Integer> retMap = new HashMap(); // ResultSet res = getCDNALengthResultSet(connection); // while (res.next()) { // Integer featureId = new Integer(res.getInt("feature_id")); // Integer seqlen = new Integer(res.getInt("seqlen")); // retMap.put(featureId, seqlen); // return retMap; private Item makePhenotypeAnnotation(String alleleItemIdentifier, String value, Item dataSetItem, List<String> publicationsItemIdList) throws ObjectStoreException { Item phenotypeAnnotation = getChadoDBConverter().createItem("PhenotypeAnnotation"); phenotypeAnnotation.addToCollection("dataSets", dataSetItem); Pattern p = Pattern.compile(FLYBASE_PROP_ATTRIBUTE_PATTERN); Matcher m = p.matcher(value); StringBuffer sb = new StringBuffer(); List<String> dbAnatomyTermIdentifiers = new ArrayList<String>(); List<String> dbDevelopmentTermIdentifiers = new ArrayList<String>(); List<String> dbCVTermIdentifiers = new ArrayList<String>(); while (m.find()) { String field = m.group(1); int colonPos = field.indexOf(':'); if (colonPos == -1) { m.appendReplacement(sb, field); } else { String identifier = field.substring(0, colonPos); if (identifier.startsWith(FLYBASE_ANATOMY_TERM_PREFIX)) { dbAnatomyTermIdentifiers.add(addCVTermColon(identifier)); } else { if (identifier.startsWith("FBdv")) { dbDevelopmentTermIdentifiers.add(addCVTermColon(identifier)); } else { if (identifier.startsWith("FBcv")) { dbCVTermIdentifiers.add(addCVTermColon(identifier)); } } } String text = field.substring(colonPos + 1); m.appendReplacement(sb, text); } } m.appendTail(sb); /* * ignore with for now because the with text is wrong in chado - see ticket #889 List<String> withAlleleIdentifiers = findWithAllele(value); if (withAlleleIdentifiers.size() > 0) { phenotypeAnnotation.setCollection("with", withAlleleIdentifiers); } */ String valueNoRefs = sb.toString(); String valueNoUps = valueNoRefs.replaceAll("<up>", "[").replaceAll("</up>", "]"); phenotypeAnnotation.setAttribute("description", valueNoUps); phenotypeAnnotation.setReference("allele", alleleItemIdentifier); if (publicationsItemIdList != null && publicationsItemIdList.size() > 0) { ReferenceList pubReferenceList = new ReferenceList("publications", publicationsItemIdList); phenotypeAnnotation.addCollection(pubReferenceList); } if (dbAnatomyTermIdentifiers.size() == 1) { String anatomyIdentifier = dbAnatomyTermIdentifiers.get(0); String anatomyTermItemId = makeAnatomyTerm(anatomyIdentifier); phenotypeAnnotation.setReference("anatomyTerm", anatomyTermItemId); } else { if (dbAnatomyTermIdentifiers.size() > 1) { throw new RuntimeException("more than one anatomy term: " + dbAnatomyTermIdentifiers); } } if (dbDevelopmentTermIdentifiers.size() == 1) { String developmentTermIdentifier = dbDevelopmentTermIdentifiers.get(0); String developmentTermItemId = makeDevelopmentTerm(developmentTermIdentifier); phenotypeAnnotation.setReference("developmentTerm", developmentTermItemId); } else { if (dbAnatomyTermIdentifiers.size() > 1) { throw new RuntimeException("more than one anatomy term: " + dbAnatomyTermIdentifiers); } } if (dbCVTermIdentifiers.size() > 0) { for (String cvTermIdentifier: dbCVTermIdentifiers) { String cvTermItemId = makeCVTerm(cvTermIdentifier); phenotypeAnnotation.addToCollection("cvTerms", cvTermItemId); } } return phenotypeAnnotation; } private static final Pattern FLYBASE_TERM_IDENTIFIER_PATTERN = Pattern.compile("^FB[^\\d][^\\d]\\d+"); /** * For a FlyBase cvterm identifier like "FBbt00000001", add a colon in the middle and return: * "FBbt:00000001" * @param identifier the identifier from chado * @return the public identifier */ protected static String addCVTermColon(String identifier) { Matcher m = FLYBASE_TERM_IDENTIFIER_PATTERN.matcher(identifier); if (m.matches()) { return identifier.substring(0, 4) + ":" + identifier.substring(4); } return identifier; } /** * Return the item identifiers of the alleles metioned in the with clauses of the argument. * Currently unused because flybase with clauses are wrong - see ticket #889 */ // @SuppressWarnings("unused") // private List<String> findWithAllele(String value) { // Pattern p = Pattern.compile("with @(FBal\\d+):"); // Matcher m = p.matcher(value); // List<String> foundIdentifiers = new ArrayList<String>(); // while (m.find()) { // String identifier = m.group(1); // if (identifier.startsWith("FBal")) { // foundIdentifiers.add(identifier); // } else { // throw new RuntimeException("identifier in a with must start: \"FBal\" not: " // + identifier); // List<String> alleleItemIdentifiers = new ArrayList<String>(); // for (String foundIdentifier: foundIdentifiers) { // if (alleleIdMap.containsKey(foundIdentifier)) { // alleleItemIdentifiers.add(alleleIdMap.get(foundIdentifier)); // } else { // // this allele wasn't stored so probably it didn't have the right organism - some // // GAL4 alleles have cerevisiae as organism, eg. FBal0060667:Scer\GAL4[sd-SG29.1] // // referenced by FBal0038994 Rac1[N17.Scer\UAS] // return alleleItemIdentifiers; /** * phenotype annotation creates and stores anatomy terms. so does librarycvterm * @param identifier identifier for anatomy term * @return refId for anatomy term object * @throws ObjectStoreException if term can't be stored */ @Override protected String makeAnatomyTerm(String identifier) throws ObjectStoreException { String newIdentifier = identifier; if (!newIdentifier.startsWith(FLYBASE_ANATOMY_TERM_PREFIX)) { newIdentifier = FLYBASE_ANATOMY_TERM_PREFIX + identifier; newIdentifier = addCVTermColon(newIdentifier); } if (anatomyTermMap.containsKey(newIdentifier)) { return anatomyTermMap.get(newIdentifier); } Item anatomyTerm = getChadoDBConverter().createItem("AnatomyTerm"); anatomyTerm.setAttribute("identifier", newIdentifier); getChadoDBConverter().store(anatomyTerm); anatomyTermMap.put(identifier, anatomyTerm.getIdentifier()); return anatomyTerm.getIdentifier(); } private String makeDevelopmentTerm(String identifier) throws ObjectStoreException { if (developmentTermMap.containsKey(identifier)) { return developmentTermMap.get(identifier); } Item developmentTerm = getChadoDBConverter().createItem("DevelopmentTerm"); developmentTerm.setAttribute("identifier", identifier); getChadoDBConverter().store(developmentTerm); developmentTermMap.put(identifier, developmentTerm.getIdentifier()); return developmentTerm.getIdentifier(); } private String makeCVTerm(String identifier) throws ObjectStoreException { if (cvTermMap.containsKey(identifier)) { return cvTermMap.get(identifier); } Item cvTerm = getChadoDBConverter().createItem("CVTerm"); cvTerm.setAttribute("identifier", identifier); getChadoDBConverter().store(cvTerm); cvTermMap.put(identifier, cvTerm.getIdentifier()); return cvTerm.getIdentifier(); } /** * Return a result set containing the interaction genes pairs, the title of the publication * that reported the interaction and its pubmed id. The method is protected * so that is can be overridden for testing. * @param connection the Connection * @throws SQLException if there is a database problem * @return the ResultSet */ protected ResultSet getInteractionResultSet(Connection connection) throws SQLException { String query = " SELECT feature.feature_id as feature_id, " + " other_feature.feature_id as other_feature_id, " + " pub.title as pub_title, dbx.accession as pubmed_id " + " FROM feature, cvterm cvt, feature other_feature, " + " feature_relationship_pub frpb, pub, " + " feature_relationship fr, pub_dbxref pdbx, dbxref dbx, db " + " WHERE feature.feature_id = subject_id " + " AND object_id = other_feature.feature_id " + " AND fr.type_id = cvt.cvterm_id AND cvt.name = 'interacts_genetically' " + " AND fr.feature_relationship_id = frpb.feature_relationship_id " + " AND frpb.pub_id = pub.pub_id AND db.name='pubmed' " + " AND pdbx.is_current=true AND pub.pub_id=pdbx.pub_id " + " AND pdbx.dbxref_id = dbx.dbxref_id AND dbx.db_id=db.db_id " + " AND NOT feature.is_obsolete AND NOT other_feature.is_obsolete " + " AND feature.feature_id IN (" + getLocatedGenesSql() + ")" + " AND other_feature.feature_id IN (" + getLocatedGenesSql() + ")"; LOG.info("executing getInteractionResultSet(): " + query); Statement stmt = connection.createStatement(); ResultSet res = stmt.executeQuery(query); return res; } /** * Return a result set containing the alleles and their featureprops. The method is protected * so that is can be overridden for testing. * @param connection the Connection * @throws SQLException if there is a database problem * @return the ResultSet */ protected ResultSet getAllelePropResultSet(Connection connection) throws SQLException { String query = "SELECT feature_id, value, cvterm.name AS type_name, featureprop_id" + " FROM featureprop, cvterm" + " WHERE featureprop.type_id = cvterm.cvterm_id" + " AND feature_id IN (" + getAlleleFeaturesSql() + ")" + " ORDER BY feature_id"; LOG.info("executing getAllelePropResultSet(): " + query); Statement stmt = connection.createStatement(); ResultSet res = stmt.executeQuery(query); return res; } /** * Return a result set containing pairs of chromosome_structure_variation (deletions) and * transposable_element_insertion_site (insertions). The method is protected * so that is can be overridden for testing. * @param connection the Connection * @throws SQLException if there is a database problem * @return the ResultSet */ protected ResultSet getIndelResultSet(Connection connection) throws SQLException { String query = "SELECT del.feature_id as deletion_feature_id," + " ins.feature_id as insertion_feature_id," + " substring(break.uniquename FROM ':([^:]+)$') AS breakpoint_type" + " FROM feature del, cvterm del_type, feature_relationship del_rel," + " cvterm del_rel_type," + " feature break, cvterm break_type," + " feature_relationship ins_rel, cvterm ins_rel_type," + " feature ins, cvterm ins_type" + " WHERE del_rel.object_id = del.feature_id" + " AND del_rel.subject_id = break.feature_id" + " AND ins_rel.subject_id = break.feature_id" + " AND ins_rel.object_id = ins.feature_id" + " AND del.type_id = del_type.cvterm_id" + " AND ins.type_id = ins_type.cvterm_id" + " AND del_type.name = 'chromosome_structure_variation'" + " AND ins_type.name = 'transposable_element_insertion_site'" + " AND del_rel.type_id = del_rel_type.cvterm_id" + " AND del_rel_type.name = 'break_of'" + " AND ins_rel.type_id = ins_rel_type.cvterm_id" + " AND ins_rel_type.name = 'progenitor'" + " AND break.type_id = break_type.cvterm_id" + " AND break_type.name = 'breakpoint'" // ignore the progenitors so we only set element1 and element2 to be the "descendants" + " AND ins.feature_id NOT IN (SELECT obj_id FROM " + INSERTION_TEMP_TABLE_NAME + ")"; LOG.info("executing getIndelResultSet(): " + query); Statement stmt = connection.createStatement(); ResultSet res = stmt.executeQuery(query); return res; } /** * Return a result set containing pairs of insertion feature_ids (eg. for "FBti0027974" => * "FBti0023081") and the fmin and fmax of the first insertion in the pair (ie. the progenitor). * The second in the pair is the "Modified descendant of" the first. The pairs are found using * the 'modified_descendant_of' relation type. All insertions are from DrosDel. * The method is protected so that is can be overridden for testing. * @param connection the Connection * @throws SQLException if there is a database problem * @return the ResultSet */ protected ResultSet getInsertionLocationsResultSet(Connection connection) throws SQLException { String query = "SELECT * from " + INSERTION_TEMP_TABLE_NAME; LOG.info("executing getInsertionLocationsResultSet(): " + query); Statement stmt = connection.createStatement(); ResultSet res = stmt.executeQuery(query); return res; } /** * Return a result set containing location for deletions (chromosome_structure_variation) * objects. The locations are in the featureprop able in the form: * 2R:12716549..12984803 (53D11;53F8) * The method is protected so that is can be overridden for testing. * @param connection the Connection * @throws SQLException if there is a database problem * @return the ResultSet */ protected ResultSet getDeletionLocationResultSet(Connection connection) throws SQLException { String query = "SELECT f.feature_id as deletion_feature_id, f.organism_id as deletion_organism_id, " + "c.name as chromosome_name, fl.fmin, fl.fmax, fl.strand " + "FROM feature f, feature b, feature_relationship fr, cvterm cvt1, cvterm cvt2, " + " featureloc fl, feature c " + "WHERE f.feature_id = fr.object_id " + " AND fr.type_id = cvt1.cvterm_id " + " AND cvt1.name = 'break_of' " + " AND fr.subject_id = b.feature_id " + " AND b.type_id = cvt2.cvterm_id " + " AND cvt2.name = 'breakpoint' " + " AND b.feature_id = fl.feature_id " + " AND f.name ~ '^Df.+' " + " AND f.uniquename like 'FBab%' " + " AND f.is_obsolete = false " + " AND fl.srcfeature_id = c.feature_id "; LOG.info("executing getDeletionLocationResultSet(): " + query); Statement stmt = connection.createStatement(); ResultSet res = stmt.executeQuery(query); return res; } /** * Return a result set containing the featureprop_id and the publication identifier of the * featureprops for al alleles. The method is protected so that is can be overridden for * testing. * @param connection the Connection * @throws SQLException if there is a database problem * @return the ResultSet */ protected ResultSet getAllelePropPubResultSet(Connection connection) throws SQLException { String query = "SELECT DISTINCT featureprop_pub.featureprop_id, dbxref.accession as pub_db_identifier" + " FROM featureprop, featureprop_pub, dbxref, db, pub, pub_dbxref" + " WHERE featureprop_pub.pub_id = pub.pub_id" + " AND featureprop.featureprop_id = featureprop_pub.featureprop_id" + " AND pub.pub_id = pub_dbxref.pub_id" + " AND pub_dbxref.dbxref_id = dbxref.dbxref_id" + " AND dbxref.db_id = db.db_id" + " AND db.name = 'pubmed'" + " AND feature_id IN (" + getAlleleFeaturesSql() + ")" + " ORDER BY featureprop_id"; LOG.info("executing getAllelePropPubResultSet(): " + query); Statement stmt = connection.createStatement(); ResultSet res = stmt.executeQuery(query); return res; } /** * Return a result set containing the feature_id and its seqlen * The method is protected so that is can be overridden for * testing. * @param connection the Connection * @throws SQLException if there is a database problem * @return the ResultSet */ protected ResultSet getCDNALengthResultSet(Connection connection) throws SQLException { String query = "SELECT cl.feature_id, fls.seqlen " + "FROM feature cl, feature fls, feature_relationship fr, cvterm fls_type " + "WHERE fls_type.name IN ('cDNA','BAC_cloned_genomic_insert') " + " AND cl.feature_id=fr.object_id " + " AND fr.subject_id=fls.feature_id " + " AND fls.type_id=fls_type.cvterm_id "; LOG.info("executing getCDNALengthResultSet(): " + query); Statement stmt = connection.createStatement(); ResultSet res = stmt.executeQuery(query); return res; } /** * Convert ISO entities from FlyBase to HTML entities. * {@inheritDoc} */ @Override protected String fixIdentifier(FeatureData fdat, String identifier) { if (StringUtils.isBlank(identifier)) { return identifier; } return XmlUtil.fixEntityNames(identifier); } /** * {@inheritDoc} */ @Override protected FeatureData makeFeatureData(int featureId, String type, String uniqueName, String name, String md5checksum, int seqlen, int organismId) throws ObjectStoreException { if ("protein".equals(type)) { if (!uniqueName.startsWith("FBpp")) { return null; } FeatureData protein = proteinFeatureDataMap.get(md5checksum); // make a synonym for the protein we're about to discard if (protein != null) { if (StringUtils.isNotEmpty(uniqueName) && !protein.getExistingSynonyms().contains(uniqueName)) { Item synonym = createSynonym(protein, uniqueName); store(synonym); } if (StringUtils.isNotEmpty(name) && !protein.getExistingSynonyms().contains(name)) { Item synonym = createSynonym(protein, name); store(synonym); } return protein; } FeatureData fdat = super.makeFeatureData(featureId, type, uniqueName, name, md5checksum, seqlen, organismId); proteinFeatureDataMap.put(md5checksum, fdat); return fdat; } if ("cDNA_clone".equals(type)) { // flybase has duplicates. to merge with BDGP we need to discard duplicates and // make a synonym FeatureData cdnaClone = cdnaCloneMap.get(name); if (cdnaClone != null) { if (StringUtils.isNotEmpty(name)) { Item synonym = createSynonym(cdnaClone, name); if (synonym != null) { store(synonym); } } return cdnaClone; } FeatureData fdat = super.makeFeatureData(featureId, type, uniqueName, name, md5checksum, seqlen, organismId); cdnaCloneMap.put(name, fdat); return fdat; } return super.makeFeatureData(featureId, type, uniqueName, name, md5checksum, seqlen, organismId); } /** * Return a query that gets the feature_ids of the allele in the feature table. */ private static String getAlleleFeaturesSql() { return "SELECT feature_id FROM " + ALLELE_TEMP_TABLE_NAME; } /** * Method to add dataSets and DataSources to items before storing */ private void processItem(Item item, Integer taxonId) { String className = item.getClassName(); if ("DataSource".equals(className) || "DataSet".equals(className) || "Organism".equals(className) || "Sequence".equals(className)) { return; } if (taxonId == null) { ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader(); ClassLoader classLoader = getClass().getClassLoader(); Thread.currentThread().setContextClassLoader(classLoader); try { throw new RuntimeException("getCurrentTaxonId() returned null while processing " + item); } finally { Thread.currentThread().setContextClassLoader(currentClassLoader); } } ChadoDBConverter converter = getChadoDBConverter(); BioStoreHook.setDataSets(getModel(), item, converter.getDataSetItem(taxonId.intValue()).getIdentifier(), converter.getDataSourceItem().getIdentifier()); } }
package loci.formats; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Hashtable; import java.util.List; import java.util.Set; import loci.common.Location; import loci.common.RandomAccessInputStream; import loci.formats.in.MetadataLevel; import loci.formats.in.MetadataOptions; import loci.formats.meta.MetadataStore; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ImageReader implements IFormatReader { // -- Constants -- private static final Logger LOGGER = LoggerFactory.getLogger(ImageReader.class); // -- Static fields -- /** Default list of reader classes, for use with noargs constructor. */ private static ClassList<IFormatReader> defaultClasses; // -- Static utility methods -- public static ClassList<IFormatReader> getDefaultReaderClasses() { if (defaultClasses == null) { // load built-in reader classes from readers.txt file try { defaultClasses = new ClassList<IFormatReader>("readers.txt", IFormatReader.class); } catch (IOException exc) { defaultClasses = new ClassList<IFormatReader>(IFormatReader.class); LOGGER.info("Could not parse class list; using default classes", exc); } } return defaultClasses; } // -- Fields -- /** List of supported file format readers. */ private IFormatReader[] readers; /** * Valid suffixes for this file format. * Populated the first time getSuffixes() is called. */ private String[] suffixes; /** Name of current file. */ private String currentId; /** Current form index. */ private int current; private boolean allowOpen = true; // -- Constructors -- /** * Constructs a new ImageReader with the default * list of reader classes from readers.txt. */ public ImageReader() { this(getDefaultReaderClasses()); } /** Constructs a new ImageReader from the given list of reader classes. */ public ImageReader(ClassList<IFormatReader> classList) { // add readers to the list List<IFormatReader> list = new ArrayList<IFormatReader>(); Class<? extends IFormatReader>[] c = classList.getClasses(); for (int i=0; i<c.length; i++) { IFormatReader reader = null; try { reader = c[i].newInstance(); } catch (IllegalAccessException exc) { } catch (InstantiationException exc) { } if (reader == null) { LOGGER.error("{} cannot be instantiated.", c[i].getName()); continue; } list.add(reader); } readers = new IFormatReader[list.size()]; list.toArray(readers); } // -- ImageReader API methods -- /** * Toggles whether or not file system access is allowed when doing type * detection. By default, file system access is allowed. */ public void setAllowOpenFiles(boolean allowOpen) { this.allowOpen = allowOpen; } /** Gets a string describing the file format for the given file. */ public String getFormat(String id) throws FormatException, IOException { return getReader(id).getFormat(); } /** Gets the reader used to open the given file. */ public IFormatReader getReader(String id) throws FormatException, IOException { // HACK: skip file existence check for fake files boolean fake = id != null && id.toLowerCase().endsWith(".fake"); boolean omero = id != null && id.toLowerCase().startsWith("omero:") && id.indexOf("\n") > 0; // blacklist temporary files that are being copied e.g. by WinSCP boolean invalid = id != null && id.toLowerCase().endsWith(".filepart"); // NB: Check that we can generate a valid handle for the ID; // e.g., for files, this will throw an exception if the file is missing. if (!fake && !omero) Location.getHandle(id).close(); if (!id.equals(currentId)) { // initialize file boolean success = false; if (!invalid) { for (int i=0; i<readers.length; i++) { if (readers[i].isThisType(id, allowOpen)) { current = i; currentId = id; success = true; break; } } } if (!success) { throw new UnknownFormatException("Unknown file format: " + id); } } return getReader(); } /** Gets the reader used to open the current file. */ public IFormatReader getReader() { FormatTools.assertId(currentId, true, 2); return readers[current]; } /** Gets the file format reader instance matching the given class. */ public IFormatReader getReader(Class<? extends IFormatReader> c) { for (int i=0; i<readers.length; i++) { if (readers[i].getClass().equals(c)) return readers[i]; } return null; } /** Gets all constituent file format readers. */ public IFormatReader[] getReaders() { IFormatReader[] r = new IFormatReader[readers.length]; System.arraycopy(readers, 0, r, 0, readers.length); return r; } // -- IMetadataConfigurable API methods -- /* @see loci.formats.IMetadataConfigurable#getSupportedMetadataLevels() */ public Set<MetadataLevel> getSupportedMetadataLevels() { return getReaders()[0].getSupportedMetadataLevels(); } /* @see loci.formats.IMetadataConfigurable#getMetadataOptions() */ public MetadataOptions getMetadataOptions() { return getReaders()[0].getMetadataOptions(); } /** * @see loci.formats.IMetadataConfigurable#setMetadataOptions(MetadataOptions) */ public void setMetadataOptions(MetadataOptions options) { for (IFormatReader reader : readers) { reader.setMetadataOptions(options); } } // -- IFormatReader API methods -- /* @see IFormatReader#isThisType(String, boolean) */ public boolean isThisType(String name, boolean open) { for (int i=0; i<readers.length; i++) { if (readers[i].isThisType(name, open)) return true; } return false; } /* @see IFormatReader.isThisType(byte[]) */ public boolean isThisType(byte[] block) { for (int i=0; i<readers.length; i++) { if (readers[i].isThisType(block)) return true; } return false; } /* @see IFormatReader.isThisType(RandomAccessInputStream) */ public boolean isThisType(RandomAccessInputStream stream) throws IOException { for (int i=0; i<readers.length; i++) { if (readers[i].isThisType(stream)) return true; } return false; } /* @see IFormatReader#getImageCount() */ public int getImageCount() { return getReader().getImageCount(); } /* @see IFormatReader#isRGB() */ public boolean isRGB() { return getReader().isRGB(); } /* @see IFormatReader#getSizeX() */ public int getSizeX() { return getReader().getSizeX(); } /* @see IFormatReader#getSizeY() */ public int getSizeY() { return getReader().getSizeY(); } /* @see IFormatReader#getSizeC() */ public int getSizeC() { return getReader().getSizeC(); } /* @see IFormatReader#getSizeZ() */ public int getSizeZ() { return getReader().getSizeZ(); } /* @see IFormatReader#getSizeT() */ public int getSizeT() { return getReader().getSizeT(); } /* @see IFormatReader#getPixelType() */ public int getPixelType() { return getReader().getPixelType(); } /* @see IFormatReader#getBitsPerPixel() */ public int getBitsPerPixel() { return getReader().getBitsPerPixel(); } /* @see IFormatReader#getEffectiveSizeC() */ public int getEffectiveSizeC() { return getReader().getEffectiveSizeC(); } /* @see IFormatReader#getRGBChannelCount() */ public int getRGBChannelCount() { return getReader().getRGBChannelCount(); } /* @see IFormatReader#isIndexed() */ public boolean isIndexed() { return getReader().isIndexed(); } /* @see IFormatReader#isFalseColor() */ public boolean isFalseColor() { return getReader().isFalseColor(); } /* @see IFormatReader#get8BitLookupTable() */ public byte[][] get8BitLookupTable() throws FormatException, IOException { return getReader().get8BitLookupTable(); } /* @see IFormatReader#get16BitLookupTable() */ public short[][] get16BitLookupTable() throws FormatException, IOException { return getReader().get16BitLookupTable(); } /* @see IFormatReader#getChannelDimLengths() */ public int[] getChannelDimLengths() { return getReader().getChannelDimLengths(); } /* @see IFormatReader#getChannelDimTypes() */ public String[] getChannelDimTypes() { return getReader().getChannelDimTypes(); } /* @see IFormatReader#getThumbSizeX() */ public int getThumbSizeX() { return getReader().getThumbSizeX(); } /* @see IFormatReader#getThumbSizeY() */ public int getThumbSizeY() { return getReader().getThumbSizeY(); } /* @see IFormatReader#isLittleEndian() */ public boolean isLittleEndian() { return getReader().isLittleEndian(); } /* @see IFormatReader#getDimensionOrder() */ public String getDimensionOrder() { return getReader().getDimensionOrder(); } /* @see IFormatReader#isOrderCertain() */ public boolean isOrderCertain() { return getReader().isOrderCertain(); } /* @see IFormatReader#isThumbnailSeries() */ public boolean isThumbnailSeries() { return getReader().isThumbnailSeries(); } /* @see IFormatReader#isInterleaved() */ public boolean isInterleaved() { return getReader().isInterleaved(); } /* @see IFormatReader#isInterleaved(int) */ public boolean isInterleaved(int subC) { return getReader().isInterleaved(subC); } /* @see IFormatReader#openBytes(int) */ public byte[] openBytes(int no) throws FormatException, IOException { return getReader().openBytes(no); } /* @see IFormatReader#openBytes(int, int, int, int, int) */ public byte[] openBytes(int no, int x, int y, int w, int h) throws FormatException, IOException { return getReader().openBytes(no, x, y, w, h); } /* @see IFormatReader#openBytes(int, byte[]) */ public byte[] openBytes(int no, byte[] buf) throws FormatException, IOException { return getReader().openBytes(no, buf); } /* @see IFormatReader#openBytes(int, byte[], int, int, int, int) */ public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException { return getReader().openBytes(no, buf, x, y, w, h); } /* @see IFormatReader#openPlane(int, int, int, int, int) */ public Object openPlane(int no, int x, int y, int w, int h) throws FormatException, IOException { return getReader().openPlane(no, x, y, w, h); } /* @see IFormatReader#openThumbBytes(int) */ public byte[] openThumbBytes(int no) throws FormatException, IOException { return getReader().openThumbBytes(no); } /* @see IFormatReader#getSeriesCount() */ public int getSeriesCount() { return getReader().getSeriesCount(); } /* @see IFormatReader#setSeries(int) */ public void setSeries(int no) { getReader().setSeries(no); } /* @see IFormatReader#getSeries() */ public int getSeries() { return getReader().getSeries(); } /* @see IFormatReader#getUsedFiles() */ public String[] getUsedFiles() { return getReader().getUsedFiles(); } /* @see IFormatReader#getUsedFiles(boolean) */ public String[] getUsedFiles(boolean noPixels) { return getReader().getUsedFiles(noPixels); } /* @see IFormatReader#getSeriesUsedFiles() */ public String[] getSeriesUsedFiles() { return getReader().getSeriesUsedFiles(); } /* @see IFormatReader#getSeriesUsedFiles(boolean) */ public String[] getSeriesUsedFiles(boolean noPixels) { return getReader().getSeriesUsedFiles(noPixels); } /* @see IFormatReader#getAdvancedUsedFiles(boolean) */ public FileInfo[] getAdvancedUsedFiles(boolean noPixels) { return getReader().getAdvancedUsedFiles(noPixels); } /* @see IFormatReader#getAdvancedSeriesUsedFiles(boolean) */ public FileInfo[] getAdvancedSeriesUsedFiles(boolean noPixels) { return getReader().getAdvancedSeriesUsedFiles(noPixels); } /* @see IFormatReader#getIndex(int, int, int) */ public int getIndex(int z, int c, int t) { return getReader().getIndex(z, c, t); } /* @see IFormatReader#getZCTCoords(int) */ public int[] getZCTCoords(int index) { return getReader().getZCTCoords(index); } /* @see IFormatReader#getMetadataValue(String) */ public Object getMetadataValue(String field) { return getReader().getMetadataValue(field); } /* @see IFormatReader#getSeriesMetadataValue(String) */ public Object getSeriesMetadataValue(String field) { return getReader().getSeriesMetadataValue(field); } /* @see IFormatReader#getGlobalMetadata() */ public Hashtable<String, Object> getGlobalMetadata() { return getReader().getGlobalMetadata(); } /* @see IFormatReader#getSeriesMetadata() */ public Hashtable<String, Object> getSeriesMetadata() { return getReader().getSeriesMetadata(); } /** @deprecated */ public Hashtable<String, Object> getMetadata() { return getReader().getMetadata(); } /* @see IFormatReader#getCoreMetadata() */ public CoreMetadata[] getCoreMetadata() { return getReader().getCoreMetadata(); } /* @see IFormatReader#close(boolean) */ public void close(boolean fileOnly) throws IOException { for (int i=0; i<readers.length; i++) readers[i].close(fileOnly); if (!fileOnly) currentId = null; } /* @see IFormatReader#setGroupFiles(boolean) */ public void setGroupFiles(boolean group) { FormatTools.assertId(currentId, false, 2); for (int i=0; i<readers.length; i++) readers[i].setGroupFiles(group); } /* @see IFormatReader#isGroupFiles() */ public boolean isGroupFiles() { return getReader().isGroupFiles(); } /* @see IFormatReader#fileGroupOption(String) */ public int fileGroupOption(String id) throws FormatException, IOException { return getReader(id).fileGroupOption(id); } /* @see IFormatReader#isMetadataComplete() */ public boolean isMetadataComplete() { return getReader().isMetadataComplete(); } /* @see IFormatReader#setNormalized(boolean) */ public void setNormalized(boolean normalize) { FormatTools.assertId(currentId, false, 2); for (int i=0; i<readers.length; i++) readers[i].setNormalized(normalize); } /* @see IFormatReader#isNormalized() */ public boolean isNormalized() { // NB: all readers should have the same normalization setting return readers[0].isNormalized(); } /** * @deprecated * @see IFormatReader#setMetadataCollected(boolean) */ public void setMetadataCollected(boolean collect) { FormatTools.assertId(currentId, false, 2); for (int i=0; i<readers.length; i++) { readers[i].setMetadataCollected(collect); } } /** * @deprecated * @see IFormatReader#isMetadataCollected() */ public boolean isMetadataCollected() { return readers[0].isMetadataCollected(); } /* @see IFormatReader#setOriginalMetadataPopulated(boolean) */ public void setOriginalMetadataPopulated(boolean populate) { FormatTools.assertId(currentId, false, 1); for (int i=0; i<readers.length; i++) { readers[i].setOriginalMetadataPopulated(populate); } } /* @see IFormatReader#isOriginalMetadataPopulated() */ public boolean isOriginalMetadataPopulated() { return readers[0].isOriginalMetadataPopulated(); } /* @see IFormatReader#getCurrentFile() */ public String getCurrentFile() { if (currentId == null) return null; return getReader().getCurrentFile(); } /* @see IFormatReader#setMetadataFiltered(boolean) */ public void setMetadataFiltered(boolean filter) { FormatTools.assertId(currentId, false, 2); for (int i=0; i<readers.length; i++) readers[i].setMetadataFiltered(filter); } /* @see IFormatReader#isMetadataFiltered() */ public boolean isMetadataFiltered() { // NB: all readers should have the same metadata filtering setting return readers[0].isMetadataFiltered(); } /* @see IFormatReader#setMetadataStore(MetadataStore) */ public void setMetadataStore(MetadataStore store) { FormatTools.assertId(currentId, false, 2); for (int i=0; i<readers.length; i++) readers[i].setMetadataStore(store); } /* @see IFormatReader#getMetadataStore() */ public MetadataStore getMetadataStore() { return getReader().getMetadataStore(); } /* @see IFormatReader#getMetadataStoreRoot() */ public Object getMetadataStoreRoot() { return getReader().getMetadataStoreRoot(); } /* @see IFormatReader#getUnderlyingReaders() */ public IFormatReader[] getUnderlyingReaders() { return getReaders(); } /* @see IFormatReader#isSingleFile(String) */ public boolean isSingleFile(String id) throws FormatException, IOException { return getReader(id).isSingleFile(id); } /* @see IFormatReader#getDatasetStructureDescription() */ public String getDatasetStructureDescription() { return getReader().getDatasetStructureDescription(); } /* @see IFormatReader#hasCompanionFiles() */ public boolean hasCompanionFiles() { return getReader().hasCompanionFiles(); } /* @see IFormatReader#getPossibleDomains(String) */ public String[] getPossibleDomains(String id) throws FormatException, IOException { return getReader(id).getPossibleDomains(id); } /* @see IFormatReader#getDomains() */ public String[] getDomains() { return getReader().getDomains(); } /* @see IFormatReader#getOptimalTileWidth() */ public int getOptimalTileWidth() { return getReader().getOptimalTileWidth(); } /* @see IFormatReader#getOptimalTileHeight() */ public int getOptimalTileHeight() { return getReader().getOptimalTileHeight(); } /* @see IFormatReader#getResolutionCount() */ public int getResolutionCount() { return getReader().getResolutionCount(); } /* @see IFormatReader#setResolution(int) */ public void setResolution(int no) { getReader().setResolution(no); } /* @see IFormatReader#hasFlattenedResolutions() */ public boolean hasFlattenedResolutions() { return getReader().hasFlattenedResolutions(); } /* @see IFormatReader#setFlattenedResolutions(boolean) */ public void setFlattenedResolutions(boolean flattened) { for (IFormatReader reader : readers) { reader.setFlattenedResolutions(flattened); } } // -- IFormatHandler API methods -- /* @see IFormatHandler#isThisType(String) */ public boolean isThisType(String name) { // if necessary, open the file for further analysis // but check isThisType(name, false) first, for efficiency return isThisType(name, false) || isThisType(name, true); } /* @see IFormatHandler#getFormat() */ public String getFormat() { return getReader().getFormat(); } /* @see IFormatHandler#getSuffixes() */ public String[] getSuffixes() { if (suffixes == null) { HashSet<String> suffixSet = new HashSet<String>(); for (int i=0; i<readers.length; i++) { String[] suf = readers[i].getSuffixes(); for (int j=0; j<suf.length; j++) suffixSet.add(suf[j]); } suffixes = new String[suffixSet.size()]; suffixSet.toArray(suffixes); Arrays.sort(suffixes); } return suffixes; } /* @see IFormatHandler#getNativeDataType() */ public Class<?> getNativeDataType() { return getReader().getNativeDataType(); } /* @see IFormatHandler#setId(String) */ public void setId(String id) throws FormatException, IOException { getReader(id).setId(id); } /* @see IFormatHandler#close() */ public void close() throws IOException { close(false); } }
package gov.nih.nci.caadapter.common.util; import gov.nih.nci.caadapter.common.Log; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.util.HashMap; import java.util.List; import java.util.Properties; import java.util.Arrays; import java.util.ArrayList; import java.util.Enumeration; import java.util.Set; import java.util.StringTokenizer; public class CaadapterUtil { private static ArrayList<String> ACTIVATED_CAADAPTER_COMPONENTS =new ArrayList<String>(); private static ArrayList<String> INLINETEXT_ATTRIBUTES =new ArrayList<String>(); private static ArrayList<String> MANDATORY_SELECTED_ATTRIBUTES =new ArrayList<String>(); // private static ArrayList<String> RESOURCE_REQUIRED =new ArrayList<String>(); private static HashMap<String, ArrayList<String>> RESOURCE_MODULE_REQUIRED =new HashMap<String, ArrayList<String>>(); private static HashMap prefs; private static boolean authorizedUser=false; static { //mkdir for logging File logDir=new File("log"); if (!logDir.exists()) logDir.mkdir(); InputStream fi = null; //load caadapter component types to run Properties properties=new Properties(); try { File srcFile=new File("conf/caadapter-components.properties"); if (srcFile.exists()) { fi =new FileInputStream(srcFile); } else fi = CaadapterUtil.class.getClassLoader().getResource("caadapter-components.properties").openStream(); properties.load(fi); if (properties != null) { //read the value for each component and add it into the ActivatedList Enumeration propKeys=properties.keys(); while (propKeys.hasMoreElements()) { String onePropKey=(String)propKeys.nextElement(); String onePropValue=(String)properties.getProperty(onePropKey); if (onePropValue!=null&onePropValue.trim().equalsIgnoreCase("true")) { ACTIVATED_CAADAPTER_COMPONENTS.add(onePropKey); } } } //load datatypes require inlineText String inlineTextTypes=(String)properties.getProperty(Config.CAADAPTER_COMPONENT_HL7_SPECFICATION_ATTRIBUTE_INLINETEXT_REQUIRED); if (inlineTextTypes!=null) { StringTokenizer tk=new StringTokenizer(inlineTextTypes, ","); while(tk.hasMoreElements()) INLINETEXT_ATTRIBUTES.add((String)tk.nextElement()); } String mandatorySelectedAttributes=(String)properties.getProperty(Config.CAADAPTER_COMPONENT_HL7_SPECFICATION_ATTRIBUTE_MANDATORY_SELECTED); if (mandatorySelectedAttributes!=null) { StringTokenizer tk=new StringTokenizer(mandatorySelectedAttributes, ","); while(tk.hasMoreElements()) MANDATORY_SELECTED_ATTRIBUTES.add((String)tk.nextElement()); } fi.close(); Properties rsrcProp=new Properties(); fi = CaadapterUtil.class.getClassLoader().getResource("caadapter-resources.properties").openStream(); rsrcProp.load(fi); readResourceRequired(rsrcProp); } catch (Exception ex) { Log.logException(CaadapterUtil.class, "caadapter-components.properties is not found", ex); } finally { if (fi != null) try { fi.close(); } catch (IOException ignore) { } } readPreferencesMap(); } private static void readResourceRequired(Properties prop) { //it is not required for webstart installation if (ACTIVATED_CAADAPTER_COMPONENTS.contains(Config.CAADAPTER_COMPONENT_WEBSTART_ACTIVATED)) return; //always add common required addModuleResource(Config.CAADAPTER_COMMON_RESOURCE_REQUIRED,prop); if (ACTIVATED_CAADAPTER_COMPONENTS.contains(Config.CAADAPTER_COMPONENT_HL7_TRANSFORMATION_ACTIVATED)) addModuleResource(Config.CAADAPTER_HL7_TRANSFORMATION_RESOURCE_REQUIRED,prop); if (ACTIVATED_CAADAPTER_COMPONENTS.contains(Config.CAADAPTER_COMPONENT_HL7_V2V3_CONVERSION_ACTIVATED)) addModuleResource(Config.CAADAPTER_HL7_V2V3_CONVERSION_RESOURCE_REQUIRED,prop); if (ACTIVATED_CAADAPTER_COMPONENTS.contains(Config.CAADAPTER_QUERYBUILDER_MENU_ACTIVATED)) addModuleResource(Config.CAADAPTER_QUERYBUILDER_RESOURCE_REQUIRED,prop); } private static void addModuleResource(String moduleName, Properties prop) { ArrayList moduleRsc=RESOURCE_MODULE_REQUIRED.get(moduleName); if (moduleRsc==null) moduleRsc=new ArrayList<String>(); String rsrcList=prop.getProperty(moduleName); StringTokenizer tk=new StringTokenizer(rsrcList, ","); while(tk.hasMoreElements()) { String nxtRsc=(String)tk.nextElement(); if (!moduleRsc.contains(nxtRsc)) moduleRsc.add(nxtRsc); } RESOURCE_MODULE_REQUIRED.put(moduleName, moduleRsc); } // getters. public static final ArrayList getInlineTextAttributes() { return INLINETEXT_ATTRIBUTES; } public static final ArrayList getAllActivatedComponents() { return ACTIVATED_CAADAPTER_COMPONENTS; } public static final ArrayList getMandatorySelectedAttributes() { return MANDATORY_SELECTED_ATTRIBUTES; } public static ArrayList getAllResourceRequired() { ArrayList<String>rtnList=new ArrayList<String>(); Set<String> keySet=RESOURCE_MODULE_REQUIRED.keySet(); for(String keyValue:keySet) { ArrayList<String> modRsc=RESOURCE_MODULE_REQUIRED.get(keyValue); for (String rsrc:modRsc) { if (!rtnList.contains(rsrc)) rtnList.add(rsrc); } } return rtnList; } public static ArrayList<String> getModuleResourceMissed(String moduleName) { ArrayList <String> missRsrc=new ArrayList<String>(); File libFile=new File("lib"); if (!libFile.exists()||!libFile.isDirectory()) return missRsrc; String[] libRsrc=libFile.list(); List<String> foundRsrc=Arrays.asList(libRsrc); ArrayList<String> requiredRsc; if (moduleName==null|moduleName.equals("")) requiredRsc=getAllResourceRequired(); else requiredRsc=RESOURCE_MODULE_REQUIRED.get(moduleName); if (requiredRsc!=null) for (String rsrc:requiredRsc) { if (!foundRsrc.contains(rsrc)) missRsrc.add(rsrc); } //always include the common resource list if (!moduleName.equals(Config.CAADAPTER_COMMON_RESOURCE_REQUIRED)) { requiredRsc=RESOURCE_MODULE_REQUIRED.get(Config.CAADAPTER_COMMON_RESOURCE_REQUIRED); if (requiredRsc!=null) for (String rsrc:requiredRsc) { if (!foundRsrc.contains(rsrc) &&!missRsrc.contains(rsrc)) missRsrc.add(rsrc); } } return missRsrc; } /** * Move this method from GeneralUtilities * @param objectArray * @param separator * @return */ public static String join(Object[] objectArray, String separator){ if (objectArray == null) return null; String[] stringArray = new String[objectArray.length]; for (int i = 0; i < objectArray.length; i++) { stringArray[i] = "" + objectArray[i]; } return join(stringArray, separator); } //copied the following method from javaSIG source code //decouple the dependence of "common" component from javaSIG /** * Joins a string array into one string with <code>separator</code> * between elements. * * @param as array of tokens to join * @param separator separator character * @return the joined string */ private static String join(String[] as, String separator) { if (as == null) return null; else if (as.length == 1) return as[0]; else { StringBuffer sb = new StringBuffer(); for (int i = 0; i < as.length; ++i) { if (i > 0) sb.append(separator); sb.append(as[i]); } return sb.toString(); } } private static void readPreferencesMap() { prefs=new HashMap(); try { FileInputStream f_out = new FileInputStream(System.getProperty("user.home") + "\\.caadapter"); ObjectInputStream obj_out = new ObjectInputStream(f_out); prefs = (HashMap) obj_out.readObject(); //System.out.println(prefs); } catch (Exception e) { e.printStackTrace(); } } public static HashMap getCaAdapterPreferences() { return prefs; } public static void setCaAdapterPreferences(HashMap _prefs){ prefs = _prefs; } /** * Read a preference value given its key as a string * * @param key -- The key value of a preference * @return A preference value as a string */ public static String readPrefParams(String key) { HashMap prefs = CaadapterUtil.getCaAdapterPreferences(); if (prefs == null) return null; return (String) prefs.get(key); } public static void savePrefParams(String key, String value) { try { if (CaadapterUtil.getCaAdapterPreferences() != null) { CaadapterUtil.getCaAdapterPreferences().put(key, value); } else { HashMap tempMap = new HashMap(); tempMap.put(key, value); CaadapterUtil.setCaAdapterPreferences(tempMap); } } catch (Exception e) { e.printStackTrace(); } } public static boolean isAuthorizedUser() { return authorizedUser; } public static void setAuthorizedUser(boolean authorizedUser) { CaadapterUtil.authorizedUser = authorizedUser; } }
package gov.nih.nci.caadapter.common.util; import gov.nih.nci.caadapter.common.Log; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.util.HashMap; import java.util.List; import java.util.Properties; import java.util.Arrays; import java.util.ArrayList; import java.util.Enumeration; import java.util.Set; import java.util.StringTokenizer; public class CaadapterUtil { private static ArrayList<String> ACTIVATED_CAADAPTER_COMPONENTS =new ArrayList<String>(); private static ArrayList<String> INLINETEXT_ATTRIBUTES =new ArrayList<String>(); private static ArrayList<String> MANDATORY_SELECTED_ATTRIBUTES =new ArrayList<String>(); // private static ArrayList<String> RESOURCE_REQUIRED =new ArrayList<String>(); private static HashMap<String, ArrayList<String>> RESOURCE_MODULE_REQUIRED =new HashMap<String, ArrayList<String>>(); private static HashMap prefs; private static boolean authorizedUser=false; static { //mkdir for logging File logDir=new File("log"); if (!logDir.exists()) logDir.mkdir(); InputStream fi = null; //load caadapter component types to run Properties properties=new Properties(); try { File srcFile=new File("conf/caadapter-components.properties"); if (srcFile.exists()) { fi =new FileInputStream(srcFile); } else fi = CaadapterUtil.class.getClassLoader().getResource("caadapter-components.properties").openStream(); properties.load(fi); if (properties != null) { //read the value for each component and add it into the ActivatedList Enumeration propKeys=properties.keys(); while (propKeys.hasMoreElements()) { String onePropKey=(String)propKeys.nextElement(); String onePropValue=(String)properties.getProperty(onePropKey); if (onePropValue!=null&onePropValue.trim().equalsIgnoreCase("true")) { ACTIVATED_CAADAPTER_COMPONENTS.add(onePropKey); } } } //load datatypes require inlineText String inlineTextTypes=(String)properties.getProperty(Config.CAADAPTER_COMPONENT_HL7_SPECFICATION_ATTRIBUTE_INLINETEXT_REQUIRED); if (inlineTextTypes!=null) { StringTokenizer tk=new StringTokenizer(inlineTextTypes, ","); while(tk.hasMoreElements()) INLINETEXT_ATTRIBUTES.add((String)tk.nextElement()); } String mandatorySelectedAttributes=(String)properties.getProperty(Config.CAADAPTER_COMPONENT_HL7_SPECFICATION_ATTRIBUTE_MANDATORY_SELECTED); if (mandatorySelectedAttributes!=null) { StringTokenizer tk=new StringTokenizer(mandatorySelectedAttributes, ","); while(tk.hasMoreElements()) MANDATORY_SELECTED_ATTRIBUTES.add((String)tk.nextElement()); } fi.close(); Properties rsrcProp=new Properties(); fi = CaadapterUtil.class.getClassLoader().getResource("caadapter-resources.properties").openStream(); rsrcProp.load(fi); readResourceRequired(rsrcProp); } catch (Exception ex) { Log.logException(CaadapterUtil.class, "caadapter-components.properties is not found", ex); } finally { if (fi != null) try { fi.close(); } catch (IOException ignore) { } } readPreferencesMap(); } private static void readResourceRequired(Properties prop) { //it is not required for webstart installation if (ACTIVATED_CAADAPTER_COMPONENTS.contains(Config.CAADAPTER_COMPONENT_WEBSTART_ACTIVATED)) return; //always add common required addModuleResource(Config.CAADAPTER_COMMON_RESOURCE_REQUIRED,prop); //no additional resource is required except the common ones if (ACTIVATED_CAADAPTER_COMPONENTS.contains(Config.CAADAPTER_CSV_XMI_MENU_ACTIVATED)) return; if (ACTIVATED_CAADAPTER_COMPONENTS.contains(Config.CAADAPTER_COMPONENT_HL7_TRANSFORMATION_ACTIVATED)) addModuleResource(Config.CAADAPTER_HL7_TRANSFORMATION_RESOURCE_REQUIRED,prop); if (ACTIVATED_CAADAPTER_COMPONENTS.contains(Config.CAADAPTER_COMPONENT_HL7_V2V3_CONVERSION_ACTIVATED)) addModuleResource(Config.CAADAPTER_HL7_V2V3_CONVERSION_RESOURCE_REQUIRED,prop); if (ACTIVATED_CAADAPTER_COMPONENTS.contains(Config.CAADAPTER_QUERYBUILDER_MENU_ACTIVATED)) addModuleResource(Config.CAADAPTER_QUERYBUILDER_RESOURCE_REQUIRED,prop); } private static void addModuleResource(String moduleName, Properties prop) { ArrayList moduleRsc=RESOURCE_MODULE_REQUIRED.get(moduleName); if (moduleRsc==null) moduleRsc=new ArrayList<String>(); String rsrcList=prop.getProperty(moduleName); StringTokenizer tk=new StringTokenizer(rsrcList, ","); while(tk.hasMoreElements()) { String nxtRsc=(String)tk.nextElement(); if (!moduleRsc.contains(nxtRsc)) moduleRsc.add(nxtRsc); } RESOURCE_MODULE_REQUIRED.put(moduleName, moduleRsc); } // getters. public static final ArrayList getInlineTextAttributes() { return INLINETEXT_ATTRIBUTES; } public static final ArrayList getAllActivatedComponents() { return ACTIVATED_CAADAPTER_COMPONENTS; } public static final ArrayList getMandatorySelectedAttributes() { return MANDATORY_SELECTED_ATTRIBUTES; } public static ArrayList getAllResourceRequired() { ArrayList<String>rtnList=new ArrayList<String>(); Set<String> keySet=RESOURCE_MODULE_REQUIRED.keySet(); for(String keyValue:keySet) { ArrayList<String> modRsc=RESOURCE_MODULE_REQUIRED.get(keyValue); for (String rsrc:modRsc) { if (!rtnList.contains(rsrc)) rtnList.add(rsrc); } } return rtnList; } public static ArrayList<String> getModuleResourceMissed(String moduleName) { ArrayList <String> missRsrc=new ArrayList<String>(); File libFile=new File("lib"); if (!libFile.exists()||!libFile.isDirectory()) return missRsrc; String[] libRsrc=libFile.list(); List<String> foundRsrc=Arrays.asList(libRsrc); ArrayList<String> requiredRsc; if (moduleName==null|moduleName.equals("")) requiredRsc=getAllResourceRequired(); else requiredRsc=RESOURCE_MODULE_REQUIRED.get(moduleName); if (requiredRsc!=null) for (String rsrc:requiredRsc) { if (!foundRsrc.contains(rsrc)) missRsrc.add(rsrc); } //always include the common resource list if (!moduleName.equals(Config.CAADAPTER_COMMON_RESOURCE_REQUIRED)) { requiredRsc=RESOURCE_MODULE_REQUIRED.get(Config.CAADAPTER_COMMON_RESOURCE_REQUIRED); if (requiredRsc!=null) for (String rsrc:requiredRsc) { if (!foundRsrc.contains(rsrc) &&!missRsrc.contains(rsrc)) missRsrc.add(rsrc); } } return missRsrc; } /** * Move this method from GeneralUtilities * @param objectArray * @param separator * @return */ public static String join(Object[] objectArray, String separator){ if (objectArray == null) return null; String[] stringArray = new String[objectArray.length]; for (int i = 0; i < objectArray.length; i++) { stringArray[i] = "" + objectArray[i]; } return join(stringArray, separator); } //copied the following method from javaSIG source code //decouple the dependence of "common" component from javaSIG /** * Joins a string array into one string with <code>separator</code> * between elements. * * @param as array of tokens to join * @param separator separator character * @return the joined string */ private static String join(String[] as, String separator) { if (as == null) return null; else if (as.length == 1) return as[0]; else { StringBuffer sb = new StringBuffer(); for (int i = 0; i < as.length; ++i) { if (i > 0) sb.append(separator); sb.append(as[i]); } return sb.toString(); } } private static void readPreferencesMap() { prefs=new HashMap(); try { FileInputStream f_out = new FileInputStream(System.getProperty("user.home") + "\\.caadapter"); ObjectInputStream obj_out = new ObjectInputStream(f_out); prefs = (HashMap) obj_out.readObject(); //System.out.println(prefs); } catch (Exception e) { e.printStackTrace(); } } public static HashMap getCaAdapterPreferences() { return prefs; } public static void setCaAdapterPreferences(HashMap _prefs){ prefs = _prefs; } /** * Read a preference value given its key as a string * * @param key -- The key value of a preference * @return A preference value as a string */ public static String readPrefParams(String key) { HashMap prefs = CaadapterUtil.getCaAdapterPreferences(); if (prefs == null) return null; return (String) prefs.get(key); } public static void savePrefParams(String key, String value) { try { if (CaadapterUtil.getCaAdapterPreferences() != null) { CaadapterUtil.getCaAdapterPreferences().put(key, value); } else { HashMap tempMap = new HashMap(); tempMap.put(key, value); CaadapterUtil.setCaAdapterPreferences(tempMap); } } catch (Exception e) { e.printStackTrace(); } } public static boolean isAuthorizedUser() { return authorizedUser; } public static void setAuthorizedUser(boolean authorizedUser) { CaadapterUtil.authorizedUser = authorizedUser; } }
package au.edu.federation.caliko.visualisation; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import au.edu.federation.utils.Vec3f; import au.edu.federation.utils.Vec3i; //TODO: This is pretty ineficient - change all the for..each loops to be normals loops to stop Java allocating memory. //TODO: Also provide a proper copy-constructor rather than a clone method - they should do the same thing. /** * A class to represent and load a 3D model in WaveFront .OBJ format. * <p> * Vertices, normals, and faces with or without normal indices are supported. * <p> * Models must be stored as triangles, not quads. * <p> * There is no support for textures, texture coordinates, or grouped objects at this time. * * @author Al Lansley * @version 0.5.1 - 07/01/2016 */ public class Model { private static boolean VERBOSE = false; private static final String NUMBER_OF_VERTICES_LOG = "Number of vertices in data array: %d (%d bytes)"; private static final String NUMBER_OF_NORMALS_LOG = "Number of normals in data array: %d (%d bytes)"; private static final String WRONG_COMPONENT_COUNT_LOG = "Found %s data with wrong component count at line number: %d - Skipping!"; // These are the models values as read from the file - they are not the final, consolidated model data private List<Vec3f> vertices = new ArrayList<>(); private List<Vec3f> normals = new ArrayList<>(); private List<Vec3i> normalIndices = new ArrayList<>(); private List<Vec3i> faces = new ArrayList<>(); //ArrayList texCoords = new ArrayList<Vector>(); // The vertexData and normalData arrays are the final consolidated data which we can draw with. // Note: If the model has only vertices and/or normals, then the vertexData and normalData will be a direct 'unwrapped' // version of the vertices and normals arrays. However, if we're using faces then there will likely be a lower number of // vertices / normals as each vertex / normal may be used more than once in the model - the end result of this is that // the vertexData and normalData will likely be larger than the 'as-read-from-file' vertices and normals arrays because // of this duplication of values from the face data. private List<Float> vertexData = new ArrayList<>(); private List<Float> normalData = new ArrayList<>(); //ArrayList texCoordData = new ArrayList<Vector>(); // Counters to keep track of how many vertices, normals, normal indices, texture coordinates and faces private int numVertices; private int numNormals; private int numNormalIndices; private int numFaces; //private int numTexCoords; /** Default constructor. */ public Model() { } /** * Constructor which creates a model object and loads the model from file. * * @param filename The file to load the model data from. */ public Model(String filename) { load(filename); } /** Enable verbose messages. */ public static void enableVerbose() { VERBOSE = true; } /** Disable verbose messages. */ public static void disableVerbose() { VERBOSE = false; } // Method provide create a deep copy of a Model so we can say copyOfMyModel.equals(myModel); // Note: We only deep copy the vertexData and normalData arrays, not all the vectors! public static Model clone(Model sourceModel) { // Create a new Model which we will clone across the data to from our source model Model model = new Model(); // Update the counts of vertices and normals for the clone to match the source model model.numVertices = sourceModel.getNumVertices(); model.numNormals = sourceModel.getNumNormals(); // If the source model has vertices then copy them across to the clone... if (model.numVertices > 0) { // For (foo IN bar) loops leak memory - go old-school int vertCount = sourceModel.getNumVertices(); for (int loop = 0; loop < vertCount; loop++) { //model.vertexData.add(f) } for ( Float f : sourceModel.getVertexData() ) { model.vertexData.add(f); } } else // ...or abort if we have no vertices to copy! { throw new RuntimeException("Model created using clone method has 0 vertices!"); } // If the source model has normals then copy them across to the clone... if (model.numNormals > 0) { for ( Float f : sourceModel.getNormalData() ) { model.normalData.add(f); } } else // ...or (potentially) inform the user if they are no normals. This is not necessarily a deal breaker though, so we don't abort. { if (VERBOSE) { System.out.println( "Model created using clone method has 0 normals - continuing..."); } } // Display final status if appropriate if (VERBOSE) { System.out.println( "Model successfully cloned."); } // Finally, return our cloned model return model; } /** * Load a .OBJ model from file. * <p> * By default, no feedback is provided on the model loading. If you wish to see what's going on * internally, call Model.enableVerbose() before loading the model - this will display statistics * about any vertices/normals/normal indices/faces found in the model, as well as any malformed data. * <p> * If the model file does not contain any vertices then a RuntimeException is thrown. * If the file cannot be found then a FileNotFoundException is thrown. * If there was a file-system-type error when reading the file then an IOException is thrown. * * @param filename The name of the Wavefront .OBJ format model to load, include the path if necessary. * @return Whether the file loaded successfully or not. Loading with warnings still counts as a * successful load - if necessary enable verbose mode to ensure your model loaded cleanly. */ public boolean load(String filename) { // Load the model file boolean modelLoadedCleanly = loadModel(filename); // Did we load the file without errors? if (VERBOSE) { if (modelLoadedCleanly) { System.out.println("Model loaded cleanly."); } else { System.out.println("Model loaded with errors."); } } // Do we have vertices? If not then this is a non-recoverable error and we abort! if ( hasVertices() ) { if (VERBOSE) { System.out.println("Model vertex count: " + getNumVertices() ); if ( hasFaces() ) { System.out.println( "Model face count: " + getNumFaces() ); } if ( hasNormals() ) { System.out.println( "Model normal count: " + getNumNormals() ); } if ( hasNormalIndices() ) { System.out.println( "Model normal index count: " + getNumNormalIndices() ); } } } else { throw new RuntimeException("Model has no vertices."); } // Transfer the loaded data in our vectors to the data arrays setupData(); // Delete the vertices, normals, normalIndices and faces Lists as we now have the final // data stored in the vertexData and normalData Lists. vertices.clear(); normals.clear(); normalIndices.clear(); faces.clear(); vertices = null; normals = null; normalIndices = null; faces = null; // Indicate that the model loaded successfully return true; } /** * Get the vertex data as a list of floats. * * @return The vertex data. */ public List<Float> getVertexData() { return vertexData; } /** * Get the vertex normals as a list of floats. * * @return The vertex normal data. */ public List<Float> getNormalData() { return normalData; } /** * Get the vertex data as a float array suitable for transfer into a FloatBuffer for drawing. * * @return The vertex data as a float array. **/ public float[] getVertexFloatArray() { // How many floats are there in our list of vertex data? int numVertexFloats = vertexData.size(); // Create an array big enough to hold them float[] vertexFloatArray = new float[numVertexFloats]; // Loop over each item in the list, setting it to the appropriate element in the array for (int loop = 0; loop < numVertexFloats; loop++) { vertexFloatArray[loop] = vertexData.get(loop); } // Finally, return the float array return vertexFloatArray; } /** * Get the vertex normal data as a float array suitable for transfer into a FloatBuffer for drawing. * * @return The vertex normal data as a float array. */ public float[] getNormalFloatArray() { // How many floats are there in our list of normal data? int numNormalFloats = normalData.size(); // Create an array big enough to hold them float[] normalFloatArray = new float[numNormalFloats]; // Loop over each item in the list, setting it to the appropriate element in the array for (int loop = 0; loop < numNormalFloats; loop++) { normalFloatArray[loop] = normalData.get(loop); } // Finally, return the float array return normalFloatArray; } // Methods to get the sizes of various data arrays // Note: Type.BYTES returns the size of on object of this type in Bytes, and we multiply // by 3 because there are 3 components to a vertex (x/y/z), normal (s/t/p) and 3 vertexes comprising a face (i.e. triangle) /** * Get the vertex data size in bytes. * * @return The vertex data size in bytes. */ public int getVertexDataSizeBytes() { return numVertices * 3 * Float.BYTES; } /** * Get the vertex normal data size in bytes. * * @return The vertex normal data size in bytes. */ public int getNormalDataSizeBytes() { return numNormals * 3 * Float.BYTES; } /** * Get the face data size in bytes. * * @return The face data size in bytes. **/ public int getFaceDataSizeBytes() { return numFaces * 3 * Integer.BYTES; } /** * Get the number of vertices in this model. * * @return The number of vertices in this model. */ public int getNumVertices() { return numVertices; } /** * Get the number of vertex normals in this model. * * @return The number of normals in this model. */ public int getNumNormals() { return numNormals; } /** Get the number of normal indices in this model. * * * @return The number of normal indices in this model. */ public int getNumNormalIndices() { return numNormalIndices; } /** * Get the number of faces in this model. * * @return The number of faces in this model. */ public int getNumFaces() { return numFaces; } /** * Scale this model uniformly along the x/y/z axes. * * @param scale The amount to scale the model. **/ public void scale(float scale) { int numVerts = vertexData.size(); for (int loop = 0; loop < numVerts; ++loop) { vertexData.set(loop, vertexData.get(loop) * scale); } } /** * Scale this model on the X axis. * * @param scale The amount to scale the model on the X axis. */ public void scaleX(float scale) { int numVerts = vertexData.size(); for (int loop = 0; loop < numVerts; loop += 3) { vertexData.set( loop, vertexData.get(loop) * scale); } } /** * Scale this model on the Y axis. * * @param scale The amount to scale the model on the Y axis. */ public void scaleY(float scale) { int numVerts = vertexData.size(); for (int loop = 1; loop < numVerts; loop += 3) { vertexData.set( loop, vertexData.get(loop) * scale); } } /** * Scale this model on the Z axis. * * @param scale The amount to scale the model on the Z axis. */ public void scaleZ(float scale) { int numVerts = vertexData.size(); for (int loop = 2; loop < numVerts; loop += 3) { vertexData.set( loop, vertexData.get(loop) * scale); } } /** * Scale this model by various amounts along separate axes. * * @param xScale The amount to scale the model on the X axis. * @param yScale The amount to scale the model on the Y axis. * @param zScale The amount to scale the model on the Z axis. */ public void scale(float xScale, float yScale, float zScale) { int numVerts = vertexData.size(); for (int loop = 0; loop < numVerts; ++loop) { switch (loop % 3) { case 0: vertexData.set(loop, vertexData.get(loop) * xScale); break; case 1: vertexData.set(loop, vertexData.get(loop) * yScale); break; case 2: vertexData.set(loop, vertexData.get(loop) * zScale); break; } } } /** Print out the vertices of this model. */ public void printVertices() { for (Vec3f v : vertices) { System.out.println( "Vertex: " + v.toString() ); } } /** * Print out the vertex normal data for this model. * <p> * Note: This is the contents of the normals list, not the (possibly expanded) normalData array. */ public void printNormals() { for (Vec3f n : normals) { System.out.println( "Normal: " + n.toString() ); } } /** * Print the face data of this model. * <p> * Note: Faces are ONE indexed, not zero indexed. */ public void printFaces() { for (Vec3i face : faces) { System.out.println( "Face: " + face.toString() ); } } /** * Print the vertex data of this model. * <p> * Note: This is the contents of the vertexlData array which is actually used when drawing - and which may be * different to the 'vertices' list when using faces (where vertices get re-used). */ public void printVertexData() { for (int loop = 0; loop < vertexData.size(); loop += 3) { System.out.println( "Vertex data element " + (loop / 3) + " is x: " + vertexData.get(loop) + "\ty: " + vertexData.get(loop+1) + "\tz: " + vertexData.get(loop+2) ); } } /** * Print the normal data of this model. * <p> * Note: This is the contents of the normalData array which is actually used when drawing - and which may be * different to the 'normals' list when using faces (where normals get re-used). */ public void printNormalData() { for (int loop = 0; loop < normalData.size(); loop += 3) { System.out.println( "Normal data element " + (loop / 3) + " is x: " + normalData.get(loop) + "\ty: " + normalData.get(loop+1) + "\tz: " + normalData.get(loop+2)); } } // Method to read through the model file adding all vertices, faces and normals to our // vertices, faces and normals vectors. // Note: This does NOT transfer the data into our vertexData, faceData or normalData arrays! // That must be done as a separate step by calling setupData() after building up the // arraylists with this method! // Also: This method does not decrement the face number of normal index by 1 (because .OBJ // files start their counts at 1) to put them in a range starting from 0, that job // is done in the setupData() method performed after calling this method! private boolean loadModel(String filename) { // Initialise lists vertices = new ArrayList<>(); normals = new ArrayList<>(); normalIndices = new ArrayList<>(); faces = new ArrayList<>(); //texCoords = new ArrayList<Vec2f(); vertexData = new ArrayList<>(); normalData = new ArrayList<>(); //texCoordData = new ArrayList<Vec2f>(); // Our vectors of attributes are initially empty numVertices = 0; numNormals = 0; numNormalIndices = 0; numFaces = 0; //numTexCoords = 0; boolean loadedCleanly = true; // Counter to keep track of what line we're on int lineCount = 0; // Use this for jar packaged resources InputStream is = this.getClass().getResourceAsStream(filename); try (BufferedReader br = new BufferedReader( new InputStreamReader(is) ) ) // This version loads from within jar archive, required for caliko-demo-jar-with-resources.jar //try (BufferedReader br = new BufferedReader( new FileReader(filename) ) ) // Use this for loading from file in Eclipse or such { // We'll read through the file one line at a time - this will hold the current line we're working on String line; // While there are lines left to read in the file... while ((line = br.readLine()) != null) { ++lineCount; // If the line isn't empty (the 1 character is the carriage return), process it... if (line.length() > 1) { // Split line on spaces into an array of strings.The + on the end of "\\s+" means 'do not accept // blank entries' which can occur if you have two consecutive space characters (as happens when // you export a .obj from 3ds max - you get "v 1.23 4.56 7.89" etc.) String[] token = line.split("\\s+"); // If the first token is "v", then we're dealing with vertex data if ( "v".equalsIgnoreCase(token[0]) ) { // As long as there's 4 tokens on the line... if (token.length == 4) { // ...get the remaining 3 tokens as the x/y/z float values... float x = Float.parseFloat(token[1]); float y = Float.parseFloat(token[2]); float z = Float.parseFloat(token[3]); // ... and push them into the vertices vector ... vertices.add( new Vec3f(x, y, z) ); // .. then increase our vertex count. numVertices++; } else // If we got vertex data without 3 components - whine! { loadedCleanly = false; System.out.printf(WRONG_COMPONENT_COUNT_LOG,"vertex",lineCount); } } else if ( "vn".equalsIgnoreCase(token[0]) ) // If the first token is "vn", then we're dealing with a vertex normal { // As long as there's 4 tokens on the line... if (token.length == 4) { // ...get the remaining 3 tokens as the x/y/z normal float values... float normalX = Float.parseFloat(token[1]); float normalY = Float.parseFloat(token[2]); float normalZ = Float.parseFloat(token[3]); // ... and push them into the normals vector ... normals.add( new Vec3f(normalX, normalY, normalZ) ); // .. then increase our normal count. numNormals++; } else // If we got normal data without 3 components - whine! { loadedCleanly = false; System.out.printf(WRONG_COMPONENT_COUNT_LOG,"normal",lineCount); } } // End of vertex line parsing // If the first token is "f", then we're dealing with faces // Note: Faces can be described in two ways - we can have data like 'f 123 456 789' which means that the face is comprised // of vertex 123, vertex 456 and vertex 789. Or, we have have data like f 123//111 456//222 789//333 which means that // the face is comprised of vertex 123 using normal 111, vertex 456 using normal 222 and vertex 789 using normal 333. else if ( "f".equalsIgnoreCase(token[0]) ) { // Check if there's a double-slash in the line int pos = line.indexOf(" // As long as there's four tokens on the line and they don't contain a "//"... if ( (token.length == 4) && (pos == -1) ) { // ...get the face vertex numbers as ints ... int v1 = Integer.parseInt(token[1]); int v2 = Integer.parseInt(token[2]); int v3 = Integer.parseInt(token[3]); // ... and push them into the faces vector ... faces.add( new Vec3i(v1, v2, v3) ); // .. then increase our face count. numFaces++; } else if ( (token.length == 4) && (pos != -1) ) // 4 tokens and found 'vertex//normal' notation? { // Find where the double-slash starts in that token int faceEndPos = token[1].indexOf(" // Put sub-String from the start to the beginning of the double-slash into our subToken String String faceToken1 = token[1].substring(0, faceEndPos); // Convert face token value to int int ft1 = Integer.parseInt(faceToken1); // Mark the start of our next subtoken int nextTokenStartPos = faceEndPos + 2; // Copy from first character after the "//" to the end of the token String normalToken1 = token[1].substring(nextTokenStartPos); // Convert normal token value to int int nt1 = Integer.parseInt(normalToken1); // Find where the double-slash starts in that token faceEndPos = token[2].indexOf(" // Put sub-String from the start to the beginning of the double-slash into our subToken String String faceToken2 = token[2].substring(0, faceEndPos); // Convert face token value to int int ft2 = Integer.parseInt(faceToken2); // Mark the start of our next subtoken nextTokenStartPos = faceEndPos + 2; // Copy from first character after the "//" to the end of the token String normalToken2 = token[2].substring(nextTokenStartPos); // Convert normal token value to int int nt2 = Integer.parseInt(normalToken2); // Find where the double-slash starts in that token faceEndPos = token[3].indexOf(" // Put sub-String from the start to the beginning of the double-slash into our subToken String String faceToken3 = token[3].substring(0, faceEndPos); // Convert face token value to int int ft3 = Integer.parseInt(faceToken3); // Mark the start of our next subtoken nextTokenStartPos = faceEndPos + 2; // Copy from first character after the "//" to the end String normalToken3 = token[3].substring(nextTokenStartPos); // Convert normal token value to int int nt3 = Integer.parseInt(normalToken3); // Finally, add the face to the faces array list and increment the face count... faces.add( new Vec3i(ft1, ft2, ft3) ); numFaces++; // ...and do the same for the normal indices and the normal index count. normalIndices.add( new Vec3i(nt1, nt2, nt3) ); numNormalIndices++; } else // If we got face data without 3 components - whine! { loadedCleanly = false; System.out.printf(WRONG_COMPONENT_COUNT_LOG,"face",lineCount); } } // End of if token is "f" (i.e. face indices) // IMPLIED ELSE: If first token is something we don't recognise then we ignore it as a comment. } // End of line parsing section } // End of if line length > 1 check // No need to close the file ( i.e. br.close() ) - try-with-resources does that for us. } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } // Return our boolean flag to say whether we loaded the model cleanly or not return loadedCleanly; } /** * Return whether or not this model contains vertex data. * * @return whether or not this model contains vertex data. */ public boolean hasVertices() { return (numVertices > 0); } /** * Return whether or not this model contains face data. * * @return whether or not this model contains face data. */ public boolean hasFaces() { return (numFaces > 0); } /** * Return whether or not this model contains normal data. * * @return whether or not this model contains normal data. */ public boolean hasNormals() { return (numNormals > 0); } /** * Return whether or not this model contains normal index data. * * @return whether or not this model contains normal index data. */ public boolean hasNormalIndices() { return (numNormalIndices > 0); } /** * Set up our plain arrays of floats for OpenGL to work with. * <p> * Note: We CANNOT have size mismatches! The vertex count must match the * normal count i.e. every vertex must have precisely ONE normal - no more, no less! */ private void setupData() { if (VERBOSE) { System.out.println( "Setting up model data to draw as arrays."); } // If we ONLY have vertex data, then transfer just that... if ( ( hasVertices() ) && ( !hasFaces() ) && ( !hasNormals() ) ) { if (VERBOSE) { System.out.println( "Model has no faces or normals. Transferring vertex data only."); } // Reset the vertex count numVertices = 0; // Transfer all vertices from the vertices vector to the vertexData array for (Vec3f v : vertices) { vertexData.add( v.x ); vertexData.add( v.y ); vertexData.add( v.z ); ++numVertices; } // Print a summary of the vertex data if (VERBOSE) { System.out.printf( NUMBER_OF_VERTICES_LOG, numVertices, getVertexDataSizeBytes()); } } // If we have vertices AND faces BUT NOT normals... else if ( ( hasVertices() ) && ( hasFaces() ) && ( !hasNormals() ) ) { if (VERBOSE) { System.out.println("Model has vertices and faces, but no normals. Per-face normals will be generated.") ; } // Create the vertexData and normalData arrays from the vector of faces // Note: We generate the face normals ourselves. int vertexCount = 0; int normalCount = 0; for (Vec3i iv : faces) { // Get the numbers of the three vertices that this face is comprised of int firstVertexNum = iv.x; int secondVertexNum = iv.y; int thirdVertexNum = iv.z; // Now that we have the vertex numbers, we need to get the actual vertices // Note: We subtract 1 from the number of the vertex because faces start at // face number 1 in the .OBJ format, while in our code the first vertex // will be at location zero. Vec3f faceVert1 = vertices.get(firstVertexNum - 1); Vec3f faceVert2 = vertices.get(secondVertexNum - 1); Vec3f faceVert3 = vertices.get(thirdVertexNum - 1); // Now that we have the 3 vertices, we need to calculate the normal of the face // formed by these vertices... // Convert this vertex data into a pure form Vec3f v1 = faceVert2.minus(faceVert1); Vec3f v2 = faceVert3.minus(faceVert1); // Generate the normal as the cross product and normalise it Vec3f normal = v1.cross(v2); Vec3f normalisedNormal = normal.normalise(); // Put the vertex data into our vertexData array vertexData.add( faceVert1.x ); vertexData.add( faceVert1.y ); vertexData.add( faceVert1.z ); vertexCount++; vertexData.add( faceVert2.x ); vertexData.add( faceVert2.y ); vertexData.add( faceVert2.z ); vertexCount++; vertexData.add( faceVert3.x ); vertexData.add( faceVert3.y ); vertexData.add( faceVert3.z ); vertexCount++; // Put the normal data into our normalData array // Note: we put the same normal into the normalData array for each of the 3 vertices comprising the face! // This gives use a 'faceted' looking model, but is easy! You could try to calculate an interpolated // normal based on surrounding normals, but that's not a trivial task (although 3ds max will do it for you // if you load up the model and export it with normals!) normalData.add( normalisedNormal.x ); normalData.add( normalisedNormal.y ); normalData.add( normalisedNormal.z ); normalCount++; normalData.add( normalisedNormal.x ); normalData.add( normalisedNormal.y ); normalData.add( normalisedNormal.z ); normalCount++; normalData.add( normalisedNormal.x ); normalData.add( normalisedNormal.y ); normalData.add( normalisedNormal.z ); normalCount++; } // End of loop iterating over the model faces numVertices = vertexCount; numNormals = normalCount; if (VERBOSE) { System.out.printf( NUMBER_OF_VERTICES_LOG, numVertices, getVertexDataSizeBytes()); System.out.printf( NUMBER_OF_NORMALS_LOG, numNormals, getNormalDataSizeBytes()); } } // If we have vertices AND faces AND normals AND normalIndices... else if ( ( hasVertices() ) && ( hasFaces() ) && ( hasNormals() ) && ( hasNormalIndices() ) ) { if (VERBOSE) { System.out.println("Model has vertices, faces, normals & normal indices. Transferring data."); } //FIXME: Change this to use the numVertices and numNormals directly - I don't see a reason to use separate vertexCount and normalCount vars... int vertexCount = 0; int normalCount = 0; // Look up each vertex specified by each face and add the vertex data to the vertexData array for (Vec3i iv : faces) { // Get the numbers of the three vertices that this face is comprised of int firstVertexNum = iv.x; int secondVertexNum = iv.y; int thirdVertexNum = iv.z; // Now that we have the vertex numbers, we need to get the actual vertices // Note: We subtract 1 from the number of the vertex because faces start at // face number 1 in the .oBJ format, while in our code the first vertex // will be at location zero. Vec3f faceVert1 = vertices.get(firstVertexNum - 1); Vec3f faceVert2 = vertices.get(secondVertexNum - 1); Vec3f faceVert3 = vertices.get(thirdVertexNum - 1); // Put the vertex data into our vertexData array vertexData.add( faceVert1.x ); vertexData.add( faceVert1.y ); vertexData.add( faceVert1.z ); ++vertexCount; vertexData.add( faceVert2.x ); vertexData.add( faceVert2.y ); vertexData.add( faceVert2.z ); ++vertexCount; vertexData.add( faceVert3.x ); vertexData.add( faceVert3.y ); vertexData.add( faceVert3.z ); ++vertexCount; } // Look up each normal specified by each normal index and add the normal data to the normalData array for (Vec3i normInd : normalIndices) { // Get the numbers of the three normals that this face uses int firstNormalNum = normInd.x; int secondNormalNum = normInd.y; int thirdNormalNum = normInd.z; // Now that we have the normal index numbers, we need to get the actual normals // Note: We subtract 1 from the number of the normal because normals start at // number 1 in the .obJ format, while in our code the first vertex // will be at location zero. Vec3f normal1 = normals.get(firstNormalNum - 1); Vec3f normal2 = normals.get(secondNormalNum - 1); Vec3f normal3 = normals.get(thirdNormalNum - 1); // Put the normal data into our normalData array normalData.add( normal1.x ); normalData.add( normal1.y ); normalData.add( normal1.z ); normalCount++; normalData.add( normal2.x ); normalData.add( normal2.y ); normalData.add( normal2.z ); normalCount++; normalData.add( normal3.x ); normalData.add( normal3.y ); normalData.add( normal3.z ); normalCount++; } // End of loop iterating over the model faces numVertices = vertexCount; numNormals = normalCount; if (VERBOSE) { System.out.printf( NUMBER_OF_VERTICES_LOG, numVertices, getVertexDataSizeBytes()); System.out.printf( NUMBER_OF_NORMALS_LOG, numNormals, getNormalDataSizeBytes()); } } else { System.out.println("Something bad happened in Model.setupData() =("); } } // End of setupData method } // End of Model class
package de.fhg.camel.ids.comm.ws.protocol; import static org.junit.Assert.assertTrue; import java.net.URI; import java.util.Arrays; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import com.google.gson.Gson; import de.fhg.aisec.ids.attestation.PcrMessage; import de.fhg.aisec.ids.attestation.PcrValue; import de.fhg.aisec.ids.attestation.REST; import de.fhg.aisec.ids.messages.AttestationProtos.Pcr; import de.fhg.aisec.ids.messages.AttestationProtos.IdsAttestationType; import de.fhg.aisec.ids.messages.Idscp.AttestationResponse; import de.fhg.aisec.ids.messages.Idscp.ConnectorMessage; import de.fhg.ids.comm.ws.protocol.rat.TrustedThirdParty; public class TrustedThirdPartyTest { private static Server server; private static URI ttpUri; Pcr one; Pcr two; String zero = "0000000000000000000000000000000000000000000000000000000000000000"; TrustedThirdParty ttp; PcrMessage msg; @BeforeClass public static void initRepo() throws Exception { ServletHolder jerseyServlet = context.addServlet(org.glassfish.jersey.servlet.ServletContainer.class, "/*"); jerseyServlet.setInitOrder(0); jerseyServlet.setInitParameter("jersey.config.server.provider.classnames", REST.class.getCanonicalName()); // Start Server server.start(); int port = connector.getLocalPort();*/ ttpUri = new URI(String.format("http://127.0.0.1:%d", 7331)); } /* @AfterClass public static void stopRepo() throws Exception { server.stop(); server.destroy(); } */ @Before public void initTest() { PcrValue[] one = new PcrValue[10]; PcrValue[] two = new PcrValue[23]; for(int i = 0; i<10;i++) { one[i] = new PcrValue(i, zero); } for(int i = 0; i<23;i++) { two[i] = new PcrValue(i, zero); } msg = new PcrMessage(two); this.ttp = new TrustedThirdParty(one, ttpUri); } @Test public void testObjToJsonString() throws Exception { String result = "{\"success\":false,\"signature\":\"\",\"values\":[{\"order\":0,\"value\":\"0000000000000000000000000000000000000000000000000000000000000000\"},{\"order\":1,\"value\":\"0000000000000000000000000000000000000000000000000000000000000000\"},{\"order\":2,\"value\":\"0000000000000000000000000000000000000000000000000000000000000000\"},{\"order\":3,\"value\":\"0000000000000000000000000000000000000000000000000000000000000000\"},{\"order\":4,\"value\":\"0000000000000000000000000000000000000000000000000000000000000000\"},{\"order\":5,\"value\":\"0000000000000000000000000000000000000000000000000000000000000000\"},{\"order\":6,\"value\":\"0000000000000000000000000000000000000000000000000000000000000000\"},{\"order\":7,\"value\":\"0000000000000000000000000000000000000000000000000000000000000000\"},{\"order\":8,\"value\":\"0000000000000000000000000000000000000000000000000000000000000000\"},{\"order\":9,\"value\":\"0000000000000000000000000000000000000000000000000000000000000000\"}]}"; assertTrue(this.ttp.jsonToString("").equals(result)); } @Test public void testReadResponse() throws Exception { msg.setNonce("abc"); msg.setSignature("bcd"); msg.setSuccess(false); Gson gson = new Gson(); PcrMessage pcrResult = this.ttp.readResponse(gson.toJson(msg)); assertTrue(pcrResult.getNonce().equals("abc")); assertTrue(pcrResult.getSignature().equals("bcd")); } }
package com.clavain.munin; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintStream; import java.net.InetSocketAddress; import java.net.Socket; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.StringTokenizer; import static com.clavain.muninmxcd.p; import static com.clavain.muninmxcd.logger; import static com.clavain.utils.Generic.getUnixtime; import static com.clavain.muninmxcd.logMore; /** * * @author enricokern */ public class MuninPlugin { private String str_PluginName; private String str_PluginTitle; private String str_PluginInfo; private String str_PluginCategory; private String str_PluginLabel; private long l_lastFrontendQuery; private transient long l_lastMuninQuery; private transient Socket csMuninSocket; private transient boolean b_IntervalIsSeconds = false; private ArrayList<MuninGraph> v_graphs = new ArrayList<MuninGraph>();; public void addGraph(MuninGraph p_graph) { getGraphs().add(p_graph); } /** * @return the str_PluginName */ public String getPluginName() { return str_PluginName; } /** * @param str_PluginName the str_PluginName to set */ public void setPluginName(String str_PluginName) { this.str_PluginName = str_PluginName; } /** * @return the str_GraphTitle */ public String getPluginTitle() { return str_PluginTitle; } /** * @param str_GraphTitle the str_GraphTitle to set */ public void setPluginTitle(String str_GraphTitle) { this.str_PluginTitle = str_GraphTitle; } /** * @return the str_GraphInfo */ public String getPluginInfo() { return str_PluginInfo; } /** * @param str_PluginInfo the str_GraphInfo to set */ public void setPluginInfo(String str_GraphInfo) { this.str_PluginInfo = str_GraphInfo; } /** * @return the v_graphs */ public ArrayList<MuninGraph> getGraphs() { return v_graphs; } /** * @param v_graphs the v_graphs to set */ public void setGraphs(ArrayList<MuninGraph> v_graphs) { this.v_graphs = v_graphs; } /** * @return the l_lastFrontendQuery */ public long getLastFrontendQuery() { return l_lastFrontendQuery; } /** * @param l_lastFrontendQuery the l_lastFrontendQuery to set */ public void setLastFrontendQuery(long l_lastFrontendQuery) { this.l_lastFrontendQuery = l_lastFrontendQuery; } /** * Sets lastFrontendQuery to current unixtime */ public void setLastFrontendQuery() { l_lastFrontendQuery = System.currentTimeMillis() / 1000L; } /* * will connect to munin if no connections exists and will update * values for all graphs, then return all graphs with updated stats */ public void updateAllGraps(String p_strHostname, int p_iPort, Socket p_socket, int p_queryInterval) { try { csMuninSocket = p_socket; // connection available? if(csMuninSocket != null) { if(!csMuninSocket.isConnected() || csMuninSocket.isClosed()) { csMuninSocket = null; csMuninSocket = new Socket(); csMuninSocket.setSoTimeout(5000); csMuninSocket.setKeepAlive(false); csMuninSocket.setSoLinger(true, 0); csMuninSocket.setReuseAddress(false); csMuninSocket.connect(new InetSocketAddress(p_strHostname, p_iPort),5000); logger.info("Reconnecting to " + p_strHostname); } } else { csMuninSocket = new Socket(); csMuninSocket.setSoTimeout(5000); csMuninSocket.setKeepAlive(false); csMuninSocket.setSoLinger(true, 0); csMuninSocket.setReuseAddress(false); csMuninSocket.connect(new InetSocketAddress(p_strHostname, p_iPort),5000); } PrintStream os = new PrintStream( csMuninSocket.getOutputStream() ); BufferedReader in = new BufferedReader(new InputStreamReader( csMuninSocket.getInputStream()) ); os.println("fetch " + this.getPluginName()); String line; while((line = in.readLine()) != null) { if(line.startsWith(".")) { return; } //System.out.println(line); if(line.contains("value") && !line.contains(" { String l_graphName = line.substring(0,line.indexOf(".")); String l_value = line.substring(line.indexOf(" ")+1,line.length()); if(logMore) { logger.info(p_strHostname + " - " + l_graphName + " - " + l_value); } Iterator it = this.v_graphs.iterator(); while (it.hasNext()) { MuninGraph l_mg = (MuninGraph) it.next(); l_mg.setQueryInterval(p_queryInterval); // required for customer plugin intervals if(IntervalIsSeconds() != false) { l_mg.setIntervalIsSeconds(true); } if(l_mg.getGraphName().equals(l_graphName)) { if(l_value.trim().length() < 1) { l_mg.setGraphValue("0"); } else { // check.... try { l_mg.setGraphValue(l_value.trim()); } catch (Exception ex) { l_mg.setGraphValue("U"); System.err.println(p_strHostname + " setvalue error on "+this.str_PluginName+" with " + l_value + " details: " + ex.getLocalizedMessage()); ex.printStackTrace(); } } } } } } //os.close(); //in.close(); //csMuninSocket.close(); //csMuninSocket = null; } catch (Exception ex) { //try { csMuninSocket.close(); } catch (Exception e) {}; logger.error(p_strHostname + " Unable to connect/process: " + ex.getMessage()); ex.printStackTrace(); } } public ArrayList<MuninGraph> returnAllGraphs() { return v_graphs; } void setPluginCategory(String p_strCategory) { setStr_PluginCategory(p_strCategory); } /** * @return the str_PluginLabel */ public String getPluginLabel() { return str_PluginLabel; } /** * @param str_PluginLabel the str_PluginLabel to set */ public void setPluginLabel(String str_PluginLabel) { this.str_PluginLabel = str_PluginLabel; } /** * @return the str_PluginCategory */ public String getStr_PluginCategory() { return str_PluginCategory; } /** * @param str_PluginCategory the str_PluginCategory to set */ public void setStr_PluginCategory(String str_PluginCategory) { this.str_PluginCategory = str_PluginCategory; } /** * @return the b_IntervalIsSeconds */ public boolean IntervalIsSeconds() { return b_IntervalIsSeconds; } /** * @param b_IntervalIsSeconds the b_IntervalIsSeconds to set */ public void set_IntervalIsSeconds(boolean b_IntervalIsSeconds) { this.b_IntervalIsSeconds = b_IntervalIsSeconds; } }
package com.cmeon.nfchomeauto; import android.util.Log; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; public class Message { private String msg; private static final String YAP_SERVER_URL = "http://mmu-foe-capstone.appspot.com/control?group=15&msg="; public Message(String msg) { this.msg = msg; } public String getStringUrl() { String url = null; try { url = YAP_SERVER_URL + URLEncoder.encode(msg, "utf-8"); Log.d("url", url); } catch (UnsupportedEncodingException e) { // handle exception } return url; } }
package net.justinwhite.score_model; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class Phase10PlayerTest { private final String testName = "Test Phase10Player"; private final String testInitials = "TP"; private final int testScore = 11; private final int testPhase = 1; private Phase10Player testPhase10Player; @Before public void setUp() { testPhase10Player = new Phase10Player(testName); testPhase10Player.addScore(testScore); testPhase10Player.nextPhase(); } @Test public void testToString() throws Exception { assertEquals(String.format( "Name '%s'; Score %s; Phase %d", testName, testScore, testPhase ), testPhase10Player.toString() ); } @Test public void testAddScore() throws Exception { testPhase10Player.addScore(testScore); assertEquals(testScore * 2, testPhase10Player.getScore()); } @Test public void testNextPhase() throws Exception { testPhase10Player.nextPhase(); assertEquals(testPhase + 1, testPhase10Player.getPhase()); } }
package com.dmdirc; import com.dmdirc.config.ConfigManager; import com.dmdirc.ui.core.dialogs.sslcertificate.CertificateAction; import com.dmdirc.ui.core.dialogs.sslcertificate.SSLCertificateDialogModel; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.security.InvalidAlgorithmParameterException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; import java.security.cert.PKIXParameters; import java.security.cert.TrustAnchor; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Semaphore; import javax.naming.InvalidNameException; import javax.naming.ldap.LdapName; import javax.naming.ldap.Rdn; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.X509TrustManager; /** * Manages storage and validation of certificates used when connecting to * SSL servers. * * @since 0.6.3 * @author chris */ public class CertificateManager implements X509TrustManager { /** The password for the global java cacert file. */ private final String cacertpass; /** The server name the user is trying to connect to. */ private final String serverName; /** The configuration manager to use for settings. */ private final ConfigManager config; /** The set of CAs from the global cacert file. */ private Set<X509Certificate> globalTrustedCAs = new HashSet<X509Certificate>(); /** Whether or not to check specified parts of the certificate. */ private boolean checkDate, checkIssuer, checkHost; /** Used to synchronise the manager with the certificate dialog. */ private final Semaphore actionSem = new Semaphore(0); /** The action to perform. */ private CertificateAction action; /** * Creates a new certificate manager for a client connecting to the * specified server. * * @param serverName The name the user used to connect to the server * @param config The configuration manager to use */ public CertificateManager(final String serverName, final ConfigManager config) { this.serverName = serverName; this.config = config; this.cacertpass = config.getOption("ssl", "cacertpass", "changeit"); this.checkDate = config.getOptionBool("ssl", "checkdate", true); this.checkIssuer = config.getOptionBool("ssl", "checkissuer", true); this.checkHost = config.getOptionBool("ssl", "checkhost", true); loadTrustedCAs(); } /** * Loads the trusted CA certificates from the Java cacerts store. */ protected void loadTrustedCAs() { try { String filename = System.getProperty("java.home") + "/lib/security/cacerts".replace('/', File.separatorChar); FileInputStream is = new FileInputStream(filename); KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); keystore.load(is, cacertpass.toCharArray()); // This class retrieves the most-trusted CAs from the keystore PKIXParameters params = new PKIXParameters(keystore); for (TrustAnchor anchor : params.getTrustAnchors()) { globalTrustedCAs.add(anchor.getTrustedCert()); } } catch (CertificateException ex) { } catch (IOException ex) { } catch (InvalidAlgorithmParameterException ex) { } catch (KeyStoreException ex) { } catch (NoSuchAlgorithmException ex) { } } /** * Retrieves a KeyManager[] for the client certicate specified in the * configuration, if there is one. * * @return A KeyManager to use for the SSL connection */ public KeyManager[] getKeyManager() { if (config.hasOption("ssl", "clientcert.file")) { FileInputStream fis = null; try { final char[] pass; if (config.hasOption("ssl", "clientcert.pass")) { pass = config.getOption("ssl", "clientcert.pass").toCharArray(); } else { pass = null; } fis = new FileInputStream(config.getOption("ssl", "clientcert.file")); final KeyStore ks = KeyStore.getInstance("pkcs12"); ks.load(fis, pass); final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(ks, pass); return kmf.getKeyManagers(); } catch (KeyStoreException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } catch (CertificateException ex) { ex.printStackTrace(); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } catch (UnrecoverableKeyException ex) { ex.printStackTrace(); } finally { if (fis != null) { try { fis.close(); } catch (IOException ex) { } } } } return null; } /** {@inheritDoc} */ @Override public void checkClientTrusted(final X509Certificate[] chain, final String authType) throws CertificateException { throw new CertificateException("Not supported."); } /** {@inheritDoc} */ @Override public void checkServerTrusted(final X509Certificate[] chain, final String authType) throws CertificateException { final List<CertificateException> problems = new ArrayList<CertificateException>(); boolean verified = false; if (checkHost) { // Check that the cert is issued to the correct host final Map<String, String> fields = getDNFieldsFromCert(chain[0]); if (fields.containsKey("CN") && fields.get("CN").equals(serverName)) { verified = true; } if (chain[0].getSubjectAlternativeNames() != null && !verified) { for (List<?> entry : chain[0].getSubjectAlternativeNames()) { final int type = ((Integer) entry.get(0)).intValue(); // DNS or IP if ((type == 2 || type == 7) && entry.get(1).equals(serverName)) { verified = true; break; } } } if (!verified) { problems.add(new CertificateDoesntMatchHostException( "Certificate was not issued to " + serverName)); } verified = false; } for (X509Certificate cert : chain) { if (checkDate) { // Check that the certificate is in-date try { cert.checkValidity(); } catch (CertificateException ex) { problems.add(ex); } } if (checkIssuer) { // Check that we trust an issuer try { for (X509Certificate trustedCert : globalTrustedCAs) { if (cert.getSerialNumber().equals(trustedCert.getSerialNumber()) && cert.getIssuerDN().getName().equals(trustedCert.getIssuerDN().getName())) { cert.verify(trustedCert.getPublicKey()); verified = true; break; } } } catch (Exception ex) { problems.add(new CertificateException("Issuer couldn't be verified", ex)); } } } if (!verified && checkIssuer) { problems.add(new CertificateNotTrustedException("Issuer is not trusted")); } if (!problems.isEmpty()) { Main.getUI().showSSLCertificateDialog( new SSLCertificateDialogModel(chain, problems, this)); actionSem.acquireUninterruptibly(); switch (action) { case DISCONNECT: throw new CertificateException("Not trusted"); case IGNORE_PERMANENTY: // TODO: implement break; case IGNORE_TEMPORARILY: // TODO: implement break; } } } /** * Sets the action to perform for the request that's in progress. * * @param action The action that's been selected */ public void setAction(final CertificateAction action) { this.action = action; actionSem.release(); } /** * Reads the fields from the subject's designated name in the specified * certificate. * * @param cert The certificate to read * @return A map of the fields in the certificate's subject's designated * name */ public static Map<String, String> getDNFieldsFromCert(final X509Certificate cert) { final Map<String, String> res = new HashMap<String, String>(); try { final LdapName name = new LdapName(cert.getSubjectX500Principal().getName()); for (Rdn rdn : name.getRdns()) { res.put(rdn.getType(), rdn.getValue().toString()); } } catch (InvalidNameException ex) { // Don't care } return res; } /** {@inheritDoc} */ @Override public X509Certificate[] getAcceptedIssuers() { return globalTrustedCAs.toArray(new X509Certificate[globalTrustedCAs.size()]); } /** * An exception to indicate that the host on a certificate doesn't match * the host we're trying to connect to. */ public static class CertificateDoesntMatchHostException extends CertificateException { /** * A version number for this class. It should be changed whenever the * class structure is changed (or anything else that would prevent * serialized objects being unserialized with the new class). */ private static final long serialVersionUID = 1; /** * Creates a new CertificateDoesntMatchHostException * * @param msg A description of the problem */ public CertificateDoesntMatchHostException(String msg) { super(msg); } } /** * An exception to indicate that we do not trust the issuer of the * certificate (or the CA). */ public static class CertificateNotTrustedException extends CertificateException { /** * A version number for this class. It should be changed whenever the * class structure is changed (or anything else that would prevent * serialized objects being unserialized with the new class). */ private static final long serialVersionUID = 1; /** * Creates a new CertificateNotTrustedException * * @param msg A description of the problem */ public CertificateNotTrustedException(String msg) { super(msg); } } }
package org.thingml.testjar; import java.io.File; import java.io.PrintWriter; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.concurrent.Callable; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.thingml.testjar.lang.TargetedLanguage; /** * * @author sintef */ public class TestCase { public TargetedLanguage lang; public int status; public boolean isLastStepASuccess = true; public File complerJar; public File srcTestCase; public File genCfgDir; public File genCfg; public File genCodeDir; public File logFile; public String category; public String log; public String result; public String name; public String oracleExpected; public String oracleActual; public Command ongoingCmd; public TestCase(File srcTestCase, File complerJar, TargetedLanguage lang, File genCodeDir, File genCfgDir, File logDir) { this.lang = lang; this.status = 0; this.complerJar = complerJar; this.srcTestCase = srcTestCase; this.genCfgDir = genCfgDir; this.genCodeDir = genCodeDir; this.logFile = logDir; this.log = ""; this.result = ""; this.name = srcTestCase.getName().split("\\.thingml")[0]; this.ongoingCmd = lang.generateThingML(this); this.category = srcTestCase.getParentFile().getName(); } public TestCase(File srcTestCase, File complerJar, TargetedLanguage lang, File genCodeDir, File genCfgDir, File logDir, boolean notGen) { this.lang = lang; this.status = 1; this.complerJar = complerJar; this.srcTestCase = srcTestCase; this.genCfgDir = genCfgDir; this.genCodeDir = genCodeDir; this.logFile = logDir; this.log = ""; this.result = ""; this.name = srcTestCase.getName().split("\\.thingml")[0]; this.ongoingCmd = this.lang.generateTargeted(this); this.category = srcTestCase.getParentFile().getName(); } public TestCase(File genCfg, TestCase t) { this.name = genCfg.getName().split("\\.thingml")[0]; this.genCfg = genCfg; this.lang = t.lang; this.status = 1; this.complerJar = t.complerJar; this.srcTestCase = t.srcTestCase; this.genCfgDir = t.genCfgDir; this.genCodeDir = t.genCodeDir; this.logFile = new File(t.logFile, "_" + lang.compilerID + "/" + name); this.log = "Test: " + name + "\n" + " '-> Source: " + genCfg.getAbsolutePath() + "\n" + "Generated from: " + t.srcTestCase.getName() + "\n" + " '-> Source: " + t.srcTestCase.getAbsolutePath() + "\n"; this.result = t.result; this.ongoingCmd = lang.generateTargeted(this); this.category = srcTestCase.getParentFile().getName(); } public List<TestCase> generateChildren() { LinkedList<TestCase> res = new LinkedList<>(); String testConfigPattern = upperFirstChar(name) + "_([0-9]+)\\.thingml"; File dir = new File(genCfgDir, "_" + lang.compilerID); //System.out.println("[genCfgDir] " + dir.getAbsolutePath()); //System.out.println("[pattern] " + testConfigPattern); for(File f : listTestFiles(dir, testConfigPattern)) { res.add(new TestCase(f, this)); } return res; } public void collectResults() { if(isLastStepASuccess) { isLastStepASuccess = ongoingCmd.isSuccess; log += "\n\n************************************************* "; log += "\n\n[Cmd] "; for(String str : ongoingCmd.cmd) { log += str + " "; } log += "\n\n[stdout] "; log += ongoingCmd.stdlog; log += "\n\n[sterr] "; log += ongoingCmd.errlog; if(!isLastStepASuccess) { if(status == 0) { result = "Error at ThingML generation"; } else if (status == 1) { result = "Error at ThingML compilation"; } else if (status == 2) { result = "Error at " + lang.compilerID + " compilation "; } else if (status == 3) { result = "Error at " + lang.compilerID + " execution "; } else { result = "Unknown Error"; } log = result + "\n" + log; //writeLogFile(); } else { if (status == 1) { ongoingCmd = lang.compileTargeted(this); status = 2; } else if (status == 2) { ongoingCmd = lang.execTargeted(this); status = 3; } else if (status == 3) { log += "\n\n************************************************* "; if(oracle()) result = "Success"; else result = "Failure"; log = result + "\n" + log; //writeLogFile(); } else { result = "Unknown Error"; log = result + "\n" + log; //writeLogFile(); } } } writeLogFile(); } public boolean oracle() { String exp = null, actual = null; ongoingCmd.stdlog = ongoingCmd.stdlog.replaceAll("\\s",""); if(ongoingCmd.stdlog.split("\\[Expected\\]").length > 1) exp = ongoingCmd.stdlog.split("\\[Expected\\]")[1].split("\\[Test\\]")[0]; else return false; if(ongoingCmd.stdlog.split("\\[Test\\]").length > 1) actual = ongoingCmd.stdlog.split("\\[Test\\]")[1].split("\\[Done\\]")[0]; else return false; if(exp.charAt(0) == ' ') exp = exp.substring(1); boolean res = false; if((exp != null) && (actual != null)) { Pattern p = Pattern.compile(exp); if(p != null) { Matcher m = p.matcher(actual); res = m.matches(); //res = m.find(); String oracleLog = ""; oracleLog += "[test] <" + name + ">" + " for " + lang.compilerID + "\n"; //oracleLog += "[raw output] <\n" + ongoingCmd.stdlog + "\n>" + "\n"; oracleLog += "[expected] <" + exp + ">" + "\n"; oracleLog += "[ actual ] <" + actual + ">" + "\n"; oracleLog += "[ match? ] <" + res + ">" + "\n"; oracleExpected = exp; oracleActual = actual; log += "\n\n[Oracle] \n" + oracleLog; System.out.println(oracleLog); isLastStepASuccess = res; } else { oracleExpected = "Error at Expected pattern compilation"; oracleActual = "Error at Expected pattern compilation"; log += "\n\n[Oracle] \n" + "Error at Expected pattern compilation"; } } else { oracleExpected = "Error at Output reading"; oracleActual = "Error at Output reading"; log += "\n\n[Oracle] \n" + "Error at Output reading"; } return res; } public static String upperFirstChar(String str) { return str.substring(0, 1).toUpperCase() + str.substring(1); } public static Set<File> listTestFiles(final File folder, String pattern) { Set<File> res = new HashSet<>(); Pattern p = Pattern.compile(pattern); for (final File fileEntry : folder.listFiles()) { if (fileEntry.isDirectory()) { res.addAll(listTestFiles(fileEntry, pattern)); } else { Matcher m = p.matcher(fileEntry.getName()); //System.out.println("[file] " + fileEntry.getName()); if (m.matches()) { res.add(fileEntry); } } } return res; } public void writeLogFile() { if (!logFile.getParentFile().exists()) logFile.getParentFile().mkdirs(); try { PrintWriter w = new PrintWriter(logFile); w.print(log); w.close(); } catch (Exception ex) { System.err.println("Problem writting log"); ex.printStackTrace(); } } }
package com.ecyrd.jspwiki; import java.security.AccessControlException; import java.security.Principal; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import javax.security.auth.Subject; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.login.LoginContext; import javax.security.auth.login.LoginException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import com.ecyrd.jspwiki.auth.AuthenticationManager; import com.ecyrd.jspwiki.auth.Authorizer; import com.ecyrd.jspwiki.auth.GroupPrincipal; import com.ecyrd.jspwiki.auth.NoSuchPrincipalException; import com.ecyrd.jspwiki.auth.SessionMonitor; import com.ecyrd.jspwiki.auth.WikiPrincipal; import com.ecyrd.jspwiki.auth.authorize.Group; import com.ecyrd.jspwiki.auth.authorize.GroupManager; import com.ecyrd.jspwiki.auth.authorize.Role; import com.ecyrd.jspwiki.auth.login.CookieAssertionLoginModule; import com.ecyrd.jspwiki.auth.login.PrincipalWrapper; import com.ecyrd.jspwiki.auth.user.UserDatabase; import com.ecyrd.jspwiki.auth.user.UserProfile; import com.ecyrd.jspwiki.event.WikiEvent; import com.ecyrd.jspwiki.event.WikiEventListener; import com.ecyrd.jspwiki.event.WikiSecurityEvent; public final class WikiSession implements WikiEventListener { /** An anonymous user's session status. */ public static final String ANONYMOUS = "anonymous"; /** An asserted user's session status. */ public static final String ASSERTED = "asserted"; /** An authenticated user's session status. */ public static final String AUTHENTICATED = "authenticated"; private static final int ONE = 48; private static final int NINE = 57; private static final int DOT = 46; private static final Logger log = Logger.getLogger( WikiSession.class ); private static final String ALL = "*"; private final Subject m_subject = new Subject(); private final Map m_messages = new HashMap(); private String m_cachedCookieIdentity= null; private String m_cachedRemoteUser = null; private Principal m_cachedUserPrincipal = null; /** The WikiEngine that created this session. */ private WikiEngine m_engine = null; private boolean m_isNew = true; private String m_status = ANONYMOUS; private Principal m_userPrincipal = WikiPrincipal.GUEST; private Principal m_loginPrincipal = WikiPrincipal.GUEST; /** * Returns <code>true</code> if one of this WikiSession's user Principals * can be shown to belong to a particular wiki group. If the user is * not authenticated, this method will always return <code>false</code>. * @param group the group to test * @return the result */ protected final boolean isInGroup( Group group ) { Principal[] principals = getPrincipals(); for ( int i = 0; i < principals.length; i++ ) { if ( isAuthenticated() && group.isMember( principals[i] ) ) { return true; } } return false; } /** * Returns <code>true</code> if the wiki session is newly initialized. */ protected final boolean isNew() { return m_isNew; } /** * Sets the status of this wiki session. * @param isNew whether this session should be considered "new". */ protected final void setNew( boolean isNew ) { m_isNew = isNew; } /** * Private constructor to prevent WikiSession from being instantiated * directly. */ private WikiSession() { } /** * Returns <code>true</code> if the user is considered asserted via * a session cookie; that is, the Subject contains the Principal * Role.ASSERTED. * @return Returns <code>true</code> if the user is asserted */ public final boolean isAsserted() { return ( m_subject.getPrincipals().contains( Role.ASSERTED ) ); } /** * Returns the authentication status of the user's session. The user is * considered authenticated if the Subject contains the Principal * Role.AUTHENTICATED; * @return Returns <code>true</code> if the user is authenticated */ public final boolean isAuthenticated() { return ( m_subject.getPrincipals().contains( Role.AUTHENTICATED ) ); } /** * <p>Determines whether the current session is anonymous. This will be * true if any of these conditions are true:</p> * <ul> * <li>The session's Principal set contains * {@link com.ecyrd.jspwiki.auth.authorize.Role#ANONYMOUS}</li> * <li>The session's Principal set contains * {@link com.ecyrd.jspwiki.auth.WikiPrincipal#GUEST}</li> * <li>The Principal returned by {@link #getUserPrincipal()} evaluates * to an IP address.</li> * </ul> * <p>The criteria above are listed in the order in which they are * evaluated.</p> * @return whether the current user's identity is equivalent to an IP * address */ public final boolean isAnonymous() { Set principals = m_subject.getPrincipals(); return ( principals.contains( Role.ANONYMOUS ) || principals.contains( WikiPrincipal.GUEST ) || isIPV4Address( getUserPrincipal().getName() ) ); } /** * Creates and returns a new login context for this wiki session. * This method is called by * {@link com.ecyrd.jspwiki.auth.AuthenticationManager}. * @param application the name of the application * @param handler the callback handler */ public final LoginContext getLoginContext( String application, CallbackHandler handler ) throws LoginException { return new LoginContext( application, m_subject, handler ); } /** * <p> Returns the Principal used to log in to an authenticated session. The * login principal is determined by examining the Subject's Principal set * for PrincipalWrappers or WikiPrincipals with type designator * <code>LOGIN_NAME</code>; the first one found is the login principal. * If one is not found, this method returns the first principal that isn't * of type Role or GroupPrincipal. If neither of these conditions hold, this method returns * {@link com.ecyrd.jspwiki.auth.WikiPrincipal#GUEST}. * @return the login Principal. If it is a PrincipalWrapper containing an * externally-provided Principal, the object returned is the Principal, not * the wrapper around it. */ public final Principal getLoginPrincipal() { if ( m_loginPrincipal instanceof PrincipalWrapper ) { return ((PrincipalWrapper)m_loginPrincipal).getPrincipal(); } return m_loginPrincipal; } /** * <p>Returns the primary user Principal associated with this session. The * primary user principal is determined as follows:</p> <ol> <li>If the * Subject's Principal set contains WikiPrincipals, the first WikiPrincipal * with type designator <code>WIKI_NAME</code> or (alternatively) * <code>FULL_NAME</code> is the primary Principal.</li> * <li>For all other cases, the first Principal in the Subject's principal * collection that that isn't of type Role or GroupPrincipal is the primary.</li> * </ol> * If no primary user Principal is found, this method returns * {@link com.ecyrd.jspwiki.auth.WikiPrincipal#GUEST}. * @return the primary user Principal */ public final Principal getUserPrincipal() { if ( m_loginPrincipal instanceof PrincipalWrapper ) { return ((PrincipalWrapper)m_userPrincipal).getPrincipal(); } return m_userPrincipal; } /** * Adds a message to the generic list of messages associated with the * session. These messages retain their order of insertion and remain until * the {@link #clearMessages()} method is called. * @param message the message to add; if <code>null</code> it is ignored. */ public final void addMessage(String message) { addMessage( ALL, message ); } /** * Adds a message to the specific set of messages associated with the * session. These messages retain their order of insertion and remain until * the {@link #clearMessages()} method is called. * @param topic the topic to associate the message to; * @param message the message to add */ public final void addMessage(String topic, String message) { if ( topic == null ) { throw new IllegalArgumentException( "addMessage: topic cannot be null." ); } if ( message == null ) { message = ""; } Set messages = (Set)m_messages.get( topic ); if (messages == null ) { messages = new LinkedHashSet(); m_messages.put( topic, messages ); } messages.add( message ); } /** * Clears all messages associated with this session. */ public final void clearMessages() { m_messages.clear(); } /** * Clears all messages associated with a session topic. * @param topic the topic whose messages should be cleared. */ public final void clearMessages( String topic ) { Set messages = (Set)m_messages.get( topic ); if ( messages != null ) { m_messages.clear(); } } /** * Returns all generic messages associated with this session. * The messages stored with the session persist throughout the * session unless they have been reset with {@link #clearMessages()}. * @return the current messsages. */ public final String[] getMessages() { return getMessages( ALL ); } /** * Returns all messages associated with a session topic. * The messages stored with the session persist throughout the * session unless they have been reset with {@link #clearMessages(String)}. * @return the current messsages. */ public final String[] getMessages( String topic ) { Set messages = (Set)m_messages.get( topic ); if ( messages == null || messages.size() == 0 ) { return new String[0]; } return (String[])messages.toArray( new String[messages.size()] ); } /** * Returns all user Principals associated with this session. User principals * are those in the Subject's principal collection that aren't of type Role or * of type GroupPrincipal. This is a defensive copy. * @return Returns the user principal * @see com.ecyrd.jspwiki.auth.AuthenticationManager#isUserPrincipal(Principal) */ public final Principal[] getPrincipals() { ArrayList principals = new ArrayList(); { // Take the first non Role as the main Principal for( Iterator it = m_subject.getPrincipals().iterator(); it.hasNext(); ) { Principal principal = (Principal) it.next(); if ( AuthenticationManager.isUserPrincipal( principal ) ) { principals.add( principal ); } } } return (Principal[]) principals.toArray( new Principal[principals.size()] ); } /** * Returns an array of Principal objects that represents the groups and * roles that the user associated with a WikiSession possesses. The array is * built by iterating through the Subject's Principal set and extracting all * Role and GroupPrincipal objects into a list. The list is returned as an * array sorted in the natural order implied by each Principal's * <code>getName</code> method. Note that this method does <em>not</em> * consult the external Authorizer or GroupManager; it relies on the * Principals that have been injected into the user's Subject at login time, * or after group creation/modification/deletion. * @return an array of Principal objects corresponding to the roles the * Subject possesses */ public final Principal[] getRoles() { Set roles = new HashSet(); // Add all of the Roles possessed by the Subject directly roles.addAll( m_subject.getPrincipals( Role.class ) ); // Add all of the GroupPrincipals possessed by the Subject directly roles.addAll( m_subject.getPrincipals( GroupPrincipal.class ) ); // Return a defensive copy Principal[] roleArray = ( Principal[] )roles.toArray( new Principal[roles.size()] ); Arrays.sort( roleArray, WikiPrincipal.COMPARATOR ); return roleArray; } /** * Removes the wiki session associated with the user's HTTP request * from the cache of wiki sessions, typically as part of a logout * process. * @param engine the wiki engine * @param request the users's HTTP request */ public static final void removeWikiSession( WikiEngine engine, HttpServletRequest request ) { if ( engine == null || request == null ) { throw new IllegalArgumentException( "Request or engine cannot be null." ); } SessionMonitor monitor = SessionMonitor.getInstance( engine ); monitor.remove( request.getSession() ); } /** * Returns <code>true</code> if the WikiSession's Subject * possess a supplied Principal. This method eliminates the need * to externally request and inspect the JAAS subject. * @param principal the Principal to test * @return the result */ public final boolean hasPrincipal( Principal principal ) { return m_subject.getPrincipals().contains( principal ); } /** * Listens for WikiEvents generated by source objects such as the * GroupManager. This method adds Principals to the private Subject managed * by the WikiSession. * @see com.ecyrd.jspwiki.event.WikiEventListener#actionPerformed(com.ecyrd.jspwiki.event.WikiEvent) */ public final void actionPerformed( WikiEvent event ) { if ( event instanceof WikiSecurityEvent ) { WikiSecurityEvent e = (WikiSecurityEvent)event; if ( e.getTarget() != null ) { switch (e.getType() ) { case WikiSecurityEvent.GROUP_ADD: { Group group = (Group)e.getTarget(); if ( isInGroup( group ) ) { m_subject.getPrincipals().add( group.getPrincipal() ); } break; } case WikiSecurityEvent.GROUP_REMOVE: { Group group = (Group)e.getTarget(); if ( m_subject.getPrincipals().contains( group.getPrincipal() ) ) { m_subject.getPrincipals().remove( group.getPrincipal() ); } break; } case WikiSecurityEvent.GROUP_CLEAR_GROUPS: { m_subject.getPrincipals().removeAll( m_subject.getPrincipals( GroupPrincipal.class ) ); break; } case WikiSecurityEvent.LOGIN_INITIATED: { WikiSession target = (WikiSession)e.getTarget(); if ( this.equals( target ) ) { updatePrincipals(); } break; } case WikiSecurityEvent.LOGIN_ASSERTED: { WikiSession target = (WikiSession)e.getTarget(); if ( this.equals( target ) ) { m_status = ASSERTED; } break; } case WikiSecurityEvent.LOGIN_AUTHENTICATED: { WikiSession target = (WikiSession)e.getTarget(); if ( this.equals( target ) ) { m_status = AUTHENTICATED; injectUserProfilePrincipals(); // Add principals for the user profile injectRolePrincipals(); // Inject role and group principals updatePrincipals(); } break; } case WikiSecurityEvent.PROFILE_SAVE: { WikiSession target = (WikiSession)e.getTarget(); if ( this.equals( target ) ) { injectUserProfilePrincipals(); // Add principals for the user profile updatePrincipals(); } break; } } } } } /** * Invalidates the WikiSession and resets its Subject's * Principals to the equivalent of a "guest session". */ public final void invalidate() { m_subject.getPrincipals().clear(); m_subject.getPrincipals().add( WikiPrincipal.GUEST ); m_subject.getPrincipals().add( Role.ANONYMOUS ); m_subject.getPrincipals().add( Role.ALL ); m_cachedCookieIdentity = null; m_cachedRemoteUser = null; m_cachedUserPrincipal = null; } /** * Returns whether the HTTP servlet container's authentication status has * changed. Used to detect whether the container has logged in a user since * the last call to this function. This method is stateful. After calling * this function, the cached values are set to those in the current request. * If the servlet request is <code>null</code>, this method always returns * <code>false</code>. Note that once a user authenticates, the container * status for the session will <em>never</em> change again, unless the * session is invalidated by timeout or logout. * @param request the servlet request * @return <code>true</code> if the status has changed, <code>false</code> * otherwise */ protected final boolean isContainerStatusChanged( HttpServletRequest request ) { if ( request == null || m_status.equals( AUTHENTICATED ) ) { return false; } String remoteUser = request.getRemoteUser(); Principal userPrincipal = request.getUserPrincipal(); String cookieIdentity = CookieAssertionLoginModule.getUserCookie( request ); boolean changed = false; // If request contains non-null remote user, update cached value if changed if ( remoteUser != null && !remoteUser.equals( m_cachedRemoteUser) ) { m_cachedRemoteUser = remoteUser; log.info( "Remote user changed to " + remoteUser ); changed = true; } // If request contains non-null user principal, updated cached value if changed if ( userPrincipal != null && !userPrincipal.equals( m_cachedUserPrincipal ) ) { m_cachedUserPrincipal = userPrincipal; log.info( "User principal changed to " + userPrincipal.getName() ); changed = true; } // If cookie identity changed (to a different value or back to null), update cache if ( ( cookieIdentity != null && !cookieIdentity.equals( m_cachedCookieIdentity ) ) || ( cookieIdentity == null && m_cachedCookieIdentity != null ) ) { m_cachedCookieIdentity = cookieIdentity; log.info( "Cookie changed to " + cookieIdentity ); changed = true; } return changed; } /** * Injects GroupPrincipal and Role objects into the user's Principal set * based on the groups and roles the user belongs to. * For Roles, the algorithm first calls the * {@link Authorizer#getRoles()} to obtain the array of * Principals the authorizer knows about. Then, the method * {@link Authorizer#isUserInRole(WikiSession, Principal)} is * called for each Principal. If the user possesses the role, * an equivalent role Principal is injected into the user's * principal set. * Reloads user Principals into the suppplied WikiSession's Subject. * Existing Role principals are preserved; all other Principal * types are flushed and replaced by those returned by * {@link com.ecyrd.jspwiki.auth.user.UserDatabase#getPrincipals(String)}. * This method should generally be called after a user's {@link com.ecyrd.jspwiki.auth.user.UserProfile} * is saved. If the wiki session is null, or there is no matching user profile, the * method returns silently. */ protected final void injectRolePrincipals() { // Get the GroupManager and test for each Group GroupManager manager = m_engine.getGroupManager(); Principal[] groups = manager.getRoles(); for ( int i = 0; i < groups.length; i++ ) { if ( manager.isUserInRole( this, groups[i] ) ) { m_subject.getPrincipals().add( groups[i] ); } } // Get the authorizer's known roles, then test for each try { Authorizer authorizer = m_engine.getAuthorizationManager().getAuthorizer(); Principal[] roles = authorizer.getRoles(); for ( int i = 0; i < roles.length; i++ ) { Principal role = roles[i]; if ( authorizer.isUserInRole( this, role ) ) { String roleName = role.getName(); if ( !Role.isReservedName( roleName ) ) { m_subject.getPrincipals().add( new Role( roleName ) ); } } } } catch ( WikiException e ) { log.error( "Could not refresh role principals: " + e.getMessage() ); } } /** * Adds Principal objects to the Subject that correspond to the * logged-in user's profile attributes for the wiki name, full name * and login name. These Principals will be WikiPrincipals, and they * will replace all other WikiPrincipals in the Subject. <em>Note: * this method is never called during anonymous or asserted sessions.</em> */ protected final void injectUserProfilePrincipals() { // Copy all Role and GroupPrincipal principals into a temporary cache Set oldPrincipals = m_subject.getPrincipals(); Set newPrincipals = new HashSet(); for (Iterator it = oldPrincipals.iterator(); it.hasNext();) { Principal principal = (Principal)it.next(); if ( AuthenticationManager.isRolePrincipal( principal ) ) { newPrincipals.add( principal ); } } String searchId = getUserPrincipal().getName(); if ( searchId == null ) { // Oh dear, this wasn't an authenticated user after all log.info("Refresh principals failed because WikiSession had no user Principal; maybe not logged in?"); return; } // Look up the user and go get the new Principals UserDatabase database = m_engine.getUserManager().getUserDatabase(); if ( database == null ) { throw new IllegalStateException( "User database cannot be null." ); } try { UserProfile profile = database.find( searchId ); Principal[] principals = database.getPrincipals( profile.getLoginName() ); for (int i = 0; i < principals.length; i++) { Principal principal = principals[i]; newPrincipals.add( principal ); } // Replace the Subject's old Principals with the new ones oldPrincipals.clear(); oldPrincipals.addAll( newPrincipals ); } catch ( NoSuchPrincipalException e ) { // It would be extremely surprising if we get here.... log.error("Refresh principals failed because user profile matching '" + searchId + "' not found."); } } /** * Updates the internally cached principals returned by {@link #getUserPrincipal()} and * {@link #getLoginPrincipal()}. This method is called when the WikiSession receives * the {@link com.ecyrd.jspwiki.event.WikiSecurityEvent#LOGIN_INITIATED} message. */ protected final void updatePrincipals() { Set principals = m_subject.getPrincipals(); m_loginPrincipal = null; m_userPrincipal = null; Principal wikinamePrincipal = null; Principal fullnamePrincipal = null; Principal otherPrincipal = null; for( Iterator it = principals.iterator(); it.hasNext(); ) { Principal currentPrincipal = (Principal) it.next(); if ( !( currentPrincipal instanceof Role || currentPrincipal instanceof GroupPrincipal ) ) { // For login principal, take the first PrincipalWrapper or WikiPrincipal of type LOGIN_NAME // For user principal take the first WikiPrincipal of type WIKI_NAME if ( currentPrincipal instanceof PrincipalWrapper ) { m_loginPrincipal = currentPrincipal; } else if ( currentPrincipal instanceof WikiPrincipal ) { WikiPrincipal wp = (WikiPrincipal) currentPrincipal; if ( wp.getType().equals( WikiPrincipal.LOGIN_NAME ) ) { m_loginPrincipal = wp; } else if ( wp.getType().equals( WikiPrincipal.WIKI_NAME ) ) { wikinamePrincipal = currentPrincipal; m_userPrincipal = wp; } else if ( wp.getType().equals( WikiPrincipal.FULL_NAME ) ) { fullnamePrincipal = currentPrincipal; } else { otherPrincipal = currentPrincipal; } } else if ( otherPrincipal == null ) { otherPrincipal = currentPrincipal; } } } if ( otherPrincipal == null ) { otherPrincipal = WikiPrincipal.GUEST; } // If no login principal, use wiki name, full name or other principal (in that order) if ( m_loginPrincipal == null ) { m_loginPrincipal = wikinamePrincipal; if ( m_loginPrincipal == null ) { m_loginPrincipal = fullnamePrincipal; if ( m_loginPrincipal == null ) { m_loginPrincipal = otherPrincipal; } } } // If no user principal, use wiki name, full name or login principal (in that order) if ( m_userPrincipal == null ) { m_userPrincipal = wikinamePrincipal; if ( m_userPrincipal == null ) { m_userPrincipal = fullnamePrincipal; if ( m_userPrincipal == null ) { m_userPrincipal = m_loginPrincipal; } } } } /** * <p>Returns the status of the wiki session as a text string. Valid values are:</p> * <ul> * <li>{@link #AUTHENTICATED}</li> * <li>{@link #ASSERTED}</li> * <li>{@link #ANONYMOUS}</li> * </ul> * @return the user's session status */ public final String getStatus() { return m_status; } /** * <p>Static factory method that returns the WikiSession object associated with * the current HTTP request. This method looks up the associated HttpSession * in an internal WeakHashMap and attempts to retrieve the WikiSession. If * not found, one is created. This method is guaranteed to always return a * WikiSession, although the authentication status is unpredictable until * the user attempts to log in. If the servlet request parameter is * <code>null</code>, a synthetic {@link #guestSession(WikiEngine)}is returned.</p> * <p>When a session is created, this method attaches a WikiEventListener * to the GroupManager so that changes to groups are detected automatically.</p> * @param engine the wiki engine * @param request the servlet request object * @return the existing (or newly created) wiki session */ public final static WikiSession getWikiSession( WikiEngine engine, HttpServletRequest request ) { // If request is null, return guest session if ( request == null ) { if ( log.isDebugEnabled() ) { log.debug( "Looking up WikiSession for NULL HttpRequest: returning guestSession()" ); } return guestSession( engine ); } // Look for a WikiSession associated with the user's Http Session // and create one if it isn't there yet. HttpSession session = request.getSession(); SessionMonitor monitor = SessionMonitor.getInstance( engine ); WikiSession wikiSession = monitor.find( session ); // Attach reference to wiki engine wikiSession.m_engine = engine; // Start the session monitor thread if not started already if ( !monitor.isAlive() ) { monitor.start(); } return wikiSession; } /** * Static factory method that creates a new "guest" session containing a single * user Principal {@link com.ecyrd.jspwiki.auth.WikiPrincipal#GUEST}, * plus the role principals {@link Role#ALL} and * {@link Role#ANONYMOUS}. This method also adds the session as a listener * for GroupManager or AuthenticationManager events. * @param engine the wiki engine * @return the guest wiki session */ public static final WikiSession guestSession( WikiEngine engine ) { WikiSession session = new WikiSession(); session.m_engine = engine; session.invalidate(); // Add the session as listener for GroupManager, AuthManager events GroupManager groupMgr = engine.getGroupManager(); AuthenticationManager authMgr = engine.getAuthenticationManager(); groupMgr.addWikiEventListener( session ); authMgr.addWikiEventListener( session ); return session; } /** * Returns the total number of active wiki sessions for a * particular wiki. This method delegates to the wiki's * {@link SessionMonitor#sessions()} method. * @param engine the wiki session * @return the number of sessions */ public static final int sessions( WikiEngine engine ) { SessionMonitor monitor = SessionMonitor.getInstance( engine ); return monitor.sessions(); } /** * Returns Principals representing the current users known * to a particular wiki. Each Principal will correspond to the * value returned by each WikiSession's {@link #getUserPrincipal()} * method. This method delegates to {@link SessionMonitor#userPrincipals()}. * @param engine the wiki engine * @return an array of Principal objects, sorted by name */ public static final Principal[] userPrincipals( WikiEngine engine ) { SessionMonitor monitor = SessionMonitor.getInstance( engine ); return monitor.userPrincipals(); } /** * Wrapper for * {@link javax.security.auth.Subject#doAsPrivileged(Subject, java.security.PrivilegedExceptionAction, java.security.AccessControlContext)} * that executes an action with the privileges posssessed by a * WikiSession's Subject. The action executes with a <code>null</code> * AccessControlContext, which has the effect of running it "cleanly" * without the AccessControlContexts of the caller. * @param session the wiki session * @param action the privileged action * @return the result of the privileged action; may be <code>null</code> * @throws java.security.AccessControlException if the action is not permitted * by the security policy */ public static final Object doPrivileged( WikiSession session, PrivilegedAction action ) throws AccessControlException { return Subject.doAsPrivileged( session.m_subject, action, null ); } /** * Verifies whether a String represents an IPv4 address. The algorithm is * extremely efficient and does not allocate any objects. * @param name the address to test * @return the result */ protected static final boolean isIPV4Address( String name ) { if ( name.charAt( 0 ) == DOT || name.charAt( name.length() - 1 ) == DOT ) { return false; } int[] addr = new int[] { 0, 0, 0, 0 }; int currentOctet = 0; for( int i = 0; i < name.length(); i++ ) { int ch = name.charAt( i ); boolean isDigit = ( ch >= ONE && ch <= NINE ); boolean isDot = ( ch == DOT ); if ( !isDigit && !isDot ) { return false; } if ( isDigit ) { addr[currentOctet] = 10 * addr[currentOctet] + ( ch - ONE ); if ( addr[currentOctet] > 255 ) { return false; } } else if ( name.charAt( i - 1 ) == DOT ) { return false; } else { currentOctet++; } } return ( currentOctet == 3 ); } }
package com.elusivehawk.util; import java.io.File; import java.lang.management.ManagementFactory; import com.elusivehawk.util.io.FileHelper; /** * * Static API for basic specifications regarding the current computer. * * @author Elusivehawk */ public final class CompInfo { private CompInfo(){} public static final boolean IS_64_BIT = System.getProperty("os.arch").endsWith("64"), DEBUG = ManagementFactory.getRuntimeMXBean().getInputArguments().toString().contains("-agentlib:jdwp"); public static final String JAVA_VERSION = System.getProperty("java.vm.specification.version"), TIME_ZONE = System.getProperty("user.timezone"), USERNAME = System.getProperty("user.name"), VENDOR = System.getProperty("java.vendor"); public static final String[] PATH = System.getProperty("java.library.path").split(System.getProperty("path.separator")); public static final EnumOS OS = EnumOS.getCurrentOS(); public static final int CORES = Runtime.getRuntime().availableProcessors(); public static final File JAR_DIR = FileHelper.getRootResDir(), USER_DIR = new File(System.getProperty("user.home")), TMP_DIR = new File(System.getProperty("java.io.tmpdir")); public static final boolean BUILT = FileHelper.getExtension(JAR_DIR) != null; }
package com.gh4a.loader; import java.io.IOException; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.eclipse.egit.github.core.Release; import org.eclipse.egit.github.core.RepositoryId; import org.eclipse.egit.github.core.service.RepositoryService; import android.content.Context; import com.gh4a.Gh4Application; public class ReleaseLoader extends BaseLoader<List<Release>> { private String mRepoOwner; private String mRepoName; public ReleaseLoader(Context context, String repoOwner, String repoName) { super(context); mRepoOwner = repoOwner; mRepoName = repoName; } @Override public List<Release> doLoadInBackground() throws IOException { RepositoryService repoService = (RepositoryService) Gh4Application.get(getContext()).getService(Gh4Application.REPO_SERVICE); List<Release> releases = repoService.getReleases(new RepositoryId(mRepoOwner, mRepoName)); Collections.sort(releases, new Comparator<Release>() { @Override public int compare(Release lhs, Release rhs) { return rhs.getCreatedAt().compareTo(lhs.getCreatedAt()); } }); return releases; } }
package org.timepedia.chronoscope.client.browser; import org.timepedia.chronoscope.client.ChronoscopeOptions; import org.timepedia.chronoscope.client.Cursor; import org.timepedia.chronoscope.client.canvas.AbstractLayer; import org.timepedia.chronoscope.client.canvas.Bounds; import org.timepedia.chronoscope.client.canvas.Canvas; import org.timepedia.chronoscope.client.canvas.CanvasImage; import org.timepedia.chronoscope.client.canvas.CanvasPattern; import org.timepedia.chronoscope.client.canvas.Color; import org.timepedia.chronoscope.client.canvas.Layer; import org.timepedia.chronoscope.client.canvas.PaintStyle; import org.timepedia.chronoscope.client.canvas.RadialGradient; import org.timepedia.chronoscope.client.render.LinearGradient; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.Element; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Image; /** * An implementation of the Layer interface using the Safari/WHATWG Javascript * CANVAS. * * @author Ray Cromwell &lt;ray@timepedia.org&gt; */ public class BrowserLayer extends AbstractLayer { private static final String[] compositeModes = {"copy", "source-atop", "source-in", "source-out", "source-over", "destination-atop", "destination-in", "destination-out", "destination-over", "darker", "lighter", "xor"}; private static final String[] TEXT_ALIGN = { "start", "end", "left", "right", "center"}; private static final String[] TEXT_BASELINE = { "top", "hanging", "middle", "alphabetic", "ideographic", "bottom"}; private static int layerCount = 0; private Element canvas; private JavaScriptObject ctx; private JavaScriptObject ctxText; private String strokeColor; private Color _strokeColor; private String fillColor; private Color _fillColor; private Bounds bounds; private final String layerId; private final String layerIdText; private Element layerContainer; private int zorder; private int scrollLeft; public BrowserLayer(Canvas canvas, String layerId, Bounds b) { super(canvas); this.layerId = layerId; this.layerIdText = layerId+"text"; init(b); } public native void arc(double x, double y, double radius, double startAngle, double endAngle, int clockwise) /*-{ this.@org.timepedia.chronoscope.client.browser.BrowserLayer::ctx.arc(x,y,radius,startAngle, endAngle, clockwise); }-*/; public native void beginPath() /*-{ this.@org.timepedia.chronoscope.client.browser.BrowserLayer::ctx.beginPath(); }-*/; /*public void arc(double x, double y, double radius, double startAngle, double endAngle, int clockwise) { arc0(ctx, x, y, radius, startAngle, endAngle, clockwise); }*/ public void clearRect(double x, double y, double width, double height) { if (width != 0 && height != 0) { clearRect0(ctx, x, y, width, height); } } public void clear() { clear0(ctx, canvas); } public void clearTextLayer(String textLayer) { // clear0(ctxText, canvasText); } public void clip(double x, double y, double width, double height) { super.clip(x, y, width, height); beginPath(); rect(x, y, width, height); clip0(ctx); } public void closePath() { closePath0(ctx); } public LinearGradient createLinearGradient(double x, double y, double w, double h) { return new BrowserLinearGradient(this, x, y, w, h); } public PaintStyle createPattern(String imageUri) { return new BrowserCanvasPattern(this, imageUri); } public RadialGradient createRadialGradient(double x0, double y0, double r0, double x1, double y1, double r1) { return new BrowserRadialGradient(this, x0, y0, r0, x1, y1, r1); } public void drawImage(Layer layer, double x, double y, double width, double height) { if (layer instanceof BrowserCanvas) { drawImage0(ctx, ((BrowserLayer) ((BrowserCanvas) layer).getRootLayer()).getElement(), x, y, width, height); } else { drawImage0(ctx, ((BrowserLayer) layer).getElement(), x, y, width, height); } } public void drawImage(Layer layer, double sx, double sy, double swidth, double sheight, double dx, double dy, double dwidth, double dheight) { if (layer instanceof BrowserCanvas) { drawImageSrcDest0(ctx, ((BrowserLayer) ((BrowserCanvas) layer).getRootLayer()).getElement(), sx, sy, swidth, sheight, dx, dy, dwidth, dheight); } else { drawImageSrcDest0(ctx, ((BrowserLayer) layer).getElement(), sx, sy, swidth, sheight, dx, dy, dwidth, dheight); } } public void drawImage(CanvasImage image, double dx, double dy, double dwidth, double dheight) { Image im = ((BrowserCanvasImage)image).getNative(); drawImageSrcDest0(ctx, im.getElement(), im.getOriginLeft(), im.getOriginTop(), im.getWidth(), im.getHeight(), dx, dy, dwidth, dheight); } public void fill() { fill0(ctx); } public native void fillRect(double x, double y, double w, double h) /*-{ this.@org.timepedia.chronoscope.client.browser.BrowserLayer::ctx.fillRect(x, y, w, h); }-*/; public Bounds getBounds() { return bounds; } @Override public int stringWidth(String label, String fontFamily, String fontWeight, String fontSize) { return csw(ctx, label, fontSize + " "+ fontFamily); } private native int csw(JavaScriptObject ctx, String label, String font) /*-{ ctx.font = font; return ctx.measureText(label).width; }-*/; /* this is a hack because there is no height but it usually works. */ @Override public int stringHeight(String label, String fontFamily, String fontWeight, String fontSize) { return csw(ctx, "h", fontSize + " "+ fontFamily)*2; } // TODO - alignment public void drawText(double x, double y, String label, String fontFamily, String fontWeight, String fontSize, String layerName, Cursor cursorStyle) { Color _prevStrokeColor = _strokeColor; Color _prevFillColor = _fillColor; if (cursorStyle == Cursor.CONTRASTED) { setLineWidth(2); setStrokeColor(Color.WHITE); strokeText(label, x, y, fontFamily, fontSize, TEXT_BASELINE[TEXT_BASELINE_TOP]); setStrokeColor(_prevStrokeColor); } else { setLineWidth(1); setStrokeColor(Color.WHITE); strokeText(label, x, y, fontFamily, fontSize, TEXT_BASELINE[TEXT_BASELINE_TOP]); setStrokeColor(_prevStrokeColor); } setFillColor(_strokeColor); fillText(label, x, y, fontFamily, fontSize, TEXT_BASELINE[TEXT_BASELINE_TOP]); setFillColor(_prevFillColor); if (cursorStyle == Cursor.CLICKABLE) { // DOM.setStyleAttribute(textDiv, "textDecoration", "underline"); // DOM.setStyleAttribute(textDiv, "cursor", "pointer"); } } protected void fillText(String label, double x, double y, String fontFamily, String fontSize, String baseline) { fillText0(ctxText, label, x,y, fontSize+" "+fontFamily, baseline); } private native void fillText0(JavaScriptObject ctx, String label, double x, double y, String font, String baseline) /*-{ ctx.font = font; ctx.textBaseline = baseline; ctx.fillText(label, x, y); }-*/; // TODO - alignment protected void strokeText(String label, double x, double y, String fontFamily, String fontSize, String baseline) { strokeText0(ctxText, label, x,y, fontSize+" "+fontFamily, baseline); } private native void strokeText0(JavaScriptObject ctx, String label, double x, double y, String font, String baseline) /*-{ ctx.font = font; ctx.textBaseline = baseline; ctx.strokeText(label, x, y); }-*/; public Element getElement() { return canvas; } public double getHeight() { return bounds.height; } public float getLayerAlpha() { return DOM.getIntStyleAttribute(canvas, "opacity"); } public Element getLayerElement() { return layerContainer; } public String getLayerId() { return layerId; } public int getLayerOrder() { return zorder; } public int getScrollLeft() { return scrollLeft; } public String getStrokeColor() { return strokeColor; } public String getTransparency() { return getTransparency0(ctx); } public double getWidth() { return bounds.width; } public boolean isVisible() { return DOM.getStyleAttribute(layerContainer, "visibility") .equals("visible"); } public native void lineTo(double x, double y) /*-{ this.@org.timepedia.chronoscope.client.browser.BrowserLayer::ctx.lineTo(x, y); }-*/; public native void moveTo(double x, double y) /*-{ this.@org.timepedia.chronoscope.client.browser.BrowserLayer::ctx.moveTo(x, y); }-*/; public void rect(double x, double y, double width, double height) { rect0(ctx, x, y, width, height); } @Override public void rotate(double angle) { rotate0(ctx, angle); } private native void rotate0(JavaScriptObject ctx, double angle) /*-{ ctx.rotate(angle); }-*/; public void restore() { restore0(ctx); } public void save() { save0(ctx); } public void scale(double sx, double sy) { assert sx > 0.0 : "Scale X is zero"; assert sy > 0.0 : "Scale Y is zero"; scale0(sx, sy); } public native void scale0(double sx, double sy) /*-{ this.@org.timepedia.chronoscope.client.browser.BrowserLayer::ctx.scale(sx, sy); }-*/; public void setCanvasPattern(CanvasPattern canvasPattern) { setCanvasPattern0(ctx, ((BrowserCanvasPattern) canvasPattern).getNative()); } public void setComposite(int mode) { setComposite0(ctx, compositeModes[mode]); } public void setFillColor(Color c) { _fillColor = c; String color = c.getCSSColor(); if ("transparent".equals(color)) { color = "rgba(0,0,0,0)"; } try { fillColor = color; setFillColor0(ctx, color); } catch (Throwable t) { if (ChronoscopeOptions.isErrorReportingEnabled()) { Window.alert("Error is " + t + " for color " + color); } } } public void setLayerAlpha(float alpha) { DOM.setStyleAttribute(canvas, "opacity", "" + alpha); } public void setLayerOrder(int zorder) { DOM.setIntStyleAttribute(canvas, "zIndex", zorder); DOM.setIntStyleAttribute(layerContainer, "zIndex", zorder); DOM.setIntStyleAttribute(layerContainer, "zIndex", zorder+1); this.zorder = zorder; } public void setLinearGradient(LinearGradient lingrad) { try { setGradient0(ctx, ((BrowserLinearGradient) lingrad).getNative()); } catch (Throwable t) { if (ChronoscopeOptions.isErrorReportingEnabled()) { Window.alert("setLinearGradient: " + t); } } } public native void setLineWidth(double width) /*-{ this.@org.timepedia.chronoscope.client.browser.BrowserLayer::ctx.lineWidth=width; }-*/; public void setRadialGradient(RadialGradient radialGradient) { setGradient0(ctx, ((BrowserRadialGradient) radialGradient).getNative()); } public void setScrollLeft(int i) { scrollLeft = i; DOM.setStyleAttribute(canvas, "left", i + "px"); } public void setShadowBlur(double width) { setShadowBlur0(ctx, width); } public void setShadowColor(String color) { setShadowColor0(ctx, color); } public void setShadowOffsetX(double x) { setShadowOffsetX0(ctx, x); } public void setShadowOffsetY(double y) { setShadowOffsetY0(ctx, y); } public void setStrokeColor(Color c) { _strokeColor = c; String color = c.getCSSColor(); if ("transparent".equals(color)) { color = "rgba(0,0,0,0)"; } try { strokeColor = color; setStrokeColor0(ctx, color); } catch (Throwable t) { if (ChronoscopeOptions.isErrorReportingEnabled()) { Window.alert("Error is " + t + " for strokecolor " + color); } } } public void setTransparency(float value) { setTransparency0(ctx, value); } public void setVisibility(boolean visibility) { DOM.setStyleAttribute(layerContainer, "visibility", visibility ? "visible" : "hidden"); } public native void stroke() /*-{ this.@org.timepedia.chronoscope.client.browser.BrowserLayer::ctx.stroke(); }-*/; public void translate(double x, double y) { translate0(ctx, x, y); } JavaScriptObject getContext() { return ctx; } public void setTextLayerBounds(String layerName, Bounds bounds) { this.bounds = new Bounds(bounds); this.setVisibility(true); } void init(Bounds b) { layerContainer = DOM.createElement("div"); this.bounds = new Bounds(b); canvas = DOM.createElement("canvas"); String lc = String.valueOf(layerCount++); DOM.setElementAttribute(layerContainer, "id", "_lc_" + layerId + lc); DOM.setElementAttribute(canvas, "id", "_cv_" + layerId + lc); DOM.setElementAttribute(canvas, "width", "" + b.width); DOM.setElementAttribute(canvas, "height", "" + b.height); DOM.setStyleAttribute(canvas, "width", "" + b.width + "px"); DOM.setStyleAttribute(canvas, "height", "" + b.height + "px"); DOM.setStyleAttribute(canvas, "position", "relative"); DOM.setStyleAttribute(layerContainer, "width", "" + b.width + "px"); DOM.setStyleAttribute(layerContainer, "height", "" + b.height + "px"); DOM.setStyleAttribute(layerContainer, "visibility", "visible"); DOM.setStyleAttribute(layerContainer, "position", "absolute"); DOM.setStyleAttribute(layerContainer, "overflow", "hidden"); DOM.setStyleAttribute(layerContainer, "top", b.y + "px"); DOM.setStyleAttribute(layerContainer, "left", b.x + "px"); DOM.setStyleAttribute(layerContainer, "overflow", "visible"); ctx = getCanvasContext(canvas); ctxText = getCanvasContext(canvas); DOM.appendChild(layerContainer, canvas); } private native void clear0(JavaScriptObject ctx, Element can) /*-{ ctx.clearRect(0, 0, can.width, can.height); var _width = can.width; can.width = 1; can.width = _width; }-*/; private native void clearRect0(JavaScriptObject ctx, double x, double y, double width, double height) /*-{ ctx.clearRect(x,y,width,height); }-*/; private native void clip0(JavaScriptObject ctx) /*-{ ctx.clip(); }-*/; private native void closePath0(JavaScriptObject ctx) /*-{ ctx.closePath(); }-*/; private native void drawImage0(JavaScriptObject ctx, JavaScriptObject image, double x, double y, double w, double h) /*-{ ctx.drawImage(image, x, y, w, h); }-*/; private native void drawImageSrcDest0(JavaScriptObject ctx, Element canvas, double sx, double sy, double swidth, double sheight, double dx, double dy, double dwidth, double dheight) /*-{ ctx.drawImage(canvas, sx, sy, swidth, sheight, dx, dy, dwidth, dheight); }-*/; private native void fill0(JavaScriptObject ctx) /*-{ ctx.fill(); }-*/; private native JavaScriptObject getCanvasContext(Element elem) /*-{ return elem.getContext("2d"); }-*/; private String getFillColor() { return fillColor; } private native String getTransparency0(JavaScriptObject ctx) /*-{ return ""+ctx.globalAlpha; }-*/; private native void rect0(JavaScriptObject ctx, double x, double y, double width, double height) /*-{ ctx.rect(x,y,width,height); }-*/; private native void restore0(JavaScriptObject ctx)/*-{ ctx.restore(); }-*/; private native void save0(JavaScriptObject ctx) /*-{ ctx.save(); }-*/; private native void setCanvasPattern0(JavaScriptObject ctx, JavaScriptObject pattern) /*-{ if(pattern != null) { ctx.fillStyle = pattern; } }-*/; private native void setComposite0(JavaScriptObject ctx, String compositeMode) /*-{ ctx.globalCompositeOperation=compositeMode; }-*/; private native void setFillColor0(JavaScriptObject ctx, String color) /*-{ ctx.fillStyle = color; }-*/; private native void setGradient0(JavaScriptObject ctx, JavaScriptObject lingrad) /*-{ ctx.fillStyle = lingrad; }-*/; private native void setShadowBlur0(JavaScriptObject ctx, double width) /*-{ ctx.shadowBlur=width; }-*/; private native void setShadowColor0(JavaScriptObject ctx, String color) /*-{ ctx.shadowColor=color; }-*/; private native void setShadowOffsetX0(JavaScriptObject ctx, double x) /*-{ ctx.shadowOffsetX=x; }-*/; private native void setShadowOffsetY0(JavaScriptObject ctx, double y) /*-{ ctx.shadowOffsetY=y; }-*/; private native void setStrokeColor0(JavaScriptObject ctx, String color) /*-{ ctx.strokeStyle=color; }-*/; private native void setTransparency0(JavaScriptObject ctx, float value) /*-{ ctx.globalAlpha=value; }-*/; private native void translate0(JavaScriptObject ctx, double x, double y) /*-{ ctx.translate(x,y); }-*/; }
package com.hearthsim.io; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import com.hearthsim.card.Card; import com.hearthsim.card.Deck; import com.hearthsim.card.minion.Hero; import com.hearthsim.exception.HSInvalidCardException; import com.hearthsim.exception.HSInvalidHeroException; import com.hearthsim.util.CardFactory; import com.hearthsim.util.HeroFactory; /** * Class to read in a HearthSim deck specification file * */ public class DeckListFile { Deck deck_; Hero hero_; /** * Constructor * * @param setupFilePath The file path to the deck list to be read * @throws IOException * @throws HSInvalidHeroException */ public DeckListFile(Path setupFilePath) throws HSInvalidCardException, IOException, HSInvalidHeroException { this.read(setupFilePath); } /** * Read the given file * * @param setupFilePath The file path to the deck list to be read * @throws IOException * @throws HSInvalidHeroException */ public void read(Path setupFilePath) throws HSInvalidCardException, IOException, HSInvalidHeroException { String inStr = (new String(Files.readAllBytes(setupFilePath))).replace("\\s+", "").replace("'", "").replace("\n", ""); this.parseDeckList(inStr); } /** * Parse a given deck list string and construct a Deck object out of it * * @param deckListStr */ public void parseDeckList(String deckListStr) throws HSInvalidCardException, HSInvalidHeroException { String[] deckList = deckListStr.split(","); ArrayList<Card> cards = new ArrayList<Card>(); //Ignore the first entry for now... hero classes aren't implemented yet! for (int indx = 1; indx < deckList.length; ++indx) { cards.add(CardFactory.getCard(deckList[indx])); } deck_ = new Deck(cards); hero_ = HeroFactory.getHero(deckList[0]); } /** * Get the deck * @return */ public Deck getDeck() { return deck_; } /** * Get the Hero * @return */ public Hero getHero() { return hero_; } }
package edu.cmu.cs.gabriel; import java.io.IOException; import java.util.List; import android.content.Context; import android.graphics.ImageFormat; import android.hardware.Camera; import android.hardware.Camera.PreviewCallback; import android.hardware.Camera.Size; import android.util.AttributeSet; import android.util.Log; import android.view.SurfaceHolder; import android.view.SurfaceView; public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback { private static final String LOG_TAG = "CameraPreview"; private SurfaceHolder mHolder; private boolean isSurfaceReady = false; private boolean waitingToStart = false; private boolean isPreviewing = false; private Camera mCamera = null; private List<int[]> supportingFPS = null; private List<Camera.Size> supportingSize = null; public CameraPreview(Context context, AttributeSet attrs) { super(context, attrs); Log.v(LOG_TAG , "++CameraPreview"); if (mCamera == null) { // Launching Camera App using voice command need to wait. try { Thread.sleep(1000); } catch (InterruptedException e) {} mCamera = Camera.open(); } mHolder = getHolder(); mHolder.addCallback(this); mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); } /** * This is only needed because once the application is onPaused, close() will be called, and during onResume, * the CameraPreview constructor is not called again. */ public Camera checkCamera() { if (mCamera == null) { mCamera = Camera.open(); } return mCamera; } public void start() { if (mCamera == null) { mCamera = Camera.open(); } if (isSurfaceReady) { try { mCamera.setPreviewDisplay(mHolder); } catch (IOException exception) { Log.e(LOG_TAG, "Error in setting camera holder: " + exception.getMessage()); this.close(); } updateCameraConfigurations(Const.CAPTURE_FPS, Const.IMAGE_WIDTH, Const.IMAGE_HEIGHT); } else { waitingToStart = true; } } public void close() { if (mCamera != null) { mCamera.stopPreview(); isPreviewing = false; mCamera.release(); mCamera = null; } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // TODO Auto-generated method stub super.onMeasure(widthMeasureSpec, heightMeasureSpec); } public void changeConfiguration(int[] range, Size imageSize) { Camera.Parameters parameters = mCamera.getParameters(); if (range != null){ Log.i("Config", "frame rate configuration : " + range[0] + "," + range[1]); parameters.setPreviewFpsRange(range[0], range[1]); } if (imageSize != null){ Log.i("Config", "image size configuration : " + imageSize.width + "," + imageSize.height); parameters.setPreviewSize(imageSize.width, imageSize.height); } //parameters.setPreviewFormat(ImageFormat.JPEG); mCamera.setParameters(parameters); } public void surfaceCreated(SurfaceHolder holder) { Log.d(LOG_TAG, "++surfaceCreated"); isSurfaceReady = true; if (mCamera == null) { mCamera = Camera.open(); } if (mCamera != null) { // get fps to capture Camera.Parameters parameters = mCamera.getParameters(); this.supportingFPS = parameters.getSupportedPreviewFpsRange(); for (int[] range: this.supportingFPS) { Log.i(LOG_TAG, "available fps ranges:" + range[0] + ", " + range[1]); } // get resolution this.supportingSize = parameters.getSupportedPreviewSizes(); for (Camera.Size size: this.supportingSize) { Log.i(LOG_TAG, "available sizes:" + size.width + ", " + size.height); } if (waitingToStart) { waitingToStart = false; try { mCamera.setPreviewDisplay(mHolder); } catch (IOException exception) { Log.e(LOG_TAG, "Error in setting camera holder: " + exception.getMessage()); this.close(); } updateCameraConfigurations(Const.CAPTURE_FPS, Const.IMAGE_WIDTH, Const.IMAGE_HEIGHT); } } else { Log.w(LOG_TAG, "Camera is not open"); } } public void surfaceDestroyed(SurfaceHolder holder) { isSurfaceReady = false; this.close(); } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { Log.d(LOG_TAG, "surface changed"); /* * Camera.Parameters parameters = mCamera.getParameters(); * parameters.setPreviewSize(w, h); mCamera.setParameters(parameters); * mCamera.startPreview(); */ } public void updateCameraConfigurations(int targetFps, int imgWidth, int imgHeight) { if (mCamera != null) { if (targetFps != -1) { Const.CAPTURE_FPS = targetFps; } if (imgWidth != -1) { Const.IMAGE_WIDTH = imgWidth; Const.IMAGE_HEIGHT = imgHeight; } if (isPreviewing) mCamera.stopPreview(); // set fps to capture int index = 0, fpsDiff = Integer.MAX_VALUE; for (int i = 0; i < this.supportingFPS.size(); i++){ int[] frameRate = this.supportingFPS.get(i); int diff = Math.abs(Const.CAPTURE_FPS * 1000 - frameRate[0]) + Math.abs(Const.CAPTURE_FPS * 1000 - frameRate[1]); if (diff < fpsDiff){ fpsDiff = diff; index = i; } } int[] targetRange = this.supportingFPS.get(index); // set resolution index = 0; int sizeDiff = Integer.MAX_VALUE; for (int i = 0; i < this.supportingSize.size(); i++){ Camera.Size size = this.supportingSize.get(i); int diff = Math.abs(size.width - Const.IMAGE_WIDTH) + Math.abs(size.height - Const.IMAGE_HEIGHT); if (diff < sizeDiff){ sizeDiff = diff; index = i; } } Camera.Size target_size = this.supportingSize.get(index); changeConfiguration(targetRange, target_size); mCamera.startPreview(); isPreviewing = true; } } }
package com.lsu.vizeq; import java.io.ByteArrayOutputStream; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.JsonHttpResponseHandler; import android.os.Bundle; import android.os.Process; import android.app.ActionBar; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.view.animation.Animation; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.SpinnerAdapter; import android.widget.TabHost; import android.widget.TabHost.TabSpec; import android.widget.TableRow; import android.widget.TextView; public class ProfileActivity extends Activity implements OnItemSelectedListener{ public String mColor; LinearLayout customSearchLayout; public static ArrayList<Track> customList; OnClickListener submitListener; ActionBar actionBar; AsyncHttpClient searchClient = new AsyncHttpClient(); public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { // An item was selected. You can retrieve the selected item using parent.getItemAtPosition(pos) SharedPreferences memory = getSharedPreferences("VizEQ", MODE_PRIVATE); mColor = (String) parent.getItemAtPosition(pos); SharedPreferences.Editor saver = memory.edit(); saver.putString("color", mColor); saver.putInt("colorPos", pos); saver.commit(); actionBar = getActionBar(); int posi = memory.getInt("colorPos", -1); if (posi != -1) VizEQ.numRand = posi; switch (VizEQ.numRand) { case 0: actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.black))); break; case 1: actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.Blue))); break; case 2: actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.Green))); break; case 3: actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.Red))); break; case 4: actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.Grey85))); break; case 5: actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.Orange))); break; case 6: actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.Purple))); break; } } public void onNothingSelected(AdapterView<?> parent) { // Another interface callback actionBar = getActionBar(); SharedPreferences memory = getSharedPreferences("VizEQ", MODE_PRIVATE); int posi = memory.getInt("colorPos", -1); if (posi != -1) VizEQ.numRand = posi; switch (VizEQ.numRand) { case 0: actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.black))); break; case 1: actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.Blue))); break; case 2: actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.Green))); break; case 3: actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.Red))); break; case 4: actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.Grey85))); break; case 5: actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.Orange))); break; case 6: actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.Purple))); break; } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile); actionBar = getActionBar(); SharedPreferences memory = getSharedPreferences("VizEQ",MODE_PRIVATE); int posi = memory.getInt("colorPos", -1); if (posi != -1) VizEQ.numRand = posi; switch (VizEQ.numRand) { case 0: actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.black))); break; case 1: actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.Blue))); break; case 2: actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.Green))); break; case 3: actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.Red))); break; case 4: actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.Grey85))); break; case 5: actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.Orange))); break; case 6: actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.Purple))); break; } customSearchLayout = (LinearLayout) findViewById(R.id.customSearchLayout); final EditText searchText = (EditText) findViewById(R.id.CustomSearchField); final OnTouchListener rowTap; customList = new ArrayList<Track>(); TabHost tabhost = (TabHost) findViewById(android.R.id.tabhost); tabhost.setup(); TabSpec ts = tabhost.newTabSpec("tab01"); ts.setContent(R.id.tab01); ts.setIndicator("Search"); tabhost.addTab(ts); ts = tabhost.newTabSpec("tab02"); ts.setContent(R.id.tab02); ts.setIndicator("Playlist"); tabhost.addTab(ts); ts = tabhost.newTabSpec("tab03"); ts.setContent(R.id.tab03); ts.setIndicator("Profile"); tabhost.addTab(ts); final LinearLayout customListTab = (LinearLayout) findViewById(R.id.tab02); Button submit = (Button)findViewById(R.id.SubmitCustomList); submit.setOnClickListener(submitListener); //Animation an = new Animation(); // Color Spinner Spinner spinner = (Spinner) findViewById(R.id.colorspinner); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.color_spinner, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setOnItemSelectedListener(this); spinner.setAdapter(adapter); rowTap = new OnTouchListener() { @Override public boolean onTouch(View arg0, MotionEvent arg1) { if (arg1.getAction() == MotionEvent.ACTION_DOWN) { TableRow row = (TableRow)arg0; row.setBackgroundColor(Color.BLUE); return true; } else if (arg1.getAction() == MotionEvent.ACTION_UP) { final TrackRow row = (TrackRow)arg0; row.setBackgroundColor(row.originalColor); AlertDialog.Builder builder = new AlertDialog.Builder(ProfileActivity.this); builder.setMessage(R.string.QueueTopOrBottom) .setPositiveButton("Top", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { customList.add(0, row.getTrack()); TrackRow customListRow = row; customListRow.setOnTouchListener(null); customSearchLayout.removeView(customListRow); customListTab.addView(customListRow, 0); if (customListTab.getChildCount() > 1) { if (((TrackRow)(customListTab.getChildAt(1))).originalColor == TrackRow.color1) { customListRow.setBackgroundColor(TrackRow.color2); customListRow.originalColor = TrackRow.color2; } else { customListRow.setBackgroundColor(TrackRow.color1); customListRow.originalColor = TrackRow.color1; } } else { customListRow.setBackgroundColor(TrackRow.color1); customListRow.originalColor = TrackRow.color1; } } }) .setNegativeButton("Bottom", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { customList.add(row.getTrack()); TrackRow customListRow = row; customListRow.setOnTouchListener(null); customSearchLayout.removeView(customListRow); customListTab.addView(customListRow); if (customListTab.getChildCount() > 0) { if (((TrackRow)(customListTab.getChildAt(customListTab.getChildCount() - 1))).originalColor == TrackRow.color1) customListRow.setBackgroundColor(TrackRow.color2); else { customListRow.setBackgroundColor(TrackRow.color1); customListRow.originalColor = TrackRow.color1; } } else { customListRow.setBackgroundColor(TrackRow.color1); customListRow.originalColor = TrackRow.color1; } } }); //builder.create(); builder.show(); return true; } else if (arg1.getAction() == MotionEvent.ACTION_CANCEL) { TrackRow row = (TrackRow)arg0; row.setBackgroundColor(row.originalColor); return true; } return false; } }; findViewById(R.id.SearchOK).setOnClickListener(new OnClickListener(){ @Override public void onClick(View arg0) { // TODO Auto-generated method stub customSearchLayout.removeAllViews(); String strSearch = searchText.getText().toString(); strSearch = strSearch.replace(' ', '+'); searchText.clearFocus(); searchClient.get("http://ws.spotify.com/search/1/track.json?q=" + strSearch, new JsonHttpResponseHandler() { public void onSuccess(JSONObject response) { try { JSONArray tracks = response.getJSONArray("tracks"); //JSONObject track = tracks.getJSONObject(0); for (int i = 0; i < tracks.length(); i++) { String trackName = tracks.getJSONObject(i).getString("name"); String trackArtist = tracks.getJSONObject(i).getJSONArray("artists").getJSONObject(0).getString("name"); String uri = tracks.getJSONObject(i).getString("href"); String trackAlbum = tracks.getJSONObject(i).getJSONObject("album").getString("name"); //Log.d("Search", trackName + ": " + trackArtist); TrackRow tableRowToAdd = new TrackRow(ProfileActivity.this); TextView textViewToAdd = new TextView(ProfileActivity.this); TextView textTwoViewToAdd = new TextView(ProfileActivity.this); tableRowToAdd.mTrack = trackName; tableRowToAdd.mArtist = trackArtist; tableRowToAdd.mAlbum = trackAlbum; tableRowToAdd.mUri = uri; if (i % 2 == 0) { tableRowToAdd.setBackgroundColor(TrackRow.color1); tableRowToAdd.originalColor = TrackRow.color1; } else { tableRowToAdd.setBackgroundColor(TrackRow.color2); tableRowToAdd.originalColor = TrackRow.color2; } textViewToAdd.setText(trackName); textTwoViewToAdd.setText(trackArtist); textViewToAdd.setTextSize(20); textTwoViewToAdd.setTextColor(Color.DKGRAY); LinearLayout linearLayoutToAdd = new LinearLayout(ProfileActivity.this); linearLayoutToAdd.setOrientation(LinearLayout.VERTICAL); linearLayoutToAdd.addView(textViewToAdd); linearLayoutToAdd.addView(textTwoViewToAdd); tableRowToAdd.setOnTouchListener(rowTap); tableRowToAdd.addView(linearLayoutToAdd); customSearchLayout.addView(tableRowToAdd); } //mAlbumUri = album.getString("spotify"); //mImageUri = album.getString("image"); // Now get track details from the webapi } catch (JSONException e) { throw new RuntimeException("Could not parse the results"); } } }); } }); submitListener = new OnClickListener() { @Override public void onClick(View v) { new Runnable() { @Override public void run() { try { DatagramSocket listenSocket = new DatagramSocket(7770); DatagramSocket sendSocket = new DatagramSocket(); //while(true) //listen for search //Log.d("listen thread","listening"); //byte[] receiveData = new byte[1024]; //DatagramPacket receivedPacket = new DatagramPacket(receiveData, receiveData.length); //listenSocket.receive(receivedPacket); //Log.d("listen thread", "packet received"); /*InetAddress ip = receivedPacket.getAddress(); int port = receivedPacket.getPort(); String data = new String(receivedPacket.getData()); if (data.substring(0, 6).equals("search")) { Log.d("listen thread", "search received from "+ip.toString()+" "+ip.getHostAddress()); //send back information String information = "found "; information += (myapp.myName); Log.d("listen thread", "sending back"+information);*/ //make a packet containing all elements with newlines between each for (int j = 0; j < customList.size(); j++) { byte[] requestHeader = "request\n".getBytes(); byte[] backslashN = "\n".getBytes(); byte[] albumBytes = customList.get(j).mAlbum.getBytes(); byte[] artistBytes = customList.get(j).mArtist.getBytes(); byte[] requesterBytes = customList.get(j).mRequester.getBytes(); byte[] trackBytes= customList.get(j).mTrack.getBytes(); byte[] uriBytes = customList.get(j).mUri.getBytes(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); outputStream.write(requestHeader); outputStream.write(albumBytes); outputStream.write(backslashN); outputStream.write(artistBytes); outputStream.write(backslashN); outputStream.write(requesterBytes); outputStream.write(backslashN); outputStream.write(trackBytes); outputStream.write(backslashN); outputStream.write(uriBytes); outputStream.write(backslashN); byte[] sendData = outputStream.toByteArray(); InetAddress ip = RoleActivity.myapp.hostAddress; DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, ip, 7770); sendSocket.send(sendPacket); } } catch (Exception e) { e.printStackTrace(); } } }.run();//Say run here, once it's correct } }; } }
package org.elasticsearch.client; import com.carrotsearch.randomizedtesting.generators.CodepointSetGenerator; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.ElasticsearchStatusException; import org.elasticsearch.Version; import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.get.GetRequest; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.ingest.PutPipelineRequest; import org.elasticsearch.action.support.WriteRequest; import org.elasticsearch.action.support.master.AcknowledgedResponse; import org.elasticsearch.action.update.UpdateRequest; import org.elasticsearch.client.core.PageParams; import org.elasticsearch.client.indices.CreateIndexRequest; import org.elasticsearch.client.indices.GetIndexRequest; import org.elasticsearch.client.ml.CloseJobRequest; import org.elasticsearch.client.ml.CloseJobResponse; import org.elasticsearch.client.ml.DeleteCalendarEventRequest; import org.elasticsearch.client.ml.DeleteCalendarJobRequest; import org.elasticsearch.client.ml.DeleteCalendarRequest; import org.elasticsearch.client.ml.DeleteDataFrameAnalyticsRequest; import org.elasticsearch.client.ml.DeleteDatafeedRequest; import org.elasticsearch.client.ml.DeleteExpiredDataRequest; import org.elasticsearch.client.ml.DeleteExpiredDataResponse; import org.elasticsearch.client.ml.DeleteFilterRequest; import org.elasticsearch.client.ml.DeleteForecastRequest; import org.elasticsearch.client.ml.DeleteJobRequest; import org.elasticsearch.client.ml.DeleteJobResponse; import org.elasticsearch.client.ml.DeleteModelSnapshotRequest; import org.elasticsearch.client.ml.DeleteTrainedModelAliasRequest; import org.elasticsearch.client.ml.DeleteTrainedModelRequest; import org.elasticsearch.client.ml.EstimateModelMemoryRequest; import org.elasticsearch.client.ml.EstimateModelMemoryResponse; import org.elasticsearch.client.ml.EvaluateDataFrameRequest; import org.elasticsearch.client.ml.EvaluateDataFrameResponse; import org.elasticsearch.client.ml.ExplainDataFrameAnalyticsRequest; import org.elasticsearch.client.ml.ExplainDataFrameAnalyticsResponse; import org.elasticsearch.client.ml.FlushJobRequest; import org.elasticsearch.client.ml.FlushJobResponse; import org.elasticsearch.client.ml.ForecastJobRequest; import org.elasticsearch.client.ml.ForecastJobResponse; import org.elasticsearch.client.ml.GetCalendarEventsRequest; import org.elasticsearch.client.ml.GetCalendarEventsResponse; import org.elasticsearch.client.ml.GetCalendarsRequest; import org.elasticsearch.client.ml.GetCalendarsResponse; import org.elasticsearch.client.ml.GetDataFrameAnalyticsRequest; import org.elasticsearch.client.ml.GetDataFrameAnalyticsResponse; import org.elasticsearch.client.ml.GetDataFrameAnalyticsStatsRequest; import org.elasticsearch.client.ml.GetDataFrameAnalyticsStatsResponse; import org.elasticsearch.client.ml.GetDatafeedRequest; import org.elasticsearch.client.ml.GetDatafeedResponse; import org.elasticsearch.client.ml.GetDatafeedStatsRequest; import org.elasticsearch.client.ml.GetDatafeedStatsResponse; import org.elasticsearch.client.ml.GetFiltersRequest; import org.elasticsearch.client.ml.GetFiltersResponse; import org.elasticsearch.client.ml.GetJobRequest; import org.elasticsearch.client.ml.GetJobResponse; import org.elasticsearch.client.ml.GetJobStatsRequest; import org.elasticsearch.client.ml.GetJobStatsResponse; import org.elasticsearch.client.ml.GetModelSnapshotsRequest; import org.elasticsearch.client.ml.GetModelSnapshotsResponse; import org.elasticsearch.client.ml.GetTrainedModelsRequest; import org.elasticsearch.client.ml.GetTrainedModelsResponse; import org.elasticsearch.client.ml.GetTrainedModelsStatsRequest; import org.elasticsearch.client.ml.GetTrainedModelsStatsResponse; import org.elasticsearch.client.ml.MlInfoRequest; import org.elasticsearch.client.ml.MlInfoResponse; import org.elasticsearch.client.ml.OpenJobRequest; import org.elasticsearch.client.ml.OpenJobResponse; import org.elasticsearch.client.ml.PostCalendarEventRequest; import org.elasticsearch.client.ml.PostCalendarEventResponse; import org.elasticsearch.client.ml.PostDataRequest; import org.elasticsearch.client.ml.PostDataResponse; import org.elasticsearch.client.ml.PreviewDatafeedRequest; import org.elasticsearch.client.ml.PreviewDatafeedResponse; import org.elasticsearch.client.ml.PutCalendarJobRequest; import org.elasticsearch.client.ml.PutCalendarRequest; import org.elasticsearch.client.ml.PutCalendarResponse; import org.elasticsearch.client.ml.PutDataFrameAnalyticsRequest; import org.elasticsearch.client.ml.PutDataFrameAnalyticsResponse; import org.elasticsearch.client.ml.PutDatafeedRequest; import org.elasticsearch.client.ml.PutDatafeedResponse; import org.elasticsearch.client.ml.PutFilterRequest; import org.elasticsearch.client.ml.PutFilterResponse; import org.elasticsearch.client.ml.PutJobRequest; import org.elasticsearch.client.ml.PutJobResponse; import org.elasticsearch.client.ml.PutTrainedModelAliasRequest; import org.elasticsearch.client.ml.PutTrainedModelRequest; import org.elasticsearch.client.ml.PutTrainedModelResponse; import org.elasticsearch.client.ml.RevertModelSnapshotRequest; import org.elasticsearch.client.ml.RevertModelSnapshotResponse; import org.elasticsearch.client.ml.SetUpgradeModeRequest; import org.elasticsearch.client.ml.StartDataFrameAnalyticsRequest; import org.elasticsearch.client.ml.StartDatafeedRequest; import org.elasticsearch.client.ml.StartDatafeedResponse; import org.elasticsearch.client.ml.StopDataFrameAnalyticsRequest; import org.elasticsearch.client.ml.StopDataFrameAnalyticsResponse; import org.elasticsearch.client.ml.StopDatafeedRequest; import org.elasticsearch.client.ml.StopDatafeedResponse; import org.elasticsearch.client.ml.UpdateDataFrameAnalyticsRequest; import org.elasticsearch.client.ml.UpdateDatafeedRequest; import org.elasticsearch.client.ml.UpdateFilterRequest; import org.elasticsearch.client.ml.UpdateJobRequest; import org.elasticsearch.client.ml.UpdateModelSnapshotRequest; import org.elasticsearch.client.ml.UpdateModelSnapshotResponse; import org.elasticsearch.client.ml.UpgradeJobModelSnapshotRequest; import org.elasticsearch.client.ml.calendars.Calendar; import org.elasticsearch.client.ml.calendars.CalendarTests; import org.elasticsearch.client.ml.calendars.ScheduledEvent; import org.elasticsearch.client.ml.calendars.ScheduledEventTests; import org.elasticsearch.client.ml.datafeed.DatafeedConfig; import org.elasticsearch.client.ml.datafeed.DatafeedState; import org.elasticsearch.client.ml.datafeed.DatafeedStats; import org.elasticsearch.client.ml.datafeed.DatafeedUpdate; import org.elasticsearch.client.ml.dataframe.DataFrameAnalyticsConfig; import org.elasticsearch.client.ml.dataframe.DataFrameAnalyticsConfigUpdate; import org.elasticsearch.client.ml.dataframe.DataFrameAnalyticsDest; import org.elasticsearch.client.ml.dataframe.DataFrameAnalyticsSource; import org.elasticsearch.client.ml.dataframe.DataFrameAnalyticsState; import org.elasticsearch.client.ml.dataframe.DataFrameAnalyticsStats; import org.elasticsearch.client.ml.dataframe.PhaseProgress; import org.elasticsearch.client.ml.dataframe.QueryConfig; import org.elasticsearch.client.ml.dataframe.evaluation.classification.AccuracyMetric; import org.elasticsearch.client.ml.dataframe.evaluation.classification.AucRocMetric; import org.elasticsearch.client.ml.dataframe.evaluation.classification.Classification; import org.elasticsearch.client.ml.dataframe.evaluation.classification.MulticlassConfusionMatrixMetric; import org.elasticsearch.client.ml.dataframe.evaluation.classification.PerClassSingleValue; import org.elasticsearch.client.ml.dataframe.evaluation.classification.PrecisionMetric; import org.elasticsearch.client.ml.dataframe.evaluation.classification.RecallMetric; import org.elasticsearch.client.ml.dataframe.evaluation.common.AucRocPoint; import org.elasticsearch.client.ml.dataframe.evaluation.common.AucRocResult; import org.elasticsearch.client.ml.dataframe.evaluation.outlierdetection.ConfusionMatrixMetric; import org.elasticsearch.client.ml.dataframe.evaluation.outlierdetection.OutlierDetection; import org.elasticsearch.client.ml.dataframe.evaluation.regression.HuberMetric; import org.elasticsearch.client.ml.dataframe.evaluation.regression.MeanSquaredErrorMetric; import org.elasticsearch.client.ml.dataframe.evaluation.regression.MeanSquaredLogarithmicErrorMetric; import org.elasticsearch.client.ml.dataframe.evaluation.regression.RSquaredMetric; import org.elasticsearch.client.ml.dataframe.evaluation.regression.Regression; import org.elasticsearch.client.ml.dataframe.explain.FieldSelection; import org.elasticsearch.client.ml.dataframe.explain.MemoryEstimation; import org.elasticsearch.client.ml.dataframe.stats.common.DataCounts; import org.elasticsearch.client.ml.dataframe.stats.common.MemoryUsage; import org.elasticsearch.client.ml.inference.InferenceToXContentCompressor; import org.elasticsearch.client.ml.inference.MlInferenceNamedXContentProvider; import org.elasticsearch.client.ml.inference.TrainedModelConfig; import org.elasticsearch.client.ml.inference.TrainedModelDefinition; import org.elasticsearch.client.ml.inference.TrainedModelDefinitionTests; import org.elasticsearch.client.ml.inference.TrainedModelInput; import org.elasticsearch.client.ml.inference.TrainedModelStats; import org.elasticsearch.client.ml.inference.trainedmodel.RegressionConfig; import org.elasticsearch.client.ml.inference.trainedmodel.TargetType; import org.elasticsearch.client.ml.inference.trainedmodel.langident.LangIdentNeuralNetwork; import org.elasticsearch.client.ml.job.config.AnalysisConfig; import org.elasticsearch.client.ml.job.config.AnalysisLimits; import org.elasticsearch.client.ml.job.config.DataDescription; import org.elasticsearch.client.ml.job.config.Detector; import org.elasticsearch.client.ml.job.config.Job; import org.elasticsearch.client.ml.job.config.JobState; import org.elasticsearch.client.ml.job.config.JobUpdate; import org.elasticsearch.client.ml.job.config.MlFilter; import org.elasticsearch.client.ml.job.process.ModelSnapshot; import org.elasticsearch.client.ml.job.stats.JobStats; import org.elasticsearch.client.tasks.GetTaskRequest; import org.elasticsearch.client.tasks.GetTaskResponse; import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.unit.ByteSizeUnit; import org.elasticsearch.common.unit.ByteSizeValue; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.NamedXContentRegistry; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.index.query.MatchAllQueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.rest.RestStatus; import org.elasticsearch.search.SearchHit; import org.elasticsearch.tasks.TaskId; import org.junit.After; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import java.util.stream.IntStream; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.anyOf; import static org.hamcrest.Matchers.closeTo; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.hasItems; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.lessThan; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; public class MachineLearningIT extends ESRestHighLevelClientTestCase { private static final RequestOptions POST_DATA_OPTIONS = RequestOptions.DEFAULT.toBuilder() .setWarningsHandler(warnings -> Collections.singletonList("Posting data directly to anomaly detection jobs is deprecated, " + "in a future major version it will be compulsory to use a datafeed").equals(warnings) == false).build(); @After public void cleanUp() throws IOException { new MlTestStateCleaner(logger, highLevelClient()).clearMlMetadata(); } public void testPutJob() throws Exception { String jobId = randomValidJobId(); Job job = buildJob(jobId); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); PutJobResponse putJobResponse = execute(new PutJobRequest(job), machineLearningClient::putJob, machineLearningClient::putJobAsync); Job createdJob = putJobResponse.getResponse(); assertThat(createdJob.getId(), is(jobId)); assertThat(createdJob.getJobType(), is(Job.ANOMALY_DETECTOR_JOB_TYPE)); } public void testGetJob() throws Exception { String jobId1 = randomValidJobId(); String jobId2 = randomValidJobId(); Job job1 = buildJob(jobId1); Job job2 = buildJob(jobId2); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); machineLearningClient.putJob(new PutJobRequest(job1), RequestOptions.DEFAULT); machineLearningClient.putJob(new PutJobRequest(job2), RequestOptions.DEFAULT); GetJobRequest request = new GetJobRequest(jobId1, jobId2); // Test getting specific jobs GetJobResponse response = execute(request, machineLearningClient::getJob, machineLearningClient::getJobAsync); assertEquals(2, response.count()); assertThat(response.jobs(), hasSize(2)); assertThat(response.jobs().stream().map(Job::getId).collect(Collectors.toList()), containsInAnyOrder(jobId1, jobId2)); // Test getting all jobs explicitly request = GetJobRequest.getAllJobsRequest(); response = execute(request, machineLearningClient::getJob, machineLearningClient::getJobAsync); assertTrue(response.count() >= 2L); assertTrue(response.jobs().size() >= 2L); assertThat(response.jobs().stream().map(Job::getId).collect(Collectors.toList()), hasItems(jobId1, jobId2)); // Test getting all jobs implicitly response = execute(new GetJobRequest(), machineLearningClient::getJob, machineLearningClient::getJobAsync); assertTrue(response.count() >= 2L); assertTrue(response.jobs().size() >= 2L); assertThat(response.jobs().stream().map(Job::getId).collect(Collectors.toList()), hasItems(jobId1, jobId2)); } public void testDeleteJob_GivenWaitForCompletionIsTrue() throws Exception { String jobId = randomValidJobId(); Job job = buildJob(jobId); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); machineLearningClient.putJob(new PutJobRequest(job), RequestOptions.DEFAULT); DeleteJobResponse response = execute(new DeleteJobRequest(jobId), machineLearningClient::deleteJob, machineLearningClient::deleteJobAsync); assertTrue(response.getAcknowledged()); assertNull(response.getTask()); } public void testDeleteJob_GivenWaitForCompletionIsFalse() throws Exception { String jobId = randomValidJobId(); Job job = buildJob(jobId); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); machineLearningClient.putJob(new PutJobRequest(job), RequestOptions.DEFAULT); DeleteJobRequest deleteJobRequest = new DeleteJobRequest(jobId); deleteJobRequest.setWaitForCompletion(false); DeleteJobResponse response = execute(deleteJobRequest, machineLearningClient::deleteJob, machineLearningClient::deleteJobAsync); assertNull(response.getAcknowledged()); final TaskId taskId = response.getTask(); assertNotNull(taskId); // When wait_for_completion=false the DeleteJobAction stored the task result in the .tasks index. In tests we need to wait // for the delete job task to complete, otherwise the .tasks index could be created during the execution of a following test. final GetTaskRequest taskRequest = new GetTaskRequest(taskId.getNodeId(), taskId.getId()); assertBusy(() -> { Optional<GetTaskResponse> taskResponse = highLevelClient().tasks().get(taskRequest, RequestOptions.DEFAULT); assertTrue(taskResponse.isPresent()); assertTrue(taskResponse.get().isCompleted()); }, 30L, TimeUnit.SECONDS); } public void testOpenJob() throws Exception { String jobId = randomValidJobId(); Job job = buildJob(jobId); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); machineLearningClient.putJob(new PutJobRequest(job), RequestOptions.DEFAULT); OpenJobResponse response = execute(new OpenJobRequest(jobId), machineLearningClient::openJob, machineLearningClient::openJobAsync); assertTrue(response.isOpened()); } public void testCloseJob() throws Exception { String jobId = randomValidJobId(); Job job = buildJob(jobId); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); machineLearningClient.putJob(new PutJobRequest(job), RequestOptions.DEFAULT); machineLearningClient.openJob(new OpenJobRequest(jobId), RequestOptions.DEFAULT); CloseJobResponse response = execute(new CloseJobRequest(jobId), machineLearningClient::closeJob, machineLearningClient::closeJobAsync); assertTrue(response.isClosed()); } public void testFlushJob() throws Exception { String jobId = randomValidJobId(); Job job = buildJob(jobId); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); machineLearningClient.putJob(new PutJobRequest(job), RequestOptions.DEFAULT); machineLearningClient.openJob(new OpenJobRequest(jobId), RequestOptions.DEFAULT); FlushJobResponse response = execute(new FlushJobRequest(jobId), machineLearningClient::flushJob, machineLearningClient::flushJobAsync); assertTrue(response.isFlushed()); } public void testGetJobStats() throws Exception { String jobId1 = "ml-get-job-stats-test-id-1"; String jobId2 = "ml-get-job-stats-test-id-2"; Job job1 = buildJob(jobId1); Job job2 = buildJob(jobId2); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); machineLearningClient.putJob(new PutJobRequest(job1), RequestOptions.DEFAULT); machineLearningClient.putJob(new PutJobRequest(job2), RequestOptions.DEFAULT); machineLearningClient.openJob(new OpenJobRequest(jobId1), RequestOptions.DEFAULT); GetJobStatsRequest request = new GetJobStatsRequest(jobId1, jobId2); // Test getting specific GetJobStatsResponse response = execute(request, machineLearningClient::getJobStats, machineLearningClient::getJobStatsAsync); assertEquals(2, response.count()); assertThat(response.jobStats(), hasSize(2)); assertThat(response.jobStats().stream().map(JobStats::getJobId).collect(Collectors.toList()), containsInAnyOrder(jobId1, jobId2)); for (JobStats stats : response.jobStats()) { if (stats.getJobId().equals(jobId1)) { assertEquals(JobState.OPENED, stats.getState()); } else { assertEquals(JobState.CLOSED, stats.getState()); } } // Test getting all explicitly request = GetJobStatsRequest.getAllJobStatsRequest(); response = execute(request, machineLearningClient::getJobStats, machineLearningClient::getJobStatsAsync); assertTrue(response.count() >= 2L); assertTrue(response.jobStats().size() >= 2L); assertThat(response.jobStats().stream().map(JobStats::getJobId).collect(Collectors.toList()), hasItems(jobId1, jobId2)); // Test getting all implicitly response = execute(new GetJobStatsRequest(), machineLearningClient::getJobStats, machineLearningClient::getJobStatsAsync); assertTrue(response.count() >= 2L); assertTrue(response.jobStats().size() >= 2L); assertThat(response.jobStats().stream().map(JobStats::getJobId).collect(Collectors.toList()), hasItems(jobId1, jobId2)); // Test getting all with wildcard request = new GetJobStatsRequest("ml-get-job-stats-test-id-*"); response = execute(request, machineLearningClient::getJobStats, machineLearningClient::getJobStatsAsync); assertTrue(response.count() >= 2L); assertTrue(response.jobStats().size() >= 2L); assertThat(response.jobStats().stream().map(JobStats::getJobId).collect(Collectors.toList()), hasItems(jobId1, jobId2)); // Test when allow_no_match is false final GetJobStatsRequest erroredRequest = new GetJobStatsRequest("jobs-that-do-not-exist*"); erroredRequest.setAllowNoMatch(false); ElasticsearchStatusException exception = expectThrows(ElasticsearchStatusException.class, () -> execute(erroredRequest, machineLearningClient::getJobStats, machineLearningClient::getJobStatsAsync)); assertThat(exception.status().getStatus(), equalTo(404)); } public void testForecastJob() throws Exception { String jobId = "ml-forecast-job-test"; Job job = buildJob(jobId); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); machineLearningClient.putJob(new PutJobRequest(job), RequestOptions.DEFAULT); machineLearningClient.openJob(new OpenJobRequest(jobId), RequestOptions.DEFAULT); PostDataRequest.JsonBuilder builder = new PostDataRequest.JsonBuilder(); for(int i = 0; i < 30; i++) { Map<String, Object> hashMap = new HashMap<>(); hashMap.put("total", randomInt(1000)); hashMap.put("timestamp", (i+1)*1000); builder.addDoc(hashMap); } PostDataRequest postDataRequest = new PostDataRequest(jobId, builder); // Post data is deprecated, so expect a deprecation warning machineLearningClient.postData(postDataRequest, POST_DATA_OPTIONS); machineLearningClient.flushJob(new FlushJobRequest(jobId), RequestOptions.DEFAULT); ForecastJobRequest request = new ForecastJobRequest(jobId); ForecastJobResponse response = execute(request, machineLearningClient::forecastJob, machineLearningClient::forecastJobAsync); assertTrue(response.isAcknowledged()); assertNotNull(response.getForecastId()); } public void testPostData() throws Exception { String jobId = randomValidJobId(); Job job = buildJob(jobId); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); machineLearningClient.putJob(new PutJobRequest(job), RequestOptions.DEFAULT); machineLearningClient.openJob(new OpenJobRequest(jobId), RequestOptions.DEFAULT); PostDataRequest.JsonBuilder builder = new PostDataRequest.JsonBuilder(); for(int i = 0; i < 10; i++) { Map<String, Object> hashMap = new HashMap<>(); hashMap.put("total", randomInt(1000)); hashMap.put("timestamp", (i+1)*1000); builder.addDoc(hashMap); } PostDataRequest postDataRequest = new PostDataRequest(jobId, builder); // Post data is deprecated, so expect a deprecation warning PostDataResponse response = execute(postDataRequest, machineLearningClient::postData, machineLearningClient::postDataAsync, POST_DATA_OPTIONS); assertEquals(10, response.getDataCounts().getInputRecordCount()); assertEquals(0, response.getDataCounts().getOutOfOrderTimeStampCount()); } public void testUpdateJob() throws Exception { String jobId = randomValidJobId(); Job job = buildJob(jobId); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); machineLearningClient.putJob(new PutJobRequest(job), RequestOptions.DEFAULT); UpdateJobRequest request = new UpdateJobRequest(new JobUpdate.Builder(jobId).setDescription("Updated description").build()); PutJobResponse response = execute(request, machineLearningClient::updateJob, machineLearningClient::updateJobAsync); assertEquals("Updated description", response.getResponse().getDescription()); GetJobRequest getRequest = new GetJobRequest(jobId); GetJobResponse getResponse = machineLearningClient.getJob(getRequest, RequestOptions.DEFAULT); assertEquals("Updated description", getResponse.jobs().get(0).getDescription()); } public void testPutDatafeed() throws Exception { String jobId = randomValidJobId(); Job job = buildJob(jobId); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); execute(new PutJobRequest(job), machineLearningClient::putJob, machineLearningClient::putJobAsync); String datafeedId = "datafeed-" + jobId; DatafeedConfig datafeedConfig = DatafeedConfig.builder(datafeedId, jobId).setIndices("some_data_index").build(); PutDatafeedResponse response = execute(new PutDatafeedRequest(datafeedConfig), machineLearningClient::putDatafeed, machineLearningClient::putDatafeedAsync); DatafeedConfig createdDatafeed = response.getResponse(); assertThat(createdDatafeed.getId(), equalTo(datafeedId)); assertThat(createdDatafeed.getIndices(), equalTo(datafeedConfig.getIndices())); } public void testUpdateDatafeed() throws Exception { MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); String jobId = randomValidJobId(); Job job = buildJob(jobId); execute(new PutJobRequest(job), machineLearningClient::putJob, machineLearningClient::putJobAsync); String datafeedId = "datafeed-" + jobId; DatafeedConfig datafeedConfig = DatafeedConfig.builder(datafeedId, jobId).setIndices("some_data_index").build(); PutDatafeedResponse response = machineLearningClient.putDatafeed(new PutDatafeedRequest(datafeedConfig), RequestOptions.DEFAULT); DatafeedConfig createdDatafeed = response.getResponse(); assertThat(createdDatafeed.getId(), equalTo(datafeedId)); assertThat(createdDatafeed.getIndices(), equalTo(datafeedConfig.getIndices())); DatafeedUpdate datafeedUpdate = DatafeedUpdate.builder(datafeedId).setIndices("some_other_data_index").setScrollSize(10).build(); response = execute(new UpdateDatafeedRequest(datafeedUpdate), machineLearningClient::updateDatafeed, machineLearningClient::updateDatafeedAsync); DatafeedConfig updatedDatafeed = response.getResponse(); assertThat(datafeedUpdate.getId(), equalTo(updatedDatafeed.getId())); assertThat(datafeedUpdate.getIndices(), equalTo(updatedDatafeed.getIndices())); assertThat(datafeedUpdate.getScrollSize(), equalTo(updatedDatafeed.getScrollSize())); } public void testGetDatafeed() throws Exception { String jobId1 = "test-get-datafeed-job-1"; String jobId2 = "test-get-datafeed-job-2"; Job job1 = buildJob(jobId1); Job job2 = buildJob(jobId2); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); machineLearningClient.putJob(new PutJobRequest(job1), RequestOptions.DEFAULT); machineLearningClient.putJob(new PutJobRequest(job2), RequestOptions.DEFAULT); String datafeedId1 = jobId1 + "-feed"; String datafeedId2 = jobId2 + "-feed"; DatafeedConfig datafeed1 = DatafeedConfig.builder(datafeedId1, jobId1).setIndices("data_1").build(); DatafeedConfig datafeed2 = DatafeedConfig.builder(datafeedId2, jobId2).setIndices("data_2").build(); machineLearningClient.putDatafeed(new PutDatafeedRequest(datafeed1), RequestOptions.DEFAULT); machineLearningClient.putDatafeed(new PutDatafeedRequest(datafeed2), RequestOptions.DEFAULT); // Test getting specific datafeeds { GetDatafeedRequest request = new GetDatafeedRequest(datafeedId1, datafeedId2); GetDatafeedResponse response = execute(request, machineLearningClient::getDatafeed, machineLearningClient::getDatafeedAsync); assertEquals(2, response.count()); assertThat(response.datafeeds(), hasSize(2)); assertThat(response.datafeeds().stream().map(DatafeedConfig::getId).collect(Collectors.toList()), containsInAnyOrder(datafeedId1, datafeedId2)); } // Test getting a single one { GetDatafeedRequest request = new GetDatafeedRequest(datafeedId1); GetDatafeedResponse response = execute(request, machineLearningClient::getDatafeed, machineLearningClient::getDatafeedAsync); assertTrue(response.count() == 1L); assertThat(response.datafeeds().get(0).getId(), equalTo(datafeedId1)); } // Test getting all datafeeds explicitly { GetDatafeedRequest request = GetDatafeedRequest.getAllDatafeedsRequest(); GetDatafeedResponse response = execute(request, machineLearningClient::getDatafeed, machineLearningClient::getDatafeedAsync); assertTrue(response.count() == 2L); assertTrue(response.datafeeds().size() == 2L); assertThat(response.datafeeds().stream().map(DatafeedConfig::getId).collect(Collectors.toList()), hasItems(datafeedId1, datafeedId2)); } // Test getting all datafeeds implicitly { GetDatafeedResponse response = execute(new GetDatafeedRequest(), machineLearningClient::getDatafeed, machineLearningClient::getDatafeedAsync); assertTrue(response.count() >= 2L); assertTrue(response.datafeeds().size() >= 2L); assertThat(response.datafeeds().stream().map(DatafeedConfig::getId).collect(Collectors.toList()), hasItems(datafeedId1, datafeedId2)); } // Test get missing pattern with allow_no_match set to true { GetDatafeedRequest request = new GetDatafeedRequest("missing-*"); GetDatafeedResponse response = execute(request, machineLearningClient::getDatafeed, machineLearningClient::getDatafeedAsync); assertThat(response.count(), equalTo(0L)); } // Test get missing pattern with allow_no_match set to false { GetDatafeedRequest request = new GetDatafeedRequest("missing-*"); request.setAllowNoMatch(false); ElasticsearchStatusException e = expectThrows(ElasticsearchStatusException.class, () -> execute(request, machineLearningClient::getDatafeed, machineLearningClient::getDatafeedAsync)); assertThat(e.status(), equalTo(RestStatus.NOT_FOUND)); } } public void testDeleteDatafeed() throws Exception { String jobId = randomValidJobId(); Job job = buildJob(jobId); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); machineLearningClient.putJob(new PutJobRequest(job), RequestOptions.DEFAULT); String datafeedId = "datafeed-" + jobId; DatafeedConfig datafeedConfig = DatafeedConfig.builder(datafeedId, jobId).setIndices("some_data_index").build(); execute(new PutDatafeedRequest(datafeedConfig), machineLearningClient::putDatafeed, machineLearningClient::putDatafeedAsync); AcknowledgedResponse response = execute(new DeleteDatafeedRequest(datafeedId), machineLearningClient::deleteDatafeed, machineLearningClient::deleteDatafeedAsync); assertTrue(response.isAcknowledged()); } public void testStartDatafeed() throws Exception { String jobId = "test-start-datafeed"; String indexName = "start_data_1"; // Set up the index and docs createIndex(indexName, defaultMappingForTest()); BulkRequest bulk = new BulkRequest(); bulk.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); long now = (System.currentTimeMillis()/1000)*1000; long thePast = now - 60000; int i = 0; long pastCopy = thePast; while(pastCopy < now) { IndexRequest doc = new IndexRequest(); doc.index(indexName); doc.id("id" + i); doc.source("{\"total\":" +randomInt(1000) + ",\"timestamp\":"+ pastCopy +"}", XContentType.JSON); bulk.add(doc); pastCopy += 1000; i++; } highLevelClient().bulk(bulk, RequestOptions.DEFAULT); final long totalDocCount = i; // create the job and the datafeed Job job = buildJob(jobId); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); machineLearningClient.putJob(new PutJobRequest(job), RequestOptions.DEFAULT); machineLearningClient.openJob(new OpenJobRequest(jobId), RequestOptions.DEFAULT); String datafeedId = jobId + "-feed"; DatafeedConfig datafeed = DatafeedConfig.builder(datafeedId, jobId) .setIndices(indexName) .setQueryDelay(TimeValue.timeValueSeconds(1)) .setFrequency(TimeValue.timeValueSeconds(1)).build(); machineLearningClient.putDatafeed(new PutDatafeedRequest(datafeed), RequestOptions.DEFAULT); StartDatafeedRequest startDatafeedRequest = new StartDatafeedRequest(datafeedId); startDatafeedRequest.setStart(String.valueOf(thePast)); // Should only process two documents startDatafeedRequest.setEnd(String.valueOf(thePast + 2000)); StartDatafeedResponse response = execute(startDatafeedRequest, machineLearningClient::startDatafeed, machineLearningClient::startDatafeedAsync); assertTrue(response.isStarted()); assertBusy(() -> { JobStats stats = machineLearningClient.getJobStats(new GetJobStatsRequest(jobId), RequestOptions.DEFAULT).jobStats().get(0); assertEquals(2L, stats.getDataCounts().getInputRecordCount()); assertEquals(JobState.CLOSED, stats.getState()); }, 30, TimeUnit.SECONDS); machineLearningClient.openJob(new OpenJobRequest(jobId), RequestOptions.DEFAULT); StartDatafeedRequest wholeDataFeed = new StartDatafeedRequest(datafeedId); // Process all documents and end the stream wholeDataFeed.setEnd(String.valueOf(now)); StartDatafeedResponse wholeResponse = execute(wholeDataFeed, machineLearningClient::startDatafeed, machineLearningClient::startDatafeedAsync); assertTrue(wholeResponse.isStarted()); assertBusy(() -> { JobStats stats = machineLearningClient.getJobStats(new GetJobStatsRequest(jobId), RequestOptions.DEFAULT).jobStats().get(0); assertEquals(totalDocCount, stats.getDataCounts().getInputRecordCount()); assertEquals(JobState.CLOSED, stats.getState()); }, 30, TimeUnit.SECONDS); } public void testStopDatafeed() throws Exception { String jobId1 = "test-stop-datafeed1"; String jobId2 = "test-stop-datafeed2"; String jobId3 = "test-stop-datafeed3"; String indexName = "stop_data_1"; // Set up the index createIndex(indexName, defaultMappingForTest()); // create the job and the datafeed Job job1 = buildJob(jobId1); putJob(job1); openJob(job1); Job job2 = buildJob(jobId2); putJob(job2); openJob(job2); Job job3 = buildJob(jobId3); putJob(job3); openJob(job3); String datafeedId1 = createAndPutDatafeed(jobId1, indexName); String datafeedId2 = createAndPutDatafeed(jobId2, indexName); String datafeedId3 = createAndPutDatafeed(jobId3, indexName); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); machineLearningClient.startDatafeed(new StartDatafeedRequest(datafeedId1), RequestOptions.DEFAULT); machineLearningClient.startDatafeed(new StartDatafeedRequest(datafeedId2), RequestOptions.DEFAULT); machineLearningClient.startDatafeed(new StartDatafeedRequest(datafeedId3), RequestOptions.DEFAULT); { StopDatafeedRequest request = new StopDatafeedRequest(datafeedId1); request.setAllowNoMatch(false); StopDatafeedResponse stopDatafeedResponse = execute(request, machineLearningClient::stopDatafeed, machineLearningClient::stopDatafeedAsync); assertTrue(stopDatafeedResponse.isStopped()); } { StopDatafeedRequest request = new StopDatafeedRequest(datafeedId2, datafeedId3); request.setAllowNoMatch(false); StopDatafeedResponse stopDatafeedResponse = execute(request, machineLearningClient::stopDatafeed, machineLearningClient::stopDatafeedAsync); assertTrue(stopDatafeedResponse.isStopped()); } { StopDatafeedResponse stopDatafeedResponse = execute(new StopDatafeedRequest("datafeed_that_doesnot_exist*"), machineLearningClient::stopDatafeed, machineLearningClient::stopDatafeedAsync); assertTrue(stopDatafeedResponse.isStopped()); } { StopDatafeedRequest request = new StopDatafeedRequest("datafeed_that_doesnot_exist*"); request.setAllowNoMatch(false); ElasticsearchStatusException exception = expectThrows(ElasticsearchStatusException.class, () -> execute(request, machineLearningClient::stopDatafeed, machineLearningClient::stopDatafeedAsync)); assertThat(exception.status().getStatus(), equalTo(404)); } } public void testGetDatafeedStats() throws Exception { String jobId1 = "ml-get-datafeed-stats-test-id-1"; String jobId2 = "ml-get-datafeed-stats-test-id-2"; String indexName = "datafeed_stats_data_1"; // Set up the index createIndex(indexName, defaultMappingForTest()); // create the job and the datafeed Job job1 = buildJob(jobId1); putJob(job1); openJob(job1); Job job2 = buildJob(jobId2); putJob(job2); String datafeedId1 = createAndPutDatafeed(jobId1, indexName); String datafeedId2 = createAndPutDatafeed(jobId2, indexName); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); machineLearningClient.startDatafeed(new StartDatafeedRequest(datafeedId1), RequestOptions.DEFAULT); GetDatafeedStatsRequest request = new GetDatafeedStatsRequest(datafeedId1); // Test getting specific GetDatafeedStatsResponse response = execute(request, machineLearningClient::getDatafeedStats, machineLearningClient::getDatafeedStatsAsync); assertEquals(1, response.count()); assertThat(response.datafeedStats(), hasSize(1)); assertThat(response.datafeedStats().get(0).getDatafeedId(), equalTo(datafeedId1)); assertThat(response.datafeedStats().get(0).getDatafeedState().toString(), equalTo(DatafeedState.STARTED.toString())); // Test getting all explicitly request = GetDatafeedStatsRequest.getAllDatafeedStatsRequest(); response = execute(request, machineLearningClient::getDatafeedStats, machineLearningClient::getDatafeedStatsAsync); assertTrue(response.count() >= 2L); assertTrue(response.datafeedStats().size() >= 2L); assertThat(response.datafeedStats().stream().map(DatafeedStats::getDatafeedId).collect(Collectors.toList()), hasItems(datafeedId1, datafeedId2)); // Test getting all implicitly response = execute(new GetDatafeedStatsRequest(), machineLearningClient::getDatafeedStats, machineLearningClient::getDatafeedStatsAsync); assertTrue(response.count() >= 2L); assertTrue(response.datafeedStats().size() >= 2L); assertThat(response.datafeedStats().stream().map(DatafeedStats::getDatafeedId).collect(Collectors.toList()), hasItems(datafeedId1, datafeedId2)); // Test getting all with wildcard request = new GetDatafeedStatsRequest("ml-get-datafeed-stats-test-id-*"); response = execute(request, machineLearningClient::getDatafeedStats, machineLearningClient::getDatafeedStatsAsync); assertEquals(2L, response.count()); assertThat(response.datafeedStats(), hasSize(2)); assertThat(response.datafeedStats().stream().map(DatafeedStats::getDatafeedId).collect(Collectors.toList()), hasItems(datafeedId1, datafeedId2)); // Test when allow_no_match is false final GetDatafeedStatsRequest erroredRequest = new GetDatafeedStatsRequest("datafeeds-that-do-not-exist*"); erroredRequest.setAllowNoMatch(false); ElasticsearchStatusException exception = expectThrows(ElasticsearchStatusException.class, () -> execute(erroredRequest, machineLearningClient::getDatafeedStats, machineLearningClient::getDatafeedStatsAsync)); assertThat(exception.status().getStatus(), equalTo(404)); } public void testPreviewDatafeed() throws Exception { String jobId = "test-preview-datafeed"; String indexName = "preview_data_1"; // Set up the index and docs createIndex(indexName, defaultMappingForTest()); BulkRequest bulk = new BulkRequest(); bulk.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); long now = (System.currentTimeMillis()/1000)*1000; long thePast = now - 60000; int i = 0; List<Integer> totalTotals = new ArrayList<>(60); while(thePast < now) { Integer total = randomInt(1000); IndexRequest doc = new IndexRequest(); doc.index(indexName); doc.id("id" + i); doc.source("{\"total\":" + total + ",\"timestamp\":"+ thePast +"}", XContentType.JSON); bulk.add(doc); thePast += 1000; i++; totalTotals.add(total); } highLevelClient().bulk(bulk, RequestOptions.DEFAULT); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); // create the job and the datafeed Job job = buildJob(jobId); putJob(job); openJob(job); String datafeedId = jobId + "-feed"; DatafeedConfig datafeed = DatafeedConfig.builder(datafeedId, jobId) .setIndices(indexName) .setQueryDelay(TimeValue.timeValueSeconds(1)) .setFrequency(TimeValue.timeValueSeconds(1)).build(); machineLearningClient.putDatafeed(new PutDatafeedRequest(datafeed), RequestOptions.DEFAULT); PreviewDatafeedResponse response = execute(new PreviewDatafeedRequest(datafeedId), machineLearningClient::previewDatafeed, machineLearningClient::previewDatafeedAsync); Integer[] totals = response.getDataList().stream().map(map -> (Integer)map.get("total")).toArray(Integer[]::new); assertThat(totalTotals, containsInAnyOrder(totals)); } public void testDeleteExpiredDataGivenNothingToDelete() throws Exception { // Tests that nothing goes wrong when there's nothing to delete MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); DeleteExpiredDataResponse response = execute(new DeleteExpiredDataRequest(), machineLearningClient::deleteExpiredData, machineLearningClient::deleteExpiredDataAsync); assertTrue(response.getDeleted()); } private String createExpiredData(String jobId) throws Exception { String indexName = jobId + "-data"; // Set up the index and docs createIndex(indexName, defaultMappingForTest()); BulkRequest bulk = new BulkRequest(); bulk.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); long nowMillis = System.currentTimeMillis(); int totalBuckets = 2 * 24; int normalRate = 10; int anomalousRate = 100; int anomalousBucket = 30; for (int bucket = 0; bucket < totalBuckets; bucket++) { long timestamp = nowMillis - TimeValue.timeValueHours(totalBuckets - bucket).getMillis(); int bucketRate = bucket == anomalousBucket ? anomalousRate : normalRate; for (int point = 0; point < bucketRate; point++) { IndexRequest indexRequest = new IndexRequest(indexName); indexRequest.source(XContentType.JSON, "timestamp", timestamp, "total", randomInt(1000)); bulk.add(indexRequest); } } highLevelClient().bulk(bulk, RequestOptions.DEFAULT); { // Index a randomly named unused state document String docId = "non_existing_job_" + randomFrom("model_state_1234567#1", "quantiles", "categorizer_state#1"); IndexRequest indexRequest = new IndexRequest(".ml-state-000001").id(docId); indexRequest.source(Collections.emptyMap(), XContentType.JSON); indexRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); highLevelClient().index(indexRequest, RequestOptions.DEFAULT); } Job job = buildJobForExpiredDataTests(jobId); putJob(job); openJob(job); String datafeedId = createAndPutDatafeed(jobId, indexName); startDatafeed(datafeedId, String.valueOf(0), String.valueOf(nowMillis - TimeValue.timeValueHours(24).getMillis())); waitForJobToClose(jobId); long prevJobTimeStamp = System.currentTimeMillis() / 1000; // Check that the current timestamp component, in seconds, differs from previously. // Note that we used to use an 'awaitBusy(() -> false, 1, TimeUnit.SECONDS);' // for the same purpose but the new approach... // a) explicitly checks that the timestamps, in seconds, are actually different and // b) is slightly more efficient since we may not need to wait an entire second for the timestamp to increment assertBusy(() -> { long timeNow = System.currentTimeMillis() / 1000; assertThat(prevJobTimeStamp, lessThan(timeNow)); }); // Update snapshot timestamp to force it out of snapshot retention window long oneDayAgo = nowMillis - TimeValue.timeValueHours(24).getMillis() - 1; updateModelSnapshotTimestamp(jobId, String.valueOf(oneDayAgo)); openJob(job); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); ForecastJobRequest forecastJobRequest = new ForecastJobRequest(jobId); forecastJobRequest.setDuration(TimeValue.timeValueHours(3)); forecastJobRequest.setExpiresIn(TimeValue.timeValueSeconds(1)); ForecastJobResponse forecastJobResponse = machineLearningClient.forecastJob(forecastJobRequest, RequestOptions.DEFAULT); waitForForecastToComplete(jobId, forecastJobResponse.getForecastId()); // Wait for the forecast to expire // FIXME: We should wait for something specific to change, rather than waiting for time to pass. waitUntil(() -> false, 1, TimeUnit.SECONDS); // Run up to now startDatafeed(datafeedId, String.valueOf(0), String.valueOf(nowMillis)); waitForJobToClose(jobId); return forecastJobResponse.getForecastId(); } public void testDeleteExpiredData() throws Exception { String jobId = "test-delete-expired-data"; String forecastId = createExpiredData(jobId); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); GetModelSnapshotsRequest getModelSnapshotsRequest = new GetModelSnapshotsRequest(jobId); GetModelSnapshotsResponse getModelSnapshotsResponse = execute(getModelSnapshotsRequest, machineLearningClient::getModelSnapshots, machineLearningClient::getModelSnapshotsAsync); assertEquals(2L, getModelSnapshotsResponse.count()); assertTrue(forecastExists(jobId, forecastId)); { // Verify .ml-state* contains the expected unused state document Iterable<SearchHit> hits = searchAll(".ml-state*"); List<SearchHit> target = new ArrayList<>(); hits.forEach(target::add); long numMatches = target.stream() .filter(c -> c.getId().startsWith("non_existing_job")) .count(); assertThat(numMatches, equalTo(1L)); } DeleteExpiredDataRequest request = new DeleteExpiredDataRequest(); DeleteExpiredDataResponse response = execute(request, machineLearningClient::deleteExpiredData, machineLearningClient::deleteExpiredDataAsync); assertTrue(response.getDeleted()); // Wait for the forecast to expire // FIXME: We should wait for something specific to change, rather than waiting for time to pass. waitUntil(() -> false, 1, TimeUnit.SECONDS); GetModelSnapshotsRequest getModelSnapshotsRequest1 = new GetModelSnapshotsRequest(jobId); GetModelSnapshotsResponse getModelSnapshotsResponse1 = execute(getModelSnapshotsRequest1, machineLearningClient::getModelSnapshots, machineLearningClient::getModelSnapshotsAsync); assertEquals(1L, getModelSnapshotsResponse1.count()); assertFalse(forecastExists(jobId, forecastId)); { // Verify .ml-state* doesn't contain unused state documents Iterable<SearchHit> hits = searchAll(".ml-state*"); List<SearchHit> hitList = new ArrayList<>(); hits.forEach(hitList::add); long numMatches = hitList.stream() .filter(c -> c.getId().startsWith("non_existing_job")) .count(); assertThat(numMatches, equalTo(0L)); } } public void testDeleteForecast() throws Exception { String jobId = "test-delete-forecast"; Job job = buildJob(jobId); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); machineLearningClient.putJob(new PutJobRequest(job), RequestOptions.DEFAULT); machineLearningClient.openJob(new OpenJobRequest(jobId), RequestOptions.DEFAULT); Job noForecastsJob = buildJob("test-delete-forecast-none"); machineLearningClient.putJob(new PutJobRequest(noForecastsJob), RequestOptions.DEFAULT); PostDataRequest.JsonBuilder builder = new PostDataRequest.JsonBuilder(); for(int i = 0; i < 30; i++) { Map<String, Object> hashMap = new HashMap<>(); hashMap.put("total", randomInt(1000)); hashMap.put("timestamp", (i+1)*1000); builder.addDoc(hashMap); } PostDataRequest postDataRequest = new PostDataRequest(jobId, builder); // Post data is deprecated, so expect a deprecation warning machineLearningClient.postData(postDataRequest, POST_DATA_OPTIONS); machineLearningClient.flushJob(new FlushJobRequest(jobId), RequestOptions.DEFAULT); ForecastJobResponse forecastJobResponse1 = machineLearningClient.forecastJob(new ForecastJobRequest(jobId), RequestOptions.DEFAULT); ForecastJobResponse forecastJobResponse2 = machineLearningClient.forecastJob(new ForecastJobRequest(jobId), RequestOptions.DEFAULT); waitForForecastToComplete(jobId, forecastJobResponse1.getForecastId()); waitForForecastToComplete(jobId, forecastJobResponse2.getForecastId()); { DeleteForecastRequest request = new DeleteForecastRequest(jobId); request.setForecastIds(forecastJobResponse1.getForecastId(), forecastJobResponse2.getForecastId()); AcknowledgedResponse response = execute(request, machineLearningClient::deleteForecast, machineLearningClient::deleteForecastAsync); assertTrue(response.isAcknowledged()); assertFalse(forecastExists(jobId, forecastJobResponse1.getForecastId())); assertFalse(forecastExists(jobId, forecastJobResponse2.getForecastId())); } { DeleteForecastRequest request = DeleteForecastRequest.deleteAllForecasts(noForecastsJob.getId()); request.setAllowNoForecasts(true); AcknowledgedResponse response = execute(request, machineLearningClient::deleteForecast, machineLearningClient::deleteForecastAsync); assertTrue(response.isAcknowledged()); } { DeleteForecastRequest request = DeleteForecastRequest.deleteAllForecasts(noForecastsJob.getId()); request.setAllowNoForecasts(false); ElasticsearchStatusException exception = expectThrows(ElasticsearchStatusException.class, () -> execute(request, machineLearningClient::deleteForecast, machineLearningClient::deleteForecastAsync)); assertThat(exception.status().getStatus(), equalTo(404)); } } private void waitForForecastToComplete(String jobId, String forecastId) throws Exception { GetRequest request = new GetRequest(".ml-anomalies-" + jobId); request.id(jobId + "_model_forecast_request_stats_" + forecastId); assertBusy(() -> { GetResponse getResponse = highLevelClient().get(request, RequestOptions.DEFAULT); assertTrue(getResponse.isExists()); assertTrue(getResponse.getSourceAsString().contains("finished")); }, 30, TimeUnit.SECONDS); } private boolean forecastExists(String jobId, String forecastId) throws Exception { GetRequest getRequest = new GetRequest(".ml-anomalies-" + jobId); getRequest.id(jobId + "_model_forecast_request_stats_" + forecastId); GetResponse getResponse = highLevelClient().get(getRequest, RequestOptions.DEFAULT); return getResponse.isExists(); } public void testPutCalendar() throws IOException { Calendar calendar = CalendarTests.testInstance(); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); PutCalendarResponse putCalendarResponse = execute(new PutCalendarRequest(calendar), machineLearningClient::putCalendar, machineLearningClient::putCalendarAsync); assertThat(putCalendarResponse.getCalendar(), equalTo(calendar)); } public void testPutCalendarJob() throws IOException { Calendar calendar = new Calendar("put-calendar-job-id", Collections.singletonList("put-calendar-job-0"), null); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); PutCalendarResponse putCalendarResponse = machineLearningClient.putCalendar(new PutCalendarRequest(calendar), RequestOptions.DEFAULT); assertThat(putCalendarResponse.getCalendar().getJobIds(), containsInAnyOrder( "put-calendar-job-0")); String jobId1 = "put-calendar-job-1"; String jobId2 = "put-calendar-job-2"; PutCalendarJobRequest putCalendarJobRequest = new PutCalendarJobRequest(calendar.getId(), jobId1, jobId2); putCalendarResponse = execute(putCalendarJobRequest, machineLearningClient::putCalendarJob, machineLearningClient::putCalendarJobAsync); assertThat(putCalendarResponse.getCalendar().getJobIds(), containsInAnyOrder(jobId1, jobId2, "put-calendar-job-0")); } public void testDeleteCalendarJob() throws IOException { Calendar calendar = new Calendar("del-calendar-job-id", Arrays.asList("del-calendar-job-0", "del-calendar-job-1", "del-calendar-job-2"), null); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); PutCalendarResponse putCalendarResponse = machineLearningClient.putCalendar(new PutCalendarRequest(calendar), RequestOptions.DEFAULT); assertThat(putCalendarResponse.getCalendar().getJobIds(), containsInAnyOrder("del-calendar-job-0", "del-calendar-job-1", "del-calendar-job-2")); String jobId1 = "del-calendar-job-0"; String jobId2 = "del-calendar-job-2"; DeleteCalendarJobRequest deleteCalendarJobRequest = new DeleteCalendarJobRequest(calendar.getId(), jobId1, jobId2); putCalendarResponse = execute(deleteCalendarJobRequest, machineLearningClient::deleteCalendarJob, machineLearningClient::deleteCalendarJobAsync); assertThat(putCalendarResponse.getCalendar().getJobIds(), containsInAnyOrder("del-calendar-job-1")); } public void testGetCalendars() throws Exception { Calendar calendar1 = CalendarTests.testInstance(); Calendar calendar2 = CalendarTests.testInstance(); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); machineLearningClient.putCalendar(new PutCalendarRequest(calendar1), RequestOptions.DEFAULT); machineLearningClient.putCalendar(new PutCalendarRequest(calendar2), RequestOptions.DEFAULT); GetCalendarsRequest getCalendarsRequest = new GetCalendarsRequest(); getCalendarsRequest.setCalendarId("_all"); GetCalendarsResponse getCalendarsResponse = execute(getCalendarsRequest, machineLearningClient::getCalendars, machineLearningClient::getCalendarsAsync); assertEquals(2, getCalendarsResponse.count()); assertEquals(2, getCalendarsResponse.calendars().size()); assertThat(getCalendarsResponse.calendars().stream().map(Calendar::getId).collect(Collectors.toList()), hasItems(calendar1.getId(), calendar1.getId())); getCalendarsRequest.setCalendarId(calendar1.getId()); getCalendarsResponse = execute(getCalendarsRequest, machineLearningClient::getCalendars, machineLearningClient::getCalendarsAsync); assertEquals(1, getCalendarsResponse.count()); assertEquals(calendar1, getCalendarsResponse.calendars().get(0)); } public void testDeleteCalendar() throws IOException { Calendar calendar = CalendarTests.testInstance(); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); execute(new PutCalendarRequest(calendar), machineLearningClient::putCalendar, machineLearningClient::putCalendarAsync); AcknowledgedResponse response = execute(new DeleteCalendarRequest(calendar.getId()), machineLearningClient::deleteCalendar, machineLearningClient::deleteCalendarAsync); assertTrue(response.isAcknowledged()); // calendar is missing ElasticsearchStatusException exception = expectThrows(ElasticsearchStatusException.class, () -> execute(new DeleteCalendarRequest(calendar.getId()), machineLearningClient::deleteCalendar, machineLearningClient::deleteCalendarAsync)); assertThat(exception.status().getStatus(), equalTo(404)); } public void testGetCalendarEvent() throws Exception { Calendar calendar = new Calendar("get-calendar-event-id", Collections.singletonList("get-calendar-event-job"), null); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); machineLearningClient.putCalendar(new PutCalendarRequest(calendar), RequestOptions.DEFAULT); List<ScheduledEvent> events = new ArrayList<>(3); for (int i = 0; i < 3; i++) { events.add(ScheduledEventTests.testInstance(calendar.getId(), null)); } machineLearningClient.postCalendarEvent(new PostCalendarEventRequest(calendar.getId(), events), RequestOptions.DEFAULT); { GetCalendarEventsRequest getCalendarEventsRequest = new GetCalendarEventsRequest(calendar.getId()); GetCalendarEventsResponse getCalendarEventsResponse = execute(getCalendarEventsRequest, machineLearningClient::getCalendarEvents, machineLearningClient::getCalendarEventsAsync); assertThat(getCalendarEventsResponse.events().size(), equalTo(3)); assertThat(getCalendarEventsResponse.count(), equalTo(3L)); } { GetCalendarEventsRequest getCalendarEventsRequest = new GetCalendarEventsRequest(calendar.getId()); getCalendarEventsRequest.setPageParams(new PageParams(1, 2)); GetCalendarEventsResponse getCalendarEventsResponse = execute(getCalendarEventsRequest, machineLearningClient::getCalendarEvents, machineLearningClient::getCalendarEventsAsync); assertThat(getCalendarEventsResponse.events().size(), equalTo(2)); assertThat(getCalendarEventsResponse.count(), equalTo(3L)); } { machineLearningClient.putJob(new PutJobRequest(buildJob("get-calendar-event-job")), RequestOptions.DEFAULT); GetCalendarEventsRequest getCalendarEventsRequest = new GetCalendarEventsRequest("_all"); getCalendarEventsRequest.setJobId("get-calendar-event-job"); GetCalendarEventsResponse getCalendarEventsResponse = execute(getCalendarEventsRequest, machineLearningClient::getCalendarEvents, machineLearningClient::getCalendarEventsAsync); assertThat(getCalendarEventsResponse.events().size(), equalTo(3)); assertThat(getCalendarEventsResponse.count(), equalTo(3L)); } } public void testPostCalendarEvent() throws Exception { Calendar calendar = CalendarTests.testInstance(); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); machineLearningClient.putCalendar(new PutCalendarRequest(calendar), RequestOptions.DEFAULT); List<ScheduledEvent> events = new ArrayList<>(3); for (int i = 0; i < 3; i++) { events.add(ScheduledEventTests.testInstance(calendar.getId(), null)); } PostCalendarEventRequest postCalendarEventRequest = new PostCalendarEventRequest(calendar.getId(), events); PostCalendarEventResponse postCalendarEventResponse = execute(postCalendarEventRequest, machineLearningClient::postCalendarEvent, machineLearningClient::postCalendarEventAsync); assertThat(postCalendarEventResponse.getScheduledEvents(), containsInAnyOrder(events.toArray())); } public void testDeleteCalendarEvent() throws IOException { Calendar calendar = CalendarTests.testInstance(); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); machineLearningClient.putCalendar(new PutCalendarRequest(calendar), RequestOptions.DEFAULT); List<ScheduledEvent> events = new ArrayList<>(3); for (int i = 0; i < 3; i++) { events.add(ScheduledEventTests.testInstance(calendar.getId(), null)); } machineLearningClient.postCalendarEvent(new PostCalendarEventRequest(calendar.getId(), events), RequestOptions.DEFAULT); GetCalendarEventsResponse getCalendarEventsResponse = machineLearningClient.getCalendarEvents(new GetCalendarEventsRequest(calendar.getId()), RequestOptions.DEFAULT); assertThat(getCalendarEventsResponse.events().size(), equalTo(3)); String deletedEvent = getCalendarEventsResponse.events().get(0).getEventId(); DeleteCalendarEventRequest deleteCalendarEventRequest = new DeleteCalendarEventRequest(calendar.getId(), deletedEvent); AcknowledgedResponse response = execute(deleteCalendarEventRequest, machineLearningClient::deleteCalendarEvent, machineLearningClient::deleteCalendarEventAsync); assertThat(response.isAcknowledged(), is(true)); getCalendarEventsResponse = machineLearningClient.getCalendarEvents(new GetCalendarEventsRequest(calendar.getId()), RequestOptions.DEFAULT); List<String> remainingIds = getCalendarEventsResponse.events() .stream() .map(ScheduledEvent::getEventId) .collect(Collectors.toList()); assertThat(remainingIds.size(), equalTo(2)); assertThat(remainingIds, not(hasItem(deletedEvent))); } public void testEstimateModelMemory() throws Exception { MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); String byFieldName = randomAlphaOfLength(10); String influencerFieldName = randomAlphaOfLength(10); AnalysisConfig analysisConfig = AnalysisConfig.builder( Collections.singletonList( Detector.builder().setFunction("count").setByFieldName(byFieldName).build() )).setInfluencers(Collections.singletonList(influencerFieldName)).build(); EstimateModelMemoryRequest estimateModelMemoryRequest = new EstimateModelMemoryRequest(analysisConfig); estimateModelMemoryRequest.setOverallCardinality(Collections.singletonMap(byFieldName, randomNonNegativeLong())); estimateModelMemoryRequest.setMaxBucketCardinality(Collections.singletonMap(influencerFieldName, randomNonNegativeLong())); EstimateModelMemoryResponse estimateModelMemoryResponse = execute( estimateModelMemoryRequest, machineLearningClient::estimateModelMemory, machineLearningClient::estimateModelMemoryAsync); ByteSizeValue modelMemoryEstimate = estimateModelMemoryResponse.getModelMemoryEstimate(); assertThat(modelMemoryEstimate.getBytes(), greaterThanOrEqualTo(10000000L)); } public void testPutDataFrameAnalyticsConfig_GivenOutlierDetectionAnalysis() throws Exception { MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); String configId = "test-put-df-analytics-outlier-detection"; DataFrameAnalyticsConfig config = DataFrameAnalyticsConfig.builder() .setId(configId) .setSource(DataFrameAnalyticsSource.builder() .setIndex("put-test-source-index") .build()) .setDest(DataFrameAnalyticsDest.builder() .setIndex("put-test-dest-index") .build()) .setAnalysis(org.elasticsearch.client.ml.dataframe.OutlierDetection.createDefault()) .setDescription("some description") .build(); createIndex("put-test-source-index", defaultMappingForTest()); PutDataFrameAnalyticsResponse putDataFrameAnalyticsResponse = execute( new PutDataFrameAnalyticsRequest(config), machineLearningClient::putDataFrameAnalytics, machineLearningClient::putDataFrameAnalyticsAsync); DataFrameAnalyticsConfig createdConfig = putDataFrameAnalyticsResponse.getConfig(); assertThat(createdConfig.getId(), equalTo(config.getId())); assertThat(createdConfig.getSource().getIndex(), equalTo(config.getSource().getIndex())); assertThat(createdConfig.getSource().getQueryConfig(), equalTo(new QueryConfig(new MatchAllQueryBuilder()))); // default value assertThat(createdConfig.getDest().getIndex(), equalTo(config.getDest().getIndex())); assertThat(createdConfig.getDest().getResultsField(), equalTo("ml")); // default value assertThat(createdConfig.getAnalysis(), equalTo(org.elasticsearch.client.ml.dataframe.OutlierDetection.builder() .setComputeFeatureInfluence(true) .setOutlierFraction(0.05) .setStandardizationEnabled(true).build())); assertThat(createdConfig.getAnalyzedFields(), equalTo(config.getAnalyzedFields())); assertThat(createdConfig.getModelMemoryLimit(), equalTo(ByteSizeValue.parseBytesSizeValue("1gb", ""))); // default value assertThat(createdConfig.getDescription(), equalTo("some description")); assertThat(createdConfig.getMaxNumThreads(), equalTo(1)); } public void testPutDataFrameAnalyticsConfig_GivenRegression() throws Exception { MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); String configId = "test-put-df-analytics-regression"; DataFrameAnalyticsConfig config = DataFrameAnalyticsConfig.builder() .setId(configId) .setSource(DataFrameAnalyticsSource.builder() .setIndex("put-test-source-index") .build()) .setDest(DataFrameAnalyticsDest.builder() .setIndex("put-test-dest-index") .build()) .setAnalysis(org.elasticsearch.client.ml.dataframe.Regression.builder("my_dependent_variable") .setPredictionFieldName("my_dependent_variable_prediction") .setTrainingPercent(80.0) .setRandomizeSeed(42L) .setLambda(1.0) .setGamma(1.0) .setEta(1.0) .setMaxTrees(10) .setFeatureBagFraction(0.5) .setNumTopFeatureImportanceValues(3) .setLossFunction(org.elasticsearch.client.ml.dataframe.Regression.LossFunction.MSLE) .setLossFunctionParameter(1.0) .setAlpha(0.5) .setEtaGrowthRatePerTree(1.0) .setSoftTreeDepthLimit(1.0) .setSoftTreeDepthTolerance(0.1) .setDownsampleFactor(0.5) .setMaxOptimizationRoundsPerHyperparameter(3) .setMaxOptimizationRoundsPerHyperparameter(3) .setEarlyStoppingEnabled(false) .build()) .setDescription("this is a regression") .build(); createIndex("put-test-source-index", defaultMappingForTest()); PutDataFrameAnalyticsResponse putDataFrameAnalyticsResponse = execute( new PutDataFrameAnalyticsRequest(config), machineLearningClient::putDataFrameAnalytics, machineLearningClient::putDataFrameAnalyticsAsync); DataFrameAnalyticsConfig createdConfig = putDataFrameAnalyticsResponse.getConfig(); assertThat(createdConfig.getId(), equalTo(config.getId())); assertThat(createdConfig.getSource().getIndex(), equalTo(config.getSource().getIndex())); assertThat(createdConfig.getSource().getQueryConfig(), equalTo(new QueryConfig(new MatchAllQueryBuilder()))); // default value assertThat(createdConfig.getDest().getIndex(), equalTo(config.getDest().getIndex())); assertThat(createdConfig.getDest().getResultsField(), equalTo("ml")); // default value assertThat(createdConfig.getAnalysis(), equalTo(config.getAnalysis())); assertThat(createdConfig.getAnalyzedFields(), equalTo(config.getAnalyzedFields())); assertThat(createdConfig.getModelMemoryLimit(), equalTo(ByteSizeValue.parseBytesSizeValue("1gb", ""))); // default value assertThat(createdConfig.getDescription(), equalTo("this is a regression")); } public void testPutDataFrameAnalyticsConfig_GivenClassification() throws Exception { MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); String configId = "test-put-df-analytics-classification"; DataFrameAnalyticsConfig config = DataFrameAnalyticsConfig.builder() .setId(configId) .setSource(DataFrameAnalyticsSource.builder() .setIndex("put-test-source-index") .build()) .setDest(DataFrameAnalyticsDest.builder() .setIndex("put-test-dest-index") .build()) .setAnalysis(org.elasticsearch.client.ml.dataframe.Classification.builder("my_dependent_variable") .setPredictionFieldName("my_dependent_variable_prediction") .setTrainingPercent(80.0) .setRandomizeSeed(42L) .setClassAssignmentObjective( org.elasticsearch.client.ml.dataframe.Classification.ClassAssignmentObjective.MAXIMIZE_ACCURACY) .setNumTopClasses(1) .setLambda(1.0) .setGamma(1.0) .setEta(1.0) .setMaxTrees(10) .setFeatureBagFraction(0.5) .setNumTopFeatureImportanceValues(3) .setAlpha(0.5) .setEtaGrowthRatePerTree(1.0) .setSoftTreeDepthLimit(1.0) .setSoftTreeDepthTolerance(0.1) .setDownsampleFactor(0.5) .setMaxOptimizationRoundsPerHyperparameter(3) .setEarlyStoppingEnabled(false) .build()) .setDescription("this is a classification") .build(); createIndex("put-test-source-index", defaultMappingForTest()); PutDataFrameAnalyticsResponse putDataFrameAnalyticsResponse = execute( new PutDataFrameAnalyticsRequest(config), machineLearningClient::putDataFrameAnalytics, machineLearningClient::putDataFrameAnalyticsAsync); DataFrameAnalyticsConfig createdConfig = putDataFrameAnalyticsResponse.getConfig(); assertThat(createdConfig.getId(), equalTo(config.getId())); assertThat(createdConfig.getSource().getIndex(), equalTo(config.getSource().getIndex())); assertThat(createdConfig.getSource().getQueryConfig(), equalTo(new QueryConfig(new MatchAllQueryBuilder()))); // default value assertThat(createdConfig.getDest().getIndex(), equalTo(config.getDest().getIndex())); assertThat(createdConfig.getDest().getResultsField(), equalTo("ml")); // default value assertThat(createdConfig.getAnalysis(), equalTo(config.getAnalysis())); assertThat(createdConfig.getAnalyzedFields(), equalTo(config.getAnalyzedFields())); assertThat(createdConfig.getModelMemoryLimit(), equalTo(ByteSizeValue.parseBytesSizeValue("1gb", ""))); // default value assertThat(createdConfig.getDescription(), equalTo("this is a classification")); } public void testUpdateDataFrameAnalytics() throws Exception { MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); String configId = "test-update-df-analytics-classification"; DataFrameAnalyticsConfig config = DataFrameAnalyticsConfig.builder() .setId(configId) .setSource(DataFrameAnalyticsSource.builder().setIndex("update-test-source-index").build()) .setDest(DataFrameAnalyticsDest.builder().setIndex("update-test-dest-index").build()) .setAnalysis(org.elasticsearch.client.ml.dataframe.Classification.builder("my_dependent_variable").build()) .setDescription("this is a classification") .build(); createIndex("update-test-source-index", defaultMappingForTest()); machineLearningClient.putDataFrameAnalytics(new PutDataFrameAnalyticsRequest(config), RequestOptions.DEFAULT); UpdateDataFrameAnalyticsRequest request = new UpdateDataFrameAnalyticsRequest( DataFrameAnalyticsConfigUpdate.builder().setId(config.getId()).setDescription("Updated description").build()); PutDataFrameAnalyticsResponse response = execute(request, machineLearningClient::updateDataFrameAnalytics, machineLearningClient::updateDataFrameAnalyticsAsync); assertThat(response.getConfig().getDescription(), equalTo("Updated description")); GetDataFrameAnalyticsRequest getRequest = new GetDataFrameAnalyticsRequest(config.getId()); GetDataFrameAnalyticsResponse getResponse = machineLearningClient.getDataFrameAnalytics(getRequest, RequestOptions.DEFAULT); assertThat(getResponse.getAnalytics().get(0).getDescription(), equalTo("Updated description")); } public void testGetDataFrameAnalyticsConfig_SingleConfig() throws Exception { MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); String configId = "get-test-config"; DataFrameAnalyticsConfig config = DataFrameAnalyticsConfig.builder() .setId(configId) .setSource(DataFrameAnalyticsSource.builder() .setIndex("get-test-source-index") .build()) .setDest(DataFrameAnalyticsDest.builder() .setIndex("get-test-dest-index") .build()) .setAnalysis(org.elasticsearch.client.ml.dataframe.OutlierDetection.createDefault()) .build(); createIndex("get-test-source-index", defaultMappingForTest()); PutDataFrameAnalyticsResponse putDataFrameAnalyticsResponse = execute( new PutDataFrameAnalyticsRequest(config), machineLearningClient::putDataFrameAnalytics, machineLearningClient::putDataFrameAnalyticsAsync); DataFrameAnalyticsConfig createdConfig = putDataFrameAnalyticsResponse.getConfig(); GetDataFrameAnalyticsResponse getDataFrameAnalyticsResponse = execute( new GetDataFrameAnalyticsRequest(configId), machineLearningClient::getDataFrameAnalytics, machineLearningClient::getDataFrameAnalyticsAsync); assertThat(getDataFrameAnalyticsResponse.getAnalytics(), hasSize(1)); assertThat(getDataFrameAnalyticsResponse.getAnalytics(), contains(createdConfig)); } public void testGetDataFrameAnalyticsConfig_MultipleConfigs() throws Exception { createIndex("get-test-source-index", defaultMappingForTest()); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); String configIdPrefix = "get-test-config-"; int numberOfConfigs = 10; List<DataFrameAnalyticsConfig> createdConfigs = new ArrayList<>(); for (int i = 0; i < numberOfConfigs; ++i) { String configId = configIdPrefix + i; DataFrameAnalyticsConfig config = DataFrameAnalyticsConfig.builder() .setId(configId) .setSource(DataFrameAnalyticsSource.builder() .setIndex("get-test-source-index") .build()) .setDest(DataFrameAnalyticsDest.builder() .setIndex("get-test-dest-index") .build()) .setAnalysis(org.elasticsearch.client.ml.dataframe.OutlierDetection.createDefault()) .build(); PutDataFrameAnalyticsResponse putDataFrameAnalyticsResponse = execute( new PutDataFrameAnalyticsRequest(config), machineLearningClient::putDataFrameAnalytics, machineLearningClient::putDataFrameAnalyticsAsync); DataFrameAnalyticsConfig createdConfig = putDataFrameAnalyticsResponse.getConfig(); createdConfigs.add(createdConfig); } { GetDataFrameAnalyticsResponse getDataFrameAnalyticsResponse = execute( GetDataFrameAnalyticsRequest.getAllDataFrameAnalyticsRequest(), machineLearningClient::getDataFrameAnalytics, machineLearningClient::getDataFrameAnalyticsAsync); assertThat(getDataFrameAnalyticsResponse.getAnalytics(), hasSize(numberOfConfigs)); assertThat(getDataFrameAnalyticsResponse.getAnalytics(), containsInAnyOrder(createdConfigs.toArray())); } { GetDataFrameAnalyticsResponse getDataFrameAnalyticsResponse = execute( new GetDataFrameAnalyticsRequest(configIdPrefix + "*"), machineLearningClient::getDataFrameAnalytics, machineLearningClient::getDataFrameAnalyticsAsync); assertThat(getDataFrameAnalyticsResponse.getAnalytics(), hasSize(numberOfConfigs)); assertThat(getDataFrameAnalyticsResponse.getAnalytics(), containsInAnyOrder(createdConfigs.toArray())); } { GetDataFrameAnalyticsResponse getDataFrameAnalyticsResponse = execute( new GetDataFrameAnalyticsRequest(configIdPrefix + "9", configIdPrefix + "1", configIdPrefix + "4"), machineLearningClient::getDataFrameAnalytics, machineLearningClient::getDataFrameAnalyticsAsync); assertThat(getDataFrameAnalyticsResponse.getAnalytics(), hasSize(3)); assertThat( getDataFrameAnalyticsResponse.getAnalytics(), containsInAnyOrder(createdConfigs.get(1), createdConfigs.get(4), createdConfigs.get(9))); } { GetDataFrameAnalyticsRequest getDataFrameAnalyticsRequest = new GetDataFrameAnalyticsRequest(configIdPrefix + "*"); getDataFrameAnalyticsRequest.setPageParams(new PageParams(3, 4)); GetDataFrameAnalyticsResponse getDataFrameAnalyticsResponse = execute( getDataFrameAnalyticsRequest, machineLearningClient::getDataFrameAnalytics, machineLearningClient::getDataFrameAnalyticsAsync); assertThat(getDataFrameAnalyticsResponse.getAnalytics(), hasSize(4)); assertThat( getDataFrameAnalyticsResponse.getAnalytics(), containsInAnyOrder(createdConfigs.get(3), createdConfigs.get(4), createdConfigs.get(5), createdConfigs.get(6))); } } public void testGetDataFrameAnalyticsConfig_ConfigNotFound() { MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); GetDataFrameAnalyticsRequest request = new GetDataFrameAnalyticsRequest("config_that_does_not_exist"); ElasticsearchStatusException exception = expectThrows(ElasticsearchStatusException.class, () -> execute(request, machineLearningClient::getDataFrameAnalytics, machineLearningClient::getDataFrameAnalyticsAsync)); assertThat(exception.status().getStatus(), equalTo(404)); } public void testGetDataFrameAnalyticsStats() throws Exception { String sourceIndex = "get-stats-test-source-index"; String destIndex = "get-stats-test-dest-index"; createIndex(sourceIndex, defaultMappingForTest()); highLevelClient().index(new IndexRequest(sourceIndex).source(XContentType.JSON, "total", 10000), RequestOptions.DEFAULT); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); String configId = "get-stats-test-config"; DataFrameAnalyticsConfig config = DataFrameAnalyticsConfig.builder() .setId(configId) .setSource(DataFrameAnalyticsSource.builder() .setIndex(sourceIndex) .build()) .setDest(DataFrameAnalyticsDest.builder() .setIndex(destIndex) .build()) .setAnalysis(org.elasticsearch.client.ml.dataframe.OutlierDetection.createDefault()) .build(); execute( new PutDataFrameAnalyticsRequest(config), machineLearningClient::putDataFrameAnalytics, machineLearningClient::putDataFrameAnalyticsAsync); GetDataFrameAnalyticsStatsResponse statsResponse = execute( new GetDataFrameAnalyticsStatsRequest(configId), machineLearningClient::getDataFrameAnalyticsStats, machineLearningClient::getDataFrameAnalyticsStatsAsync); assertThat(statsResponse.getAnalyticsStats(), hasSize(1)); DataFrameAnalyticsStats stats = statsResponse.getAnalyticsStats().get(0); assertThat(stats.getId(), equalTo(configId)); assertThat(stats.getState(), equalTo(DataFrameAnalyticsState.STOPPED)); assertNull(stats.getFailureReason()); assertNull(stats.getNode()); assertNull(stats.getAssignmentExplanation()); assertThat(statsResponse.getNodeFailures(), hasSize(0)); assertThat(statsResponse.getTaskFailures(), hasSize(0)); List<PhaseProgress> progress = stats.getProgress(); assertThat(progress, is(notNullValue())); assertThat(progress.size(), equalTo(4)); assertThat(progress.get(0), equalTo(new PhaseProgress("reindexing", 0))); assertThat(progress.get(1), equalTo(new PhaseProgress("loading_data", 0))); assertThat(progress.get(2), equalTo(new PhaseProgress("computing_outliers", 0))); assertThat(progress.get(3), equalTo(new PhaseProgress("writing_results", 0))); assertThat(stats.getMemoryUsage().getPeakUsageBytes(), equalTo(0L)); assertThat(stats.getMemoryUsage().getStatus(), equalTo(MemoryUsage.Status.OK)); assertThat(stats.getMemoryUsage().getMemoryReestimateBytes(), is(nullValue())); assertThat(stats.getDataCounts(), equalTo(new DataCounts(0, 0, 0))); } public void testStartDataFrameAnalyticsConfig() throws Exception { String sourceIndex = "start-test-source-index"; String destIndex = "start-test-dest-index"; createIndex(sourceIndex, defaultMappingForTest()); highLevelClient().index(new IndexRequest(sourceIndex).source(XContentType.JSON, "total", 10000) .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE), RequestOptions.DEFAULT); // Verify that the destination index does not exist. Otherwise, analytics' reindexing step would fail. assertFalse(highLevelClient().indices().exists(new GetIndexRequest(destIndex), RequestOptions.DEFAULT)); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); String configId = "start-test-config"; DataFrameAnalyticsConfig config = DataFrameAnalyticsConfig.builder() .setId(configId) .setSource(DataFrameAnalyticsSource.builder() .setIndex(sourceIndex) .build()) .setDest(DataFrameAnalyticsDest.builder() .setIndex(destIndex) .build()) .setAnalysis(org.elasticsearch.client.ml.dataframe.OutlierDetection.createDefault()) .build(); execute( new PutDataFrameAnalyticsRequest(config), machineLearningClient::putDataFrameAnalytics, machineLearningClient::putDataFrameAnalyticsAsync); assertThat(getAnalyticsState(configId), equalTo(DataFrameAnalyticsState.STOPPED)); AcknowledgedResponse startDataFrameAnalyticsResponse = execute( new StartDataFrameAnalyticsRequest(configId), machineLearningClient::startDataFrameAnalytics, machineLearningClient::startDataFrameAnalyticsAsync); assertTrue(startDataFrameAnalyticsResponse.isAcknowledged()); // Wait for the analytics to stop. assertBusy(() -> assertThat(getAnalyticsState(configId), equalTo(DataFrameAnalyticsState.STOPPED)), 30, TimeUnit.SECONDS); // Verify that the destination index got created. assertTrue(highLevelClient().indices().exists(new GetIndexRequest(destIndex), RequestOptions.DEFAULT)); } @AwaitsFix(bugUrl = "https://github.com/elastic/elasticsearch/issues/43924") public void testStopDataFrameAnalyticsConfig() throws Exception { String sourceIndex = "stop-test-source-index"; String destIndex = "stop-test-dest-index"; createIndex(sourceIndex, defaultMappingForTest()); highLevelClient().index(new IndexRequest(sourceIndex).source(XContentType.JSON, "total", 10000) .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE), RequestOptions.DEFAULT); // Verify that the destination index does not exist. Otherwise, analytics' reindexing step would fail. assertFalse(highLevelClient().indices().exists(new GetIndexRequest(destIndex), RequestOptions.DEFAULT)); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); String configId = "stop-test-config"; DataFrameAnalyticsConfig config = DataFrameAnalyticsConfig.builder() .setId(configId) .setSource(DataFrameAnalyticsSource.builder() .setIndex(sourceIndex) .build()) .setDest(DataFrameAnalyticsDest.builder() .setIndex(destIndex) .build()) .setAnalysis(org.elasticsearch.client.ml.dataframe.OutlierDetection.createDefault()) .build(); execute( new PutDataFrameAnalyticsRequest(config), machineLearningClient::putDataFrameAnalytics, machineLearningClient::putDataFrameAnalyticsAsync); assertThat(getAnalyticsState(configId), equalTo(DataFrameAnalyticsState.STOPPED)); AcknowledgedResponse startDataFrameAnalyticsResponse = execute( new StartDataFrameAnalyticsRequest(configId), machineLearningClient::startDataFrameAnalytics, machineLearningClient::startDataFrameAnalyticsAsync); assertTrue(startDataFrameAnalyticsResponse.isAcknowledged()); assertThat(getAnalyticsState(configId), anyOf(equalTo(DataFrameAnalyticsState.STARTED), equalTo(DataFrameAnalyticsState.REINDEXING), equalTo(DataFrameAnalyticsState.ANALYZING))); StopDataFrameAnalyticsResponse stopDataFrameAnalyticsResponse = execute( new StopDataFrameAnalyticsRequest(configId), machineLearningClient::stopDataFrameAnalytics, machineLearningClient::stopDataFrameAnalyticsAsync); assertTrue(stopDataFrameAnalyticsResponse.isStopped()); assertThat(getAnalyticsState(configId), equalTo(DataFrameAnalyticsState.STOPPED)); } private DataFrameAnalyticsState getAnalyticsState(String configId) throws IOException { MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); GetDataFrameAnalyticsStatsResponse statsResponse = machineLearningClient.getDataFrameAnalyticsStats(new GetDataFrameAnalyticsStatsRequest(configId), RequestOptions.DEFAULT); assertThat(statsResponse.getAnalyticsStats(), hasSize(1)); DataFrameAnalyticsStats stats = statsResponse.getAnalyticsStats().get(0); return stats.getState(); } public void testDeleteDataFrameAnalyticsConfig() throws Exception { MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); String configId = "delete-test-config"; DataFrameAnalyticsConfig config = DataFrameAnalyticsConfig.builder() .setId(configId) .setSource(DataFrameAnalyticsSource.builder() .setIndex("delete-test-source-index") .build()) .setDest(DataFrameAnalyticsDest.builder() .setIndex("delete-test-dest-index") .build()) .setAnalysis(org.elasticsearch.client.ml.dataframe.OutlierDetection.createDefault()) .build(); createIndex("delete-test-source-index", defaultMappingForTest()); GetDataFrameAnalyticsResponse getDataFrameAnalyticsResponse = execute( new GetDataFrameAnalyticsRequest(configId + "*"), machineLearningClient::getDataFrameAnalytics, machineLearningClient::getDataFrameAnalyticsAsync); assertThat(getDataFrameAnalyticsResponse.getAnalytics(), hasSize(0)); execute( new PutDataFrameAnalyticsRequest(config), machineLearningClient::putDataFrameAnalytics, machineLearningClient::putDataFrameAnalyticsAsync); getDataFrameAnalyticsResponse = execute( new GetDataFrameAnalyticsRequest(configId + "*"), machineLearningClient::getDataFrameAnalytics, machineLearningClient::getDataFrameAnalyticsAsync); assertThat(getDataFrameAnalyticsResponse.getAnalytics(), hasSize(1)); DeleteDataFrameAnalyticsRequest deleteRequest = new DeleteDataFrameAnalyticsRequest(configId); if (randomBoolean()) { deleteRequest.setForce(randomBoolean()); } AcknowledgedResponse deleteDataFrameAnalyticsResponse = execute(deleteRequest, machineLearningClient::deleteDataFrameAnalytics, machineLearningClient::deleteDataFrameAnalyticsAsync); assertTrue(deleteDataFrameAnalyticsResponse.isAcknowledged()); getDataFrameAnalyticsResponse = execute( new GetDataFrameAnalyticsRequest(configId + "*"), machineLearningClient::getDataFrameAnalytics, machineLearningClient::getDataFrameAnalyticsAsync); assertThat(getDataFrameAnalyticsResponse.getAnalytics(), hasSize(0)); } public void testDeleteDataFrameAnalyticsConfig_ConfigNotFound() { MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); DeleteDataFrameAnalyticsRequest request = new DeleteDataFrameAnalyticsRequest("config_that_does_not_exist"); ElasticsearchStatusException exception = expectThrows(ElasticsearchStatusException.class, () -> execute( request, machineLearningClient::deleteDataFrameAnalytics, machineLearningClient::deleteDataFrameAnalyticsAsync)); assertThat(exception.status().getStatus(), equalTo(404)); } public void testEvaluateDataFrame_OutlierDetection() throws IOException { String indexName = "evaluate-test-index"; createIndex(indexName, mappingForOutlierDetection()); BulkRequest bulk = new BulkRequest() .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE) .add(docForOutlierDetection(indexName, "blue", false, 0.1)) // .add(docForOutlierDetection(indexName, "blue", false, 0.2)) // .add(docForOutlierDetection(indexName, "blue", false, 0.3)) // .add(docForOutlierDetection(indexName, "blue", false, 0.4)) // .add(docForOutlierDetection(indexName, "blue", false, 0.7)) // .add(docForOutlierDetection(indexName, "blue", true, 0.2)) // .add(docForOutlierDetection(indexName, "green", true, 0.3)) // .add(docForOutlierDetection(indexName, "green", true, 0.4)) // .add(docForOutlierDetection(indexName, "green", true, 0.8)) // .add(docForOutlierDetection(indexName, "green", true, 0.9)); // highLevelClient().bulk(bulk, RequestOptions.DEFAULT); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); EvaluateDataFrameRequest evaluateDataFrameRequest = new EvaluateDataFrameRequest( indexName, null, new OutlierDetection( actualField, probabilityField, org.elasticsearch.client.ml.dataframe.evaluation.outlierdetection.PrecisionMetric.at(0.4, 0.5, 0.6), org.elasticsearch.client.ml.dataframe.evaluation.outlierdetection.RecallMetric.at(0.5, 0.7), ConfusionMatrixMetric.at(0.5), org.elasticsearch.client.ml.dataframe.evaluation.outlierdetection.AucRocMetric.withCurve())); EvaluateDataFrameResponse evaluateDataFrameResponse = execute(evaluateDataFrameRequest, machineLearningClient::evaluateDataFrame, machineLearningClient::evaluateDataFrameAsync); assertThat(evaluateDataFrameResponse.getEvaluationName(), equalTo(OutlierDetection.NAME)); assertThat(evaluateDataFrameResponse.getMetrics().size(), equalTo(4)); org.elasticsearch.client.ml.dataframe.evaluation.outlierdetection.PrecisionMetric.Result precisionResult = evaluateDataFrameResponse.getMetricByName( org.elasticsearch.client.ml.dataframe.evaluation.outlierdetection.PrecisionMetric.NAME); assertThat( precisionResult.getMetricName(), equalTo(org.elasticsearch.client.ml.dataframe.evaluation.outlierdetection.PrecisionMetric.NAME)); // Precision is 3/5=0.6 as there were 3 true examples (#7, #8, #9) among the 5 positive examples (#3, #4, #7, #8, #9) assertThat(precisionResult.getScoreByThreshold("0.4"), closeTo(0.6, 1e-9)); // Precision is 2/3=0.(6) as there were 2 true examples (#8, #9) among the 3 positive examples (#4, #8, #9) assertThat(precisionResult.getScoreByThreshold("0.5"), closeTo(0.666666666, 1e-9)); // Precision is 2/3=0.(6) as there were 2 true examples (#8, #9) among the 3 positive examples (#4, #8, #9) assertThat(precisionResult.getScoreByThreshold("0.6"), closeTo(0.666666666, 1e-9)); assertNull(precisionResult.getScoreByThreshold("0.1")); org.elasticsearch.client.ml.dataframe.evaluation.outlierdetection.RecallMetric.Result recallResult = evaluateDataFrameResponse.getMetricByName(org.elasticsearch.client.ml.dataframe.evaluation.outlierdetection.RecallMetric.NAME); assertThat( recallResult.getMetricName(), equalTo(org.elasticsearch.client.ml.dataframe.evaluation.outlierdetection.RecallMetric.NAME)); // Recall is 2/5=0.4 as there were 2 true positive examples (#8, #9) among the 5 true examples (#5, #6, #7, #8, #9) assertThat(recallResult.getScoreByThreshold("0.5"), closeTo(0.4, 1e-9)); // Recall is 2/5=0.4 as there were 2 true positive examples (#8, #9) among the 5 true examples (#5, #6, #7, #8, #9) assertThat(recallResult.getScoreByThreshold("0.7"), closeTo(0.4, 1e-9)); assertNull(recallResult.getScoreByThreshold("0.1")); ConfusionMatrixMetric.Result confusionMatrixResult = evaluateDataFrameResponse.getMetricByName(ConfusionMatrixMetric.NAME); assertThat(confusionMatrixResult.getMetricName(), equalTo(ConfusionMatrixMetric.NAME)); ConfusionMatrixMetric.ConfusionMatrix confusionMatrix = confusionMatrixResult.getScoreByThreshold("0.5"); assertThat(confusionMatrix.getTruePositives(), equalTo(2L)); // docs #8 and #9 assertThat(confusionMatrix.getFalsePositives(), equalTo(1L)); // doc assertThat(confusionMatrix.getTrueNegatives(), equalTo(4L)); // docs #0, #1, #2 and #3 assertThat(confusionMatrix.getFalseNegatives(), equalTo(3L)); // docs #5, #6 and #7 assertNull(confusionMatrixResult.getScoreByThreshold("0.1")); AucRocResult aucRocResult = evaluateDataFrameResponse.getMetricByName(org.elasticsearch.client.ml.dataframe.evaluation.outlierdetection.AucRocMetric.NAME); assertThat(aucRocResult.getMetricName(), equalTo(AucRocMetric.NAME)); assertThat(aucRocResult.getValue(), closeTo(0.70, 1e-3)); assertNotNull(aucRocResult.getCurve()); List<AucRocPoint> curve = aucRocResult.getCurve(); AucRocPoint curvePointAtThreshold0 = curve.stream().filter(p -> p.getThreshold() == 0.0).findFirst().get(); assertThat(curvePointAtThreshold0.getTruePositiveRate(), equalTo(1.0)); assertThat(curvePointAtThreshold0.getFalsePositiveRate(), equalTo(1.0)); assertThat(curvePointAtThreshold0.getThreshold(), equalTo(0.0)); AucRocPoint curvePointAtThreshold1 = curve.stream().filter(p -> p.getThreshold() == 1.0).findFirst().get(); assertThat(curvePointAtThreshold1.getTruePositiveRate(), equalTo(0.0)); assertThat(curvePointAtThreshold1.getFalsePositiveRate(), equalTo(0.0)); assertThat(curvePointAtThreshold1.getThreshold(), equalTo(1.0)); } public void testEvaluateDataFrame_OutlierDetection_WithQuery() throws IOException { String indexName = "evaluate-with-query-test-index"; createIndex(indexName, mappingForOutlierDetection()); BulkRequest bulk = new BulkRequest() .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE) .add(docForOutlierDetection(indexName, "blue", true, 1.0)) // .add(docForOutlierDetection(indexName, "blue", true, 1.0)) // .add(docForOutlierDetection(indexName, "blue", true, 1.0)) // .add(docForOutlierDetection(indexName, "blue", true, 1.0)) // .add(docForOutlierDetection(indexName, "blue", true, 0.0)) // .add(docForOutlierDetection(indexName, "blue", true, 0.0)) // .add(docForOutlierDetection(indexName, "green", true, 0.0)) // .add(docForOutlierDetection(indexName, "green", true, 0.0)) // .add(docForOutlierDetection(indexName, "green", true, 0.0)) // .add(docForOutlierDetection(indexName, "green", true, 1.0)); // highLevelClient().bulk(bulk, RequestOptions.DEFAULT); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); EvaluateDataFrameRequest evaluateDataFrameRequest = new EvaluateDataFrameRequest( indexName, // Request only "blue" subset to be evaluated new QueryConfig(QueryBuilders.termQuery(datasetField, "blue")), new OutlierDetection(actualField, probabilityField, ConfusionMatrixMetric.at(0.5))); EvaluateDataFrameResponse evaluateDataFrameResponse = execute(evaluateDataFrameRequest, machineLearningClient::evaluateDataFrame, machineLearningClient::evaluateDataFrameAsync); assertThat(evaluateDataFrameResponse.getEvaluationName(), equalTo(OutlierDetection.NAME)); assertThat(evaluateDataFrameResponse.getMetrics().size(), equalTo(1)); ConfusionMatrixMetric.Result confusionMatrixResult = evaluateDataFrameResponse.getMetricByName(ConfusionMatrixMetric.NAME); assertThat(confusionMatrixResult.getMetricName(), equalTo(ConfusionMatrixMetric.NAME)); ConfusionMatrixMetric.ConfusionMatrix confusionMatrix = confusionMatrixResult.getScoreByThreshold("0.5"); assertThat(confusionMatrix.getTruePositives(), equalTo(4L)); // docs #0, #1, #2 and #3 assertThat(confusionMatrix.getFalsePositives(), equalTo(0L)); assertThat(confusionMatrix.getTrueNegatives(), equalTo(0L)); assertThat(confusionMatrix.getFalseNegatives(), equalTo(2L)); // docs #4 and #5 } public void testEvaluateDataFrame_Regression() throws IOException { String regressionIndex = "evaluate-regression-test-index"; createIndex(regressionIndex, mappingForRegression()); BulkRequest regressionBulk = new BulkRequest() .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE) .add(docForRegression(regressionIndex, 0.3, 0.1)) // .add(docForRegression(regressionIndex, 0.3, 0.2)) // .add(docForRegression(regressionIndex, 0.3, 0.3)) // .add(docForRegression(regressionIndex, 0.3, 0.4)) // .add(docForRegression(regressionIndex, 0.3, 0.7)) // .add(docForRegression(regressionIndex, 0.5, 0.2)) // .add(docForRegression(regressionIndex, 0.5, 0.3)) // .add(docForRegression(regressionIndex, 0.5, 0.4)) // .add(docForRegression(regressionIndex, 0.5, 0.8)) // .add(docForRegression(regressionIndex, 0.5, 0.9)); // highLevelClient().bulk(regressionBulk, RequestOptions.DEFAULT); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); EvaluateDataFrameRequest evaluateDataFrameRequest = new EvaluateDataFrameRequest( regressionIndex, null, new Regression( actualRegression, predictedRegression, new MeanSquaredErrorMetric(), new MeanSquaredLogarithmicErrorMetric(1.0), new HuberMetric(1.0), new RSquaredMetric())); EvaluateDataFrameResponse evaluateDataFrameResponse = execute(evaluateDataFrameRequest, machineLearningClient::evaluateDataFrame, machineLearningClient::evaluateDataFrameAsync); assertThat(evaluateDataFrameResponse.getEvaluationName(), equalTo(Regression.NAME)); assertThat(evaluateDataFrameResponse.getMetrics().size(), equalTo(4)); MeanSquaredErrorMetric.Result mseResult = evaluateDataFrameResponse.getMetricByName(MeanSquaredErrorMetric.NAME); assertThat(mseResult.getMetricName(), equalTo(MeanSquaredErrorMetric.NAME)); assertThat(mseResult.getValue(), closeTo(0.061000000, 1e-9)); MeanSquaredLogarithmicErrorMetric.Result msleResult = evaluateDataFrameResponse.getMetricByName(MeanSquaredLogarithmicErrorMetric.NAME); assertThat(msleResult.getMetricName(), equalTo(MeanSquaredLogarithmicErrorMetric.NAME)); assertThat(msleResult.getValue(), closeTo(0.02759231770210426, 1e-9)); HuberMetric.Result huberResult = evaluateDataFrameResponse.getMetricByName(HuberMetric.NAME); assertThat(huberResult.getMetricName(), equalTo(HuberMetric.NAME)); assertThat(huberResult.getValue(), closeTo(0.029669771640929276, 1e-9)); RSquaredMetric.Result rSquaredResult = evaluateDataFrameResponse.getMetricByName(RSquaredMetric.NAME); assertThat(rSquaredResult.getMetricName(), equalTo(RSquaredMetric.NAME)); assertThat(rSquaredResult.getValue(), closeTo(-5.1000000000000005, 1e-9)); } public void testEvaluateDataFrame_Classification() throws IOException { String indexName = "evaluate-classification-test-index"; createIndex(indexName, mappingForClassification()); BulkRequest regressionBulk = new BulkRequest() .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE) .add(docForClassification(indexName, "cat", "cat", "dog", "ant")) .add(docForClassification(indexName, "cat", "cat", "dog", "ant")) .add(docForClassification(indexName, "cat", "cat", "horse", "dog")) .add(docForClassification(indexName, "cat", "dog", "cat", "mule")) .add(docForClassification(indexName, "cat", "fish", "cat", "dog")) .add(docForClassification(indexName, "dog", "cat", "dog", "mule")) .add(docForClassification(indexName, "dog", "dog", "cat", "ant")) .add(docForClassification(indexName, "dog", "dog", "cat", "ant")) .add(docForClassification(indexName, "dog", "dog", "cat", "ant")) .add(docForClassification(indexName, "ant", "cat", "ant", "wasp")); highLevelClient().bulk(regressionBulk, RequestOptions.DEFAULT); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); { // AucRoc EvaluateDataFrameRequest evaluateDataFrameRequest = new EvaluateDataFrameRequest( indexName, null, new Classification(actualClassField, null, topClassesField, AucRocMetric.forClassWithCurve("cat"))); EvaluateDataFrameResponse evaluateDataFrameResponse = execute(evaluateDataFrameRequest, machineLearningClient::evaluateDataFrame, machineLearningClient::evaluateDataFrameAsync); assertThat(evaluateDataFrameResponse.getEvaluationName(), equalTo(Classification.NAME)); assertThat(evaluateDataFrameResponse.getMetrics().size(), equalTo(1)); AucRocResult aucRocResult = evaluateDataFrameResponse.getMetricByName(AucRocMetric.NAME); assertThat(aucRocResult.getMetricName(), equalTo(AucRocMetric.NAME)); assertThat(aucRocResult.getValue(), closeTo(0.619, 1e-3)); assertNotNull(aucRocResult.getCurve()); } { // Accuracy EvaluateDataFrameRequest evaluateDataFrameRequest = new EvaluateDataFrameRequest( indexName, null, new Classification(actualClassField, predictedClassField, null, new AccuracyMetric())); EvaluateDataFrameResponse evaluateDataFrameResponse = execute(evaluateDataFrameRequest, machineLearningClient::evaluateDataFrame, machineLearningClient::evaluateDataFrameAsync); assertThat(evaluateDataFrameResponse.getEvaluationName(), equalTo(Classification.NAME)); assertThat(evaluateDataFrameResponse.getMetrics().size(), equalTo(1)); AccuracyMetric.Result accuracyResult = evaluateDataFrameResponse.getMetricByName(AccuracyMetric.NAME); assertThat(accuracyResult.getMetricName(), equalTo(AccuracyMetric.NAME)); assertThat( accuracyResult.getClasses(), equalTo( List.of( // 9 out of 10 examples were classified correctly new PerClassSingleValue("ant", 0.9), // 6 out of 10 examples were classified correctly new PerClassSingleValue("cat", 0.6), // 8 out of 10 examples were classified correctly new PerClassSingleValue("dog", 0.8)))); assertThat(accuracyResult.getOverallAccuracy(), equalTo(0.6)); // 6 out of 10 examples were classified correctly } { // Precision EvaluateDataFrameRequest evaluateDataFrameRequest = new EvaluateDataFrameRequest( indexName, null, new Classification(actualClassField, predictedClassField, null, new PrecisionMetric())); EvaluateDataFrameResponse evaluateDataFrameResponse = execute(evaluateDataFrameRequest, machineLearningClient::evaluateDataFrame, machineLearningClient::evaluateDataFrameAsync); assertThat(evaluateDataFrameResponse.getEvaluationName(), equalTo(Classification.NAME)); assertThat(evaluateDataFrameResponse.getMetrics().size(), equalTo(1)); PrecisionMetric.Result precisionResult = evaluateDataFrameResponse.getMetricByName(PrecisionMetric.NAME); assertThat(precisionResult.getMetricName(), equalTo(PrecisionMetric.NAME)); assertThat( precisionResult.getClasses(), equalTo( List.of( // 3 out of 5 examples labeled as "cat" were classified correctly new PerClassSingleValue("cat", 0.6), // 3 out of 4 examples labeled as "dog" were classified correctly new PerClassSingleValue("dog", 0.75)))); assertThat(precisionResult.getAvgPrecision(), equalTo(0.675)); } { // Recall EvaluateDataFrameRequest evaluateDataFrameRequest = new EvaluateDataFrameRequest( indexName, null, new Classification(actualClassField, predictedClassField, null, new RecallMetric())); EvaluateDataFrameResponse evaluateDataFrameResponse = execute(evaluateDataFrameRequest, machineLearningClient::evaluateDataFrame, machineLearningClient::evaluateDataFrameAsync); assertThat(evaluateDataFrameResponse.getEvaluationName(), equalTo(Classification.NAME)); assertThat(evaluateDataFrameResponse.getMetrics().size(), equalTo(1)); RecallMetric.Result recallResult = evaluateDataFrameResponse.getMetricByName(RecallMetric.NAME); assertThat(recallResult.getMetricName(), equalTo(RecallMetric.NAME)); assertThat( recallResult.getClasses(), equalTo( List.of( // 3 out of 5 examples labeled as "cat" were classified correctly new PerClassSingleValue("cat", 0.6), // 3 out of 4 examples labeled as "dog" were classified correctly new PerClassSingleValue("dog", 0.75), // no examples labeled as "ant" were classified correctly new PerClassSingleValue("ant", 0.0)))); assertThat(recallResult.getAvgRecall(), equalTo(0.45)); } { // No size provided for MulticlassConfusionMatrixMetric, default used instead EvaluateDataFrameRequest evaluateDataFrameRequest = new EvaluateDataFrameRequest( indexName, null, new Classification(actualClassField, predictedClassField, null, new MulticlassConfusionMatrixMetric())); EvaluateDataFrameResponse evaluateDataFrameResponse = execute(evaluateDataFrameRequest, machineLearningClient::evaluateDataFrame, machineLearningClient::evaluateDataFrameAsync); assertThat(evaluateDataFrameResponse.getEvaluationName(), equalTo(Classification.NAME)); assertThat(evaluateDataFrameResponse.getMetrics().size(), equalTo(1)); MulticlassConfusionMatrixMetric.Result mcmResult = evaluateDataFrameResponse.getMetricByName(MulticlassConfusionMatrixMetric.NAME); assertThat(mcmResult.getMetricName(), equalTo(MulticlassConfusionMatrixMetric.NAME)); assertThat( mcmResult.getConfusionMatrix(), equalTo( List.of( new MulticlassConfusionMatrixMetric.ActualClass( "ant", 1L, List.of( new MulticlassConfusionMatrixMetric.PredictedClass("ant", 0L), new MulticlassConfusionMatrixMetric.PredictedClass("cat", 1L), new MulticlassConfusionMatrixMetric.PredictedClass("dog", 0L)), 0L), new MulticlassConfusionMatrixMetric.ActualClass( "cat", 5L, List.of( new MulticlassConfusionMatrixMetric.PredictedClass("ant", 0L), new MulticlassConfusionMatrixMetric.PredictedClass("cat", 3L), new MulticlassConfusionMatrixMetric.PredictedClass("dog", 1L)), 1L), new MulticlassConfusionMatrixMetric.ActualClass( "dog", 4L, List.of( new MulticlassConfusionMatrixMetric.PredictedClass("ant", 0L), new MulticlassConfusionMatrixMetric.PredictedClass("cat", 1L), new MulticlassConfusionMatrixMetric.PredictedClass("dog", 3L)), 0L)))); assertThat(mcmResult.getOtherActualClassCount(), equalTo(0L)); } { // Explicit size provided for MulticlassConfusionMatrixMetric metric EvaluateDataFrameRequest evaluateDataFrameRequest = new EvaluateDataFrameRequest( indexName, null, new Classification(actualClassField, predictedClassField, null, new MulticlassConfusionMatrixMetric(2))); EvaluateDataFrameResponse evaluateDataFrameResponse = execute(evaluateDataFrameRequest, machineLearningClient::evaluateDataFrame, machineLearningClient::evaluateDataFrameAsync); assertThat(evaluateDataFrameResponse.getEvaluationName(), equalTo(Classification.NAME)); assertThat(evaluateDataFrameResponse.getMetrics().size(), equalTo(1)); MulticlassConfusionMatrixMetric.Result mcmResult = evaluateDataFrameResponse.getMetricByName(MulticlassConfusionMatrixMetric.NAME); assertThat(mcmResult.getMetricName(), equalTo(MulticlassConfusionMatrixMetric.NAME)); assertThat( mcmResult.getConfusionMatrix(), equalTo( List.of( new MulticlassConfusionMatrixMetric.ActualClass( "cat", 5L, List.of( new MulticlassConfusionMatrixMetric.PredictedClass("cat", 3L), new MulticlassConfusionMatrixMetric.PredictedClass("dog", 1L)), 1L), new MulticlassConfusionMatrixMetric.ActualClass( "dog", 4L, List.of( new MulticlassConfusionMatrixMetric.PredictedClass("cat", 1L), new MulticlassConfusionMatrixMetric.PredictedClass("dog", 3L)), 0L) ))); assertThat(mcmResult.getOtherActualClassCount(), equalTo(1L)); } } private static XContentBuilder defaultMappingForTest() throws IOException { return XContentFactory.jsonBuilder().startObject() .startObject("properties") .startObject("timestamp") .field("type", "date") .endObject() .startObject("total") .field("type", "long") .endObject() .endObject() .endObject(); } private static final String datasetField = "dataset"; private static final String actualField = "label"; private static final String probabilityField = "p"; private static XContentBuilder mappingForOutlierDetection() throws IOException { return XContentFactory.jsonBuilder().startObject() .startObject("properties") .startObject(datasetField) .field("type", "keyword") .endObject() .startObject(actualField) .field("type", "keyword") .endObject() .startObject(probabilityField) .field("type", "double") .endObject() .endObject() .endObject(); } private static IndexRequest docForOutlierDetection(String indexName, String dataset, boolean isTrue, double p) { return new IndexRequest() .index(indexName) .source(XContentType.JSON, datasetField, dataset, actualField, Boolean.toString(isTrue), probabilityField, p); } private static final String actualClassField = "actual_class"; private static final String predictedClassField = "predicted_class"; private static final String topClassesField = "top_classes"; private static XContentBuilder mappingForClassification() throws IOException { return XContentFactory.jsonBuilder().startObject() .startObject("properties") .startObject(actualClassField) .field("type", "keyword") .endObject() .startObject(predictedClassField) .field("type", "keyword") .endObject() .startObject(topClassesField) .field("type", "nested") .endObject() .endObject() .endObject(); } private static IndexRequest docForClassification(String indexName, String actualClass, String... topPredictedClasses) { assert topPredictedClasses.length > 0; return new IndexRequest() .index(indexName) .source(XContentType.JSON, actualClassField, actualClass, predictedClassField, topPredictedClasses[0], topClassesField, IntStream.range(0, topPredictedClasses.length) // Consecutive assigned probabilities are: 0.5, 0.25, 0.125, etc. .mapToObj(i -> Map.of("class_name", topPredictedClasses[i], "class_probability", 1.0 / (2 << i))) .collect(Collectors.toList())); } private static final String actualRegression = "regression_actual"; private static final String predictedRegression = "regression_predicted"; private static XContentBuilder mappingForRegression() throws IOException { return XContentFactory.jsonBuilder().startObject() .startObject("properties") .startObject(actualRegression) .field("type", "double") .endObject() .startObject(predictedRegression) .field("type", "double") .endObject() .endObject() .endObject(); } private static IndexRequest docForRegression(String indexName, double actualValue, double predictedValue) { return new IndexRequest() .index(indexName) .source(XContentType.JSON, actualRegression, actualValue, predictedRegression, predictedValue); } private void createIndex(String indexName, XContentBuilder mapping) throws IOException { highLevelClient().indices().create(new CreateIndexRequest(indexName).mapping(mapping), RequestOptions.DEFAULT); } public void testExplainDataFrameAnalytics() throws IOException { String indexName = "explain-df-test-index"; createIndex(indexName, mappingForOutlierDetection()); BulkRequest bulk1 = new BulkRequest() .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); for (int i = 0; i < 10; ++i) { bulk1.add(docForOutlierDetection(indexName, randomAlphaOfLength(10), randomBoolean(), randomDoubleBetween(0.0, 1.0, true))); } highLevelClient().bulk(bulk1, RequestOptions.DEFAULT); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); ExplainDataFrameAnalyticsRequest explainRequest = new ExplainDataFrameAnalyticsRequest( DataFrameAnalyticsConfig.builder() .setSource(DataFrameAnalyticsSource.builder().setIndex(indexName).build()) .setAnalysis(org.elasticsearch.client.ml.dataframe.OutlierDetection.createDefault()) .build()); // We are pretty liberal here as this test does not aim at verifying concrete numbers but rather end-to-end user workflow. ByteSizeValue lowerBound = new ByteSizeValue(1, ByteSizeUnit.KB); ByteSizeValue upperBound = new ByteSizeValue(1, ByteSizeUnit.GB); // Data Frame has 10 rows, expect that the returned estimates fall within (1kB, 1GB) range. ExplainDataFrameAnalyticsResponse response1 = execute(explainRequest, machineLearningClient::explainDataFrameAnalytics, machineLearningClient::explainDataFrameAnalyticsAsync); MemoryEstimation memoryEstimation1 = response1.getMemoryEstimation(); assertThat(memoryEstimation1.getExpectedMemoryWithoutDisk(), allOf(greaterThanOrEqualTo(lowerBound), lessThan(upperBound))); assertThat(memoryEstimation1.getExpectedMemoryWithDisk(), allOf(greaterThanOrEqualTo(lowerBound), lessThan(upperBound))); List<FieldSelection> fieldSelection = response1.getFieldSelection(); assertThat(fieldSelection.size(), equalTo(3)); assertThat(fieldSelection.stream().map(FieldSelection::getName).collect(Collectors.toList()), contains("dataset", "label", "p")); BulkRequest bulk2 = new BulkRequest() .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); for (int i = 10; i < 100; ++i) { bulk2.add(docForOutlierDetection(indexName, randomAlphaOfLength(10), randomBoolean(), randomDoubleBetween(0.0, 1.0, true))); } highLevelClient().bulk(bulk2, RequestOptions.DEFAULT); // Data Frame now has 100 rows, expect that the returned estimates will be greater than or equal to the previous ones. ExplainDataFrameAnalyticsResponse response2 = execute( explainRequest, machineLearningClient::explainDataFrameAnalytics, machineLearningClient::explainDataFrameAnalyticsAsync); MemoryEstimation memoryEstimation2 = response2.getMemoryEstimation(); assertThat( memoryEstimation2.getExpectedMemoryWithoutDisk(), allOf(greaterThanOrEqualTo(memoryEstimation1.getExpectedMemoryWithoutDisk()), lessThan(upperBound))); assertThat( memoryEstimation2.getExpectedMemoryWithDisk(), allOf(greaterThanOrEqualTo(memoryEstimation1.getExpectedMemoryWithDisk()), lessThan(upperBound))); } public void testGetTrainedModels() throws Exception { MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); String modelIdPrefix = "get-trained-model-"; int numberOfModels = 5; for (int i = 0; i < numberOfModels; ++i) { String modelId = modelIdPrefix + i; putTrainedModel(modelId); } { GetTrainedModelsResponse getTrainedModelsResponse = execute( new GetTrainedModelsRequest(modelIdPrefix + 0) .setDecompressDefinition(true) .includeDefinition() .includeTotalFeatureImportance(), machineLearningClient::getTrainedModels, machineLearningClient::getTrainedModelsAsync); assertThat(getTrainedModelsResponse.getCount(), equalTo(1L)); assertThat(getTrainedModelsResponse.getTrainedModels(), hasSize(1)); assertThat(getTrainedModelsResponse.getTrainedModels().get(0).getCompressedDefinition(), is(nullValue())); assertThat(getTrainedModelsResponse.getTrainedModels().get(0).getDefinition(), is(not(nullValue()))); assertThat(getTrainedModelsResponse.getTrainedModels().get(0).getModelId(), equalTo(modelIdPrefix + 0)); getTrainedModelsResponse = execute( new GetTrainedModelsRequest(modelIdPrefix + 0) .setDecompressDefinition(false) .includeTotalFeatureImportance() .includeDefinition(), machineLearningClient::getTrainedModels, machineLearningClient::getTrainedModelsAsync); assertThat(getTrainedModelsResponse.getCount(), equalTo(1L)); assertThat(getTrainedModelsResponse.getTrainedModels(), hasSize(1)); assertThat(getTrainedModelsResponse.getTrainedModels().get(0).getCompressedDefinition(), is(not(nullValue()))); assertThat(getTrainedModelsResponse.getTrainedModels().get(0).getDefinition(), is(nullValue())); assertThat(getTrainedModelsResponse.getTrainedModels().get(0).getModelId(), equalTo(modelIdPrefix + 0)); getTrainedModelsResponse = execute( new GetTrainedModelsRequest(modelIdPrefix + 0) .setDecompressDefinition(false), machineLearningClient::getTrainedModels, machineLearningClient::getTrainedModelsAsync); assertThat(getTrainedModelsResponse.getCount(), equalTo(1L)); assertThat(getTrainedModelsResponse.getTrainedModels(), hasSize(1)); assertThat(getTrainedModelsResponse.getTrainedModels().get(0).getCompressedDefinition(), is(nullValue())); assertThat(getTrainedModelsResponse.getTrainedModels().get(0).getDefinition(), is(nullValue())); assertThat(getTrainedModelsResponse.getTrainedModels().get(0).getModelId(), equalTo(modelIdPrefix + 0)); } { GetTrainedModelsResponse getTrainedModelsResponse = execute( GetTrainedModelsRequest.getAllTrainedModelConfigsRequest(), machineLearningClient::getTrainedModels, machineLearningClient::getTrainedModelsAsync); assertThat(getTrainedModelsResponse.getTrainedModels(), hasSize(numberOfModels + 1)); assertThat(getTrainedModelsResponse.getCount(), equalTo(5L + 1)); } { GetTrainedModelsResponse getTrainedModelsResponse = execute( new GetTrainedModelsRequest(modelIdPrefix + 4, modelIdPrefix + 2, modelIdPrefix + 3), machineLearningClient::getTrainedModels, machineLearningClient::getTrainedModelsAsync); assertThat(getTrainedModelsResponse.getTrainedModels(), hasSize(3)); assertThat(getTrainedModelsResponse.getCount(), equalTo(3L)); } { GetTrainedModelsResponse getTrainedModelsResponse = execute( new GetTrainedModelsRequest(modelIdPrefix + "*").setPageParams(new PageParams(1, 2)), machineLearningClient::getTrainedModels, machineLearningClient::getTrainedModelsAsync); assertThat(getTrainedModelsResponse.getTrainedModels(), hasSize(2)); assertThat(getTrainedModelsResponse.getCount(), equalTo(5L)); assertThat( getTrainedModelsResponse.getTrainedModels().stream().map(TrainedModelConfig::getModelId).collect(Collectors.toList()), containsInAnyOrder(modelIdPrefix + 1, modelIdPrefix + 2)); } } public void testPutTrainedModel() throws Exception { String modelId = "test-put-trained-model"; String modelIdCompressed = "test-put-trained-model-compressed-definition"; MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); TrainedModelDefinition definition = TrainedModelDefinitionTests.createRandomBuilder(TargetType.REGRESSION).build(); TrainedModelConfig trainedModelConfig = TrainedModelConfig.builder() .setDefinition(definition) .setModelId(modelId) .setInferenceConfig(new RegressionConfig()) .setInput(new TrainedModelInput(Arrays.asList("col1", "col2", "col3", "col4"))) .setDescription("test model") .build(); PutTrainedModelResponse putTrainedModelResponse = execute(new PutTrainedModelRequest(trainedModelConfig), machineLearningClient::putTrainedModel, machineLearningClient::putTrainedModelAsync); TrainedModelConfig createdModel = putTrainedModelResponse.getResponse(); assertThat(createdModel.getModelId(), equalTo(modelId)); definition = TrainedModelDefinitionTests.createRandomBuilder(TargetType.REGRESSION).build(); trainedModelConfig = TrainedModelConfig.builder() .setCompressedDefinition(InferenceToXContentCompressor.deflate(definition)) .setModelId(modelIdCompressed) .setInferenceConfig(new RegressionConfig()) .setInput(new TrainedModelInput(Arrays.asList("col1", "col2", "col3", "col4"))) .setDescription("test model") .build(); putTrainedModelResponse = execute(new PutTrainedModelRequest(trainedModelConfig), machineLearningClient::putTrainedModel, machineLearningClient::putTrainedModelAsync); createdModel = putTrainedModelResponse.getResponse(); assertThat(createdModel.getModelId(), equalTo(modelIdCompressed)); GetTrainedModelsResponse getTrainedModelsResponse = execute( new GetTrainedModelsRequest(modelIdCompressed).setDecompressDefinition(true).includeDefinition(), machineLearningClient::getTrainedModels, machineLearningClient::getTrainedModelsAsync); assertThat(getTrainedModelsResponse.getCount(), equalTo(1L)); assertThat(getTrainedModelsResponse.getTrainedModels(), hasSize(1)); assertThat(getTrainedModelsResponse.getTrainedModels().get(0).getCompressedDefinition(), is(nullValue())); assertThat(getTrainedModelsResponse.getTrainedModels().get(0).getDefinition(), is(not(nullValue()))); assertThat(getTrainedModelsResponse.getTrainedModels().get(0).getModelId(), equalTo(modelIdCompressed)); } public void testPutTrainedModelAlias() throws Exception { MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); String modelId = "model-with-an-alias"; putTrainedModel(modelId); String modelId2 = "another-model-with-an-alias"; putTrainedModel(modelId2); AcknowledgedResponse acknowledgedResponse = execute( new PutTrainedModelAliasRequest("my-first-alias", modelId, null), machineLearningClient::putTrainedModelAlias, machineLearningClient::putTrainedModelAliasAsync ); assertThat(acknowledgedResponse.isAcknowledged(), is(true)); GetTrainedModelsResponse getTrainedModelsResponse = execute( new GetTrainedModelsRequest("my-first-alias"), machineLearningClient::getTrainedModels, machineLearningClient::getTrainedModelsAsync); assertThat(getTrainedModelsResponse.getCount(), equalTo(1L)); assertThat(getTrainedModelsResponse.getTrainedModels(), hasSize(1)); assertThat(getTrainedModelsResponse.getTrainedModels().get(0).getModelId(), equalTo(modelId)); acknowledgedResponse = execute( new PutTrainedModelAliasRequest("my-first-alias", modelId2, true), machineLearningClient::putTrainedModelAlias, machineLearningClient::putTrainedModelAliasAsync ); assertThat(acknowledgedResponse.isAcknowledged(), is(true)); getTrainedModelsResponse = execute( new GetTrainedModelsRequest("my-first-alias"), machineLearningClient::getTrainedModels, machineLearningClient::getTrainedModelsAsync ); assertThat(getTrainedModelsResponse.getCount(), equalTo(1L)); assertThat(getTrainedModelsResponse.getTrainedModels(), hasSize(1)); assertThat(getTrainedModelsResponse.getTrainedModels().get(0).getModelId(), equalTo(modelId2)); } public void testDeleteTrainedModelAlias() throws Exception { MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); String modelId = "model-with-an-deleted-alias"; putTrainedModel(modelId); AcknowledgedResponse acknowledgedResponse = execute( new PutTrainedModelAliasRequest("my-first-deleted-alias", modelId, null), machineLearningClient::putTrainedModelAlias, machineLearningClient::putTrainedModelAliasAsync ); assertThat(acknowledgedResponse.isAcknowledged(), is(true)); GetTrainedModelsResponse getTrainedModelsResponse = execute( new GetTrainedModelsRequest("my-first-deleted-alias"), machineLearningClient::getTrainedModels, machineLearningClient::getTrainedModelsAsync); assertThat(getTrainedModelsResponse.getCount(), equalTo(1L)); assertThat(getTrainedModelsResponse.getTrainedModels(), hasSize(1)); assertThat(getTrainedModelsResponse.getTrainedModels().get(0).getModelId(), equalTo(modelId)); acknowledgedResponse = execute( new DeleteTrainedModelAliasRequest("my-first-deleted-alias", modelId), machineLearningClient::deleteTrainedModelAlias, machineLearningClient::deleteTrainedModelAliasAsync ); assertThat(acknowledgedResponse.isAcknowledged(), is(true)); ElasticsearchStatusException exception = expectThrows(ElasticsearchStatusException.class, () -> execute( new GetTrainedModelsRequest("my-first-deleted-alias"), machineLearningClient::getTrainedModels, machineLearningClient::getTrainedModelsAsync )); assertThat(exception.status().getStatus(), equalTo(404)); } @AwaitsFix(bugUrl = "https://github.com/elastic/elasticsearch/issues/71139") public void testGetTrainedModelsStats() throws Exception { MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); String modelIdPrefix = "a-get-trained-model-stats-"; int numberOfModels = 5; for (int i = 0; i < numberOfModels; ++i) { String modelId = modelIdPrefix + i; putTrainedModel(modelId); } String regressionPipeline = "{" + " \"processors\": [\n" + " {\n" + " \"inference\": {\n" + " \"target_field\": \"regression_value\",\n" + " \"model_id\": \"" + modelIdPrefix + 0 + "\",\n" + " \"inference_config\": {\"regression\": {}},\n" + " \"field_map\": {\n" + " \"col1\": \"col1\",\n" + " \"col2\": \"col2\",\n" + " \"col3\": \"col3\",\n" + " \"col4\": \"col4\"\n" + " }\n" + " }\n" + " }]}\n"; highLevelClient().ingest().putPipeline( new PutPipelineRequest("regression-stats-pipeline", new BytesArray(regressionPipeline.getBytes(StandardCharsets.UTF_8)), XContentType.JSON), RequestOptions.DEFAULT); { GetTrainedModelsStatsResponse getTrainedModelsStatsResponse = execute( GetTrainedModelsStatsRequest.getAllTrainedModelStatsRequest(), machineLearningClient::getTrainedModelsStats, machineLearningClient::getTrainedModelsStatsAsync); assertThat(getTrainedModelsStatsResponse.getTrainedModelStats(), hasSize(numberOfModels + 1)); assertThat(getTrainedModelsStatsResponse.getCount(), equalTo(5L + 1)); assertThat(getTrainedModelsStatsResponse.getTrainedModelStats().get(0).getPipelineCount(), equalTo(1)); assertThat(getTrainedModelsStatsResponse.getTrainedModelStats().get(1).getPipelineCount(), equalTo(0)); } { GetTrainedModelsStatsResponse getTrainedModelsStatsResponse = execute( new GetTrainedModelsStatsRequest(modelIdPrefix + 4, modelIdPrefix + 2, modelIdPrefix + 3), machineLearningClient::getTrainedModelsStats, machineLearningClient::getTrainedModelsStatsAsync); assertThat(getTrainedModelsStatsResponse.getTrainedModelStats(), hasSize(3)); assertThat(getTrainedModelsStatsResponse.getCount(), equalTo(3L)); } { GetTrainedModelsStatsResponse getTrainedModelsStatsResponse = execute( new GetTrainedModelsStatsRequest(modelIdPrefix + "*").setPageParams(new PageParams(1, 2)), machineLearningClient::getTrainedModelsStats, machineLearningClient::getTrainedModelsStatsAsync); assertThat(getTrainedModelsStatsResponse.getTrainedModelStats(), hasSize(2)); assertThat(getTrainedModelsStatsResponse.getCount(), equalTo(5L)); assertThat( getTrainedModelsStatsResponse.getTrainedModelStats() .stream() .map(TrainedModelStats::getModelId) .collect(Collectors.toList()), containsInAnyOrder(modelIdPrefix + 1, modelIdPrefix + 2)); } } public void testDeleteTrainedModel() throws Exception { MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); String modelId = "delete-trained-models-test"; putTrainedModel(modelId); GetTrainedModelsResponse getTrainedModelsResponse = execute( new GetTrainedModelsRequest(modelId + "*").setAllowNoMatch(true), machineLearningClient::getTrainedModels, machineLearningClient::getTrainedModelsAsync); assertThat(getTrainedModelsResponse.getCount(), equalTo(1L)); assertThat(getTrainedModelsResponse.getTrainedModels(), hasSize(1)); AcknowledgedResponse deleteTrainedModelResponse = execute( new DeleteTrainedModelRequest(modelId), machineLearningClient::deleteTrainedModel, machineLearningClient::deleteTrainedModelAsync); assertTrue(deleteTrainedModelResponse.isAcknowledged()); getTrainedModelsResponse = execute( new GetTrainedModelsRequest(modelId + "*").setAllowNoMatch(true), machineLearningClient::getTrainedModels, machineLearningClient::getTrainedModelsAsync); assertThat(getTrainedModelsResponse.getCount(), equalTo(0L)); assertThat(getTrainedModelsResponse.getTrainedModels(), hasSize(0)); } public void testGetPrepackagedModels() throws Exception { MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); GetTrainedModelsResponse getTrainedModelsResponse = execute( new GetTrainedModelsRequest("lang_ident_model_1").includeDefinition(), machineLearningClient::getTrainedModels, machineLearningClient::getTrainedModelsAsync); assertThat(getTrainedModelsResponse.getCount(), equalTo(1L)); assertThat(getTrainedModelsResponse.getTrainedModels(), hasSize(1)); assertThat(getTrainedModelsResponse.getTrainedModels().get(0).getModelId(), equalTo("lang_ident_model_1")); assertThat(getTrainedModelsResponse.getTrainedModels().get(0).getDefinition().getTrainedModel(), instanceOf(LangIdentNeuralNetwork.class)); } public void testPutFilter() throws Exception { String filterId = "filter-job-test"; MlFilter mlFilter = MlFilter.builder(filterId) .setDescription(randomAlphaOfLength(10)) .setItems(generateRandomStringArray(10, 10, false, false)) .build(); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); PutFilterResponse putFilterResponse = execute(new PutFilterRequest(mlFilter), machineLearningClient::putFilter, machineLearningClient::putFilterAsync); MlFilter createdFilter = putFilterResponse.getResponse(); assertThat(createdFilter, equalTo(mlFilter)); } public void testGetFilters() throws Exception { String filterId1 = "get-filter-test-1"; String filterId2 = "get-filter-test-2"; String filterId3 = "get-filter-test-3"; MlFilter mlFilter1 = MlFilter.builder(filterId1) .setDescription(randomAlphaOfLength(10)) .setItems(generateRandomStringArray(10, 10, false, false)) .build(); MlFilter mlFilter2 = MlFilter.builder(filterId2) .setDescription(randomAlphaOfLength(10)) .setItems(generateRandomStringArray(10, 10, false, false)) .build(); MlFilter mlFilter3 = MlFilter.builder(filterId3) .setDescription(randomAlphaOfLength(10)) .setItems(generateRandomStringArray(10, 10, false, false)) .build(); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); machineLearningClient.putFilter(new PutFilterRequest(mlFilter1), RequestOptions.DEFAULT); machineLearningClient.putFilter(new PutFilterRequest(mlFilter2), RequestOptions.DEFAULT); machineLearningClient.putFilter(new PutFilterRequest(mlFilter3), RequestOptions.DEFAULT); { GetFiltersRequest getFiltersRequest = new GetFiltersRequest(); getFiltersRequest.setFilterId(filterId1); GetFiltersResponse getFiltersResponse = execute(getFiltersRequest, machineLearningClient::getFilter, machineLearningClient::getFilterAsync); assertThat(getFiltersResponse.count(), equalTo(1L)); assertThat(getFiltersResponse.filters().get(0), equalTo(mlFilter1)); } { GetFiltersRequest getFiltersRequest = new GetFiltersRequest(); getFiltersRequest.setFrom(1); getFiltersRequest.setSize(2); GetFiltersResponse getFiltersResponse = execute(getFiltersRequest, machineLearningClient::getFilter, machineLearningClient::getFilterAsync); assertThat(getFiltersResponse.count(), equalTo(3L)); assertThat(getFiltersResponse.filters().size(), equalTo(2)); assertThat(getFiltersResponse.filters().stream().map(MlFilter::getId).collect(Collectors.toList()), containsInAnyOrder("get-filter-test-2", "get-filter-test-3")); } } public void testUpdateFilter() throws Exception { String filterId = "update-filter-test"; MlFilter mlFilter = MlFilter.builder(filterId) .setDescription("old description") .setItems(Arrays.asList("olditem1", "olditem2")) .build(); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); machineLearningClient.putFilter(new PutFilterRequest(mlFilter), RequestOptions.DEFAULT); UpdateFilterRequest updateFilterRequest = new UpdateFilterRequest(filterId); updateFilterRequest.setAddItems(Arrays.asList("newItem1", "newItem2")); updateFilterRequest.setRemoveItems(Collections.singletonList("olditem1")); updateFilterRequest.setDescription("new description"); MlFilter filter = execute(updateFilterRequest, machineLearningClient::updateFilter, machineLearningClient::updateFilterAsync).getResponse(); assertThat(filter.getDescription(), equalTo(updateFilterRequest.getDescription())); assertThat(filter.getItems(), contains("newItem1", "newItem2", "olditem2")); } public void testDeleteFilter() throws Exception { String filterId = "delete-filter-job-test"; MlFilter mlFilter = MlFilter.builder(filterId) .setDescription(randomAlphaOfLength(10)) .setItems(generateRandomStringArray(10, 10, false, false)) .build(); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); PutFilterResponse putFilterResponse = execute(new PutFilterRequest(mlFilter), machineLearningClient::putFilter, machineLearningClient::putFilterAsync); MlFilter createdFilter = putFilterResponse.getResponse(); assertThat(createdFilter, equalTo(mlFilter)); DeleteFilterRequest deleteFilterRequest = new DeleteFilterRequest(filterId); AcknowledgedResponse response = execute(deleteFilterRequest, machineLearningClient::deleteFilter, machineLearningClient::deleteFilterAsync); assertTrue(response.isAcknowledged()); ElasticsearchStatusException exception = expectThrows(ElasticsearchStatusException.class, () -> execute(deleteFilterRequest, machineLearningClient::deleteFilter, machineLearningClient::deleteFilterAsync)); assertThat(exception.status().getStatus(), equalTo(404)); } public void testGetMlInfo() throws Exception { MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); MlInfoResponse infoResponse = execute(new MlInfoRequest(), machineLearningClient::getMlInfo, machineLearningClient::getMlInfoAsync); Map<String, Object> info = infoResponse.getInfo(); assertThat(info, notNullValue()); assertTrue(info.containsKey("defaults")); assertTrue(info.containsKey("limits")); } public static String randomValidJobId() { CodepointSetGenerator generator = new CodepointSetGenerator("abcdefghijklmnopqrstuvwxyz0123456789".toCharArray()); return generator.ofCodePointsLength(random(), 10, 10); } private static Job buildJobForExpiredDataTests(String jobId) { Job.Builder builder = new Job.Builder(jobId); builder.setDescription(randomAlphaOfLength(10)); Detector detector = new Detector.Builder() .setFunction("count") .setDetectorDescription(randomAlphaOfLength(10)) .build(); AnalysisConfig.Builder configBuilder = new AnalysisConfig.Builder(Collections.singletonList(detector)); configBuilder.setBucketSpan(new TimeValue(1, TimeUnit.HOURS)); builder.setAnalysisConfig(configBuilder); builder.setModelSnapshotRetentionDays(1L); builder.setDailyModelSnapshotRetentionAfterDays(1L); DataDescription.Builder dataDescription = new DataDescription.Builder(); dataDescription.setTimeFormat(DataDescription.EPOCH_MS); dataDescription.setTimeField("timestamp"); builder.setDataDescription(dataDescription); return builder.build(); } public static Job buildJob(String jobId) { Job.Builder builder = new Job.Builder(jobId); builder.setDescription(randomAlphaOfLength(10)); Detector detector = new Detector.Builder() .setFieldName("total") .setFunction("sum") .setDetectorDescription(randomAlphaOfLength(10)) .build(); AnalysisConfig.Builder configBuilder = new AnalysisConfig.Builder(Arrays.asList(detector)); configBuilder.setBucketSpan(new TimeValue(5, TimeUnit.SECONDS)); builder.setAnalysisConfig(configBuilder); builder.setAnalysisLimits(new AnalysisLimits(512L, 4L)); DataDescription.Builder dataDescription = new DataDescription.Builder(); dataDescription.setTimeFormat(DataDescription.EPOCH_MS); dataDescription.setTimeField("timestamp"); builder.setDataDescription(dataDescription); return builder.build(); } private void putJob(Job job) throws IOException { highLevelClient().machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT); } private void openJob(Job job) throws IOException { highLevelClient().machineLearning().openJob(new OpenJobRequest(job.getId()), RequestOptions.DEFAULT); } private void putTrainedModel(String modelId) throws IOException { TrainedModelDefinition definition = TrainedModelDefinitionTests.createRandomBuilder(TargetType.REGRESSION).build(); TrainedModelConfig trainedModelConfig = TrainedModelConfig.builder() .setDefinition(definition) .setModelId(modelId) .setInferenceConfig(new RegressionConfig()) .setInput(new TrainedModelInput(Arrays.asList("col1", "col2", "col3", "col4"))) .setDescription("test model") .build(); highLevelClient().machineLearning().putTrainedModel(new PutTrainedModelRequest(trainedModelConfig), RequestOptions.DEFAULT); } private void waitForJobToClose(String jobId) throws Exception { MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); assertBusy(() -> { JobStats stats = machineLearningClient.getJobStats(new GetJobStatsRequest(jobId), RequestOptions.DEFAULT).jobStats().get(0); assertEquals(JobState.CLOSED, stats.getState()); }, 30, TimeUnit.SECONDS); } private void startDatafeed(String datafeedId, String start, String end) throws Exception { MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); StartDatafeedRequest startDatafeedRequest = new StartDatafeedRequest(datafeedId); startDatafeedRequest.setStart(start); startDatafeedRequest.setEnd(end); StartDatafeedResponse response = execute(startDatafeedRequest, machineLearningClient::startDatafeed, machineLearningClient::startDatafeedAsync); assertTrue(response.isStarted()); } private void updateModelSnapshotTimestamp(String jobId, String timestamp) throws Exception { MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); GetModelSnapshotsRequest getModelSnapshotsRequest = new GetModelSnapshotsRequest(jobId); GetModelSnapshotsResponse getModelSnapshotsResponse = execute(getModelSnapshotsRequest, machineLearningClient::getModelSnapshots, machineLearningClient::getModelSnapshotsAsync); assertThat(getModelSnapshotsResponse.count(), greaterThanOrEqualTo(1L)); ModelSnapshot modelSnapshot = getModelSnapshotsResponse.snapshots().get(0); String snapshotId = modelSnapshot.getSnapshotId(); String documentId = jobId + "_model_snapshot_" + snapshotId; String snapshotUpdate = "{ \"timestamp\": " + timestamp + "}"; UpdateRequest updateSnapshotRequest = new UpdateRequest(".ml-anomalies-" + jobId, documentId); updateSnapshotRequest.doc(snapshotUpdate.getBytes(StandardCharsets.UTF_8), XContentType.JSON); highLevelClient().update(updateSnapshotRequest, RequestOptions.DEFAULT); } private String createAndPutDatafeed(String jobId, String indexName) throws IOException { String datafeedId = jobId + "-feed"; DatafeedConfig datafeed = DatafeedConfig.builder(datafeedId, jobId) .setIndices(indexName) .setQueryDelay(TimeValue.timeValueSeconds(1)) .setFrequency(TimeValue.timeValueSeconds(1)).build(); highLevelClient().machineLearning().putDatafeed(new PutDatafeedRequest(datafeed), RequestOptions.DEFAULT); return datafeedId; } public void createModelSnapshot(String jobId, String snapshotId) throws IOException { String documentId = jobId + "_model_snapshot_" + snapshotId; Job job = MachineLearningIT.buildJob(jobId); highLevelClient().machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT); IndexRequest indexRequest = new IndexRequest(".ml-anomalies-shared").id(documentId); indexRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); indexRequest.source("{\"job_id\":\"" + jobId + "\", \"timestamp\":1541587919000, " + "\"description\":\"State persisted due to job close at 2018-11-07T10:51:59+0000\", " + "\"snapshot_id\":\"" + snapshotId + "\", \"snapshot_doc_count\":1, \"model_size_stats\":{" + "\"job_id\":\"" + jobId + "\", \"result_type\":\"model_size_stats\",\"model_bytes\":51722, " + "\"total_by_field_count\":3, \"total_over_field_count\":0, \"total_partition_field_count\":2," + "\"bucket_allocation_failures_count\":0, \"memory_status\":\"ok\", \"log_time\":1541587919000, " + "\"timestamp\":1519930800000}, \"latest_record_time_stamp\":1519931700000," + "\"latest_result_time_stamp\":1519930800000, \"retain\":false, \"min_version\":\"" + Version.CURRENT.toString() + "\"}", XContentType.JSON); highLevelClient().index(indexRequest, RequestOptions.DEFAULT); } public void createModelSnapshots(String jobId, List<String> snapshotIds) throws IOException { Job job = MachineLearningIT.buildJob(jobId); highLevelClient().machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT); for(String snapshotId : snapshotIds) { String documentId = jobId + "_model_snapshot_" + snapshotId; IndexRequest indexRequest = new IndexRequest(".ml-anomalies-shared").id(documentId); indexRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); indexRequest.source("{\"job_id\":\"" + jobId + "\", \"timestamp\":1541587919000, " + "\"description\":\"State persisted due to job close at 2018-11-07T10:51:59+0000\", " + "\"snapshot_id\":\"" + snapshotId + "\", \"snapshot_doc_count\":1, \"model_size_stats\":{" + "\"job_id\":\"" + jobId + "\", \"result_type\":\"model_size_stats\",\"model_bytes\":51722, " + "\"total_by_field_count\":3, \"total_over_field_count\":0, \"total_partition_field_count\":2," + "\"bucket_allocation_failures_count\":0, \"memory_status\":\"ok\", \"log_time\":1541587919000, " + "\"timestamp\":1519930800000}, \"latest_record_time_stamp\":1519931700000," + "\"latest_result_time_stamp\":1519930800000, \"retain\":false, " + "\"quantiles\":{\"job_id\":\""+jobId+"\", \"timestamp\":1541587919000, " + "\"quantile_state\":\"state\"}}", XContentType.JSON); highLevelClient().index(indexRequest, RequestOptions.DEFAULT); } } public void testDeleteModelSnapshot() throws IOException { String jobId = "test-delete-model-snapshot"; String snapshotId = "1541587919"; createModelSnapshot(jobId, snapshotId); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); DeleteModelSnapshotRequest request = new DeleteModelSnapshotRequest(jobId, snapshotId); AcknowledgedResponse response = execute(request, machineLearningClient::deleteModelSnapshot, machineLearningClient::deleteModelSnapshotAsync); assertTrue(response.isAcknowledged()); } public void testUpdateModelSnapshot() throws Exception { String jobId = "test-update-model-snapshot"; String snapshotId = "1541587919"; createModelSnapshot(jobId, snapshotId); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); GetModelSnapshotsRequest getModelSnapshotsRequest = new GetModelSnapshotsRequest(jobId); GetModelSnapshotsResponse getModelSnapshotsResponse1 = execute(getModelSnapshotsRequest, machineLearningClient::getModelSnapshots, machineLearningClient::getModelSnapshotsAsync); assertEquals(getModelSnapshotsResponse1.count(), 1L); assertEquals("State persisted due to job close at 2018-11-07T10:51:59+0000", getModelSnapshotsResponse1.snapshots().get(0).getDescription()); UpdateModelSnapshotRequest request = new UpdateModelSnapshotRequest(jobId, snapshotId); request.setDescription("Updated description"); request.setRetain(true); UpdateModelSnapshotResponse response = execute(request, machineLearningClient::updateModelSnapshot, machineLearningClient::updateModelSnapshotAsync); assertTrue(response.getAcknowledged()); assertEquals("Updated description", response.getModel().getDescription()); assertTrue(response.getModel().getRetain()); GetModelSnapshotsResponse getModelSnapshotsResponse2 = execute(getModelSnapshotsRequest, machineLearningClient::getModelSnapshots, machineLearningClient::getModelSnapshotsAsync); assertEquals(getModelSnapshotsResponse2.count(), 1L); assertEquals("Updated description", getModelSnapshotsResponse2.snapshots().get(0).getDescription()); } public void testUpgradeJobSnapshot() throws Exception { String jobId = "test-upgrade-model-snapshot"; String snapshotId = "1541587919"; createModelSnapshot(jobId, snapshotId); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); UpgradeJobModelSnapshotRequest request = new UpgradeJobModelSnapshotRequest(jobId, snapshotId, null, true); ElasticsearchException ex = expectThrows(ElasticsearchException.class, () -> execute(request, machineLearningClient::upgradeJobSnapshot, machineLearningClient::upgradeJobSnapshotAsync)); assertThat( ex.getMessage(), containsString( "Cannot upgrade job [test-upgrade-model-snapshot] snapshot [1541587919] as it is already compatible with current version" ) ); } public void testRevertModelSnapshot() throws IOException { String jobId = "test-revert-model-snapshot"; List<String> snapshotIds = new ArrayList<>(); String snapshotId1 = "1541587919"; String snapshotId2 = "1541588919"; String snapshotId3 = "1541589919"; snapshotIds.add(snapshotId1); snapshotIds.add(snapshotId2); snapshotIds.add(snapshotId3); createModelSnapshots(jobId, snapshotIds); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); for (String snapshotId : snapshotIds){ RevertModelSnapshotRequest request = new RevertModelSnapshotRequest(jobId, snapshotId); if (randomBoolean()) { request.setDeleteInterveningResults(randomBoolean()); } RevertModelSnapshotResponse response = execute(request, machineLearningClient::revertModelSnapshot, machineLearningClient::revertModelSnapshotAsync); ModelSnapshot model = response.getModel(); assertEquals(snapshotId, model.getSnapshotId()); } } public void testEnableUpgradeMode() throws Exception { MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); MlInfoResponse mlInfoResponse = machineLearningClient.getMlInfo(new MlInfoRequest(), RequestOptions.DEFAULT); assertThat(mlInfoResponse.getInfo().get("upgrade_mode"), equalTo(false)); AcknowledgedResponse setUpgrademodeResponse = execute(new SetUpgradeModeRequest(true), machineLearningClient::setUpgradeMode, machineLearningClient::setUpgradeModeAsync); assertThat(setUpgrademodeResponse.isAcknowledged(), is(true)); mlInfoResponse = machineLearningClient.getMlInfo(new MlInfoRequest(), RequestOptions.DEFAULT); assertThat(mlInfoResponse.getInfo().get("upgrade_mode"), equalTo(true)); setUpgrademodeResponse = execute(new SetUpgradeModeRequest(false), machineLearningClient::setUpgradeMode, machineLearningClient::setUpgradeModeAsync); assertThat(setUpgrademodeResponse.isAcknowledged(), is(true)); mlInfoResponse = machineLearningClient.getMlInfo(new MlInfoRequest(), RequestOptions.DEFAULT); assertThat(mlInfoResponse.getInfo().get("upgrade_mode"), equalTo(false)); } @Override protected NamedXContentRegistry xContentRegistry() { return new NamedXContentRegistry(new MlInferenceNamedXContentProvider().getNamedXContentParsers()); } }
package org.jpos.q2.cli; import org.flywaydb.core.Flyway; import org.jpos.ee.DB; import org.jpos.q2.CLIContext; import org.jpos.q2.CLISubSystem; import java.util.Properties; public class FLYWAY implements CLISubSystem { public static final String PREFIX = "flyway.dbmodifier"; @Override public String getPrompt(CLIContext ctx, String[] args) { String prefix = null; if (args.length > 1) { prefix = args[1]; ctx.getUserData().put(PREFIX, prefix); } else { ctx.getUserData().remove(PREFIX); } new DB(prefix); // force DB initialization return "flyway" + (prefix != null ? "[" + args[1] + "]" : "") + "> "; } @Override public String[] getCompletionPrefixes(CLIContext ctx, String[] args) { return new String[] { "org.jpos.q2.cli.flyway." }; } private Flyway getFlyWay() { Properties p = new DB().getProperties(); return Flyway.configure().dataSource( p.getProperty("hibernate.connection.url"), p.getProperty("hibernate.connection.username"), p.getProperty("hibernate.connection.password")).load(); } }
package com.timepath.image; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; /** * * @author TimePath */ public class ImageUtils { /** * 8 bytes per 4*4 */ public static BufferedImage loadDXT1(byte[] b, int width, int height) { BufferedImage bi = new BufferedImage(Math.max(width, 4), Math.max(height, 4), BufferedImage.TYPE_INT_ARGB); int pos = 0; for(int y = 0; y < height; y += 4) { for(int x = 0; x < width; x += 4) { int color_0 = ((b[pos++] & 0xFF) + ((b[pos++] & 0xFF) << 8)) & 0xFFFF; // 2 bytes int color_1 = ((b[pos++] & 0xFF) + ((b[pos++] & 0xFF) << 8)) & 0xFFFF; // 2 bytes Color[] colour = new Color[4]; colour[0] = extract565(color_0); colour[1] = extract565(color_1); if(color_0 > color_1) { colour[2] = new Color( Math.round(((2 * colour[0].getRed()) + colour[1].getRed()) / 3), Math.round(((2 * colour[0].getGreen()) + colour[1].getGreen()) / 3), Math.round(((2 * colour[0].getBlue()) + colour[1].getBlue()) / 3)); colour[3] = new Color( Math.round(((2 * colour[1].getRed()) + colour[0].getRed()) / 3), Math.round(((2 * colour[1].getGreen()) + colour[0].getGreen()) / 3), Math.round(((2 * colour[1].getBlue()) + colour[0].getBlue()) / 3)); } else { colour[2] = new Color( Math.round((colour[0].getRed() + colour[1].getRed()) / 2), Math.round((colour[0].getGreen() + colour[1].getGreen()) / 2), Math.round((colour[0].getBlue() + colour[1].getBlue()) / 2)); colour[3] = new Color(0, 0, 0, 0); } for(int y1 = 0; y1 < 4; y1++) { // 16 bits / 4 rows = 4 bits/line = 1 byte/row byte rowData = b[pos++]; int[] rowBits = {(rowData & 0xC0) >>> 6, (rowData & 0x30) >>> 4, (rowData & 0xC) >>> 2, rowData & 0x3}; for(int x1 = 0; x1 < 4; x1++) { // column scan Color col = new Color(colour[rowBits[3 - x1]].getRed(), colour[rowBits[3 - x1]].getGreen(), colour[rowBits[3 - x1]].getBlue(), colour[rowBits[3 - x1]].getAlpha()); bi.setRGB(x + x1, y + y1, col.getRGB()); } } } } return bi; } //<editor-fold defaultstate="collapsed" desc="Currently unimplemented"> /** * * 8 bytes for alpha channel, additional 8 per 4*4 chunk * * TODO: fully implement correct colours */ BufferedImage loadDXT3(byte[] b, int width, int height) { BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g = (Graphics2D) bi.getGraphics(); int pos = 0; int bits_12 = 0xC0; // first 2 bits int bits_34 = 0x30; // next 2 bits int bits_56 = 0xC; // next 2 bits int bits_78 = 0x3; // last 2 bits // RGB 565: WORD pixel565 = (red_value << 11) | (green_value << 5) | blue_value; int xBlocks = (width / 4); if(xBlocks < 1) { xBlocks = 1; } int yBlocks = (height / 4); if(yBlocks < 1) { yBlocks = 1; } // System.err.println("SIZE="+xBlocks+", "+yBlocks+" = " + b.length); for(int y = 0; y < yBlocks; y++) { for(int x = 0; x < xBlocks; x++) { pos += 8; // 64 bits of alpha channel data (two 8 bit alpha values and a 4x4 3 bit lookup table) int color_0 = (b[pos] & 0xff) + ((b[pos + 1] & 0xff) << 8); // 2 bytes pos += 2; int color_1 = (b[pos] & 0xff) + ((b[pos + 1] & 0xff) << 8); // 2 bytes pos += 2; int red1, green1, blue1, red2, green2, blue2; Color c1, c2; red1 = ((color_0 & red_mask_565) >> 11) << 3; green1 = ((color_0 & green_mask_565) >> 5) << 2; blue1 = ((color_0 & blue_mask_565) << 3); c1 = new Color(red1, green1, blue1); red2 = ((color_1 & red_mask_565) >> 11) << 3; green2 = ((color_1 & green_mask_565) >> 5) << 2; blue2 = (color_1 & blue_mask_565) << 3; c2 = new Color(red2, green2, blue2); // remaining 4 bytes byte[] next4 = {b[pos], b[pos + 1], b[pos + 2], b[pos + 3]}; pos += 4; for(int y1 = 0; y1 < 4; y1++) { // 16 bits / 4 lines = 4 bits/line = 1 byte/line int[] bits = new int[] {(next4[y1] & bits_12) >> 6, (next4[y1] & bits_34) >> 4, (next4[y1] & bits_56) >> 2, next4[y1] & bits_78}; for(int i = 0; i < 4; i++) { // horizontal scan int bit = bits[i]; if(bit == 0) { g.setColor(c1); } else if(bit == 1) { g.setColor(c2); } else if(bit == 2) { int cred = (2 * (c1.getRed() / 3)) + (c2.getRed() / 3); int cgrn = (2 * (c1.getGreen() / 3)) + (c2.getGreen() / 3); int cblu = (2 * (c1.getBlue() / 3)) + (c2.getBlue() / 3); Color c = new Color(cred, cgrn, cblu); g.setColor(c); } else if(bit == 3) { int cred = (c1.getRed() / 3) + (2 * (c2.getRed() / 3)); int cgrn = (c1.getGreen() / 3) + (2 * (c2.getGreen() / 3)); int cblu = (c1.getBlue() / 3) + (2 * (c2.getBlue() / 3)); Color c = new Color(cred, cgrn, cblu); g.setColor(c); } g.drawLine((x * 4) + 4 - i, (y * 4) + y1, (x * 4) + 4 - i, (y * 4) + y1); } } } } return bi; } //</editor-fold> /** * 8 bytes for alpha channel, additional 8 per 4*4 chunk */ public static BufferedImage loadDXT5(byte[] b, int width, int height) { BufferedImage bi = new BufferedImage(Math.max(width, 4), Math.max(height, 4), BufferedImage.TYPE_INT_ARGB); int pos = 0; for(int y = 0; y < height; y += 4) { for(int x = 0; x < width; x += 4) { //<editor-fold defaultstate="collapsed" desc="Alpha"> int[] a = new int[8]; a[0] = (b[pos++] & 0xFF); // 64 bits of alpha channel data (two 8 bit alpha values and a 4x4 3 bit lookup table) a[1] = (b[pos++] & 0xFF); if(a[0] > a[1]) { a[2] = Math.round((6 * a[0] + 1 * a[1]) / 7); a[3] = Math.round((5 * a[0] + 2 * a[1]) / 7); a[4] = Math.round((4 * a[0] + 3 * a[1]) / 7); a[5] = Math.round((3 * a[0] + 4 * a[1]) / 7); a[6] = Math.round((2 * a[0] + 5 * a[1]) / 7); a[7] = Math.round((1 * a[0] + 6 * a[1]) / 7); } else { a[2] = Math.round((4 * a[0] + 1 * a[1]) / 5); a[3] = Math.round((3 * a[0] + 2 * a[1]) / 5); a[4] = Math.round((2 * a[0] + 3 * a[1]) / 5); a[5] = Math.round((1 * a[0] + 4 * a[1]) / 5); a[6] = 0; a[7] = 255; } int[][] alphas = new int[4][4]; int[] alphaByte = {b[pos++] & 0xFF, b[pos++] & 0xFF, b[pos++] & 0xFF, b[pos++] & 0xFF, b[pos++] & 0xFF, b[pos++] & 0xFF}; int sel1 = ((alphaByte[2] << 16) | (alphaByte[1] << 8) | alphaByte[0]) & 0xFFFFFF; int sel2 = ((alphaByte[5] << 16) | (alphaByte[4] << 8) | alphaByte[3]) & 0xFFFFFF; for(int yi = 0; yi < 2; yi++) { for(int xi = 0; xi < 4; xi++) { alphas[yi][xi] = a[sel1 & 0x7]; sel1 >>>= 3; } } for(int yi = 2; yi < 4; yi++) { for(int xi = 0; xi < 4; xi++) { alphas[yi][xi] = a[sel2 & 0x7]; sel2 >>>= 3; } } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="DXT1 color info"> int color_0 = ((b[pos++] & 0xFF) + ((b[pos++] & 0xFF) << 8)) & 0xFFFF; // 2 bytes int color_1 = ((b[pos++] & 0xFF) + ((b[pos++] & 0xFF) << 8)) & 0xFFFF; // 2 bytes Color[] colour = new Color[4]; colour[0] = extract565(color_0); colour[1] = extract565(color_1); if(color_0 > color_1) { colour[2] = new Color( Math.round(((2 * colour[0].getRed()) + colour[1].getRed()) / 3), Math.round(((2 * colour[0].getGreen()) + colour[1].getGreen()) / 3), Math.round(((2 * colour[0].getBlue()) + colour[1].getBlue()) / 3)); colour[3] = new Color( Math.round(((2 * colour[1].getRed()) + colour[0].getRed()) / 3), Math.round(((2 * colour[1].getGreen()) + colour[0].getGreen()) / 3), Math.round(((2 * colour[1].getBlue()) + colour[0].getBlue()) / 3)); } else { colour[2] = new Color( Math.round((colour[0].getRed() + colour[1].getRed()) / 2), Math.round((colour[0].getGreen() + colour[1].getGreen()) / 2), Math.round((colour[0].getBlue() + colour[1].getBlue()) / 2)); colour[3] = new Color(0, 0, 0); } for(int y1 = 0; y1 < 4; y1++) { // 16 bits / 4 rows = 4 bits/line = 1 byte/row byte rowData = b[pos++]; int[] rowBits = {(rowData & 0xC0) >>> 6, (rowData & 0x30) >>> 4, (rowData & 0xC) >>> 2, rowData & 0x3}; for(int x1 = 0; x1 < 4; x1++) { // column scan Color col = new Color(colour[rowBits[3 - x1]].getRed(), colour[rowBits[3 - x1]].getGreen(), colour[rowBits[3 - x1]].getBlue(), alphas[y1][x1]); bi.setRGB((x + x1), (y + y1), col.getRGB()); } } //</editor-fold> } } return bi; } public static BufferedImage loadUV(byte[] b, int width, int height) { BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g = (Graphics2D) bi.getGraphics(); int pos = 0; for(int y = 0; y < height; y++) { for(int x = 0; x < width; x++) { g.setColor(new Color( (b[pos] & 0xff) + ((b[pos + 1] & 0xff) << 16) + ((255 & 0xff) << 24))); pos += 2; g.drawLine(x, y, x, y); } } return bi; } public static BufferedImage loadBGR(byte[] b, int width, int height) { BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g = (Graphics2D) bi.getGraphics(); int pos = 0; for(int y = 0; y < height; y++) { for(int x = 0; x < width; x++) { g.setColor(new Color( (b[pos] & 0xff) + ((b[pos + 1] & 0xff) << 8) + ((b[pos + 2] & 0xff) << 16) + ((255 & 0xff) << 24))); pos += 3; g.drawLine(x, y, x, y); } } return bi; } public static BufferedImage loadBGRA(byte[] b, int width, int height) { BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g = (Graphics2D) bi.getGraphics(); g.setComposite(AlphaComposite.Src); int pos = 0; for(int y = 0; y < height; y++) { for(int x = 0; x < width; x++) { g.setColor(new Color((b[pos + 2] & 0xff), (b[pos + 1] & 0xff), (b[pos] & 0xff), (b[pos + 3] & 0xff))); pos += 4; g.drawLine(x, y, x, y); } } return bi; } public static BufferedImage loadRGBA(byte[] b, int width, int height) { BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g = (Graphics2D) bi.getGraphics(); g.setComposite(AlphaComposite.Src); int pos = 0; for(int y = 0; y < height; y++) { for(int x = 0; x < width; x++) { g.setColor(new Color((b[pos] & 0xff), (b[pos + 1] & 0xff), (b[pos + 2] & 0xff), (b[pos + 3] & 0xff))); pos += 4; g.drawLine(x, y, x, y); } } return bi; } /** * First 5 bits */ private static final int red_mask_565 = 0xF800; /** * Next 6 bits */ private static final int green_mask_565 = 0x7E0; /** * Last 5 bits */ private static final int blue_mask_565 = 0x1F; private static Color extract565(int c) { return createColor((float) (((c & red_mask_565) >>> 11) << 3), (float) (((c & green_mask_565) >>> 5) << 2), (float) ((c & blue_mask_565) << 3), 255); } private static final int red_mask_555 = 0x7C00; // first 5 bits private static final int green_mask_555 = 0x3E0; // next 5 bits private static final int blue_mask_555 = 0x1F; private static final int alpha_mask_555 = 0x1; private static Color extract555(int c) { return createColor((float) (((c & red_mask_555) >>> 10) << 3), (float) (((c & green_mask_555) >>> 5) << 3), (float) ((c & blue_mask_555) << 3), (float) ((c & alpha_mask_555) << 7)); } private static Color createColor(float r, float g, float b, float a) { return new Color(Math.round(r), Math.round(g), Math.round(b), Math.round(a)); } }
package com.twu.biblioteca; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class InputOutputHandlerTest { private ByteArrayOutputStream byteArrayOutputStream; @Before public void setUp() { byteArrayOutputStream = new ByteArrayOutputStream(); System.setOut(new PrintStream(byteArrayOutputStream)); } @Test public void shouldBeAbleToDisplayWelcomeMessage() { InputOutputHandler inputOutputHandler = new InputOutputHandler(); inputOutputHandler.welcomeMessage(); String actualMessage = byteArrayOutputStream.toString(); assertThat(actualMessage, is(equalTo("***Welcome to Biblioteca***\n"))); } @Test public void shouldBeAbleToDisplayBookDetails() { InputOutputHandler inputOutputHandler = new InputOutputHandler(); inputOutputHandler.bookDetails(new Books()); String actualBookDetails = byteArrayOutputStream.toString(); assertThat(actualBookDetails, is(equalTo("| Harry Potter and The Sorcer's Stone | JK Rowling | 1999 |\n" + "| Harry Potter and The Chamber of Secrets | JK Rowling | 2000 |\n"))); } @Test public void shouldBeAbleToDisplayAMenuWithListOfOptions() { InputOutputHandler inputOutputHandler = new InputOutputHandler(); inputOutputHandler.listOptions(new Menu()); assertThat(byteArrayOutputStream.toString(), is(equalTo("1. List Books\nEnter your choice..."))); } @After public void tearDown() throws Exception { System.setOut(null); } }
package com.twu.biblioteca.unit.model; import com.twu.biblioteca.THelper; import com.twu.biblioteca.model.*; import org.junit.Assert; import org.junit.Test; import static org.junit.Assert.*; import java.util.*; public class LibraryTest { @Test public void should_ListAllAvailableBooks_When_BooksAreAdded() { List<Book> initialList = THelper.listOfBooks(); Library library = new Library(); library.addBooks(initialList); List<Book> availableLibraryItems = library.getAvailableBooks(); assert(availableLibraryItems.containsAll(initialList)); } @Test public void should_ListAllAvailableMovies_When_MoviesAreAdded() { List<Movie> initialList = THelper.listOfMovies(); Library library = new Library(); library.addMovies(initialList); List<Movie> availableMovies = library.getAvailableMovies(); assertTrue(availableMovies.containsAll(initialList)); } @Test public void should_ListAvailableBooks_When_ABookIsAdded() { Library library = new Library(); Book book = new Book("Test", "Test Author", "2003"); library.addBook(book); List<Book> availableLibraryItems = library.getAvailableBooks(); assertTrue(availableLibraryItems.contains(book)); } @Test public void should_ListAvailableMovies_When_AMovieIsAdded() { Library library = new Library(); Movie movie = new Movie("TestMovie", "Test", "2003", "10"); library.addMovie(movie); List<Movie> availableMovies = library.getAvailableMovies(); assertTrue(availableMovies.contains(movie)); } @Test public void should_RemoveBook_When_BookIsCheckedOut1() throws Exception { Library library = THelper.initLibrary(); UserAccount user = THelper.sampleUser(); LibraryItem libraryItem = library.getBookByTitle("The Agile Samurai"); library.checkoutItem(libraryItem, user.getID()); List<Book> availableLibraryItems = library.getAvailableBooks(); for (LibraryItem tmpLibraryItem : availableLibraryItems) { assertFalse(tmpLibraryItem == libraryItem); } } @Test public void should_RemoveBook_When_BookIsCheckedOut2() throws Exception { Library library = THelper.initLibrary(); UserAccount user = THelper.sampleUser(); Book libraryItem = library.getBookByTitle("The Agile Samurai"); library.checkoutItem(libraryItem, user.getID()); List<Book> list = library.getUnavailableBooks(); Book book = list.get(0); assertTrue(book == libraryItem); } @Test public void should_RemoveMovie_When_MovieIsCheckedOut() throws Exception { Library library = THelper.initLibrary(); UserAccount user = THelper.sampleUser(); Movie libraryItem = library.getMovieByTitle("Star Wars"); library.checkoutItem(libraryItem, user.getID()); List<Movie> list = library.getUnavailableMovies(); Movie movie = list.get(0); assertTrue(movie == libraryItem); } @Test public void getBookByTitle_Should_ReturnCorrectBook() { Library library = THelper.initLibrary(); LibraryItem libraryItem = library.getBookByTitle("The Agile Samurai"); assertTrue(libraryItem.getTitle().equals("The Agile Samurai")); } @Test (expected = NoSuchElementException.class) public void getBookByTitle_Should_ThrowException_When_NoBooksExist() { Library library = THelper.initLibrary(); LibraryItem libraryItem = library.getBookByTitle("Test book"); } @Test public void getMovieByTitle_Should_ReturnMovie() { Library library = THelper.initLibrary(); LibraryItem libraryItem = library.getMovieByTitle("The Shawshank Redemption"); assertTrue (libraryItem.getTitle().equals("The Shawshank Redemption")); } @Test (expected = NoSuchElementException.class) public void getMovieByTitle_Should_ThrowException_When_NoBooksExist() { Library library = THelper.initLibrary(); LibraryItem libraryItem = library.getMovieByTitle("Test movie"); } @Test public void bookExists_Should_ReturnTrue_IfItExists() { Library library = THelper.initLibrary(); assertFalse(library.bookExists("Test book")); } @Test public void bookExists_Should_ReturnFalse_IfItDoesntExist() { Library library = THelper.initLibrary(); assertTrue(library.bookExists("The Agile Samurai")); } @Test public void movieExists_Should_ReturnTrue_IfItExists() { Library library = THelper.initLibrary(); assertFalse(library.movieExists("Test movie")); } @Test public void movieExists_Should_ReturnFalse_IfItDoesntExist() { Library library = THelper.initLibrary(); assertTrue(library.movieExists("The Shawshank Redemption")); } }
package de.kimminich.kata.tcg; import de.kimminich.kata.tcg.strategy.AiStrategy; import de.kimminich.kata.tcg.strategy.HighestCardFirstStrategy; import de.kimminich.kata.tcg.strategy.LowestCardFirstStrategy; import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; public class GameIntegrationTest { private Game game; @Test public void gameWillHaveWinnerWhenOver() { Player player1 = new Player("1", new AiStrategy()); Player player2 = new Player("2", new AiStrategy()); game = new Game(player1, player2); game.run(); assertThat(game.getWinner(), is(notNullValue())); } }
package com.valkryst.VTerminal; import com.valkryst.VTerminal.component.Component; import com.valkryst.VTerminal.component.Layer; import com.valkryst.VTerminal.font.Font; import com.valkryst.VTerminal.font.FontLoader; import com.valkryst.VTerminal.misc.ImageCache; import com.valkryst.VTerminal.palette.ColorPalette; import lombok.Getter; import lombok.NonNull; import org.apache.commons.lang3.SystemUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javax.swing.event.MouseInputListener; import java.awt.*; import java.awt.event.*; import java.awt.image.BufferStrategy; import java.io.IOException; import java.util.ArrayList; import java.util.EventListener; import java.util.List; import java.util.concurrent.locks.ReentrantReadWriteLock; public class Screen { /** The canvas on which the screen is drawn. */ @Getter private final Canvas canvas = new Canvas(); /** The image cache. */ @Getter private final ImageCache imageCache; /** The tiles. */ @Getter private final TileGrid tiles; private final int[][] tileHashes; /** The components on the screen. */ private final List<Component> components = new ArrayList<>(0); /** The lock used to control access to the components. */ private final ReentrantReadWriteLock componentsLock = new ReentrantReadWriteLock(); /** The last known tile-based position of the mouse. */ private final Point mousePosition = new Point(0, 0); /** The color palette of the Screen. Does not apply to child components. */ private ColorPalette colorPalette; private boolean isInFullScreenExclusiveMode = false; /** * Constructs a new 80x40 Screen with the 18pt DejaVu Sans Mono font. * * @throws IOException * If an IOException occurs while loading the font. * */ public Screen() throws IOException { this(FontLoader.loadFontFromJar("Fonts/DejaVu Sans Mono/20pt/bitmap.png", "Fonts/DejaVu Sans Mono/20pt/data.fnt", 0.41)); } /** * Constructs a new Screen with the 18pt DejaVu Sans Mono font. * * @param width * The width, in tiles, of the screen. * * @param height * The height, in tiles, of the screen. * * @throws IOException * If an IOException occurs while loading the font. */ public Screen(final int width, final int height) throws IOException { this(width, height, FontLoader.loadFontFromJar("Fonts/DejaVu Sans Mono/20pt/bitmap.png", "Fonts/DejaVu Sans Mono/20pt/data.fnt", 0.41)); } /** * Constructs a new 80x40 Screen. * * @param font * The font. */ public Screen(final @NonNull Font font) { this(new Dimension(80, 40), font); } /** * Constructs a new Screen. * * @param width * The width, in tiles, of the screen. * * @param height * The height, in tiles, of the screen. * * @param font * The font. * * @throws NullPointerException * If the imageCache is null. */ public Screen(final int width, final int height, final @NonNull Font font) { this(new Dimension(width, height), font); } /** * Constructs a new Screen. * * @param dimensions * The dimensions, in tiles, of the screen * * @param font * The font. * * @throws NullPointerException * If the dimensions or imageCache is null. */ public Screen(final @NonNull Dimension dimensions, final @NonNull Font font) { tiles = new TileGrid(dimensions, new Point(0, 0)); tileHashes = new int[dimensions.height][dimensions.width]; setColorPalette(new ColorPalette()); this.imageCache = new ImageCache(font); // Initialize canvas. final int pixelWidth = dimensions.width * imageCache.getFont().getWidth(); final int pixelHeight = dimensions.height * imageCache.getFont().getHeight(); canvas.setPreferredSize(new Dimension(pixelWidth, pixelHeight)); canvas.setIgnoreRepaint(true); // Add mouse movement listener. addListener(new MouseMotionListener() { @Override public void mouseDragged(final MouseEvent e) {} @Override public void mouseMoved(final MouseEvent e) { final Font font = imageCache.getFont(); final int mouseX = e.getX() / font.getWidth(); final int mouseY = e.getY() / font.getHeight(); mousePosition.setLocation(mouseX, mouseY); } }); } /** * Adds the screen's canvas to a Frame and sets the frame to visible. * * @return * A frame with the canvas on it. */ public Frame addCanvasToFrame() { final Frame frame = new Frame(); frame.add(canvas); frame.setResizable(false); frame.pack(); frame.setLocationRelativeTo(null); frame.setIgnoreRepaint(true); frame.addWindowListener(new WindowAdapter() { public void windowClosing(final WindowEvent e) { frame.dispose(); System.exit(0); } }); frame.setBackground(colorPalette.getDefaultBackground()); frame.setForeground(colorPalette.getDefaultForeground()); frame.setVisible(true); // There's a rare, hard to reproduce, issue where, on the first // render of a Screen, it may just display a blank white canvas. // This sleep is meant to fix that issue by giving the Canvas time // to initialize, or something like that. try { Thread.sleep(100); } catch (final InterruptedException ignored) {} draw(); return frame; } /** * Adds the screen's canvas to a Frame, sets the frame to visible, * and enables full-screen exclusive mode on the Frame, for a * specific device (monitor). * * @param device * The device (monitor) to enable full-screen for. * * @return * A full-screened frame with the canvas on it. * * @throws NullPointerException * If the device is null. */ public Frame addCanvasToFullScreenFrame(final @NonNull GraphicsDevice device) { if (! device.isFullScreenSupported()) { LogManager.getLogger().error("Full screen is not supported for the device '" + device.getIDstring() + "'."); addCanvasToFrame(); } // Resize the font, so that it fills the screen properly. final DisplayMode displayMode = device.getDisplayMode(); final double scaleX = displayMode.getWidth() / canvas.getPreferredSize().getWidth(); final double scaleY = displayMode.getHeight() / canvas.getPreferredSize().getHeight(); imageCache.getFont().resize(scaleX, scaleY); // Resize the canvas, so that it has enough room to fit the resized font. final int pixelWidth = tiles.getWidth() * imageCache.getFont().getWidth(); final int pixelHeight = tiles.getHeight() * imageCache.getFont().getHeight(); canvas.setPreferredSize(new Dimension(pixelWidth, pixelHeight)); // Create the frame. final Frame frame = new Frame(); frame.setUndecorated(true); frame.setBackground(colorPalette.getDefaultBackground()); frame.setForeground(colorPalette.getDefaultForeground()); frame.addWindowListener(new WindowAdapter() { public void windowClosing(final WindowEvent e) { device.setFullScreenWindow(null); frame.dispose(); System.exit(0); } }); frame.add(canvas); frame.setResizable(false); frame.setIgnoreRepaint(true); frame.setVisible(true); device.setFullScreenWindow(frame); isInFullScreenExclusiveMode = true; // There's a rare, hard to reproduce, issue where, on the first // render of a Screen, it may just display a blank white canvas. // This sleep is meant to fix that issue by giving the Canvas time // to initialize, or something like that. try { Thread.sleep(100); } catch (final InterruptedException ignored) {} draw(); return frame; } /** Draws all of the screen's tiles onto the canvas. */ public void draw() { // Draw components on screen. componentsLock.readLock().lock(); for (final Component component : components) { component.draw(tiles); } componentsLock.readLock().unlock(); // Draw screen on canvas. final BufferStrategy bs = canvas.getBufferStrategy(); do { do { final Graphics2D gc; try { gc = (Graphics2D) bs.getDrawGraphics(); gc.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED); gc.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE); gc.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY); gc.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); // Font characters are pre-rendered images, so no need for AA. gc.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); // No-need for text rendering related options. gc.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_OFF); gc.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); // If alpha is used in the character images, we want computations related to drawing them to be fast. gc.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_SPEED); // Draw every tile, whose hash has changed, onto the canvas. for (int y = 0; y < tiles.getHeight(); y++) { final int yPosition = tiles.getYPosition() + y; for (int x = 0; x < tiles.getWidth(); x++) { final int xPosition = tiles.getXPosition() + x; final Tile tile = tiles.getTileAt(x, y); // Determine if hash has changed. if (tileHashes[y][x] == 0 || tileHashes[y][x] != tile.getCacheHash()) { tileHashes[y][x] = tile.getCacheHash(); tiles.getTileAt(x, y).draw(gc, imageCache, xPosition, yPosition); } } } gc.dispose(); } catch (final NullPointerException | IllegalStateException e) { if (bs == null) { // Create Canvas BufferStrategy if (isInFullScreenExclusiveMode && SystemUtils.IS_OS_WINDOWS) { canvas.createBufferStrategy(1); } else { canvas.createBufferStrategy(2); } draw(); return; } final Logger logger = LogManager.getLogger(); logger.error(e); } } while (bs.contentsRestored()); // Repeat render if drawing buffer contents were restored. bs.show(); } while (bs.contentsLost()); // Repeat render if drawing buffer was lost. } /** * Adds a component to the screen. * * @param component * The component. */ public void addComponent(final Component component) { if (component == null) { return; } if (component instanceof Layer) { for (final Component layerComponent : ((Layer) component).getComponents()) { addComponent(layerComponent); } } // Add the component componentsLock.writeLock().lock(); components.add(component); componentsLock.writeLock().unlock(); // Set the component's redraw function component.setRedrawFunction(this::draw); // Create the component's event listeners component.createEventListeners(this); // Add the component's event listeners for (final EventListener listener : component.getEventListeners()) { addListener(listener); } } /** * Removes a component from the screen. * * @param component * The component. */ public void removeComponent(final Component component) { if (component == null) { return; } if (component instanceof Layer) { for (final Component layerComponent : ((Layer) component).getComponents()) { removeComponent(layerComponent); } } // Remove the component componentsLock.writeLock().lock(); components.remove(component); componentsLock.writeLock().unlock(); // Unset the component's redraw function component.setRedrawFunction(() -> {}); // Remove the component's event listeners for (final EventListener listener : component.getEventListeners()) { removeListener(listener); } } /** Removes all components from the screen. */ public void removeAllComponents() { componentsLock.writeLock().lock(); for (final Component component : components) { // Remove the component components.remove(component); // Remove the component's event listeners for (final EventListener listener : component.getEventListeners()) { removeListener(listener); } } componentsLock.writeLock().unlock(); } public void addListener(final EventListener eventListener) { if (eventListener == null) { return; } if (eventListener instanceof KeyListener) { canvas.addKeyListener((KeyListener) eventListener); return; } if (eventListener instanceof MouseInputListener) { canvas.addMouseListener((MouseListener) eventListener); canvas.addMouseMotionListener((MouseMotionListener) eventListener); return; } if (eventListener instanceof MouseListener) { canvas.addMouseListener((MouseListener) eventListener); return; } if (eventListener instanceof MouseMotionListener) { canvas.addMouseMotionListener((MouseMotionListener) eventListener); return; } throw new IllegalArgumentException("The " + eventListener.getClass().getSimpleName() + " is not supported."); } public void removeListener(final EventListener eventListener) { if (eventListener == null) { return; } if (eventListener instanceof KeyListener) { canvas.removeKeyListener((KeyListener) eventListener); return; } if (eventListener instanceof MouseInputListener) { canvas.removeMouseListener((MouseListener) eventListener); canvas.removeMouseMotionListener((MouseMotionListener) eventListener); return; } if (eventListener instanceof MouseListener) { canvas.removeMouseListener((MouseListener) eventListener); return; } if (eventListener instanceof MouseMotionListener) { canvas.removeMouseMotionListener((MouseMotionListener) eventListener); return; } throw new IllegalArgumentException("The " + eventListener.getClass().getSimpleName() + " is not supported."); } /** * Retrieves the last known tile-based position of the mouse. * * @return * The last known tile-based position of the mouse. */ public Point getMousePosition() { return new Point(mousePosition); } /** * Retrieves the width, also known as the total number of columns, in * the component. * * @return * The width of the grid. */ public int getWidth() { return tiles.getWidth(); } /** * Retrieves the height, also known as the total number of rows, in * the component. * * @return * The height of the grid. */ public int getHeight() { return tiles.getHeight(); } /** * Retrieves a tile from the screen. * * @param x * The x-axis coordinate of the tile to retrieve. * * @param y * The y-axis coordinate of the tile to retrieve. * * @return * The tile, or null if the coordinates are outside the bounds * of the screen. */ public Tile getTileAt(final int x, final int y) { return tiles.getTileAt(x, y); } /** * Retrieves a tile from the screen. * * @param position * The x/y-axis coordinates of the tile to retrieve. * * @return * The tile, or null if the coordinates are outside the bounds * of the screen or if the position is null. */ public Tile getTileAt(final Point position) { if (position == null) { return null; } return tiles.getTileAt(position); } /** * Sets the fore/background color of every tile on the screen to the * default fore/background colors of a ColorPalette. * * This does not affect child components and this is not permanent. * These color changes may be overwritten during a draw call. * * @param colorPalette * The color palette. */ public void setColorPalette(final @NonNull ColorPalette colorPalette) { if (colorPalette == null) { return; } this.colorPalette = colorPalette; for (int y = 0 ; y < tiles.getHeight() ; y++) { for (int x = 0 ; x < tiles.getWidth() ; x++) { final Tile tile = tiles.getTileAt(x, y); tile.setForegroundColor(colorPalette.getDefaultForeground()); tile.setBackgroundColor(colorPalette.getDefaultBackground()); } } } }
package fitnesse.responders; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static util.RegexTestCase.assertDoesntHaveRegexp; import static util.RegexTestCase.assertHasRegexp; import static util.RegexTestCase.assertNotSubString; import static util.RegexTestCase.assertSubString; import java.util.HashMap; import java.util.Map; import fitnesse.FitNesseContext; import fitnesse.Responder; import fitnesse.authentication.SecureOperation; import fitnesse.authentication.SecureReadOperation; import fitnesse.authentication.SecureResponder; import fitnesse.http.MockRequest; import fitnesse.http.SimpleResponse; import fitnesse.testutil.FitNesseUtil; import fitnesse.wiki.PageData; import fitnesse.wiki.PathParser; import fitnesse.wiki.WikiImportProperty; import fitnesse.wiki.WikiPage; import fitnesse.wiki.WikiPageProperties; import fitnesse.wiki.WikiPageUtil; import org.junit.Before; import org.junit.Test; public class WikiPageResponderTest { private WikiPage root; private FitNesseContext context; @Before public void setUp() throws Exception { context = FitNesseUtil.makeTestContext(); root = context.getRootPage(); } @Test public void testResponse() throws Exception { WikiPage page = WikiPageUtil.addPage(root, PathParser.parse("ChildPage"), "child content"); PageData data = page.getData(); WikiPageProperties properties = data.getProperties(); properties.set(PageData.PropertySUITES, "Wiki Page tags"); page.commit(data); final MockRequest request = new MockRequest(); request.setResource("ChildPage"); final Responder responder = new WikiPageResponder(); final SimpleResponse response = (SimpleResponse) responder.makeResponse(context, request); assertEquals(200, response.getStatus()); final String body = response.getContent(); assertSubString("<html>", body); assertSubString("<body", body); assertSubString("child content", body); assertSubString("href=\"ChildPage?whereUsed\"", body); assertSubString("Cache-Control: max-age=0", response.makeHttpHeaders()); assertSubString("<h5> Wiki Page tags</h5>", body); } @Test public void testResponseWithNonWikiWordChildPage() throws Exception { WikiPage page = WikiPageUtil.addPage(root, PathParser.parse("page"), "content"); WikiPageUtil.addPage(page, PathParser.parse("child_page"), "child content"); final MockRequest request = new MockRequest(); request.setResource("page.child_page"); final Responder responder = new WikiPageResponder(); final SimpleResponse response = (SimpleResponse) responder.makeResponse(context, request); assertEquals(200, response.getStatus()); final String body = response.getContent(); assertSubString("child content", body); } @Test public void testAttributeButtons() throws Exception { WikiPageUtil.addPage(root, PathParser.parse("NormalPage"), ""); final WikiPage noButtonsPage = WikiPageUtil.addPage(root, PathParser.parse("NoButtonPage"), ""); for (final String attribute : PageData.NON_SECURITY_ATTRIBUTES) { final PageData data = noButtonsPage.getData(); data.removeAttribute(attribute); noButtonsPage.commit(data); } SimpleResponse response = requestPage("NormalPage"); assertSubString(">Edit</a>", response.getContent()); assertSubString(">Search</a>", response.getContent()); assertSubString(">Versions</a>", response.getContent()); assertNotSubString(">Suite</a>", response.getContent()); assertNotSubString(">Test</a>", response.getContent()); response = requestPage("NoButtonPage"); assertNotSubString(">Edit</a>", response.getContent()); assertNotSubString(">Search</a>", response.getContent()); assertNotSubString(">Versions</a>", response.getContent()); assertNotSubString(">Suite</a>", response.getContent()); assertNotSubString(">Test</a>", response.getContent()); } @Test public void testHeadersAndFooters() throws Exception { WikiPageUtil.addPage(root, PathParser.parse("NormalPage"), "normal"); WikiPageUtil.addPage(root, PathParser.parse("TestPage"), "test page"); WikiPageUtil.addPage(root, PathParser.parse("PageHeader"), "header"); WikiPageUtil.addPage(root, PathParser.parse("PageFooter"), "footer"); WikiPageUtil.addPage(root, PathParser.parse("SetUp"), "setup"); WikiPageUtil.addPage(root, PathParser.parse("TearDown"), "teardown"); WikiPageUtil.addPage(root, PathParser.parse("SuiteSetUp"), "suite setup"); WikiPageUtil.addPage(root, PathParser.parse("SuiteTearDown"), "suite teardown"); SimpleResponse response = requestPage("NormalPage"); String content = response.getContent(); assertHasRegexp("header", content); assertHasRegexp("normal", content); assertHasRegexp("footer", content); assertDoesntHaveRegexp("setup", content); assertDoesntHaveRegexp("teardown", content); assertDoesntHaveRegexp("suite setup", content); assertDoesntHaveRegexp("suite teardown", content); response = requestPage("TestPage"); content = response.getContent(); assertHasRegexp("header", content); assertHasRegexp("test page", content); assertHasRegexp("footer", content); assertHasRegexp("setup", content); assertHasRegexp("teardown", content); assertHasRegexp("suite setup", content); assertHasRegexp("suite teardown", content); } @Test public void testInputValues() throws Exception { WikiPageUtil.addPage(root, PathParser.parse("NormalPage"), "normal ${normalParam}"); WikiPageUtil.addPage(root, PathParser.parse("TestPage"), "test page ${testPageParam}"); WikiPageUtil.addPage(root, PathParser.parse("PageHeader"), "header ${headerParam}"); WikiPageUtil.addPage(root, PathParser.parse("PageFooter"), "footer ${footerParam}"); WikiPageUtil.addPage(root, PathParser.parse("SetUp"), "setup ${setupParam}"); WikiPageUtil.addPage(root, PathParser.parse("TearDown"), "teardown ${teardownParam}"); WikiPageUtil.addPage(root, PathParser.parse("SuiteSetUp"), "suite setup ${suiteSetupParam}"); WikiPageUtil.addPage(root, PathParser.parse("SuiteTearDown"), "suite teardown ${suiteTeardownParam}"); Map<String,String> urlInputValues = new HashMap<String,String>(); urlInputValues.put("normalParam", "normalValue"); urlInputValues.put("headerParam", "headerValue"); urlInputValues.put("footerParam", "footerValue"); SimpleResponse response = requestPage("NormalPage", urlInputValues); String content = response.getContent(); assertHasRegexp("header headerValue", content); assertHasRegexp("normal normalValue", content); assertHasRegexp("footer footerValue", content); urlInputValues = new HashMap<String,String>(); urlInputValues.put("headerParam", "headerValue"); urlInputValues.put("footerParam", "footerValue"); urlInputValues.put("testPageParam", "testPageValue"); urlInputValues.put("footerParam", "footerValue"); urlInputValues.put("setupParam", "setupValue"); urlInputValues.put("teardownParam", "teardownValue"); urlInputValues.put("suiteSetupParam", "suiteSetupValue"); urlInputValues.put("suiteTeardownParam", "suiteTeardownValue"); response = requestPage("TestPage", urlInputValues); content = response.getContent(); assertHasRegexp("header headerValue", content); assertHasRegexp("test page testPageValue", content); assertHasRegexp("footer footerValue", content); assertHasRegexp("setup setupValue", content); assertHasRegexp("teardown teardownValue", content); assertHasRegexp("suite setup suiteSetupValue", content); assertHasRegexp("suite teardown suiteTeardownValue", content); } private SimpleResponse requestPage(String name) throws Exception { return requestPage(name, new HashMap<String,String>()); } private SimpleResponse requestPage(String name, Map<String,String> inputs) throws Exception { final MockRequest request = new MockRequest(); request.setResource(name); for(String input: inputs.keySet()){ request.addInput(input, inputs.get(input)); } final Responder responder = new WikiPageResponder(); return (SimpleResponse) responder.makeResponse(context, request); } @Test public void testImportedPageIndication() throws Exception { final WikiPage page = WikiPageUtil.addPage(root, PathParser.parse("SamplePage")); final PageData data = page.getData(); final WikiImportProperty importProperty = new WikiImportProperty("blah"); importProperty.addTo(data.getProperties()); page.commit(data); final String content = requestPage("SamplePage").getContent(); assertSubString("<body class=\"imported\">", content); } @Test public void testImportedPageIndicationNotOnRoot() throws Exception { final WikiPage page = WikiPageUtil.addPage(root, PathParser.parse("SamplePage")); final PageData data = page.getData(); final WikiImportProperty importProperty = new WikiImportProperty("blah"); importProperty.setRoot(true); importProperty.addTo(data.getProperties()); page.commit(data); final String content = requestPage("SamplePage").getContent(); assertNotSubString("<body class=\"imported\">", content); } @Test public void testResponderIsSecureReadOperation() throws Exception { final Responder responder = new WikiPageResponder(); assertTrue(responder instanceof SecureResponder); final SecureOperation operation = ((SecureResponder) responder).getSecureOperation(); assertEquals(SecureReadOperation.class, operation.getClass()); } }
package com.xruby.compiler; import com.xruby.runtime.lang.RubyRuntime; /** * Test if ruby's standand lib work under xruby */ public class StdlibTest extends CompilerTestCase { public void setUp() { RubyRuntime.init(null); } public void test_test_unit_StandardError() { String[] program_texts = { "require 'test/unit/assertionfailederror'", "print Test::Unit::AssertionFailedError.superclass", }; String[] outputs = { "", "StandardError", }; compile_run_and_compare_output(program_texts, outputs); } public void test_test_unit_Failure() { String[] program_texts = { "require 'test/unit/failure'", "print Test::Unit::Failure.new('x', 'y', 'z').single_character_display", "print Test::Unit::Failure.new('x', 'y', 'z').short_display", "print Test::Unit::Failure.new('x1', [1, 2], 'z1').long_display", "print Test::Unit::Failure.new('x1', ['y'], 'z1').long_display", "print Test::Unit::Failure.new('x1', ['y'], 'z1').to_s", }; String[] outputs = { "", "F", "x: z", "Failure:\nx1\n [1\n 2]:\nz1", "Failure:\nx1y:\nz1", "Failure:\nx1y:\nz1", }; compile_run_and_compare_output(program_texts, outputs); } public void test_Rational() { String[] program_texts = { "require 'rational'", "print Rational(3,4).to_s", "print Rational(+7,4).to_i", "print Rational(-7,4).to_i", "print Rational(+7,4).to_f", "print Rational(3,4) / 2", "print Rational(3,4) / 2.0", "print Rational(3,4) * 2", "print Rational(7,4) % Rational(1,2)", "print Rational(3,4) % 1", "print Rational(3,4) % Rational(1,7)", }; String[] outputs = { "", "3/4", "1", "-2", "1.75", "3/8", "0.375", "3/2", "1/4", "3/4", "1/28", }; compile_run_and_compare_output(program_texts, outputs); } }
package com.xruby.compiler; import com.xruby.runtime.lang.RubyRuntime; /** * Test if ruby's standand lib work under xruby */ public class StdlibTest extends CompilerTestCase { public void setUp() { RubyRuntime.init(null); } public void test_test_unit_StandardError() { String[] program_texts = { "require 'test/unit/assertionfailederror'", "print Test::Unit::AssertionFailedError.superclass", }; String[] outputs = { "", "StandardError", }; compile_run_and_compare_output(program_texts, outputs); } public void test_test_unit_Failure() { String[] program_texts = { "require 'test/unit/failure'", "print Test::Unit::Failure.new('x', 'y', 'z').single_character_display", "print Test::Unit::Failure.new('x', 'y', 'z').short_display", "print Test::Unit::Failure.new('x1', [1, 2], 'z1').long_display", "print Test::Unit::Failure.new('x1', ['y'], 'z1').long_display", "print Test::Unit::Failure.new('x1', ['y'], 'z1').to_s", }; String[] outputs = { "", "F", "x: z", "Failure:\nx1\n [1\n 2]:\nz1", "Failure:\nx1y:\nz1", "Failure:\nx1y:\nz1", }; compile_run_and_compare_output(program_texts, outputs); } public void test_Rational() { String[] program_texts = { "require 'rational'", "print Rational(3,4).to_s", "print Rational(+7,4).to_i", "print Rational(-7,4).to_i", "print Rational(3,4) / 2", //"print Rational(3,4) / 2.0", //"print Rational(7,4) % Rational(1,2)", //"print Rational(3,4) % 1", //"print Rational(3,4) % Rational(1,7)", //"print Rational(3,4) % 0.26 ", }; String[] outputs = { "", "3/4", "1", "-2", "3/8", //"0.375", //"1/28", //"0.23", }; compile_run_and_compare_output(program_texts, outputs); } }
package com.ecyrd.jspwiki.plugin; import java.util.Properties; import com.ecyrd.jspwiki.TestEngine; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * @author jalkanen * * @since */ public class TableOfContentsTest extends TestCase { TestEngine testEngine; /* * @see TestCase#setUp() */ protected void setUp() throws Exception { super.setUp(); Properties props = new Properties(); props.load(TestEngine.findTestProperties()); testEngine = new TestEngine( props ); } /* * @see TestCase#tearDown() */ protected void tearDown() throws Exception { super.tearDown(); testEngine.deletePage( "Test" ); } public void testHeadingVariables() throws Exception { String src="[{SET foo=bar}]\n\n[{TableOfContents}]\n\n!!!Heading [{$foo}]"; testEngine.saveText( "Test", src ); String res = testEngine.getHTML( "Test" ); // FIXME: The <p> should not be here. assertEquals( "\n<p><div class=\"toc\">\n<div class=\"collapsebox\">\n"+ "<h4>Table of Contents</h4>\n"+ "<ul>\n"+ "<li class=\"toclevel-1\"><a class=\"wikipage\" href=\"/Wiki.jsp?page=Test#section-Test-HeadingBar\">Heading bar</a></li>\n"+ "</ul>\n</div>\n</div>\n\n</p>"+ "\n<h2 id=\"section-Test-HeadingBar\">Heading bar</h2>\n", res ); } public void testNumberedItems() throws Exception { String src="[{SET foo=bar}]\n\n[{INSERT TableOfContents WHERE numbered=true,start=3}]\n\n!!!Heading [{$foo}]\n\n!!Subheading\n\n!Subsubheading"; testEngine.saveText( "Test", src ); String res = testEngine.getHTML( "Test" ); // FIXME: The <p> should not be here. String expecting = "\n<p><div class=\"toc\">\n<div class=\"collapsebox\">\n"+ "<h4>Table of Contents</h4>\n"+ "<ul>\n"+ "<li class=\"toclevel-1\">3 <a class=\"wikipage\" href=\"/Wiki.jsp?page=Test#section-Test-HeadingBar\">Heading bar</a></li>\n"+ "<li class=\"toclevel-2\">3.1 <a class=\"wikipage\" href=\"/Wiki.jsp?page=Test#section-Test-Subheading\">Subheading</a></li>\n"+ "<li class=\"toclevel-3\">3.1.1 <a class=\"wikipage\" href=\"/Wiki.jsp?page=Test#section-Test-Subsubheading\">Subsubheading</a></li>\n"+ "</ul>\n</div>\n</div>\n\n</p>"+ "\n<h2 id=\"section-Test-HeadingBar\">Heading bar</h2>"+ "\n<h3 id=\"section-Test-Subheading\">Subheading</h3>"+ "\n<h4 id=\"section-Test-Subsubheading\">Subsubheading</h4>\n"; assertEquals(expecting, res ); } public void testNumberedItemsComplex() throws Exception { String src="[{SET foo=bar}]\n\n[{INSERT TableOfContents WHERE numbered=true,start=3}]\n\n!!!Heading [{$foo}]\n\n!!Subheading\n\n!Subsubheading\n\n!Subsubheading2\n\n!!Subheading2\n\n!Subsubheading3\n\n!!!Heading\n\n!!Subheading3"; testEngine.saveText( "Test", src ); String res = testEngine.getHTML( "Test" ); // FIXME: The <p> should not be here. String expecting = "\n<p><div class=\"toc\">\n<div class=\"collapsebox\">\n"+ "<h4>Table of Contents</h4>\n"+ "<ul>\n"+ "<li class=\"toclevel-1\">3 <a class=\"wikipage\" href=\"/Wiki.jsp?page=Test#section-Test-HeadingBar\">Heading bar</a></li>\n"+ "<li class=\"toclevel-2\">3.1 <a class=\"wikipage\" href=\"/Wiki.jsp?page=Test#section-Test-Subheading\">Subheading</a></li>\n"+ "<li class=\"toclevel-3\">3.1.1 <a class=\"wikipage\" href=\"/Wiki.jsp?page=Test#section-Test-Subsubheading\">Subsubheading</a></li>\n"+ "<li class=\"toclevel-3\">3.1.2 <a class=\"wikipage\" href=\"/Wiki.jsp?page=Test#section-Test-Subsubheading2\">Subsubheading2</a></li>\n"+ "<li class=\"toclevel-2\">3.2 <a class=\"wikipage\" href=\"/Wiki.jsp?page=Test#section-Test-Subheading2\">Subheading2</a></li>\n"+ "<li class=\"toclevel-3\">3.2.1 <a class=\"wikipage\" href=\"/Wiki.jsp?page=Test#section-Test-Subsubheading3\">Subsubheading3</a></li>\n"+ "<li class=\"toclevel-1\">4 <a class=\"wikipage\" href=\"/Wiki.jsp?page=Test#section-Test-Heading\">Heading</a></li>\n"+ "<li class=\"toclevel-2\">4.1 <a class=\"wikipage\" href=\"/Wiki.jsp?page=Test#section-Test-Subheading3\">Subheading3</a></li>\n"+ "</ul>\n</div>\n</div>\n\n</p>"+ "\n<h2 id=\"section-Test-HeadingBar\">Heading bar</h2>"+ "\n<h3 id=\"section-Test-Subheading\">Subheading</h3>"+ "\n<h4 id=\"section-Test-Subsubheading\">Subsubheading</h4>"+ "\n<h4 id=\"section-Test-Subsubheading2\">Subsubheading2</h4>"+ "\n<h3 id=\"section-Test-Subheading2\">Subheading2</h3>"+ "\n<h4 id=\"section-Test-Subsubheading3\">Subsubheading3</h4>"+ "\n<h2 id=\"section-Test-Heading\">Heading</h2>"+ "\n<h3 id=\"section-Test-Subheading3\">Subheading3</h3>\n"; assertEquals(expecting, res ); } public void testNumberedItemsComplex2() throws Exception { String src="[{SET foo=bar}]\n\n[{INSERT TableOfContents WHERE numbered=true,start=3}]\n\n!!Subheading0\n\n!!!Heading [{$foo}]\n\n!!Subheading\n\n!Subsubheading\n\n!Subsubheading2\n\n!!Subheading2\n\n!Subsubheading3\n\n!!!Heading\n\n!!Subheading3"; testEngine.saveText( "Test", src ); String res = testEngine.getHTML( "Test" ); // FIXME: The <p> should not be here. String expecting = "\n<p><div class=\"toc\">\n<div class=\"collapsebox\">\n"+ "<h4>Table of Contents</h4>\n"+ "<ul>\n"+ "<li class=\"toclevel-2\">3.1 <a class=\"wikipage\" href=\"/Wiki.jsp?page=Test#section-Test-Subheading0\">Subheading0</a></li>\n"+ "<li class=\"toclevel-1\">4 <a class=\"wikipage\" href=\"/Wiki.jsp?page=Test#section-Test-HeadingBar\">Heading bar</a></li>\n"+ "<li class=\"toclevel-2\">4.1 <a class=\"wikipage\" href=\"/Wiki.jsp?page=Test#section-Test-Subheading\">Subheading</a></li>\n"+ "<li class=\"toclevel-3\">4.1.1 <a class=\"wikipage\" href=\"/Wiki.jsp?page=Test#section-Test-Subsubheading\">Subsubheading</a></li>\n"+ "<li class=\"toclevel-3\">4.1.2 <a class=\"wikipage\" href=\"/Wiki.jsp?page=Test#section-Test-Subsubheading2\">Subsubheading2</a></li>\n"+ "<li class=\"toclevel-2\">4.2 <a class=\"wikipage\" href=\"/Wiki.jsp?page=Test#section-Test-Subheading2\">Subheading2</a></li>\n"+ "<li class=\"toclevel-3\">4.2.1 <a class=\"wikipage\" href=\"/Wiki.jsp?page=Test#section-Test-Subsubheading3\">Subsubheading3</a></li>\n"+ "<li class=\"toclevel-1\">5 <a class=\"wikipage\" href=\"/Wiki.jsp?page=Test#section-Test-Heading\">Heading</a></li>\n"+ "<li class=\"toclevel-2\">5.1 <a class=\"wikipage\" href=\"/Wiki.jsp?page=Test#section-Test-Subheading3\">Subheading3</a></li>\n"+ "</ul>\n</div>\n</div>\n\n</p>"+ "\n<h3 id=\"section-Test-Subheading0\">Subheading0</h3>"+ "\n<h2 id=\"section-Test-HeadingBar\">Heading bar</h2>"+ "\n<h3 id=\"section-Test-Subheading\">Subheading</h3>"+ "\n<h4 id=\"section-Test-Subsubheading\">Subsubheading</h4>"+ "\n<h4 id=\"section-Test-Subsubheading2\">Subsubheading2</h4>"+ "\n<h3 id=\"section-Test-Subheading2\">Subheading2</h3>"+ "\n<h4 id=\"section-Test-Subsubheading3\">Subsubheading3</h4>"+ "\n<h2 id=\"section-Test-Heading\">Heading</h2>"+ "\n<h3 id=\"section-Test-Subheading3\">Subheading3</h3>\n"; assertEquals(expecting, res ); } public void testNumberedItemsWithPrefix() throws Exception { String src="[{SET foo=bar}]\n\n[{INSERT TableOfContents WHERE numbered=true,start=3,prefix=FooBar-}]\n\n!!!Heading [{$foo}]\n\n!!Subheading\n\n!Subsubheading"; testEngine.saveText( "Test", src ); String res = testEngine.getHTML( "Test" ); // FIXME: The <p> should not be here. String expecting = "\n<p><div class=\"toc\">\n<div class=\"collapsebox\">\n"+ "<h4>Table of Contents</h4>\n"+ "<ul>\n"+ "<li class=\"toclevel-1\">FooBar-3 <a class=\"wikipage\" href=\"/Wiki.jsp?page=Test#section-Test-HeadingBar\">Heading bar</a></li>\n"+ "<li class=\"toclevel-2\">FooBar-3.1 <a class=\"wikipage\" href=\"/Wiki.jsp?page=Test#section-Test-Subheading\">Subheading</a></li>\n"+ "<li class=\"toclevel-3\">FooBar-3.1.1 <a class=\"wikipage\" href=\"/Wiki.jsp?page=Test#section-Test-Subsubheading\">Subsubheading</a></li>\n"+ "</ul>\n</div>\n</div>\n\n</p>"+ "\n<h2 id=\"section-Test-HeadingBar\">Heading bar</h2>"+ "\n<h3 id=\"section-Test-Subheading\">Subheading</h3>"+ "\n<h4 id=\"section-Test-Subsubheading\">Subsubheading</h4>\n"; assertEquals(expecting, res ); } public static Test suite() { return new TestSuite( TableOfContentsTest.class ); } }
package com.ecyrd.jspwiki.plugin; import java.util.Properties; import com.ecyrd.jspwiki.TestEngine; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * @author jalkanen * * @since */ public class TableOfContentsTest extends TestCase { TestEngine testEngine; /* * @see TestCase#setUp() */ protected void setUp() throws Exception { super.setUp(); Properties props = new Properties(); props.load(TestEngine.findTestProperties()); testEngine = new TestEngine( props ); } /* * @see TestCase#tearDown() */ protected void tearDown() throws Exception { super.tearDown(); testEngine.deletePage( "Test" ); } public void testHeadingVariables() throws Exception { String src="[{SET foo=bar}]\n\n[{TableOfContents}]\n\n!!!Heading [{$foo}]"; testEngine.saveText( "Test", src ); String res = testEngine.getHTML( "Test" ); // FIXME: The <p> should not be here. assertEquals( "\n<p><div class=\"toc\">\n<div class=\"collapsebox\">\n"+ "<h4>Table of Contents</h4>\n"+ "<ul>\n"+ "<li class=\"toclevel-1\"><a class=\"wikipage\" href=\"/Wiki.jsp?page=Test#section-Test-HeadingBar\">Heading bar</a></li>\n"+ "</ul>\n</div>\n</div>\n\n</p>"+ "\n<h2 id=\"section-Test-HeadingBar\">Heading bar</h2>\n", res ); } public void testNumberedItems() throws Exception { String src="[{SET foo=bar}]\n\n[{INSERT TableOfContents WHERE numbered=true,start=3}]\n\n!!!Heading [{$foo}]\n\n!!Subheading\n\n!Subsubheading"; testEngine.saveText( "Test", src ); String res = testEngine.getHTML( "Test" ); // FIXME: The <p> should not be here. String expecting = "\n<p><div class=\"toc\">\n<div class=\"collapsebox\">\n"+ "<h4>Table of Contents</h4>\n"+ "<ul>\n"+ "<li class=\"toclevel-1\"><a class=\"wikipage\" href=\"/Wiki.jsp?page=Test#section-Test-HeadingBar\">3 Heading bar</a></li>\n"+ "<li class=\"toclevel-2\"><a class=\"wikipage\" href=\"/Wiki.jsp?page=Test#section-Test-Subheading\">3.1 Subheading</a></li>\n"+ "<li class=\"toclevel-3\"><a class=\"wikipage\" href=\"/Wiki.jsp?page=Test#section-Test-Subsubheading\">3.1.1 Subsubheading</a></li>\n"+ "</ul>\n</div>\n</div>\n\n</p>"+ "\n<h2 id=\"section-Test-HeadingBar\">Heading bar</h2>"+ "\n<h3 id=\"section-Test-Subheading\">Subheading</h3>"+ "\n<h4 id=\"section-Test-Subsubheading\">Subsubheading</h4>\n"; assertEquals(expecting, res ); } public void testNumberedItemsComplex() throws Exception { String src="[{SET foo=bar}]\n\n[{INSERT TableOfContents WHERE numbered=true,start=3}]\n\n!!!Heading [{$foo}]\n\n!!Subheading\n\n!Subsubheading\n\n!Subsubheading2\n\n!!Subheading2\n\n!Subsubheading3\n\n!!!Heading\n\n!!Subheading3"; testEngine.saveText( "Test", src ); String res = testEngine.getHTML( "Test" ); // FIXME: The <p> should not be here. String expecting = "\n<p><div class=\"toc\">\n<div class=\"collapsebox\">\n"+ "<h4>Table of Contents</h4>\n"+ "<ul>\n"+ "<li class=\"toclevel-1\"><a class=\"wikipage\" href=\"/Wiki.jsp?page=Test#section-Test-HeadingBar\">3 Heading bar</a></li>\n"+ "<li class=\"toclevel-2\"><a class=\"wikipage\" href=\"/Wiki.jsp?page=Test#section-Test-Subheading\">3.1 Subheading</a></li>\n"+ "<li class=\"toclevel-3\"><a class=\"wikipage\" href=\"/Wiki.jsp?page=Test#section-Test-Subsubheading\">3.1.1 Subsubheading</a></li>\n"+ "<li class=\"toclevel-3\"><a class=\"wikipage\" href=\"/Wiki.jsp?page=Test#section-Test-Subsubheading2\">3.1.2 Subsubheading2</a></li>\n"+ "<li class=\"toclevel-2\"><a class=\"wikipage\" href=\"/Wiki.jsp?page=Test#section-Test-Subheading2\">3.2 Subheading2</a></li>\n"+ "<li class=\"toclevel-3\"><a class=\"wikipage\" href=\"/Wiki.jsp?page=Test#section-Test-Subsubheading3\">3.2.1 Subsubheading3</a></li>\n"+ "<li class=\"toclevel-1\"><a class=\"wikipage\" href=\"/Wiki.jsp?page=Test#section-Test-Heading\">4 Heading</a></li>\n"+ "<li class=\"toclevel-2\"><a class=\"wikipage\" href=\"/Wiki.jsp?page=Test#section-Test-Subheading3\">4.1 Subheading3</a></li>\n"+ "</ul>\n</div>\n</div>\n\n</p>"+ "\n<h2 id=\"section-Test-HeadingBar\">Heading bar</h2>"+ "\n<h3 id=\"section-Test-Subheading\">Subheading</h3>"+ "\n<h4 id=\"section-Test-Subsubheading\">Subsubheading</h4>"+ "\n<h4 id=\"section-Test-Subsubheading2\">Subsubheading2</h4>"+ "\n<h3 id=\"section-Test-Subheading2\">Subheading2</h3>"+ "\n<h4 id=\"section-Test-Subsubheading3\">Subsubheading3</h4>"+ "\n<h2 id=\"section-Test-Heading\">Heading</h2>"+ "\n<h3 id=\"section-Test-Subheading3\">Subheading3</h3>\n"; assertEquals(expecting, res ); } public void testNumberedItemsComplex2() throws Exception { String src="[{SET foo=bar}]\n\n[{INSERT TableOfContents WHERE numbered=true,start=3}]\n\n!!Subheading0\n\n!!!Heading [{$foo}]\n\n!!Subheading\n\n!Subsubheading\n\n!Subsubheading2\n\n!!Subheading2\n\n!Subsubheading3\n\n!!!Heading\n\n!!Subheading3"; testEngine.saveText( "Test", src ); String res = testEngine.getHTML( "Test" ); // FIXME: The <p> should not be here. String expecting = "\n<p><div class=\"toc\">\n<div class=\"collapsebox\">\n"+ "<h4>Table of Contents</h4>\n"+ "<ul>\n"+ "<li class=\"toclevel-2\"><a class=\"wikipage\" href=\"/Wiki.jsp?page=Test#section-Test-Subheading0\">3.1 Subheading0</a></li>\n"+ "<li class=\"toclevel-1\"><a class=\"wikipage\" href=\"/Wiki.jsp?page=Test#section-Test-HeadingBar\">4 Heading bar</a></li>\n"+ "<li class=\"toclevel-2\"><a class=\"wikipage\" href=\"/Wiki.jsp?page=Test#section-Test-Subheading\">4.1 Subheading</a></li>\n"+ "<li class=\"toclevel-3\"><a class=\"wikipage\" href=\"/Wiki.jsp?page=Test#section-Test-Subsubheading\">4.1.1 Subsubheading</a></li>\n"+ "<li class=\"toclevel-3\"><a class=\"wikipage\" href=\"/Wiki.jsp?page=Test#section-Test-Subsubheading2\">4.1.2 Subsubheading2</a></li>\n"+ "<li class=\"toclevel-2\"><a class=\"wikipage\" href=\"/Wiki.jsp?page=Test#section-Test-Subheading2\">4.2 Subheading2</a></li>\n"+ "<li class=\"toclevel-3\"><a class=\"wikipage\" href=\"/Wiki.jsp?page=Test#section-Test-Subsubheading3\">4.2.1 Subsubheading3</a></li>\n"+ "<li class=\"toclevel-1\"><a class=\"wikipage\" href=\"/Wiki.jsp?page=Test#section-Test-Heading\">5 Heading</a></li>\n"+ "<li class=\"toclevel-2\"><a class=\"wikipage\" href=\"/Wiki.jsp?page=Test#section-Test-Subheading3\">5.1 Subheading3</a></li>\n"+ "</ul>\n</div>\n</div>\n\n</p>"+ "\n<h3 id=\"section-Test-Subheading0\">Subheading0</h3>"+ "\n<h2 id=\"section-Test-HeadingBar\">Heading bar</h2>"+ "\n<h3 id=\"section-Test-Subheading\">Subheading</h3>"+ "\n<h4 id=\"section-Test-Subsubheading\">Subsubheading</h4>"+ "\n<h4 id=\"section-Test-Subsubheading2\">Subsubheading2</h4>"+ "\n<h3 id=\"section-Test-Subheading2\">Subheading2</h3>"+ "\n<h4 id=\"section-Test-Subsubheading3\">Subsubheading3</h4>"+ "\n<h2 id=\"section-Test-Heading\">Heading</h2>"+ "\n<h3 id=\"section-Test-Subheading3\">Subheading3</h3>\n"; assertEquals(expecting, res ); } public void testNumberedItemsWithPrefix() throws Exception { String src="[{SET foo=bar}]\n\n[{INSERT TableOfContents WHERE numbered=true,start=3,prefix=FooBar-}]\n\n!!!Heading [{$foo}]\n\n!!Subheading\n\n!Subsubheading"; testEngine.saveText( "Test", src ); String res = testEngine.getHTML( "Test" ); // FIXME: The <p> should not be here. String expecting = "\n<p><div class=\"toc\">\n<div class=\"collapsebox\">\n"+ "<h4>Table of Contents</h4>\n"+ "<ul>\n"+ "<li class=\"toclevel-1\"><a class=\"wikipage\" href=\"/Wiki.jsp?page=Test#section-Test-HeadingBar\">FooBar-3 Heading bar</a></li>\n"+ "<li class=\"toclevel-2\"><a class=\"wikipage\" href=\"/Wiki.jsp?page=Test#section-Test-Subheading\">FooBar-3.1 Subheading</a></li>\n"+ "<li class=\"toclevel-3\"><a class=\"wikipage\" href=\"/Wiki.jsp?page=Test#section-Test-Subsubheading\">FooBar-3.1.1 Subsubheading</a></li>\n"+ "</ul>\n</div>\n</div>\n\n</p>"+ "\n<h2 id=\"section-Test-HeadingBar\">Heading bar</h2>"+ "\n<h3 id=\"section-Test-Subheading\">Subheading</h3>"+ "\n<h4 id=\"section-Test-Subsubheading\">Subsubheading</h4>\n"; assertEquals(expecting, res ); } /** * Tests BugTableOfContentsCausesHeapdump * * @throws Exception */ public void testSelfReference() throws Exception { String src = "!!![{TableOfContents}]"; testEngine.saveText( "Test", src ); String res = testEngine.getHTML( "Test" ); assertTrue( res.indexOf("Table of Contents") != -1 ); } public void testHTML() throws Exception { String src = "[{TableOfContents}]\n\n!<i>test</i>"; testEngine.saveText( "Test", src ); String res = testEngine.getHTML( "Test" ); assertTrue( "<i>", res.indexOf("<i>") == -1 ); // Check that there is no HTML left assertTrue( "</i>", res.indexOf("</i>") == -1 ); // Check that there is no HTML left } public static Test suite() { return new TestSuite( TableOfContentsTest.class ); } }
package com.mongodb; import static org.junit.Assert.assertEquals; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import org.bson.Document; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.github.fakemongo.Fongo; import com.github.fakemongo.FongoException; import com.mongodb.client.AggregateIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; public class AggregationFongoTest { private MongoCollection<Document> collection; @Before public void beforeMethod(){ Fongo fongo = new Fongo("test"); MongoDatabase mongoDatabase = fongo.getMongo().getDatabase("test"); collection = mongoDatabase.getCollection("example"); } @After public void afetrMethod(){ collection.drop(); } @Test public void AValid$Project$filterPipelineWithCondition$eq50_AValidDocumentWithAnArrayWithTwoElementWhereOnlyOneMatchWithThePipeline_thenReturnADocumentWithOnlyOneArrayElement(){ Document workstation1 = new Document("name", "WK1").append("state", 700); Document workstation2 = new Document("name", "WK2").append("state", 50); Document workstations = new Document("_id", "1"); workstations.append("workstations", Arrays.asList(workstation1, workstation2)); Document under_filter = new Document(); under_filter.append("input", "$workstations") .append("as", "wk") .append("cond", new Document("$eq", Arrays.asList("$$wk.state", 50))); Document filter = new Document("$filter", under_filter); Document items = new Document("items", filter); Document pipeline = new Document("$project", items); Document workstationsResult = new Document("_id", "1"); workstationsResult.append("items", Arrays.asList(new Document("name", "WK2").append("state", 50))); collection.insertMany(Arrays.asList(workstations)); AggregateIterable<Document> iterable = collection.aggregate(Arrays.asList(pipeline)); Document result = iterable.first(); assertEquals(workstationsResult.toJson(), result.toJson()); } @Test public void AValid$Project$filterPipelineWithCondition$eq700_AValidDocumentWithAnArrayWithTwoElementWhereOnlyOneMatchWithThePipeline_thenReturnADocumentWithOnlyOneArrayElement(){ Document workstation1 = new Document("name", "WK1").append("state", 700); Document workstation2 = new Document("name", "WK2").append("state", 50); Document workstations = new Document("_id", "1"); workstations.append("workstations", Arrays.asList(workstation1, workstation2)); Document under_filter = new Document(); under_filter.append("input", "$workstations") .append("as", "wk") .append("cond", new Document("$eq", Arrays.asList("$$wk.state", 700))); Document filter = new Document("$filter", under_filter); Document items = new Document("items", filter); Document pipeline = new Document("$project", items); Document workstationsResult = new Document("_id", "1"); workstationsResult.append("items", Arrays.asList(new Document("name", "WK1").append("state", 700))); collection.insertMany(Arrays.asList(workstations)); AggregateIterable<Document> iterable = collection.aggregate(Arrays.asList(pipeline)); Document result = iterable.first(); assertEquals(workstationsResult.toJson(), result.toJson()); } @Test public void AValid$Project$filterPipelineWithCondition$eq700_AValidDocumentWithAnArrayWithNoElementMatchsWithThePipeline_thenReturnADocumentWithNoArrayElement(){ Document workstation1 = new Document("name", "WK1").append("state", 300); Document workstation2 = new Document("name", "WK2").append("state", 50); Document workstations = new Document("_id", "1"); workstations.append("workstations", Arrays.asList(workstation1, workstation2)); Document under_filter = new Document(); under_filter.append("input", "$workstations") .append("as", "wk") .append("cond", new Document("$eq", Arrays.asList("$$wk.state", 700))); Document filter = new Document("$filter", under_filter); Document items = new Document("items", filter); Document pipeline = new Document("$project", items); Document workstationsResult = new Document("_id", "1"); workstationsResult.append("items", Arrays.asList()); collection.insertMany(Arrays.asList(workstations)); AggregateIterable<Document> iterable = collection.aggregate(Arrays.asList(pipeline)); Document result = iterable.first(); assertEquals(workstationsResult.toJson(), result.toJson()); } @Test public void AValid$Project$filterPipelineWithCondition$eq300_TwoValidDocumentsWithAnArrayWithTwoElementsWhichMatchsWithThePipeline_thenReturnTwoDocumentWithAArrayElementForBoth(){ Document workstation1_1 = new Document("name", "WK1").append("state", 300); Document workstation1_2 = new Document("name", "WK2").append("state", 50); Document workstations1 = new Document("_id", "1"); workstations1.append("workstations", Arrays.asList(workstation1_1, workstation1_2)); Document workstation2_1 = new Document("name", "WK1").append("state", 300); Document workstation2_2 = new Document("name", "WK2").append("state", 50); Document workstations2 = new Document("_id", "2"); workstations2.append("workstations", Arrays.asList(workstation2_1, workstation2_2)); Document under_filter = new Document(); under_filter.append("input", "$workstations") .append("as", "wk") .append("cond", new Document("$eq", Arrays.asList("$$wk.state", 300))); Document filter = new Document("$filter", under_filter); Document items = new Document("items", filter); Document pipeline = new Document("$project", items); Document workstationsResult1 = new Document("_id", "1"); workstationsResult1.append("items", Arrays.asList(new Document("name", "WK1").append("state", 300))); Document workstationsResult2 = new Document("_id", "2"); workstationsResult2.append("items", Arrays.asList(new Document("name", "WK1").append("state", 300))); collection.insertMany(Arrays.asList(workstations1, workstations2)); AggregateIterable<Document> iterable = collection.aggregate(Arrays.asList(pipeline)); final Map<String, Document> result = new HashMap<String, Document>(); iterable.forEach(new Block<Document>() { @Override public void apply(Document document) { result.put((String) document.get("_id"), document); } }); assertEquals(workstationsResult1.toJson(), result.get("1").toJson()); assertEquals(workstationsResult2.toJson(), result.get("2").toJson()); } @Test(expected = FongoException.class) public void ANotValid$Project$filterPipelineWithNoArray_AValidDocuments_thenARuntimeExceptionWillBeThrown(){ Document workstation1 = new Document("name", "WK1").append("state", 700); Document workstation2 = new Document("name", "WK2").append("state", 50); Document workstations = new Document("_id", "1"); workstations.append("workstations", Arrays.asList(workstation1, workstation2)); workstations.append("location", new Document("town", "rome").append("street", "Volsci street")); Document under_filter = new Document(); under_filter.append("input", "$location") .append("as", "wk") .append("cond", new Document("$eq", Arrays.asList("$$wk.town", "Rome"))); Document filter = new Document("$filter", under_filter); Document items = new Document("items", filter); Document pipeline = new Document("$project", items); collection.insertMany(Arrays.asList(workstations)); AggregateIterable<Document> iterable = collection.aggregate(Arrays.asList(pipeline)); iterable.first(); } @Test public void ANotValid$Project$filterPipelineWithAWrongInputValue_AValidDocuments_thenReturnAdocumentWithNullItemsValue(){ Document workstation1 = new Document("name", "WK1").append("state", 700); Document workstation2 = new Document("name", "WK2").append("state", 50); Document workstations = new Document("_id", "1"); workstations.append("workstations", Arrays.asList(workstation1, workstation2)); workstations.append("location", new Document("town", "rome").append("street", "Volsci street")); Document under_filter = new Document(); under_filter.append("input", "$WRONG_workstations") .append("as", "wk") .append("cond", new Document("$eq", Arrays.asList("$$wk.town", "Rome"))); Document filter = new Document("$filter", under_filter); Document items = new Document("items", filter); Document pipeline = new Document("$project", items); Document workstationsResult = new Document("_id", "1"); workstationsResult.append("items", null); collection.insertMany(Arrays.asList(workstations)); AggregateIterable<Document> iterable = collection.aggregate(Arrays.asList(pipeline)); Document result = iterable.first(); assertEquals(workstationsResult.toJson(), result.toJson()); } @Test public void ANotValid$Project$filterPipelineWithAWrongInputValue_TwoValidDocuments_thenReturnAdocumentWithNullItemsValue(){ Document workstation1_1 = new Document("name", "WK1").append("state", 700); Document workstation1_2 = new Document("name", "WK2").append("state", 50); Document workstations1 = new Document("_id", "1"); workstations1.append("workstations", Arrays.asList(workstation1_1, workstation1_2)); workstations1.append("location", new Document("town", "rome").append("street", "Volsci street")); Document workstation2_1 = new Document("name", "WK1").append("state", 700); Document workstation2_2 = new Document("name", "WK2").append("state", 50); Document workstations2 = new Document("_id", "2"); workstations2.append("workstations", Arrays.asList(workstation2_1, workstation2_2)); workstations2.append("location", new Document("town", "rome").append("street", "Volsci street")); Document under_filter = new Document(); under_filter.append("input", "$WRONG_workstations") .append("as", "wk") .append("cond", new Document("$eq", Arrays.asList("$$wk.town", "Rome"))); Document filter = new Document("$filter", under_filter); Document items = new Document("items", filter); Document pipeline = new Document("$project", items); Document workstationsResult1 = new Document("_id", "1"); workstationsResult1.append("items", null); Document workstationsResult2 = new Document("_id", "2"); workstationsResult2.append("items", null); collection.insertMany(Arrays.asList(workstations1, workstations2)); AggregateIterable<Document> iterable = collection.aggregate(Arrays.asList(pipeline)); final Map<String, Document> result = new HashMap<String, Document>(); iterable.forEach(new Block<Document>() { @Override public void apply(Document document) { result.put((String) document.get("_id"), document); } }); assertEquals(workstationsResult1.toJson(), result.get("1").toJson()); assertEquals(workstationsResult2.toJson(), result.get("2").toJson()); } @Test public void documentionTest(){ Document item1_1 = new Document("item_id", 43).append("quantity", 2).append("price", 10); Document item1_2 = new Document("item_id", 2).append("quantity", 1).append("price", 240); Document document1 = new Document("_id", 0).append("items", Arrays.asList(item1_1, item1_2)); Document item2_1 = new Document("item_id", 23).append("quantity", 3).append("price", 110); Document item2_2 = new Document("item_id", 103).append("quantity", 4).append("price", 5); Document item2_3 = new Document("item_id", 38).append("quantity", 1).append("price", 300); Document document2 = new Document("_id", 1).append("items", Arrays.asList(item2_1, item2_2, item2_3)); Document item3_1 = new Document("item_id", 4).append("quantity", 1).append("price", 23); Document document3 = new Document("_id", 2).append("items", Arrays.asList(item3_1)); collection.insertMany(Arrays.asList(document1, document2, document3)); Document under_filter = new Document(); under_filter.append("input", "$items") .append("as", "item") .append("cond", new Document("$gte", Arrays.asList("$$item.price", 100))); Document filter = new Document("$filter", under_filter); Document items = new Document("items", filter); Document pipeline = new Document("$project", items); Document itemResult1_1 = new Document("item_id", 2).append("quantity", 1).append("price", 240); Document documentResult1 = new Document("_id", 0).append("items", Arrays.asList(itemResult1_1)); Document itemResult2_1 = new Document("item_id", 23).append("quantity", 3).append("price", 110); Document itemResult2_2 = new Document("item_id", 38).append("quantity", 1).append("price", 300); Document document1Result2 = new Document("_id", 1).append("items", Arrays.asList(itemResult2_1, itemResult2_2)); Document documentResult3 = new Document("_id", 2).append("items", Arrays.asList()); AggregateIterable<Document> iterable = collection.aggregate(Arrays.asList(pipeline)); final Map<Integer, Document> result = new HashMap<Integer, Document>(); iterable.forEach(new Block<Document>() { @Override public void apply(Document document) { result.put( (Integer) document.get("_id"), document); } }); assertEquals(documentResult1.toJson(), result.get(0).toJson()); assertEquals(document1Result2.toJson(), result.get(1).toJson()); assertEquals(documentResult3.toJson(), result.get(2).toJson()); } @Test(expected = IllegalArgumentException.class) public void ANotValid$Project$filterPipelineWithAAsValueWhichDoesntMAtch_AValidDocuments_thenARuntimeExceptionWillBeThrown(){ Document item1_1 = new Document("item_id", 43).append("quantity", 2).append("price", 10); Document item1_2 = new Document("item_id", 2).append("quantity", 1).append("price", 240); Document document1 = new Document("_id", 0).append("items", Arrays.asList(item1_1, item1_2)); Document item2_1 = new Document("item_id", 23).append("quantity", 3).append("price", 110); Document item2_2 = new Document("item_id", 103).append("quantity", 4).append("price", 5); Document item2_3 = new Document("item_id", 38).append("quantity", 1).append("price", 300); Document document2 = new Document("_id", 1).append("items", Arrays.asList(item2_1, item2_2, item2_3)); Document item3_1 = new Document("item_id", 4).append("quantity", 1).append("price", 23); Document document3 = new Document("_id", 2).append("items", Arrays.asList(item3_1)); collection.insertMany(Arrays.asList(document1, document2, document3)); Document under_filter = new Document(); under_filter.append("input", "$items") .append("as", "WRONG_item") .append("cond", new Document("$gte", Arrays.asList("$$item.price", 100))); Document filter = new Document("$filter", under_filter); Document items = new Document("items", filter); Document pipeline = new Document("$project", items); AggregateIterable<Document> iterable = collection.aggregate(Arrays.asList(pipeline)); iterable.first(); } @Test public void AValid$Project$filterPipelineWithEmptyCondition_ValidDocuments_thenReturnDocumentsNotProjected(){ Document item1_1 = new Document("item_id", 43).append("quantity", 2).append("price", 10); Document item1_2 = new Document("item_id", 2).append("quantity", 1).append("price", 240); Document document1 = new Document("_id", 0).append("items", Arrays.asList(item1_1, item1_2)); Document item2_1 = new Document("item_id", 23).append("quantity", 3).append("price", 110); Document item2_2 = new Document("item_id", 103).append("quantity", 4).append("price", 5); Document item2_3 = new Document("item_id", 38).append("quantity", 1).append("price", 300); Document document2 = new Document("_id", 1).append("items", Arrays.asList(item2_1, item2_2, item2_3)); Document item3_1 = new Document("item_id", 4).append("quantity", 1).append("price", 23); Document document3 = new Document("_id", 2).append("items", Arrays.asList(item3_1)); collection.insertMany(Arrays.asList(document1, document2, document3)); Document under_filter = new Document(); under_filter.append("input", "$items") .append("as", "item") .append("cond", new Document()); Document filter = new Document("$filter", under_filter); Document items = new Document("items", filter); Document pipeline = new Document("$project", items); AggregateIterable<Document> iterable = collection.aggregate(Arrays.asList(pipeline)); final Map<Integer, Document> result = new HashMap<Integer, Document>(); iterable.forEach(new Block<Document>() { @Override public void apply(Document document) { result.put( (Integer) document.get("_id"), document); } }); assertEquals(document1.toJson(), result.get(0).toJson()); assertEquals(document2.toJson(), result.get(1).toJson()); assertEquals(document3.toJson(), result.get(2).toJson()); } @Test public void AValid$Project$filterPipelineWithMultiFunction_AValidDocuments_thenReturnAProjectedDocument(){ Document item1_1 = new Document("item_id", 43).append("quantity", 2).append("price", 10); Document item1_2 = new Document("item_id", 2).append("quantity", 1).append("price", 240); Document document1 = new Document("_id", 0).append("items", Arrays.asList(item1_1, item1_2)); Document item2_1 = new Document("item_id", 23).append("quantity", 3).append("price", 110); Document item2_2 = new Document("item_id", 103).append("quantity", 4).append("price", 5); Document item2_3 = new Document("item_id", 38).append("quantity", 1).append("price", 300); Document document2 = new Document("_id", 1).append("items", Arrays.asList(item2_1, item2_2, item2_3)); Document item3_1 = new Document("item_id", 4).append("quantity", 1).append("price", 23); Document document3 = new Document("_id", 2).append("items", Arrays.asList(item3_1)); collection.insertMany(Arrays.asList(document1, document2, document3)); Document under_filter = new Document(); under_filter.append("input", "$items") .append("as", "item") .append("cond", new Document("$and", Arrays.asList(new Document("$gte", Arrays.asList("$$item.price", 100)), new Document("$lte", Arrays.asList("$$item.price", 250)))));//new Document("$gte", Arrays.asList("$$item.price", 100))); Document filter = new Document("$filter", under_filter); Document items = new Document("items", filter); Document pipeline = new Document("$project", items); Document itemResult1_1 = new Document("item_id", 2).append("quantity", 1).append("price", 240); Document documentResult1 = new Document("_id", 0).append("items", Arrays.asList(itemResult1_1)); Document itemResult2_1 = new Document("item_id", 23).append("quantity", 3).append("price", 110); Document documentResult2 = new Document("_id", 1).append("items", Arrays.asList(itemResult2_1)); Document documentResult3 = new Document("_id", 2).append("items", Arrays.asList()); AggregateIterable<Document> iterable = collection.aggregate(Arrays.asList(pipeline)); final Map<Integer, Document> result = new HashMap<Integer, Document>(); iterable.forEach(new Block<Document>() { @Override public void apply(Document document) { result.put( (Integer) document.get("_id"), document); } }); assertEquals(documentResult1.toJson(), result.get(0).toJson()); assertEquals(documentResult2.toJson(), result.get(1).toJson()); assertEquals(documentResult3.toJson(), result.get(2).toJson()); } @Test public void AValid$Project$filterPipelineWith$anyElementTrue_AValidDocuments_thenReturnNotProjectedDocument(){ Document item1_1 = new Document("item_id", 43).append("quantity", 2).append("price", 10); Document item1_2 = new Document("item_id", 2).append("quantity", 1).append("price", 240); Document document1 = new Document("_id", 0).append("items", Arrays.asList(item1_1, item1_2)); Document item2_1 = new Document("item_id", 23).append("quantity", 3).append("price", 110); Document item2_2 = new Document("item_id", 103).append("quantity", 4).append("price", 5); Document item2_3 = new Document("item_id", 38).append("quantity", 1).append("price", 300); Document document2 = new Document("_id", 1).append("items", Arrays.asList(item2_1, item2_2, item2_3)); Document item3_1 = new Document("item_id", 4).append("quantity", 1).append("price", 23); Document document3 = new Document("_id", 2).append("items", Arrays.asList(item3_1)); collection.insertMany(Arrays.asList(document1, document2, document3)); Document under_filter = new Document(); under_filter.append("input", "$items") .append("as", "item") .append("cond", new Document("$anyElementTrue", Arrays.asList(Arrays.asList(true, false)))); Document filter = new Document("$filter", under_filter); Document items = new Document("items", filter); Document pipeline = new Document("$project", items); AggregateIterable<Document> iterable = collection.aggregate(Arrays.asList(pipeline)); final Map<Integer, Document> result = new HashMap<Integer, Document>(); iterable.forEach(new Block<Document>() { @Override public void apply(Document document) { result.put( (Integer) document.get("_id"), document); } }); assertEquals(document1.toJson(), result.get(0).toJson()); assertEquals(document2.toJson(), result.get(1).toJson()); assertEquals(document3.toJson(), result.get(2).toJson()); } }
package harness.utils; import bio.terra.cli.service.utils.HttpUtils; import bio.terra.cloudres.google.storage.BucketCow; import bio.terra.cloudres.google.storage.StorageCow; import com.google.auth.oauth2.GoogleCredentials; import com.google.cloud.Identity; import com.google.cloud.Policy; import com.google.cloud.Role; import com.google.cloud.storage.BlobId; import com.google.cloud.storage.BlobInfo; import com.google.cloud.storage.BucketInfo; import com.google.cloud.storage.Storage; import com.google.cloud.storage.StorageClass; import com.google.cloud.storage.StorageException; import com.google.cloud.storage.StorageOptions; import com.google.cloud.storage.StorageRoles; import com.google.common.base.Optional; import harness.CRLJanitor; import harness.TestExternalResources; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.UUID; import org.apache.http.HttpStatus; /** * Utility methods for creating external GCS buckets for testing workspace references. Most methods * in the class use the CRL wrapper around the GCS client library to manipulate external buckets. * This class also includes a method to build the unwrapped GCS client object, which is what we * would expect users to call. Setup/cleanup of external buckets should use the CRL wrapper. * Fetching information from the cloud as a user may do should use the unwrapped client object. */ public class ExternalGCSBuckets { public static BucketInfo createBucket() throws IOException { String bucketName = UUID.randomUUID().toString(); StorageClass storageClass = StorageClass.STANDARD; String location = "US"; BucketCow bucket = getStorageCow() .create( BucketInfo.newBuilder(bucketName) .setStorageClass(storageClass) .setLocation(location) .build()); BucketInfo bucketInfo = bucket.getBucketInfo(); System.out.println( "Created bucket " + bucketInfo.getName() + " in " + bucketInfo.getLocation() + " with storage class " + bucketInfo.getStorageClass() + " in project " + TestExternalResources.getProjectId()); return bucketInfo; } public static void deleteBucket(BucketInfo bucketInfo) throws IOException { getStorageCow().delete(bucketInfo.getName()); } /** * Grant a given user or group object viewer access to a bucket. This method uses SA credentials * to set IAM policy on a bucket in an external (to WSM) project. */ public static void grantReadAccess(BucketInfo bucketInfo, Identity userOrGroup) throws IOException { grantAccess(bucketInfo, userOrGroup, StorageRoles.objectViewer()); } /** * Grant a given user or group admin access to a bucket. This method uses SA credentials to set * IAM policy on a bucket in an external (to WSM) project. */ public static void grantWriteAccess(BucketInfo bucketInfo, Identity userOrGroup) throws IOException { grantAccess(bucketInfo, userOrGroup, StorageRoles.admin()); } /** * Helper method to grant a given user or group roles on a bucket. This method uses SA credentials * to set IAM policy on a bucket in an external (to WSM) project. */ private static void grantAccess(BucketInfo bucketInfo, Identity userOrGroup, Role... roles) throws IOException { StorageCow storage = getStorageCow(); Policy currentPolicy = storage.getIamPolicy(bucketInfo.getName()); Policy.Builder updatedPolicyBuilder = currentPolicy.toBuilder(); for (Role role : roles) { updatedPolicyBuilder.addIdentity(role, userOrGroup); } storage.setIamPolicy(bucketInfo.getName(), updatedPolicyBuilder.build()); } /** Utility method to write an arbitrary blob to a bucket. */ public static void writeBlob(GoogleCredentials credentials, String bucketName, String blobName) throws InterruptedException { Storage storageClient = getStorageClient(credentials); BucketInfo bucket = storageClient.get(bucketName); BlobId blobId = BlobId.of(bucket.getName(), blobName); BlobInfo blobInfo = BlobInfo.newBuilder(blobId).build(); byte[] blobData = "test blob data".getBytes(StandardCharsets.UTF_8); // retry forbidden errors because we often see propagation delays when a user is just granted // access HttpUtils.callWithRetries( () -> { storageClient.create(blobInfo, blobData); return null; }, (ex) -> (ex instanceof StorageException) && ((StorageException) ex).getCode() == HttpStatus.SC_FORBIDDEN, 5, Duration.ofMinutes(1)); } private static StorageCow getStorageCow() throws IOException { StorageOptions options = StorageOptions.newBuilder() .setCredentials(TestExternalResources.getSACredentials()) .setProjectId(TestExternalResources.getProjectId()) .build(); return new StorageCow(CRLJanitor.DEFAULT_CLIENT_CONFIG, options); } /** * Helper method to build the GCS client object with the given credentials. Note this is not * wrapped by CRL because this is what we expect most users to use. */ public static Storage getStorageClient(GoogleCredentials credentials) { return StorageOptions.newBuilder() .setProjectId(TestExternalResources.getProjectId()) .setCredentials(credentials) .build() .getService(); } /** Utility method to get the gs:// path of a bucket. */ public static String getGsPath(String bucketName) { return getGsPath(bucketName, Optional.absent()); } public static String getGsPath(String bucketName, Optional<String> filePath) { if (filePath.isPresent()) { return "gs://" + bucketName + "/" + filePath.get(); } else { return "gs://" + bucketName; } } }
package net.fortuna.ical4j.model; import java.io.Serializable; import java.util.Iterator; import net.fortuna.ical4j.model.property.XProperty; import net.fortuna.ical4j.util.PropertyValidator; /** * Defines an iCalendar calendar. * * <pre> * 4.6 Calendar Components * * The body of the iCalendar object consists of a sequence of calendar * properties and one or more calendar components. The calendar * properties are attributes that apply to the calendar as a whole. The * calendar components are collections of properties that express a * particular calendar semantic. For example, the calendar component can * specify an event, a to-do, a journal entry, time zone information, or * free/busy time information, or an alarm. * * The body of the iCalendar object is defined by the following * notation: * * icalbody = calprops component * * calprops = 2*( * * ; 'prodid' and 'version' are both REQUIRED, * ; but MUST NOT occur more than once * * prodid /version / * * ; 'calscale' and 'method' are optional, * ; but MUST NOT occur more than once * * calscale / * method / * * x-prop * * ) * * component = 1*(eventc / todoc / journalc / freebusyc / * / timezonec / iana-comp / x-comp) * * iana-comp = "BEGIN" ":" iana-token CRLF * * 1*contentline * * "END" ":" iana-token CRLF * * x-comp = "BEGIN" ":" x-name CRLF * * 1*contentline * * "END" ":" x-name CRLF * </pre> * * Example 1 - Creating a new calendar: * * <pre><code> * Calendar calendar = new Calendar(); * calendar.getProperties().add(new ProdId("-//Ben Fortuna//iCal4j 1.0//EN")); * calendar.getProperties().add(Version.VERSION_2_0); * calendar.getProperties().add(CalScale.GREGORIAN); * * // Add events, etc.. * </code></pre> * * @author Ben Fortuna */ public class Calendar implements Serializable { private static final long serialVersionUID = -1654118204678581940L; public static final String BEGIN = "BEGIN"; public static final String VCALENDAR = "VCALENDAR"; public static final String END = "END"; private PropertyList properties; private ComponentList components; /** * Default constructor. */ public Calendar() { this(new PropertyList(), new ComponentList()); } /** * Constructs a new calendar with no properties and * the specified components. * @param components a list of components to add to * the calendar */ public Calendar(final ComponentList components) { this(new PropertyList(), components); } /** * Constructor. * * @param p * a list of properties * @param c * a list of components */ public Calendar(final PropertyList p, final ComponentList c) { this.properties = p; this.components = c; } /** * @see java.lang.Object#toString() */ public final String toString() { StringBuffer buffer = new StringBuffer(); buffer.append(BEGIN); buffer.append(':'); buffer.append(VCALENDAR); buffer.append("\r\n"); buffer.append(getProperties()); buffer.append(getComponents()); buffer.append(END); buffer.append(':'); buffer.append(VCALENDAR); buffer.append("\r\n"); return buffer.toString(); } /** * @return Returns the components. */ public final ComponentList getComponents() { return components; } /** * @return Returns the properties. */ public final PropertyList getProperties() { return properties; } /** * Perform validation on the calendar, its properties * and its components in its current state. * @throws ValidationException * where the calendar is not in a valid state */ public final void validate() throws ValidationException { validate(true); } /** * Perform validation on the calendar in its current state. * @param recurse indicates whether to validate the calendar's * properties and components * @throws ValidationException * where the calendar is not in a valid state */ public final void validate(final boolean recurse) throws ValidationException { // 'prodid' and 'version' are both REQUIRED, // but MUST NOT occur more than once PropertyValidator.getInstance().validateOne(Property.PRODID, properties); PropertyValidator.getInstance().validateOne(Property.VERSION, properties); // 'calscale' and 'method' are optional, // but MUST NOT occur more than once PropertyValidator.getInstance() .validateOneOrLess(Property.CALSCALE, properties); PropertyValidator.getInstance().validateOneOrLess(Property.METHOD, properties); // must contain at least one component if (getComponents().isEmpty()) { throw new ValidationException( "Calendar must contain at least one component"); } // validate properties.. for (Iterator i = getProperties().iterator(); i.hasNext();) { Property property = (Property) i.next(); if (!(property instanceof XProperty) && !property.isCalendarProperty()) { throw new IllegalArgumentException( "Invalid property: " + property.getName()); } } // validate components.. for (Iterator i = getComponents().iterator(); i.hasNext();) { Component component = (Component) i.next(); if (!component.isCalendarComponent()) { throw new IllegalArgumentException( "Invalid component: " + component.getName()); } } if (recurse) { validateProperties(); validateComponents(); } } /** * Invoke validation on the calendar properties in its current state. * @throws ValidationException * where any of the calendar properties is not in a valid state */ private void validateProperties() throws ValidationException { for (Iterator i = getProperties().iterator(); i.hasNext();) { Property property = (Property) i.next(); property.validate(); } } /** * Invoke validation on the calendar components in its current state. * @throws ValidationException * where any of the calendar components is not in a valid state */ private void validateComponents() throws ValidationException { for (Iterator i = getComponents().iterator(); i.hasNext();) { Component component = (Component) i.next(); component.validate(); } } }
package io.netty.buffer; import org.perf4j.LoggingStopWatch; import org.perf4j.StopWatch; public final class SavingsBenchmark { private static final class Savings { final double memory; final double time; private Savings(final double memory, final double time) { this.memory = memory; this.time = time; } private static String getQuantified(final double value) { if (value >= 0.0d) { return String.format("%.2f%% less", 100.0d * Math.abs(value)); } else { return String.format("%.2f%% more", 100.0d * Math.abs(value + 1.0d)); } } @Override public String toString() { return String.format("used %s memory and %s time", getQuantified(memory), getQuantified(time)); } static Savings of(final BufferResult first, final BufferResult second) { final double memory = 1.0d - (double) first.memory / (double) second.memory; final double time = 1.0d - (double) first.time / (double) second.time; return new Savings(memory, time); } } private static class BufferResult { final long time; final int memory; private BufferResult(final StopWatch time, final int memory) { this.time = time.getElapsedTime(); this.memory = memory; } } private static BufferResult makeConsumptionResult(final StopWatch stopwatch, final ByteBuf buf) { final int memory = buf.readableBytes(); buf.clear(); buf.discardReadBytes(); buf.release(); return new BufferResult(stopwatch, memory); } private static BufferResult testBufferConsumption(final int n, final ByteBuf buf) { final StopWatch stopWatch = new LoggingStopWatch(); stopWatch.start(); for (int i = 0; i < n; i++) { buf.writeLong((long) i); } stopWatch.stop("growing " + buf.getClass().getSimpleName()); return makeConsumptionResult(stopWatch, buf); } private static BufferResult testBufferConsumption(final int n, final long value, final ByteBuf buf) { final StopWatch stopWatch = new LoggingStopWatch(); stopWatch.start(); for (int i = 0; i < n; i++) { buf.writeLong(value); } stopWatch.stop("7-bit " + buf.getClass().getSimpleName()); return makeConsumptionResult(stopWatch, buf); } private static ByteBuf regular() { return Unpooled.buffer(); } private static ByteBuf regularSized(final int size) { return Unpooled.buffer(size * Long.SIZE); } private static ByteBuf variable() { return VByteBuf.wrap(regular()); } private static ByteBuf variableSized(final int size) { return VByteBuf.wrap(regularSized(size)); } public static void showSavings(final boolean warmup) { System.out.println(warmup ? "Just warmup... " : "Here we go!"); final int n = 100000000; final long value = 64L; final Savings fixWithResizing = Savings.of(testBufferConsumption(n, value, variable()), testBufferConsumption(n, value, regular())); if (!warmup) { System.out.println("writing 7-bit long with resizing " + fixWithResizing); } final Savings growingWithResizing = Savings.of(testBufferConsumption(n, variable()), testBufferConsumption(n, regular())); if (!warmup) { System.out.println("writing growing long with resizing " + growingWithResizing); } final Savings fixWithoutResizing = Savings.of(testBufferConsumption(n, value, variableSized(n)), testBufferConsumption(n, value, regularSized(n))); if (!warmup) { System.out.println("writing 7-bit long without resizing " + fixWithoutResizing); } final Savings growingWithoutResizing = Savings.of(testBufferConsumption(n, variableSized(n)), testBufferConsumption(n, regularSized(n))); if (!warmup) { System.out.println("writing growing long without resizing " + growingWithoutResizing); } } public static void main(final String... args) { showSavings(true); showSavings(false); } }