answer
stringlengths
17
10.2M
package ru.matevosyan.start; import ru.matevosyan.models.Item; import java.util.Random; public class Tracker { /** * final variable int ITEMS_CAP is items array capacity. */ private static final int ITEMS_CAP = 3; /** * Instance variable items which is array types is hold all created items. */ private Item[] items = new Item[ITEMS_CAP]; /** * int variable position is hold position elements in array items. */ private int position = 0; /** *Instance variable RM is created for value for items id. */ private Random RM = new Random(); /** * Method add created for add new item to array items. * it's may the specific type of item, for example: new Task or new Bug. * @param item which is the new item. * @return item that added to the items array */ public Item add(Item item) { item.setId(this.generateId()); this.items[position] = item; position++; return item; } /** * Method deleteItem created for deleted exist item from array of items. * it's may remove the specific type of item: Task or Bug. * @param id it is for determine which of this specific item must be deleted. * @return itemsDelete array without deleted item */ public Item[] deleteItem(String id) { Item[] itemsDelete = new Item[items.length-1]; //Item[] item = new Item[items.length]; for (int i = 0; i < items.length; i++) { //item[i] = items[i]; if (items[i] != null && items[i].getId().equals(id)) { for (int j = 0; j < items.length-1; j++) { items[j] = items[j + 1]; } } } for (int i = 0; i < items.length -1; i++) { itemsDelete[i] = items[i]; } return itemsDelete; } /** * Method editItem created for edit exist item from array of items. * it's may edit the specific type of item: Task or Bug. * @param fresh it is specific item that you want to edit. */ public void editItem(Item fresh) { for (int index = 0; index < items.length; index++) { Item item = items[index]; if (item.getId().equals(fresh.getId())) { items[index] = fresh; break; } } } /** * Method findById created for find exist item from array of items passing through method item's id. * @param id it is specific item's id that item's would you like to find out. * @return resultFindById it's concrete item that you find out */ public Item findById(String id) { Item resultFindById = null; for (Item item : items) { if (item != null && item.getId().equals(id)) { resultFindById = item; break; } } return resultFindById; } /** * Method findByName created for find exist item from array of items passing through method item's name. * @param name it is specific item's id that item's would you like to find out. * @return resultFindByName it's concrete item that you find out */ public Item findByName(String name) { Item resultFindByName = null; for (Item item : items) { if (item != null && item.getName().equals(name)) { resultFindByName = item; } } return resultFindByName; } /** * Method findByyDate created for find exist item from array of items passing through method item's created date. * @param create it is concrete item's created date that item's would you like to find out. * @return resultFindByyDate it's concrete item that you find out */ public Item findByDate(long create) { Item resultFindByDate = null; for (Item item : items) { if (item != null && item.getCreate() == (create)) { resultFindByDate = item; } } return resultFindByDate; } /** * Method generateId created for generate items id. * @return generated id number */ private String generateId() { final int idDev = 1_000_000; return String.valueOf(Math.abs(RM.nextInt()/idDev)); } /** * Method getAll created for getting all of exist item from array of items. * @return itemsDelete array without deleted item */ public Item[] getAll() { Item[] result = new Item[this.position]; for (int index = 0; index != this.position; index++) { result[index] = this.items[index]; } return result; } /** * Method addComment using for adding comment to the item. * @param item it is item that you want to comment * @param comment it is comment that you passing to the method to add to your item */ public void addComment(Item item, String comment) { item.addComment(comment); } }
package com.osmbonuspackdemo; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.osmdroid.ResourceProxy; import org.osmdroid.api.IGeoPoint; import org.osmdroid.api.IMapController; import org.osmdroid.bonuspack.kml.KmlObject; import org.osmdroid.bonuspack.kml.KmlProvider; import org.osmdroid.bonuspack.location.FlickrPOIProvider; import org.osmdroid.bonuspack.location.GeoNamesPOIProvider; import org.osmdroid.bonuspack.location.GeocoderNominatim; import org.osmdroid.bonuspack.location.NominatimPOIProvider; import org.osmdroid.bonuspack.location.POI; import org.osmdroid.bonuspack.location.PicasaPOIProvider; import org.osmdroid.bonuspack.overlays.ExtendedOverlayItem; import org.osmdroid.bonuspack.overlays.FolderOverlay; import org.osmdroid.bonuspack.overlays.ItemizedOverlayWithBubble; import org.osmdroid.bonuspack.overlays.MapEventsOverlay; import org.osmdroid.bonuspack.overlays.MapEventsReceiver; import org.osmdroid.bonuspack.overlays.Polygon; import org.osmdroid.bonuspack.overlays.Polyline; import org.osmdroid.bonuspack.routing.GoogleRoadManager; import org.osmdroid.bonuspack.routing.MapQuestRoadManager; import org.osmdroid.bonuspack.routing.OSRMRoadManager; import org.osmdroid.bonuspack.routing.Road; import org.osmdroid.bonuspack.routing.RoadManager; import org.osmdroid.bonuspack.routing.RoadNode; import org.osmdroid.tileprovider.MapTileProviderBase; import org.osmdroid.tileprovider.tilesource.ITileSource; import org.osmdroid.tileprovider.tilesource.OnlineTileSourceBase; import org.osmdroid.tileprovider.tilesource.TileSourceFactory; import org.osmdroid.tileprovider.tilesource.XYTileSource; import org.osmdroid.util.BoundingBoxE6; import org.osmdroid.util.GeoPoint; import org.osmdroid.util.NetworkLocationIgnorer; import org.osmdroid.views.MapView; import org.osmdroid.views.overlay.DirectedLocationOverlay; import org.osmdroid.views.overlay.Overlay; import org.osmdroid.views.overlay.OverlayItem; 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.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.location.Address; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.AsyncTask; import android.os.Bundle; import android.text.InputType; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MapActivity extends Activity implements MapEventsReceiver, LocationListener, SensorEventListener { protected MapView map; protected GeoPoint startPoint, destinationPoint; protected ArrayList<GeoPoint> viaPoints; protected static int START_INDEX=-2, DEST_INDEX=-1; protected ItemizedOverlayWithBubble<ExtendedOverlayItem> itineraryMarkers; //for departure, destination and viapoints protected ExtendedOverlayItem markerStart, markerDestination; DirectedLocationOverlay myLocationOverlay; //MyLocationNewOverlay myLocationNewOverlay; protected LocationManager locationManager; //protected SensorManager mSensorManager; //protected Sensor mOrientation; protected boolean mTrackingMode; Button mTrackingModeButton; float mAzimuthAngleSpeed = 0.0f; protected Polygon destinationPolygon; //enclosing polygon of destination location public static Road mRoad; //made static to pass between activities protected Polyline roadOverlay; protected ItemizedOverlayWithBubble<ExtendedOverlayItem> roadNodeMarkers; protected static final int ROUTE_REQUEST = 1; static final int OSRM=0, MAPQUEST_FASTEST=1, MAPQUEST_BICYCLE=2, MAPQUEST_PEDESTRIAN=3, GOOGLE_FASTEST=4; int whichRouteProvider; public static ArrayList<POI> mPOIs; //made static to pass between activities ItemizedOverlayWithBubble<ExtendedOverlayItem> poiMarkers; AutoCompleteTextView poiTagText; protected static final int POIS_REQUEST = 2; protected FolderOverlay kmlOverlay; //root container of overlays from KML reading protected KmlObject kmlRoot; //root container in KmlObject representation protected static final int KML_TREE_REQUEST = 3; public static KmlProvider mKmlProvider = new KmlProvider(); //made static to pass between activities static String SHARED_PREFS_APPKEY = "OSMNavigator"; static String PREF_LOCATIONS_KEY = "PREF_LOCATIONS"; OnlineTileSourceBase MAPBOXSATELLITELABELLED; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); SharedPreferences prefs = getSharedPreferences("OSMNAVIGATOR", MODE_PRIVATE); //Integrating MapBox Satellite map, which is really an impressive service. //We stole OSRM account at MapBox. Hope we will be forgiven... MAPBOXSATELLITELABELLED = new XYTileSource("MapBoxSatelliteLabelled", ResourceProxy.string.mapquest_aerial, 1, 19, 256, ".png", "http://a.tiles.mapbox.com/v3/dennisl.map-6g3jtnzm/", "http://b.tiles.mapbox.com/v3/dennisl.map-6g3jtnzm/", "http://c.tiles.mapbox.com/v3/dennisl.map-6g3jtnzm/", "http://d.tiles.mapbox.com/v3/dennisl.map-6g3jtnzm/"); TileSourceFactory.addTileSource(MAPBOXSATELLITELABELLED); map = (MapView) findViewById(R.id.map); String tileProviderName = prefs.getString("TILE_PROVIDER", "Mapnik"); try { ITileSource tileSource = TileSourceFactory.getTileSource(tileProviderName); map.setTileSource(tileSource); } catch (IllegalArgumentException e) { map.setTileSource(TileSourceFactory.MAPNIK); } map.setBuiltInZoomControls(true); map.setMultiTouchControls(true); IMapController mapController = map.getController(); //To use MapEventsReceiver methods, we add a MapEventsOverlay: MapEventsOverlay overlay = new MapEventsOverlay(this, this); map.getOverlays().add(overlay); locationManager = (LocationManager)getSystemService(LOCATION_SERVICE); //mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); //mOrientation = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION); //map prefs: mapController.setZoom(prefs.getInt("MAP_ZOOM_LEVEL", 5)); mapController.setCenter(new GeoPoint((double)prefs.getFloat("MAP_CENTER_LAT", 48.5f), (double)prefs.getFloat("MAP_CENTER_LON", 2.5f))); myLocationOverlay = new DirectedLocationOverlay(this); map.getOverlays().add(myLocationOverlay); if (savedInstanceState == null){ Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (location == null) location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (location != null) { //location known: onLocationChanged(location); } else { //no location known: hide myLocationOverlay myLocationOverlay.setEnabled(false); } startPoint = null; destinationPoint = null; viaPoints = new ArrayList<GeoPoint>(); } else { myLocationOverlay.setLocation((GeoPoint)savedInstanceState.getParcelable("location")); //TODO: restore other aspects of myLocationOverlay... startPoint = savedInstanceState.getParcelable("start"); destinationPoint = savedInstanceState.getParcelable("destination"); viaPoints = savedInstanceState.getParcelableArrayList("viapoints"); } //ScaleBarOverlay scaleBarOverlay = new ScaleBarOverlay(this); //map.getOverlays().add(scaleBarOverlay); // Itinerary markers: final ArrayList<ExtendedOverlayItem> waypointsItems = new ArrayList<ExtendedOverlayItem>(); itineraryMarkers = new ItemizedOverlayWithBubble<ExtendedOverlayItem>(this, waypointsItems, map, new ViaPointInfoWindow(R.layout.itinerary_bubble, map)); map.getOverlays().add(itineraryMarkers); updateUIWithItineraryMarkers(); //Tracking system: mTrackingModeButton = (Button)findViewById(R.id.buttonTrackingMode); mTrackingModeButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { mTrackingMode = !mTrackingMode; updateUIWithTrackingMode(); } }); if (savedInstanceState != null){ mTrackingMode = savedInstanceState.getBoolean("tracking_mode"); updateUIWithTrackingMode(); } else mTrackingMode = false; AutoCompleteOnPreferences departureText = (AutoCompleteOnPreferences) findViewById(R.id.editDeparture); departureText.setPrefKeys(SHARED_PREFS_APPKEY, PREF_LOCATIONS_KEY); Button searchDepButton = (Button)findViewById(R.id.buttonSearchDep); searchDepButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { handleSearchButton(START_INDEX, R.id.editDeparture); } }); AutoCompleteOnPreferences destinationText = (AutoCompleteOnPreferences) findViewById(R.id.editDestination); destinationText.setPrefKeys(SHARED_PREFS_APPKEY, PREF_LOCATIONS_KEY); Button searchDestButton = (Button)findViewById(R.id.buttonSearchDest); searchDestButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { handleSearchButton(DEST_INDEX, R.id.editDestination); } }); View expander = (View)findViewById(R.id.expander); expander.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { View searchPanel = (View)findViewById(R.id.search_panel); if (searchPanel.getVisibility() == View.VISIBLE){ searchPanel.setVisibility(View.GONE); } else { searchPanel.setVisibility(View.VISIBLE); } } }); View searchPanel = (View)findViewById(R.id.search_panel); searchPanel.setVisibility(prefs.getInt("PANEL_VISIBILITY", View.VISIBLE)); registerForContextMenu(searchDestButton); //context menu for clicking on the map is registered on this button. //(a little bit strange, but if we register it on mapView, it will catch map drag events) //Route and Directions whichRouteProvider = prefs.getInt("ROUTE_PROVIDER", OSRM); final ArrayList<ExtendedOverlayItem> roadItems = new ArrayList<ExtendedOverlayItem>(); roadNodeMarkers = new ItemizedOverlayWithBubble<ExtendedOverlayItem>(this, roadItems, map); map.getOverlays().add(roadNodeMarkers); if (savedInstanceState != null){ //STATIC mRoad = savedInstanceState.getParcelable("road"); updateUIWithRoad(mRoad); } //POIs: //POI search interface: String[] poiTags = getResources().getStringArray(R.array.poi_tags); poiTagText = (AutoCompleteTextView) findViewById(R.id.poiTag); ArrayAdapter<String> poiAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, poiTags); poiTagText.setAdapter(poiAdapter); Button setPOITagButton = (Button) findViewById(R.id.buttonSetPOITag); setPOITagButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //Hide the soft keyboard: InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(poiTagText.getWindowToken(), 0); //Start search: String feature = poiTagText.getText().toString(); if (!feature.equals("")) Toast.makeText(v.getContext(), "Searching:\n"+feature, Toast.LENGTH_LONG).show(); getPOIAsync(feature); } }); //POI markers: final ArrayList<ExtendedOverlayItem> poiItems = new ArrayList<ExtendedOverlayItem>(); poiMarkers = new ItemizedOverlayWithBubble<ExtendedOverlayItem>(this, poiItems, map, new POIInfoWindow(map)); map.getOverlays().add(poiMarkers); if (savedInstanceState != null){ //STATIC - mPOIs = savedInstanceState.getParcelableArrayList("poi"); updateUIWithPOI(mPOIs); } //KML handling: kmlOverlay = null; if (savedInstanceState != null){ kmlRoot = savedInstanceState.getParcelable("kml"); updateUIWithKml(); } else { //first launch: check if intent has been passed with a kml URI to load (url or file) Intent onCreateIntent = getIntent(); if (onCreateIntent.getAction().equals(Intent.ACTION_VIEW)){ String uri = onCreateIntent.getDataString(); getKml(uri); } else { //Empty folder by default: kmlRoot = new KmlObject(); kmlRoot.createAsFolder(); } } } void setViewOn(BoundingBoxE6 bb){ if (bb != null){ map.zoomToBoundingBox(bb); } } void savePrefs(){ SharedPreferences prefs = getSharedPreferences("OSMNAVIGATOR", MODE_PRIVATE); SharedPreferences.Editor ed = prefs.edit(); ed.putInt("MAP_ZOOM_LEVEL", map.getZoomLevel()); GeoPoint c = (GeoPoint) map.getMapCenter(); ed.putFloat("MAP_CENTER_LAT", c.getLatitudeE6()*1E-6f); ed.putFloat("MAP_CENTER_LON", c.getLongitudeE6()*1E-6f); MapTileProviderBase tileProvider = map.getTileProvider(); String tileProviderName = tileProvider.getTileSource().name(); View searchPanel = (View)findViewById(R.id.search_panel); ed.putInt("PANEL_VISIBILITY", searchPanel.getVisibility()); ed.putString("TILE_PROVIDER", tileProviderName); ed.putInt("ROUTE_PROVIDER", whichRouteProvider); ed.commit(); } /** * callback to store activity status before a restart (orientation change for instance) */ @Override protected void onSaveInstanceState (Bundle outState){ outState.putParcelable("location", myLocationOverlay.getLocation()); outState.putBoolean("tracking_mode", mTrackingMode); outState.putParcelable("start", startPoint); outState.putParcelable("destination", destinationPoint); outState.putParcelableArrayList("viapoints", viaPoints); //STATIC - outState.putParcelable("road", mRoad); //STATIC - outState.putParcelableArrayList("poi", mPOIs); outState.putParcelable("kml", kmlRoot); savePrefs(); } @Override protected void onActivityResult (int requestCode, int resultCode, Intent intent) { switch (requestCode) { case ROUTE_REQUEST : if (resultCode == RESULT_OK) { int nodeId = intent.getIntExtra("NODE_ID", 0); map.getController().setCenter(mRoad.mNodes.get(nodeId).mLocation); roadNodeMarkers.showBubbleOnItem(nodeId, map, true); } break; case POIS_REQUEST: if (resultCode == RESULT_OK) { int id = intent.getIntExtra("ID", 0); map.getController().setCenter(mPOIs.get(id).mLocation); poiMarkers.showBubbleOnItem(id, map, true); } break; case KML_TREE_REQUEST: if (resultCode == RESULT_OK) { kmlRoot = intent.getParcelableExtra("KML"); updateUIWithKml(); } break; default: break; } } /* String getBestProvider(){ String bestProvider = null; //bestProvider = locationManager.getBestProvider(new Criteria(), true); // => returns "Network Provider"! if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) bestProvider = LocationManager.GPS_PROVIDER; else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) bestProvider = LocationManager.NETWORK_PROVIDER; return bestProvider; } */ boolean startLocationUpdates(){ boolean result = false; for (final String provider : locationManager.getProviders(true)) { locationManager.requestLocationUpdates(provider, 2*1000, 0.0f, this); result = true; } return result; } @Override protected void onResume() { super.onResume(); boolean isOneProviderEnabled = startLocationUpdates(); myLocationOverlay.setEnabled(isOneProviderEnabled); //TODO: not used currently //mSensorManager.registerListener(this, mOrientation, SensorManager.SENSOR_DELAY_NORMAL); //sensor listener is causing a high CPU consumption... } @Override protected void onPause() { super.onPause(); locationManager.removeUpdates(this); //TODO: mSensorManager.unregisterListener(this); savePrefs(); } /** * Test MyItemizedOverlay object */ public void putMyItemizedOverlay(GeoPoint p){ ArrayList<OverlayItem> list = new ArrayList<OverlayItem>(); MyItemizedOverlay myOverlays = new MyItemizedOverlay(this, list); OverlayItem overlayItem = new OverlayItem("Home Sweet Home", "This is the place I live", p); overlayItem.setMarkerHotspot(OverlayItem.HotspotPlace.BOTTOM_CENTER); Drawable marker = getResources().getDrawable(R.drawable.marker_departure); overlayItem.setMarker(marker); myOverlays.addItem(overlayItem); map.getOverlays().add(myOverlays); map.invalidate(); } void updateUIWithTrackingMode(){ if (mTrackingMode){ mTrackingModeButton.setBackgroundResource(R.drawable.btn_tracking_on); if (myLocationOverlay.isEnabled()&& myLocationOverlay.getLocation() != null){ map.getController().animateTo(myLocationOverlay.getLocation()); } map.setMapOrientation(-mAzimuthAngleSpeed); mTrackingModeButton.setKeepScreenOn(true); } else { mTrackingModeButton.setBackgroundResource(R.drawable.btn_tracking_off); map.setMapOrientation(0.0f); mTrackingModeButton.setKeepScreenOn(false); } } /** * Reverse Geocoding */ public String getAddress(GeoPoint p){ GeocoderNominatim geocoder = new GeocoderNominatim(this); String theAddress; try { double dLatitude = p.getLatitudeE6() * 1E-6; double dLongitude = p.getLongitudeE6() * 1E-6; List<Address> addresses = geocoder.getFromLocation(dLatitude, dLongitude, 1); StringBuilder sb = new StringBuilder(); if (addresses.size() > 0) { Address address = addresses.get(0); int n = address.getMaxAddressLineIndex(); for (int i=0; i<=n; i++) { if (i!=0) sb.append(", "); sb.append(address.getAddressLine(i)); } theAddress = new String(sb.toString()); } else { theAddress = null; } } catch (IOException e) { theAddress = null; } if (theAddress != null) { return theAddress; } else { return ""; } } /** * Geocoding of the departure or destination address */ public void handleSearchButton(int index, int editResId){ EditText locationEdit = (EditText)findViewById(editResId); //Hide the soft keyboard: InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(locationEdit.getWindowToken(), 0); String locationAddress = locationEdit.getText().toString(); if (locationAddress.equals("")){ removePoint(index); map.invalidate(); return; } Toast.makeText(this, "Searching:\n"+locationAddress, Toast.LENGTH_LONG).show(); AutoCompleteOnPreferences.storePreference(this, locationAddress, SHARED_PREFS_APPKEY, PREF_LOCATIONS_KEY); GeocoderNominatim geocoder = new GeocoderNominatim(this); geocoder.setOptions(true); //ask for enclosing polygon (if any) try { List<Address> foundAdresses = geocoder.getFromLocationName(locationAddress, 1); if (foundAdresses.size() == 0) { //if no address found, display an error Toast.makeText(this, "Address not found.", Toast.LENGTH_SHORT).show(); } else { Address address = foundAdresses.get(0); //get first address if (index == START_INDEX){ startPoint = new GeoPoint(address.getLatitude(), address.getLongitude()); markerStart = putMarkerItem(markerStart, startPoint, START_INDEX, R.string.departure, R.drawable.marker_departure, -1); map.getController().setCenter(startPoint); } else if (index == DEST_INDEX){ destinationPoint = new GeoPoint(address.getLatitude(), address.getLongitude()); markerDestination = putMarkerItem(markerDestination, destinationPoint, DEST_INDEX, R.string.destination, R.drawable.marker_destination, -1); map.getController().setCenter(destinationPoint); } getRoadAsync(); //get and display enclosing polygon: Bundle extras = address.getExtras(); if (extras != null && extras.containsKey("polygonpoints")){ ArrayList<GeoPoint> polygon = extras.getParcelableArrayList("polygonpoints"); //Log.d("DEBUG", "polygon:"+polygon.size()); updateUIWithPolygon(polygon); } else { updateUIWithPolygon(null); } } } catch (Exception e) { Toast.makeText(this, "Geocoding error", Toast.LENGTH_SHORT).show(); } } //add or replace the polygon overlay public void updateUIWithPolygon(ArrayList<GeoPoint> polygon){ List<Overlay> mapOverlays = map.getOverlays(); int location = -1; if (destinationPolygon != null) location = mapOverlays.indexOf(destinationPolygon); destinationPolygon = new Polygon(this); destinationPolygon.setFillColor(0x30FF0080); destinationPolygon.setStrokeColor(0x800000FF); destinationPolygon.setStrokeWidth(5.0f); BoundingBoxE6 bb = null; if (polygon != null){ destinationPolygon.setPoints(polygon); bb = BoundingBoxE6.fromGeoPoints(polygon); } if (location != -1) mapOverlays.set(location, destinationPolygon); else mapOverlays.add(destinationPolygon); if (bb != null) setViewOn(bb); map.invalidate(); } //Async task to reverse-geocode the marker position in a separate thread: private class GeocodingTask extends AsyncTask<Object, Void, String> { ExtendedOverlayItem marker; protected String doInBackground(Object... params) { marker = (ExtendedOverlayItem)params[0]; return getAddress(marker.getPoint()); } protected void onPostExecute(String result) { marker.setDescription(result); itineraryMarkers.showBubbleOnItem(marker, map, false); //open bubble on the item } } /** add (or replace) an item in markerOverlays. p position. */ public ExtendedOverlayItem putMarkerItem(ExtendedOverlayItem item, GeoPoint p, int index, int titleResId, int markerResId, int iconResId) { if (item != null){ itineraryMarkers.removeItem(item); } Drawable marker = getResources().getDrawable(markerResId); String title = getResources().getString(titleResId); ExtendedOverlayItem overlayItem = new ExtendedOverlayItem(title, "", p, this); overlayItem.setMarkerHotspot(OverlayItem.HotspotPlace.BOTTOM_CENTER); overlayItem.setMarker(marker); if (iconResId != -1) overlayItem.setImage(getResources().getDrawable(iconResId)); overlayItem.setRelatedObject(index); itineraryMarkers.addItem(overlayItem); map.invalidate(); //Start geocoding task to update the description of the marker with its address: new GeocodingTask().execute(overlayItem); return overlayItem; } public void addViaPoint(GeoPoint p){ viaPoints.add(p); putMarkerItem(null, p, viaPoints.size()-1, R.string.viapoint, R.drawable.marker_via, -1); } public void removePoint(int index){ if (index == START_INDEX){ startPoint = null; if (markerStart != null){ itineraryMarkers.removeItem(markerStart); markerStart = null; } } else if (index == DEST_INDEX){ destinationPoint = null; if (markerDestination != null){ itineraryMarkers.removeItem(markerDestination); markerDestination = null; } } else { viaPoints.remove(index); updateUIWithItineraryMarkers(); } getRoadAsync(); } public void updateUIWithItineraryMarkers(){ itineraryMarkers.removeAllItems(); //Start marker: if (startPoint != null){ markerStart = putMarkerItem(null, startPoint, START_INDEX, R.string.departure, R.drawable.marker_departure, -1); } //Via-points markers if any: for (int index=0; index<viaPoints.size(); index++){ putMarkerItem(null, viaPoints.get(index), index, R.string.viapoint, R.drawable.marker_via, -1); } //Destination marker if any: if (destinationPoint != null){ markerDestination = putMarkerItem(null, destinationPoint, DEST_INDEX, R.string.destination, R.drawable.marker_destination, -1); } } private void putRoadNodes(Road road){ roadNodeMarkers.removeAllItems(); Drawable marker = getResources().getDrawable(R.drawable.marker_node); int n = road.mNodes.size(); TypedArray iconIds = getResources().obtainTypedArray(R.array.direction_icons); for (int i=0; i<n; i++){ RoadNode node = road.mNodes.get(i); String instructions = (node.mInstructions==null ? "" : node.mInstructions); ExtendedOverlayItem nodeMarker = new ExtendedOverlayItem( "Step " + (i+1), instructions, node.mLocation, this); nodeMarker.setSubDescription(road.getLengthDurationText(node.mLength, node.mDuration)); nodeMarker.setMarkerHotspot(OverlayItem.HotspotPlace.CENTER); nodeMarker.setMarker(marker); int iconId = iconIds.getResourceId(node.mManeuverType, R.drawable.ic_empty); if (iconId != R.drawable.ic_empty){ Drawable icon = getResources().getDrawable(iconId); nodeMarker.setImage(icon); } roadNodeMarkers.addItem(nodeMarker); } } void updateUIWithRoad(Road road){ roadNodeMarkers.removeAllItems(); TextView textView = (TextView)findViewById(R.id.routeInfo); textView.setText(""); List<Overlay> mapOverlays = map.getOverlays(); if (roadOverlay != null){ mapOverlays.remove(roadOverlay); } if (road == null) return; if (road.mStatus == Road.STATUS_DEFAULT) Toast.makeText(map.getContext(), "We have a problem to get the route", Toast.LENGTH_SHORT).show(); roadOverlay = RoadManager.buildRoadOverlay(road, map.getContext()); Overlay removedOverlay = mapOverlays.set(1, roadOverlay); //we set the road overlay at the "bottom", just above the MapEventsOverlay, //to avoid covering the other overlays. mapOverlays.add(removedOverlay); putRoadNodes(road); map.invalidate(); //Set route info in the text view: textView.setText(road.getLengthDurationText(-1)); } /** * Async task to get the road in a separate thread. */ private class UpdateRoadTask extends AsyncTask<Object, Void, Road> { protected Road doInBackground(Object... params) { @SuppressWarnings("unchecked") ArrayList<GeoPoint> waypoints = (ArrayList<GeoPoint>)params[0]; RoadManager roadManager = null; Locale locale = Locale.getDefault(); switch (whichRouteProvider){ case OSRM: roadManager = new OSRMRoadManager(); break; case MAPQUEST_FASTEST: roadManager = new MapQuestRoadManager(); roadManager.addRequestOption("locale="+locale.getLanguage()+"_"+locale.getCountry()); break; case MAPQUEST_BICYCLE: roadManager = new MapQuestRoadManager(); roadManager.addRequestOption("locale="+locale.getLanguage()+"_"+locale.getCountry()); roadManager.addRequestOption("routeType=bicycle"); break; case MAPQUEST_PEDESTRIAN: roadManager = new MapQuestRoadManager(); roadManager.addRequestOption("locale="+locale.getLanguage()+"_"+locale.getCountry()); roadManager.addRequestOption("routeType=pedestrian"); break; case GOOGLE_FASTEST: roadManager = new GoogleRoadManager(); //roadManager.addRequestOption("mode=driving"); //default break; default: return null; } return roadManager.getRoad(waypoints); } protected void onPostExecute(Road result) { mRoad = result; updateUIWithRoad(result); getPOIAsync(poiTagText.getText().toString()); } } public void getRoadAsync(){ mRoad = null; GeoPoint roadStartPoint = null; if (startPoint != null){ roadStartPoint = startPoint; } else if (myLocationOverlay.isEnabled() && myLocationOverlay.getLocation() != null){ //use my current location as itinerary start point: roadStartPoint = myLocationOverlay.getLocation(); } if (roadStartPoint == null || destinationPoint == null){ updateUIWithRoad(mRoad); return; } ArrayList<GeoPoint> waypoints = new ArrayList<GeoPoint>(2); waypoints.add(roadStartPoint); //add intermediate via points: for (GeoPoint p:viaPoints){ waypoints.add(p); } waypoints.add(destinationPoint); new UpdateRoadTask().execute(waypoints); } void updateUIWithPOI(ArrayList<POI> pois){ if (pois != null){ for (POI poi:pois){ ExtendedOverlayItem poiMarker = new ExtendedOverlayItem( poi.mType, poi.mDescription, poi.mLocation, this); Drawable marker = null; if (poi.mServiceId == POI.POI_SERVICE_NOMINATIM){ marker = getResources().getDrawable(R.drawable.marker_poi); } else if (poi.mServiceId == POI.POI_SERVICE_GEONAMES_WIKIPEDIA){ if (poi.mRank < 90) marker = getResources().getDrawable(R.drawable.marker_poi_wikipedia_16); else marker = getResources().getDrawable(R.drawable.marker_poi_wikipedia_32); } else if (poi.mServiceId == POI.POI_SERVICE_FLICKR){ marker = getResources().getDrawable(R.drawable.marker_poi_flickr); } else if (poi.mServiceId == POI.POI_SERVICE_PICASA){ marker = getResources().getDrawable(R.drawable.marker_poi_picasa_24); poiMarker.setSubDescription(poi.mCategory); } poiMarker.setMarker(marker); if (poi.mServiceId == POI.POI_SERVICE_NOMINATIM){ poiMarker.setMarkerHotspot(OverlayItem.HotspotPlace.BOTTOM_CENTER); } else { poiMarker.setMarkerHotspot(OverlayItem.HotspotPlace.CENTER); } //thumbnail loading moved in POIInfoWindow.onOpen for better performances. poiMarker.setRelatedObject(poi); poiMarkers.addItem(poiMarker); } } map.invalidate(); } ExecutorService mThreadPool = Executors.newFixedThreadPool(5); /** Loads all thumbnails in background */ void startAsyncThumbnailsLoading(ArrayList<POI> pois){ /* Try to stop existing threads: * not sure it has any effect... if (mThreadPool != null){ //Stop threads if any: mThreadPool.shutdownNow(); } mThreadPool = Executors.newFixedThreadPool(5); */ for (int i=0; i<pois.size(); i++){ final int index = i; final POI poi = pois.get(index); mThreadPool.submit(new Runnable(){ @Override public void run(){ Bitmap b = poi.getThumbnail(); if (b != null){ /* //Change POI marker: ExtendedOverlayItem item = poiMarkers.getItem(index); b = Bitmap.createScaledBitmap(b, 48, 48, true); BitmapDrawable bd = new BitmapDrawable(getResources(), b); item.setMarker(bd); */ } } }); } } private class POITask extends AsyncTask<Object, Void, ArrayList<POI>> { String mTag; protected ArrayList<POI> doInBackground(Object... params) { mTag = (String)params[0]; if (mTag == null || mTag.equals("")){ return null; } else if (mTag.equals("wikipedia")){ GeoNamesPOIProvider poiProvider = new GeoNamesPOIProvider("mkergall"); //Get POI inside the bounding box of the current map view: BoundingBoxE6 bb = map.getBoundingBox(); ArrayList<POI> pois = poiProvider.getPOIInside(bb, 30); return pois; } else if (mTag.equals("flickr")){ FlickrPOIProvider poiProvider = new FlickrPOIProvider("c39be46304a6c6efda8bc066c185cd7e"); BoundingBoxE6 bb = map.getBoundingBox(); ArrayList<POI> pois = poiProvider.getPOIInside(bb, 30); return pois; } else if (mTag.startsWith("picasa")){ PicasaPOIProvider poiProvider = new PicasaPOIProvider(null); BoundingBoxE6 bb = map.getBoundingBox(); //allow to search for keywords among picasa photos: String q = mTag.substring("picasa".length()); ArrayList<POI> pois = poiProvider.getPOIInside(bb, 50, q); return pois; } else { NominatimPOIProvider poiProvider = new NominatimPOIProvider(); //poiProvider.setService(NominatimPOIProvider.MAPQUEST_POI_SERVICE); ArrayList<POI> pois; if (mRoad == null){ BoundingBoxE6 bb = map.getBoundingBox(); pois = poiProvider.getPOIInside(bb, mTag, 100); } else { pois = poiProvider.getPOIAlong(mRoad.getRouteLow(), mTag, 100, 2.0); } return pois; } } protected void onPostExecute(ArrayList<POI> pois) { mPOIs = pois; if (mTag.equals("")){ //no search, no message } else if (mPOIs == null){ Toast.makeText(getApplicationContext(), "Technical issue when getting "+mTag+ " POI.", Toast.LENGTH_LONG).show(); } else { Toast.makeText(getApplicationContext(), ""+mPOIs.size()+" "+mTag+ " entries found", Toast.LENGTH_LONG).show(); if (mTag.equals("flickr")||mTag.startsWith("picasa")||mTag.equals("wikipedia")) startAsyncThumbnailsLoading(mPOIs); } updateUIWithPOI(mPOIs); } } void getPOIAsync(String tag){ poiMarkers.removeAllItems(); new POITask().execute(tag); } void openKMLUrlDialog(){ AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("KML url"); final EditText input = new EditText(this); input.setInputType(InputType.TYPE_CLASS_TEXT); String defaultUri = "http://mapsengine.google.com/map/kml?mid=z6IJfj90QEd4.kUUY9FoHFRdE"; SharedPreferences prefs = getSharedPreferences("OSMNAVIGATOR", MODE_PRIVATE); String uri = prefs.getString("KML_URI", defaultUri); input.setText(uri); builder.setView(input); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String uri = input.getText().toString(); SharedPreferences prefs = getSharedPreferences("OSMNAVIGATOR", MODE_PRIVATE); SharedPreferences.Editor ed = prefs.edit(); ed.putString("KML_URI", uri); ed.commit(); dialog.cancel(); getKml(uri); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.show(); } void getKml(String uri){ mKmlProvider = new KmlProvider(); if (uri.startsWith("file:/")){ uri = uri.substring("file:/".length()); File file = new File(uri); kmlRoot = mKmlProvider.parseFile(file); } else { kmlRoot = mKmlProvider.parseUrl(uri); } if (kmlRoot == null) Toast.makeText(this, "Sorry, unable to read this file.", Toast.LENGTH_SHORT).show(); updateUIWithKml(); if (kmlRoot != null && kmlRoot.mBB != null){ //setViewOn(kmlRoot.mBB); KO in onCreate - Workaround: map.getController().setCenter(new GeoPoint( kmlRoot.mBB.getLatSouthE6()+kmlRoot.mBB.getLatitudeSpanE6()/2, kmlRoot.mBB.getLonWestE6()+kmlRoot.mBB.getLongitudeSpanE6()/2)); } } void saveKml(String fileName){ boolean result = mKmlProvider.saveAsKML(mKmlProvider.getDefaultPathForAndroid(fileName), kmlRoot); if (result) Toast.makeText(this, fileName + " saved", Toast.LENGTH_SHORT).show(); else Toast.makeText(this, "Unable to save "+fileName, Toast.LENGTH_SHORT).show(); } void updateUIWithKml(){ if (kmlOverlay != null) map.getOverlays().remove(kmlOverlay); if (kmlRoot != null){ Drawable defaultKmlMarker = getResources().getDrawable(R.drawable.marker_kml_point); kmlOverlay = (FolderOverlay)kmlRoot.buildOverlays(this, map, defaultKmlMarker, mKmlProvider, true); map.getOverlays().add(kmlOverlay); } map.invalidate(); } void insertOverlaysInKml(){ //Ensure the root is a folder: if (kmlRoot == null || kmlRoot.mObjectType != KmlObject.FOLDER){ kmlRoot = new KmlObject(); kmlRoot.createAsFolder(); } //Insert relevant overlays inside: kmlRoot.addOverlay(itineraryMarkers, mKmlProvider); kmlRoot.addOverlay(roadOverlay, mKmlProvider); kmlRoot.addOverlay(roadNodeMarkers, mKmlProvider); kmlRoot.addOverlay(destinationPolygon, mKmlProvider); kmlRoot.addOverlay(poiMarkers, mKmlProvider); } GeoPoint tempClickedGeoPoint; //any other way to pass the position to the menu ??? @Override public boolean longPressHelper(IGeoPoint p) { tempClickedGeoPoint = new GeoPoint((GeoPoint)p); Button searchButton = (Button)findViewById(R.id.buttonSearchDest); openContextMenu(searchButton); //menu is hooked on the "Search Destination" button, as it must be hooked somewhere. return true; } @Override public boolean singleTapUpHelper(IGeoPoint p) { return false; } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.map_menu, menu); } @Override public boolean onContextItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_departure: startPoint = new GeoPoint((GeoPoint)tempClickedGeoPoint); markerStart = putMarkerItem(markerStart, startPoint, START_INDEX, R.string.departure, R.drawable.marker_departure, -1); getRoadAsync(); return true; case R.id.menu_destination: destinationPoint = new GeoPoint((GeoPoint)tempClickedGeoPoint); markerDestination = putMarkerItem(markerDestination, destinationPoint, DEST_INDEX, R.string.destination, R.drawable.marker_destination, -1); getRoadAsync(); return true; case R.id.menu_viapoint: GeoPoint viaPoint = new GeoPoint((GeoPoint)tempClickedGeoPoint); addViaPoint(viaPoint); getRoadAsync(); return true; default: return super.onContextItemSelected(item); } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.option_menu, menu); switch (whichRouteProvider){ case OSRM: menu.findItem(R.id.menu_route_osrm).setChecked(true); break; case MAPQUEST_FASTEST: menu.findItem(R.id.menu_route_mapquest_fastest).setChecked(true); break; case MAPQUEST_BICYCLE: menu.findItem(R.id.menu_route_mapquest_bicycle).setChecked(true); break; case MAPQUEST_PEDESTRIAN: menu.findItem(R.id.menu_route_mapquest_pedestrian).setChecked(true); break; case GOOGLE_FASTEST: menu.findItem(R.id.menu_route_google).setChecked(true); break; } if (map.getTileProvider().getTileSource() == TileSourceFactory.MAPNIK) menu.findItem(R.id.menu_tile_mapnik).setChecked(true); else if (map.getTileProvider().getTileSource() == TileSourceFactory.MAPQUESTOSM) menu.findItem(R.id.menu_tile_mapquest_osm).setChecked(true); else if (map.getTileProvider().getTileSource() == MAPBOXSATELLITELABELLED) menu.findItem(R.id.menu_tile_mapbox_satellite).setChecked(true); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { if (mRoad != null && mRoad.mNodes.size()>0) menu.findItem(R.id.menu_itinerary).setEnabled(true); else menu.findItem(R.id.menu_itinerary).setEnabled(false); if (mPOIs != null && mPOIs.size()>0) menu.findItem(R.id.menu_pois).setEnabled(true); else menu.findItem(R.id.menu_pois).setEnabled(false); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { Intent myIntent; switch (item.getItemId()) { case R.id.menu_itinerary: myIntent = new Intent(this, RouteActivity.class); myIntent.putExtra("NODE_ID", roadNodeMarkers.getBubbledItemId()); startActivityForResult(myIntent, ROUTE_REQUEST); //TODO: crash if road is too big. Pass only needed info? return true; case R.id.menu_pois: myIntent = new Intent(this, POIActivity.class); //STATIC myIntent.putParcelableArrayListExtra("POI", mPOIs); myIntent.putExtra("ID", poiMarkers.getBubbledItemId()); startActivityForResult(myIntent, POIS_REQUEST); return true; case R.id.menu_kml_url: openKMLUrlDialog(); return true; case R.id.menu_kml_file: //TODO : openKMLFileDialog(); File file = mKmlProvider.getDefaultPathForAndroid("current.kml"); getKml("file:/"+file.toString()); return true; case R.id.menu_kml_get_overlays: insertOverlaysInKml(); updateUIWithKml(); return true; case R.id.menu_kml_tree: if (kmlRoot==null) return false; myIntent = new Intent(this, KmlTreeActivity.class); myIntent.putExtra("KML", kmlRoot); startActivityForResult(myIntent, KML_TREE_REQUEST); return true; case R.id.menu_kml_save: //TODO: openKMLSaveDialog(); saveKml("current.kml"); return true; case R.id.menu_kml_clear: kmlRoot = new KmlObject(); kmlRoot.createAsFolder(); mKmlProvider = new KmlProvider(); updateUIWithKml(); return true; case R.id.menu_route_osrm: whichRouteProvider = OSRM; item.setChecked(true); getRoadAsync(); return true; case R.id.menu_route_mapquest_fastest: whichRouteProvider = MAPQUEST_FASTEST; item.setChecked(true); getRoadAsync(); return true; case R.id.menu_route_mapquest_bicycle: whichRouteProvider = MAPQUEST_BICYCLE; item.setChecked(true); getRoadAsync(); return true; case R.id.menu_route_mapquest_pedestrian: whichRouteProvider = MAPQUEST_PEDESTRIAN; item.setChecked(true); getRoadAsync(); return true; case R.id.menu_route_google: whichRouteProvider = GOOGLE_FASTEST; item.setChecked(true); getRoadAsync(); return true; case R.id.menu_tile_mapnik: map.setTileSource(TileSourceFactory.MAPNIK); item.setChecked(true); return true; case R.id.menu_tile_mapquest_osm: map.setTileSource(TileSourceFactory.MAPQUESTOSM); item.setChecked(true); return true; case R.id.menu_tile_mapbox_satellite: map.setTileSource(MAPBOXSATELLITELABELLED); item.setChecked(true); return true; default: return super.onOptionsItemSelected(item); } } private final NetworkLocationIgnorer mIgnorer = new NetworkLocationIgnorer(); long mLastTime = 0; // milliseconds double mSpeed = 0.0; // km/h @Override public void onLocationChanged(final Location pLoc) { long currentTime = System.currentTimeMillis(); if (mIgnorer.shouldIgnore(pLoc.getProvider(), currentTime)) return; double dT = currentTime - mLastTime; if (dT < 100.0){ //Toast.makeText(this, pLoc.getProvider()+" dT="+dT, Toast.LENGTH_SHORT).show(); return; } mLastTime = currentTime; GeoPoint newLocation = new GeoPoint(pLoc); if (!myLocationOverlay.isEnabled()){ //we get the location for the first time: myLocationOverlay.setEnabled(true); map.getController().animateTo(newLocation); } GeoPoint prevLocation = myLocationOverlay.getLocation(); myLocationOverlay.setLocation(newLocation); myLocationOverlay.setAccuracy((int)pLoc.getAccuracy()); if (prevLocation != null && pLoc.getProvider().equals(LocationManager.GPS_PROVIDER)){ /* double d = prevLocation.distanceTo(newLocation); mSpeed = d/dT*1000.0; // m/s mSpeed = mSpeed * 3.6; //km/h */ mSpeed = pLoc.getSpeed() * 3.6; long speedInt = Math.round(mSpeed); TextView speedTxt = (TextView)findViewById(R.id.speed); speedTxt.setText(speedInt + " km/h"); //TODO: check if speed is not too small if (mSpeed >= 0.1){ //mAzimuthAngleSpeed = (float)prevLocation.bearingTo(newLocation); mAzimuthAngleSpeed = (float)pLoc.getBearing(); myLocationOverlay.setBearing(mAzimuthAngleSpeed); } } if (mTrackingMode){ //keep the map view centered on current location: map.getController().animateTo(newLocation); map.setMapOrientation(-mAzimuthAngleSpeed); } else { //just redraw the location overlay: map.invalidate(); } } @Override public void onProviderDisabled(String provider) {} @Override public void onProviderEnabled(String provider) {} @Override public void onStatusChanged(String provider, int status, Bundle extras) {} @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { myLocationOverlay.setAccuracy(accuracy); map.invalidate(); } static float mAzimuthOrientation = 0.0f; @Override public void onSensorChanged(SensorEvent event) { switch (event.sensor.getType()){ case Sensor.TYPE_ORIENTATION: if (mSpeed < 0.1){ /* TODO Filter to implement... float azimuth = event.values[0]; if (Math.abs(azimuth-mAzimuthOrientation)>2.0f){ mAzimuthOrientation = azimuth; myLocationOverlay.setBearing(mAzimuthOrientation); if (mTrackingMode) map.setMapOrientation(-mAzimuthOrientation); else map.invalidate(); } */ } //at higher speed, we use speed vector, not phone orientation. break; default: break; } } }
package org.commcare.util.screen; import org.commcare.cases.entity.EntityUtil; import org.commcare.cases.query.QueryContext; import org.commcare.cases.query.queryset.CurrentModelQuerySet; import org.commcare.core.interfaces.UserSandbox; import org.commcare.modern.session.SessionWrapper; import org.commcare.session.CommCareSession; import org.commcare.suite.model.Action; import org.commcare.suite.model.Detail; import org.commcare.suite.model.EntityDatum; import org.commcare.suite.model.SessionDatum; import org.commcare.util.CommCarePlatform; import org.commcare.util.DatumUtil; import org.commcare.util.FormDataUtil; import org.javarosa.core.model.condition.EvaluationContext; import org.javarosa.core.model.instance.TreeReference; import org.javarosa.core.model.trace.EvaluationTraceReporter; import org.javarosa.core.model.utils.InstrumentationUtils; import org.javarosa.core.util.NoLocalizedTextException; import java.util.Hashtable; import java.util.Vector; import javax.annotation.Nonnull; import javax.annotation.Nullable; import datadog.trace.api.Trace; /** * Compound Screen to select an entity from a list and then display the one or more details that * are associated with the entity. * * Does not currently support tile based selects * * @author ctsims */ public class EntityScreen extends CompoundScreenHost { private TreeReference mCurrentSelection; private SessionWrapper mSession; private CommCarePlatform mPlatform; private Detail mShortDetail; protected EntityDatum mNeededDatum; private Action mPendingAction; private Subscreen<EntityScreen> mCurrentScreen; private boolean readyToSkip = false; private EvaluationContext evalContext; protected Hashtable<String, TreeReference> referenceMap; private boolean handleCaseIndex; private boolean needsFullInit = true; private boolean isDetailScreen = false; private Vector<TreeReference> references; private boolean initialized = false; private Action autoLaunchAction; public EntityScreen(boolean handleCaseIndex) { this.handleCaseIndex = handleCaseIndex; } /** * This constructor allows specifying whether to use the complete init or a minimal one * * @param handleCaseIndex Allow specifying entity by list index rather than unique ID * @param needsFullInit If set to false, the subscreen and referenceMap, used for * selecting and rendering entity details, will not be created. * This speeds up initialization but makes further selection impossible. */ public EntityScreen(boolean handleCaseIndex, boolean needsFullInit) { this.handleCaseIndex = handleCaseIndex; this.needsFullInit = needsFullInit; } public EntityScreen(boolean handleCaseIndex, boolean needsFullInit, SessionWrapper session, boolean isDetailScreen) throws CommCareSessionException { this.handleCaseIndex = handleCaseIndex; this.needsFullInit = needsFullInit; this.setSession(session); this.isDetailScreen = isDetailScreen; } public void evaluateAutoLaunch(String nextInput) throws CommCareSessionException { EvaluationContext subContext = getAutoLaunchEvaluationContext(nextInput); for (Action action : mShortDetail.getCustomActions(evalContext)) { if (action.isAutoLaunchAction(subContext)) { // Supply an empty case list so we can "select" from it later using getEntityFromID mCurrentScreen = new EntityListSubscreen(mShortDetail, new Vector<>(), evalContext, handleCaseIndex); this.autoLaunchAction = action; } } } @Nonnull protected EvaluationContext getAutoLaunchEvaluationContext(String nextInput) { EvaluationContext subContext = evalContext.spawnWithCleanLifecycle(); subContext.setVariable("next_input", nextInput); return subContext; } @Trace public void init(SessionWrapper session) throws CommCareSessionException { if (initialized) { if (session != this.mSession) { throw new CommCareSessionException( "Entity screen initialized with two different session wrappers"); } return; } this.setSession(session); references = expandEntityReferenceSet(evalContext); //Pulled from NodeEntityFactory. We should likely replace this whole functonality with //that from nodeentityfactory QueryContext newContext = evalContext.getCurrentQueryContext() .checkForDerivativeContextAndReturn(references.size()); newContext.setHackyOriginalContextBody(new CurrentModelQuerySet(references)); evalContext.setQueryContext(newContext); if (needsFullInit || references.size() == 1) { referenceMap = new Hashtable<>(); EntityDatum needed = (EntityDatum)session.getNeededDatum(); for (TreeReference reference : references) { referenceMap.put(getReturnValueFromSelection(reference, needed, evalContext), reference); } // for now override 'here()' with the coords of Sao Paulo, eventually allow dynamic // setting evalContext.addFunctionHandler(new ScreenUtils.HereDummyFunc(-23.56, -46.66)); if (mNeededDatum.isAutoSelectEnabled() && references.size() == 1) { this.setSelectedEntity(references.firstElement()); if (!this.setCurrentScreenToDetail()) { this.updateSession(session); readyToSkip = true; } } else { // We can simply skip evaluating Detail for entities for a detail screen Vector<TreeReference> entityListReferences = isDetailScreen ? new Vector<>() : references; mCurrentScreen = new EntityListSubscreen(mShortDetail, entityListReferences, evalContext, handleCaseIndex); } } initialized = true; } protected void setSession(SessionWrapper session) throws CommCareSessionException { SessionDatum datum = session.getNeededDatum(); if (!(datum instanceof EntityDatum)) { throw new CommCareSessionException( "Didn't find an entity select action where one is expected."); } mNeededDatum = (EntityDatum)datum; this.mSession = session; this.mPlatform = mSession.getPlatform(); String detailId = mNeededDatum.getShortDetail(); if (detailId == null) { throw new CommCareSessionException( "Can't handle entity selection with blank detail definition for datum " + mNeededDatum.getDataId()); } mShortDetail = this.mPlatform.getDetail(detailId); if (mShortDetail == null) { throw new CommCareSessionException("Missing detail definition for: " + detailId); } evalContext = mSession.getEvaluationContext(); } @Trace private Vector<TreeReference> expandEntityReferenceSet(EvaluationContext context) { return evalContext.expandReference(mNeededDatum.getNodeset()); } @Override public boolean shouldBeSkipped() { return readyToSkip; } @Override public String getScreenTitle() { try { return mShortDetail.getTitle().evaluate(evalContext).getName(); } catch (NoLocalizedTextException nlte) { return "Select (error with title string)"; } } @Override public String getBreadcrumb(String input, UserSandbox sandbox, SessionWrapper session) { String caseName = FormDataUtil.getCaseName(sandbox, input); return caseName == null ? ScreenUtils.getBestTitle(session) : caseName; } @Override public Subscreen getCurrentScreen() { return mCurrentScreen; } protected String getReturnValueFromSelection(TreeReference contextRef) { return getReturnValueFromSelection(contextRef, mNeededDatum, evalContext); } @Trace public static String getReturnValueFromSelection(TreeReference contextRef, EntityDatum needed, EvaluationContext context) { return DatumUtil.getReturnValueFromSelection(contextRef, needed, context); } @Trace @Override protected void updateSession(CommCareSession session) { if (executePendingAction(session)) { return; } String selectedValue = getReturnValueFromSelection(mCurrentSelection); session.setEntityDatum(mNeededDatum, selectedValue); } public boolean executePendingAction(CommCareSession session) { if (mPendingAction != null) { session.executeStackOperations(mPendingAction.getStackOperations(), evalContext); return true; } return false; } /** * Updates entity selected on the screen * * @param input id of the entity selected on the screen * @param selectedValues should always be null for single-select entity screen * @throws CommCareSessionException */ public void updateSelection(String input, @Nullable String[] selectedValues) throws CommCareSessionException { setSelectedEntity(input); showDetailScreen(); } /** * Updates entity selected on the screen * * @param input input to the entity selected on the screen * @param selectedRefs references for the selected entity, only contains a single element for the * single-select entity screen * @throws CommCareSessionException */ public void updateSelection(String input, TreeReference[] selectedRefs) throws CommCareSessionException { if (selectedRefs.length != 1) { throw new IllegalArgumentException( "selectedRefs should only contain one element for the single select Entity Screen"); } setSelectedEntity(selectedRefs[0]); setCurrentScreenToDetail(); } private void showDetailScreen() throws CommCareSessionException { if (isDetailScreen) { // Set entity screen to show detail and redraw setCurrentScreenToDetail(); } } @Trace public void setSelectedEntity(TreeReference selection) { this.mCurrentSelection = selection; } @Trace private void setSelectedEntity(String id) throws CommCareSessionException { mCurrentSelection = getEntityReference(id); if (this.mCurrentSelection == null) { throw new CommCareSessionException("Could not select case " + id + " on this screen. " + " If this error persists please report a bug to CommCareHQ."); } } protected TreeReference getEntityReference(String id) { if (referenceMap == null) { return mNeededDatum.getEntityFromID(evalContext, id); } else { return referenceMap.get(id); } } private boolean setCurrentScreenToDetail() throws CommCareSessionException { Detail[] longDetailList = getLongDetailList(mCurrentSelection); if (longDetailList == null) { return false; } setCurrentScreenToDetail(0); return true; } public void setCurrentScreenToDetail(int index) throws CommCareSessionException { EvaluationContext subContext = new EvaluationContext(evalContext, this.mCurrentSelection); Detail[] longDetailList = getLongDetailList(this.mCurrentSelection); TreeReference detailNodeset = longDetailList[index].getNodeset(); if (detailNodeset != null) { TreeReference contextualizedNodeset = detailNodeset.contextualize(this.mCurrentSelection); this.mCurrentScreen = new EntityListSubscreen(longDetailList[index], subContext.expandReference(contextualizedNodeset), subContext, handleCaseIndex); } else { this.mCurrentScreen = new EntityDetailSubscreen(index, longDetailList[index], subContext, getDetailListTitles(subContext, this.mCurrentSelection)); } } public Detail[] getLongDetailList(TreeReference ref) { Detail[] longDetailList; String longDetailId = this.mNeededDatum.getLongDetail(); if (longDetailId == null) { return null; } Detail d = mPlatform.getDetail(longDetailId); if (d == null) { return null; } EvaluationContext contextForChildDetailDisplayConditions = EntityUtil.prepareCompoundEvaluationContext(ref, d, evalContext); longDetailList = d.getDisplayableChildDetails(contextForChildDetailDisplayConditions); if (longDetailList == null || longDetailList.length == 0) { longDetailList = new Detail[]{d}; } return longDetailList; } public String[] getDetailListTitles(EvaluationContext subContext, TreeReference reference) { Detail[] mLongDetailList = getLongDetailList(reference); String[] titles = new String[mLongDetailList.length]; for (int i = 0; i < mLongDetailList.length; ++i) { titles[i] = mLongDetailList[i].getTitle().getText().evaluate(subContext); } return titles; } public void setPendingAction(Action pendingAction) { this.mPendingAction = pendingAction; } public Detail getShortDetail() { return mShortDetail; } public SessionWrapper getSession() { return mSession; } public void printNodesetExpansionTrace(EvaluationTraceReporter reporter) { evalContext.setDebugModeOn(reporter); this.expandEntityReferenceSet(evalContext); InstrumentationUtils.printAndClearTraces(reporter, "Entity Nodeset"); } public TreeReference resolveTreeReference(String reference) { return referenceMap.get(reference); } public EvaluationContext getEvalContext() { return evalContext; } public TreeReference getCurrentSelection() { return mCurrentSelection; } public Vector<TreeReference> getReferences() { return references; } public Action getAutoLaunchAction() { return autoLaunchAction; } @Override public String toString() { return "EntityScreen [id=" + mNeededDatum.getDataId() + ", selection=" + mCurrentSelection + "]"; } // Used by Formplayer @SuppressWarnings("unused") public Hashtable<String, TreeReference> getReferenceMap() { return referenceMap; } public boolean referencesContainStep(String stepValue) { if (referenceMap != null) { return referenceMap.containsKey(stepValue); } for (TreeReference ref : references) { String id = getReturnValueFromSelection(ref); if (id.equals(stepValue)) { return true; } } return false; } /** * Updates the datum required by the given CommCare Session. It's generally used during session replays when * we want to update the datum directly with the pre-validated input wihout doing any other input handling * * @param session Current Commcare Session that we need to update with given input * @param input Value of the datum required by the given CommCare Session */ public void updateDatum(CommCareSession session, String input) { session.setEntityDatum(session.getNeededDatum(), input); } /** * Handle auto-launch actions for EntityScreens * * @return true if the session was advanced * @throws CommCareSessionException if there was an error during evaluation of auto launch action */ public boolean evalAndExecuteAutoLaunchAction(String nextInput, CommCareSession session) throws CommCareSessionException { evaluateAutoLaunch(nextInput); if (getAutoLaunchAction() != null) { setPendingAction(getAutoLaunchAction()); executePendingAction(session); return true; } return false; } }
package com.dci.intellij.dbn.common.ui; import com.dci.intellij.dbn.common.event.EventManager; import com.dci.intellij.dbn.common.thread.ConditionalLaterInvocator; import com.dci.intellij.dbn.common.util.UIUtil; import com.dci.intellij.dbn.connection.ConnectionHandler; import com.dci.intellij.dbn.connection.ConnectionStatusListener; import com.dci.intellij.dbn.connection.VirtualConnectionHandler; import com.intellij.openapi.project.Project; import org.picocontainer.Disposable; import javax.swing.JLabel; import java.awt.Color; public class AutoCommitLabel extends JLabel implements ConnectionStatusListener, Disposable { private Project project; private ConnectionHandler connectionHandler; private boolean subscribed = false; public AutoCommitLabel() { super(""); setFont(UIUtil.BOLD_FONT); } public void setConnectionHandler(ConnectionHandler connectionHandler) { if (connectionHandler == null || connectionHandler instanceof VirtualConnectionHandler) { this.connectionHandler = null; } else { this.connectionHandler = connectionHandler; if (!subscribed) { subscribed = true; project = connectionHandler.getProject(); EventManager.subscribe(project, ConnectionStatusListener.TOPIC, this); } } update(); } private void update() { new ConditionalLaterInvocator() { @Override public void run() { if (connectionHandler != null) { setVisible(true); boolean disconnected = !connectionHandler.isConnected(); boolean autoCommit = connectionHandler.isAutoCommit(); setText(disconnected ? "Not connected to database" : autoCommit ? "Auto-Commit ON" : "Auto-Commit OFF"); setForeground(disconnected ? Color.BLACK : autoCommit ? new Color(210, 0, 0) : new Color(0, 160, 0)); setToolTipText( disconnected ? "The connection to database has been closed. No editing possible" : autoCommit ? "Auto-Commit is enabled for connection \"" + connectionHandler + "\". Data changes will be automatically committed to the database." : "Auto-Commit is disabled for connection \"" + connectionHandler + "\". Data changes will need to be manually committed to the database."); } else { setVisible(false); } } }.start(); } @Override public void statusChanged(String connectionId) { if (connectionHandler != null && connectionHandler.getId().equals(connectionId)) { update(); } } @Override public void dispose() { if (project != null) { EventManager.unsubscribe(project, this); } } }
package com.ecyrd.jspwiki.tags; import java.io.IOException; import java.util.Collection; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.PageContext; import com.ecyrd.jspwiki.WikiContext; import com.ecyrd.jspwiki.SearchResult; /** * Iterates through Search result results. * * <P><B>Attributes</B></P> * <UL> * <LI>max = how many search results should be shown. * </UL> * * @author Janne Jalkanen * @since 2.0 */ // FIXME: Shares MUCH too much in common with IteratorTag. Must refactor. public class SearchResultIteratorTag extends IteratorTag { private static final long serialVersionUID = 0L; private int m_maxItems; private int m_count = 0; private int m_start = 0; public void release() { super.release(); m_maxItems = m_count = 0; } public void setMaxItems( String arg ) { m_maxItems = Integer.parseInt(arg); } public void setStart( String arg ) { m_start = Integer.parseInt(arg); } public final int doStartTag() { // Do lazy eval if the search results have not been set. if( m_iterator == null ) { Collection searchresults = (Collection) pageContext.getAttribute( "searchresults", PageContext.REQUEST_SCOPE ); setList( searchresults ); int skip = 0; // Skip the first few ones... m_iterator = searchresults.iterator(); while( m_iterator.hasNext() && (skip++ < m_start) ) m_iterator.next(); } m_count = 0; m_wikiContext = (WikiContext) pageContext.getAttribute( WikiTagBase.ATTR_CONTEXT, PageContext.REQUEST_SCOPE ); return nextResult(); } private int nextResult() { if( m_iterator != null && m_iterator.hasNext() && m_count++ < m_maxItems ) { SearchResult r = (SearchResult) m_iterator.next(); WikiContext context = (WikiContext)m_wikiContext.clone(); context.setPage( r.getPage() ); pageContext.setAttribute( WikiTagBase.ATTR_CONTEXT, context, PageContext.REQUEST_SCOPE ); pageContext.setAttribute( getId(), r ); return EVAL_BODY_BUFFERED; } return SKIP_BODY; } public int doAfterBody() { if( bodyContent != null ) { try { JspWriter out = getPreviousOut(); out.print(bodyContent.getString()); bodyContent.clearBody(); } catch( IOException e ) { log.error("Unable to get inner tag text", e); // FIXME: throw something? } } return nextResult(); } public int doEndTag() { m_iterator = null; return super.doEndTag(); } }
package cs414.pos; import java.io.File; import java.io.IOException; import java.util.HashSet; import java.util.Set; import org.junit.After; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; public class StoreTest { Store testStore1, testStore2, testStore3, testStore4; Employee testEmployee1_store4, testEmployee2_store4, testEmployee3_store4; String testName1, testName2, testName3; LoginInfo testLoginInfo1, testLoginInfo2, testLoginInfo3; String testLoginID1, testLoginID2, testLoginID3; String testPassWord1, testPassWord2, testPassWord3; String menuName1, menuName2, menuDesc1, menuDesc2; Item test_item1, test_item2; Kiosk testKiosk1, testKiosk2; Register testRegister1, testRegister2; Order testOrder1, testOrder2; int testOrderID1, testOrderID2, testOrderID3; @Before public void setUp() throws Exception { testStore1 = new Store(); testStore2 = new Store("PizzaStore2"); testStore3 = new Store("PizzaStore3", "Stuart St."); testStore4 = new Store("PizzaStore4", "206-953-5584", "Stuart St."); testName1 = "Shimon"; testLoginID1 = "skshimon"; testPassWord1 = "uda"; testName2 = "Caleb"; testLoginID2 = "ctebbe"; testPassWord2 = "cte"; testName3 = "Nathan"; testLoginID3 = "nlightHart"; testPassWord3 = "nli"; testEmployee1_store4 = testStore4.addEmployee(testName1, testLoginID1, testPassWord1, Role.Cashier); testEmployee2_store4 = testStore4.addEmployee(testName2, testLoginID2, testPassWord2, Role.Chef); testEmployee3_store4 = testStore4.addEmployee(testName3, testLoginID3, testPassWord3, Role.Manager); menuName1 = "Menu1"; menuName2 = "Menu2"; menuDesc1 = "MenuDesc1"; menuDesc2 = "MenuDesc2"; test_item1 = new Item("item1", 10, "Test Item 1"); test_item2 = new Item("item2", 5, "Test Item 2"); Employee e3 = testStore3.addEmployee("c", "c", "pw", Role.Manager); testKiosk1 = testStore3.addKiosk(e3, 1); testKiosk2 = testStore3.addKiosk(e3, 2); testRegister1 = testStore3.addRegister(e3, 1); testRegister2 = testStore3.addRegister(e3, 2); testOrderID1 = 1; testOrderID2 = 2; testOrderID3 = 3; } @After public void tearDown() throws Exception { } @Test public void basicSerializeTest() throws IOException, ClassNotFoundException { String f = "testSave.ser"; Store s = new Store(); Employee manager = s.addEmployee("bob", "bob", "pw_bob", Role.Manager); Menu m0 = s.defineMenu(manager, "menu0", "menu0_desc"); s.addMenuItem(manager, m0, "pizza0", 5.0, "cheesy"); // save Store's state SaverLoader.save(new File(f), s); // open Store's state Store s2 = SaverLoader.load(new File(f)); assertEquals(1, s2.getSetOfMenus().size()); } @Test public void testStore() { assertEquals("", testStore1.getStoreName().toString()); assertEquals("000-000-0000", testStore1.getPhoneNumber().toString()); assertEquals("", testStore1.getAddress().getLocation().toString()); assertEquals(AddressType.Unknown, testStore1.getAddress().getAddressType()); } @Test public void testStoreStringStringString() { assertEquals("PizzaStore4", testStore4.getStoreName().toString()); assertEquals("206-953-5584", testStore4.getPhoneNumber().toString()); assertEquals("Stuart St.", testStore4.getAddress().getLocation().toString()); assertEquals(AddressType.Business, testStore4.getAddress().getAddressType()); } @Test public void testStoreStringString() { assertEquals("PizzaStore3", testStore3.getStoreName().toString()); assertEquals("000-000-0000", testStore3.getPhoneNumber().toString()); assertEquals("Stuart St.", testStore3.getAddress().getLocation().toString()); assertEquals(AddressType.Business, testStore3.getAddress().getAddressType()); } @Test public void testStoreString() { assertEquals("PizzaStore2", testStore2.getStoreName().toString()); assertEquals("000-000-0000", testStore2.getPhoneNumber().toString()); assertEquals("", testStore2.getAddress().getLocation().toString()); assertEquals(AddressType.Unknown, testStore2.getAddress().getAddressType()); } @Test public void testGetEmployeeSet() { assertEquals(0, testStore1.getEmployeeSet().size()); assertEquals(0, testStore2.getEmployeeSet().size()); assertEquals(1, testStore3.getEmployeeSet().size()); assertEquals(3, testStore4.getEmployeeSet().size()); } @Test public void testGetStoreName() { assertEquals("PizzaStore4", testStore4.getStoreName().toString()); assertEquals("PizzaStore3", testStore3.getStoreName().toString()); assertEquals("PizzaStore2", testStore2.getStoreName().toString()); assertEquals("", testStore1.getStoreName().toString()); } @Test public void testSetStoreName() { String testStoreName1_new = "PizzaStore1"; testStore1.setStoreName(testStoreName1_new); assertEquals(testStoreName1_new, testStore1.getStoreName().toString()); testStore1.setStoreName(null); assertEquals("", testStore1.getStoreName()); } @Test public void testGetPhoneNumber() { assertEquals("000-000-0000", testStore1.getPhoneNumber().toString()); assertEquals("000-000-0000", testStore2.getPhoneNumber().toString()); assertEquals("000-000-0000", testStore3.getPhoneNumber().toString()); assertEquals("206-953-5584", testStore4.getPhoneNumber().toString()); } @Test public void testSetPhoneNumber() { String testNumber1_new = "123-435-2345"; String testNumber2_new = "123-435-2346"; String testNumber3_new = "123-435-2347"; String testNumber4_new = "123-435-2348"; testStore1.setPhoneNumber(testNumber1_new); testStore2.setPhoneNumber(testNumber2_new); testStore3.setPhoneNumber(testNumber3_new); testStore4.setPhoneNumber(testNumber4_new); assertEquals(testNumber1_new, testStore1.getPhoneNumber().toString()); assertEquals(testNumber2_new, testStore2.getPhoneNumber().toString()); assertEquals(testNumber3_new, testStore3.getPhoneNumber().toString()); assertEquals(testNumber4_new, testStore4.getPhoneNumber().toString()); } @Test public void testGetAddress() { assertEquals("", testStore1.getAddress().getLocation().toString()); assertEquals("", testStore2.getAddress().getLocation().toString()); assertEquals("Stuart St.", testStore3.getAddress().getLocation().toString()); assertEquals("Stuart St.", testStore4.getAddress().getLocation().toString()); } @Test public void testSetAddress() { String testAddress1_new = "Pitkin St."; String testAddress2_new = "PitkinOus St."; testStore1.setAddress(testAddress1_new); testStore2.setAddress(testAddress2_new); assertEquals(testAddress1_new, testStore1.getAddress().getLocation().toString()); assertEquals(testAddress2_new, testStore2.getAddress().getLocation().toString()); } @Test public void testAddEmployee() { assertEquals(1, testStore3.getEmployeeSet().size()); Employee testEmployee1 = testStore3.addEmployee(testName1, testLoginID1, testPassWord1, Role.Cashier); assertEquals(2, testStore3.getEmployeeSet().size()); Employee testEmployee2 = testStore3.addEmployee(testName2, testLoginID2, testPassWord2, Role.Chef); assertEquals(3, testStore3.getEmployeeSet().size()); Employee testEmployee3 = testStore3.addEmployee(testName3, testLoginID3, testPassWord3, Role.Manager); assertEquals(4, testStore3.getEmployeeSet().size()); String test_Employee1 = testEmployee1.getEmployeeID(); String test_Employee2 = testEmployee2.getEmployeeID(); String test_Employee3 = testEmployee3.getEmployeeID(); assertEquals(test_Employee1, testStore3.getEmployee(test_Employee1).getEmployeeID()); assertEquals(test_Employee2, testStore3.getEmployee(test_Employee2).getEmployeeID()); assertEquals(test_Employee3, testStore3.getEmployee(test_Employee3).getEmployeeID()); assertEquals(testStore3, testStore3.getEmployee(test_Employee1).getWorksForStore()); assertEquals(testStore3, testStore3.getEmployee(test_Employee2).getWorksForStore()); assertEquals(testStore3, testStore3.getEmployee(test_Employee3).getWorksForStore()); assertEquals(testLoginID1, testStore3.getEmployee(test_Employee1).getEmployeeLoginInfo().getLoginId()); assertEquals(testLoginID2, testStore3.getEmployee(test_Employee2).getEmployeeLoginInfo().getLoginId()); assertEquals(testLoginID3, testStore3.getEmployee(test_Employee3).getEmployeeLoginInfo().getLoginId()); assertEquals(test_Employee1, testStore3.getEmployee(test_Employee1).getEmployeeLoginInfo().getLoginEmployee().getEmployeeID()); assertEquals(test_Employee2, testStore3.getEmployee(test_Employee2).getEmployeeLoginInfo().getLoginEmployee().getEmployeeID()); assertEquals(test_Employee3, testStore3.getEmployee(test_Employee3).getEmployeeLoginInfo().getLoginEmployee().getEmployeeID()); assertEquals(Role.Cashier, testStore3.getEmployee(test_Employee1).getRole()); assertEquals(Role.Chef, testStore3.getEmployee(test_Employee2).getRole()); assertEquals(Role.Manager, testStore3.getEmployee(test_Employee3).getRole()); assertEquals(testEmployee1, testStore3.loginAttempt(testLoginID1, testPassWord1)); assertEquals(testEmployee2, testStore3.loginAttempt(testLoginID2, testPassWord2)); assertEquals(testEmployee3, testStore3.loginAttempt(testLoginID3, testPassWord3)); assertEquals(null, testStore3.loginAttempt(testLoginID1, testPassWord2)); assertEquals(null, testStore3.loginAttempt(testLoginID2, testPassWord3)); assertEquals(null, testStore3.loginAttempt(testLoginID3, testPassWord1)); } @Test public void testAddEmployeeWithPriviledge() { assertEquals(1, testStore3.getEmployeeSet().size()); String test_Employee1 = testStore3.addEmployee(testName1, testLoginID1, testPassWord1, 0); assertEquals(2, testStore3.getEmployeeSet().size()); String test_Employee2 = testStore3.addEmployee(testName2, testLoginID2, testPassWord2, 1); assertEquals(3, testStore3.getEmployeeSet().size()); String test_Employee3 = testStore3.addEmployee(testName3, testLoginID3, testPassWord3, 2); assertEquals(4, testStore3.getEmployeeSet().size()); assertEquals(test_Employee1, testStore3.getEmployee(test_Employee1).getEmployeeID()); assertEquals(test_Employee2, testStore3.getEmployee(test_Employee2).getEmployeeID()); assertEquals(test_Employee3, testStore3.getEmployee(test_Employee3).getEmployeeID()); assertEquals(testStore3, testStore3.getEmployee(test_Employee1).getWorksForStore()); assertEquals(testStore3, testStore3.getEmployee(test_Employee2).getWorksForStore()); assertEquals(testStore3, testStore3.getEmployee(test_Employee3).getWorksForStore()); assertEquals(testLoginID1, testStore3.getEmployee(test_Employee1).getEmployeeLoginInfo().getLoginId()); assertEquals(testLoginID2, testStore3.getEmployee(test_Employee2).getEmployeeLoginInfo().getLoginId()); assertEquals(testLoginID3, testStore3.getEmployee(test_Employee3).getEmployeeLoginInfo().getLoginId()); assertEquals(test_Employee1, testStore3.getEmployee(test_Employee1).getEmployeeLoginInfo().getLoginEmployee().getEmployeeID()); assertEquals(test_Employee2, testStore3.getEmployee(test_Employee2).getEmployeeLoginInfo().getLoginEmployee().getEmployeeID()); assertEquals(test_Employee3, testStore3.getEmployee(test_Employee3).getEmployeeLoginInfo().getLoginEmployee().getEmployeeID()); assertEquals(Role.Manager, testStore3.getEmployee(test_Employee1).getRole()); assertEquals(Role.Cashier, testStore3.getEmployee(test_Employee2).getRole()); assertEquals(Role.Chef, testStore3.getEmployee(test_Employee3).getRole()); } @Test public void testAddNewMember() { String testFirstName1 = "Shimon"; String testLastName1 = "Shimon"; String phoneNumber = "888-888-8888"; assertEquals(0, testStore4.getMembers().size()); Customer newCustomer = testStore4.addNewMember(testFirstName1, testLastName1, phoneNumber); assertEquals(1, testStore4.getMembers().size()); } @Test public void testGetMember() { String testFirstName1 = "Shimon"; String testLastName1 = "Shimon"; String phoneNumber = "888-888-8888"; Customer newCustomer = testStore4.addNewMember(testFirstName1, testLastName1, phoneNumber); assertEquals(newCustomer, testStore4.getMember(newCustomer.getMemberShipNumber())); } @Test public void testLoginAttempt() { assertEquals(null, testStore4.loginAttempt(testLoginID1, testPassWord2)); assertEquals(null, testStore4.loginAttempt(testLoginID2, testPassWord3)); assertEquals(null, testStore4.loginAttempt(testLoginID3, testPassWord1)); assertEquals(null, testStore3.loginAttempt(testLoginID1, testPassWord2)); assertEquals(null, testStore3.loginAttempt(testLoginID2, testPassWord3)); assertEquals(null, testStore3.loginAttempt(testLoginID3, testPassWord1)); assertEquals(testEmployee1_store4, testStore4.loginAttempt(testLoginID1, testPassWord1)); assertEquals(testEmployee2_store4, testStore4.loginAttempt(testLoginID2, testPassWord2)); assertEquals(testEmployee3_store4, testStore4.loginAttempt(testLoginID3, testPassWord3)); } @Test public void testInitDefineMenu() { Employee test_Employee1 = testStore3.addEmployee(testName1, testLoginID1, testPassWord1, Role.Cashier); Employee test_Employee2 = testStore3.addEmployee(testName2, testLoginID2, testPassWord2, Role.Chef); Employee test_Employee3 = testStore3.addEmployee(testName3, testLoginID3, testPassWord3, Role.Manager); assertFalse(testStore3.initDefineMenu(test_Employee1)); assertFalse(testStore3.initDefineMenu(test_Employee2)); assertTrue(testStore3.initDefineMenu(test_Employee3)); //assertFalse(testStore4.initDefineMenu(test_Employee3)); } @Test public void testDefineMenu() { Employee test_Employee1 = testStore3.addEmployee(testName1, testLoginID1, testPassWord1, Role.Cashier); Employee test_Employee2 = testStore3.addEmployee(testName2, testLoginID2, testPassWord2, Role.Chef); Employee test_Employee3 = testStore3.addEmployee(testName3, testLoginID3, testPassWord3, Role.Manager); Menu m = testStore3.defineMenu(test_Employee3, menuName1, menuDesc1); assertEquals(menuName1, m.getMenuName()); assertEquals(menuDesc1, m.getMenuDescription()); assertNull(testStore3.defineMenu(test_Employee2, menuName1, menuDesc1)); assertNull(testStore3.defineMenu(test_Employee1, menuName1, menuDesc1)); } @Test public void testGetSetOfMenus() { Employee test_Employee3 = testStore3.addEmployee(testName3, testLoginID3, testPassWord3, Role.Manager); testStore3.defineMenu(test_Employee3, menuName1, menuDesc1); assertEquals(1, testStore3.getSetOfMenus().size()); testStore3.defineMenu(test_Employee3, menuName2, menuDesc2); assertEquals(2, testStore3.getSetOfMenus().size()); } @Test public void testAuthorizeEditMenus() { Employee test_Employee1 = testStore3.addEmployee(testName1, testLoginID1, testPassWord1, Role.Cashier); Employee test_Employee2 = testStore3.addEmployee(testName2, testLoginID2, testPassWord2, Role.Chef); Employee test_Employee3 = testStore3.addEmployee(testName3, testLoginID3, testPassWord3, Role.Manager); testStore3.defineMenu(test_Employee3, menuName1, menuDesc1); testStore3.defineMenu(test_Employee3, menuName2, menuDesc2); assertNull(testStore3.authorizeEditMenus(test_Employee1)); assertNull(testStore3.authorizeEditMenus(test_Employee2)); assertEquals(2, testStore3.getSetOfMenus().size()); } @Test public void testEditMenu() { Employee test_Employee3 = testStore3.addEmployee(testName3, testLoginID3, testPassWord3, Role.Manager); Menu m1 = testStore3.defineMenu(test_Employee3, menuName1, menuDesc1); m1.addItem(test_item1); m1.addItem(test_item2); assertTrue(testStore3.editMenu(test_Employee3, m1).contains(test_item1)); assertTrue(testStore3.editMenu(test_Employee3, m1).contains(test_item2)); } @Test public void testSetSpecial() { Employee test_Employee3 = testStore3.addEmployee(testName3, testLoginID3, testPassWord3, Role.Manager); Menu m1 = testStore3.defineMenu(test_Employee3, menuName1, menuDesc1); m1.addItem(test_item1); testStore3.setSpecial(test_Employee3, test_item1, 0.1); assertTrue(test_item1.isSpecial()); //TODO: to be determined... //Not sure should I add this or not: /*testStore3.setSpecial(test_Employee3, test_item2, 0.2); assertFalse(test_item2.isSpecial()); */ } @Test public void testRemoveMenuItems() { Employee test_Employee3 = testStore3.addEmployee(testName3, testLoginID3, testPassWord3, Role.Manager); Menu m1 = testStore3.defineMenu(test_Employee3, menuName1, menuDesc1); m1.addItem(test_item1); m1.addItem(test_item2); Set<Item> itemSet = new HashSet<Item>(); itemSet.add(test_item1); assertTrue(m1.getMenuItems().contains(test_item1)); testStore3.removeMenuItems(test_Employee3, m1, itemSet); assertFalse(m1.getMenuItems().contains(test_item1)); assertTrue(m1.getMenuItems().contains(test_item2)); } @Test public void testAddMenuItem() { Employee test_Employee1 = testStore3.addEmployee(testName1, testLoginID1, testPassWord1, Role.Cashier); Employee test_Employee2 = testStore3.addEmployee(testName2, testLoginID2, testPassWord2, Role.Chef); Employee test_Employee3 = testStore3.addEmployee(testName3, testLoginID3, testPassWord3, Role.Manager); Menu m1 = testStore3.defineMenu(test_Employee3, menuName1, menuDesc1); assertEquals(0, m1.getMenuItems().size()); testStore3.addMenuItem(test_Employee3, m1, "item1", 10, "test item 1"); assertEquals(1, m1.getMenuItems().size()); testStore3.addMenuItem(test_Employee3, m1, "item2", 8, "test item 2"); assertEquals(2, m1.getMenuItems().size()); testStore3.addMenuItem(test_Employee2, m1, "item3", 15, "test item 3"); assertEquals(2, m1.getMenuItems().size()); testStore3.addMenuItem(test_Employee1, m1, "item4", 19, "test item 4"); assertEquals(2, m1.getMenuItems().size()); } @Test public void testGetSetOfKiosk() { assertEquals(2, testStore3.getSetOfKiosk().size()); assertTrue(testStore3.getSetOfKiosk().contains(testKiosk1)); assertTrue(testStore3.getSetOfKiosk().contains(testKiosk2)); } @Test public void testSetSetOfKiosk() { Kiosk tempKiosk1 = new Kiosk(3); Kiosk tempKiosk2 = new Kiosk(4); Set<Kiosk> kioskSet = new HashSet<Kiosk>(); kioskSet.add(tempKiosk1); kioskSet.add(tempKiosk2); assertEquals(0, testStore4.getSetOfKiosk().size()); testStore4.setSetOfKiosk(kioskSet); assertEquals(2, testStore4.getSetOfKiosk().size()); assertTrue(testStore4.getSetOfKiosk().contains(tempKiosk1)); assertTrue(testStore4.getSetOfKiosk().contains(tempKiosk2)); } @Test public void testAddKiosk() { Employee test_Employee1 = testStore3.addEmployee(testName1, testLoginID1, testPassWord1, Role.Cashier); Employee test_Employee2 = testStore3.addEmployee(testName2, testLoginID2, testPassWord2, Role.Chef); Employee test_Employee3 = testStore3.addEmployee(testName3, testLoginID3, testPassWord3, Role.Manager); assertEquals(2, testStore3.getSetOfKiosk().size()); testStore3.addKiosk(test_Employee1, 3); assertEquals(2, testStore3.getSetOfKiosk().size()); testStore3.addKiosk(test_Employee2, 4); assertEquals(2, testStore3.getSetOfKiosk().size()); testStore3.addKiosk(test_Employee3, 5); assertEquals(3, testStore3.getSetOfKiosk().size()); } @Test public void testGetSetOfRegister() { assertEquals(2, testStore3.getSetOfRegister().size()); assertTrue(testStore3.getSetOfRegister().contains(testRegister1)); assertTrue(testStore3.getSetOfRegister().contains(testRegister2)); } @Test public void testSetSetOfRegister() { Register tempRegister1 = new Register(3); Register tempRegister2 = new Register(4); Set<Register> registerSet = new HashSet<Register>(); registerSet.add(tempRegister1); registerSet.add(tempRegister2); assertEquals(0, testStore4.getSetOfRegister().size()); testStore4.setSetOfRegister(registerSet); assertEquals(2, testStore4.getSetOfRegister().size()); assertTrue(testStore4.getSetOfRegister().contains(tempRegister1)); assertTrue(testStore4.getSetOfRegister().contains(tempRegister2)); } @Test public void testCreateOrderViaRegister() { Employee test_Employee1 = testStore3.addEmployee(testName1, testLoginID1, testPassWord1, Role.Cashier); Employee test_Employee2 = testStore3.addEmployee(testName2, testLoginID2, testPassWord2, Role.Chef); Employee test_Employee3 = testStore3.addEmployee(testName3, testLoginID3, testPassWord3, Role.Manager); Order newOrder1 = testStore3.createOrderViaRegister(test_Employee1, testRegister1.getRegisterID()); assertEquals(testStore3.getSetOfPlacedOrder().size(), newOrder1.getOrderID()); Order newOrder2 = testStore3.createOrderViaRegister(test_Employee2, testRegister2.getRegisterID()); assertNull(newOrder2); Order newOrder3 = testStore3.createOrderViaRegister(test_Employee3, testRegister2.getRegisterID()); assertEquals(testStore3.getSetOfPlacedOrder().size(), newOrder3.getOrderID()); } @Test public void testCreateOrderViaKiosk() { Order newOrder1 = testStore3.createOrderViaKiosk(testKiosk1.getKioskID()); assertEquals(newOrder1.getOrderID(), testStore3.getSetOfPlacedOrder().size()); Order newOrder2 = testStore3.createOrderViaKiosk(testKiosk2.getKioskID()); assertEquals(newOrder2.getOrderID(), testStore3.getSetOfPlacedOrder().size()); } @Test public void testGetSetOfPlacedOrder() { Employee test_Employee1 = testStore3.addEmployee(testName1, testLoginID1, testPassWord1, Role.Cashier); assertEquals(0, testStore3.getSetOfPlacedOrder().size()); Order newOrder1 = testStore3.createOrderViaRegister(test_Employee1, testRegister1.getRegisterID()); Order newOrder3 = testStore3.createOrderViaKiosk(testKiosk1.getKioskID()); assertEquals(2, testStore3.getSetOfPlacedOrder().size()); assertTrue(testStore3.getSetOfPlacedOrder().contains(newOrder1)); assertTrue(testStore3.getSetOfPlacedOrder().contains(newOrder3)); } @Test public void testSetSetOfPlacedOrder() { Order tempOrder1 = new Order(3); Order tempOrder2 = new Order(4); Set<Order> tempOrderSet = new HashSet<Order>(); tempOrderSet.add(tempOrder1); tempOrderSet.add(tempOrder2); assertEquals(0, testStore3.getSetOfPlacedOrder().size()); testStore3.setSetOfPlacedOrder(tempOrderSet); assertEquals(2, testStore3.getSetOfPlacedOrder().size()); } @Test public void testGetSetOfItems() { Employee test_Employee3 = testStore3.addEmployee(testName3, testLoginID3, testPassWord3, Role.Manager); Menu m1 = testStore3.defineMenu(test_Employee3, menuName1, menuDesc1); assertEquals(0, testStore3.getSetOfItems().size()); testStore3.addMenuItem(test_Employee3, m1, "item1", 10, "test item 1"); assertEquals(1, testStore3.getSetOfItems().size()); testStore3.addMenuItem(test_Employee3, m1, "item2", 8, "test item 2"); assertEquals(2, testStore3.getSetOfItems().size()); } @Test public void testSetSetOfItems() { Set<Item> newItemSet = new HashSet<Item>(); newItemSet.add(test_item1); newItemSet.add(test_item2); /* Employee test_Employee1 = testStore3.addEmployee(testName1, testLoginID1, testPassWord1, Privilege.Cashier); Employee test_Employee2 = testStore3.addEmployee(testName2, testLoginID2, testPassWord2,Privilege.Chef); Employee test_Employee3 = testStore3.addEmployee(testName3, testLoginID3, testPassWord3,Privilege.Manager); */ assertEquals(0, testStore3.getSetOfItems().size()); testStore3.setSetOfItems(newItemSet); assertEquals(2, testStore3.getSetOfItems().size()); } }
package com.github.fengtan.solrgui.tables; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import org.apache.commons.lang3.StringUtils; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServer; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.impl.HttpSolrServer; import org.apache.solr.client.solrj.request.LukeRequest; import org.apache.solr.client.solrj.response.FacetField; import org.apache.solr.client.solrj.response.FacetField.Count; import org.apache.solr.client.solrj.response.LukeResponse; import org.apache.solr.client.solrj.response.LukeResponse.FieldInfo; import org.apache.solr.common.SolrDocumentList; import org.eclipse.jface.viewers.CellEditor; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TextCellEditor; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CCombo; import org.eclipse.swt.custom.TableEditor; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Text; public class SolrGUITable { // TODO extend Composite ? // Fetch 50 documents at a time. TODO make this configurable ? private static final int PAGE_SIZE = 50; private Map<Integer, SolrDocumentList> pages; private List<FieldInfo> fields; private Map<String, FacetField> facets; private Map<String, String> filters = new HashMap<String, String>(); private Table table; private TableViewer tableViewer; private SolrServer server; public SolrGUITable(Composite parent, String url) { this.server = new HttpSolrServer(url); this.fields = getRemoteFields(); // TODO what if new fields get created ? refresh ? this.facets = getRemoteFacets(); this.table = createTable(parent); this.tableViewer = createTableViewer(); // Initialize cache + row count clear(); } /** * Create the Table */ private Table createTable(Composite parent) { int style = SWT.SINGLE | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.HIDE_SELECTION | SWT.VIRTUAL; // TODO HIDE_SELECTION ? final Table table = new Table(parent, style); GridData gridData = new GridData(GridData.FILL_BOTH); gridData.grabExcessVerticalSpace = true; gridData.horizontalSpan = 5; // 5 according to number of buttons. TODO needed ? table.setLayoutData(gridData); table.setLinesVisible(true); table.setHeaderVisible(true); /* TODO implement table.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent event) { // TODO document in readme: typing 'Suppr' deletes a row. if (event.keyCode == SWT.DEL) { Table table = (Table) event.getSource(); TableItem item = table.getSelection()[0]; // TODO what if [0] does not exist. SolrDocument document = (SolrDocument) item.getData(); server.removeDocument(document); } } }); */ // Initialize item count to 1 so we can populate the first row with filters. table.setItemCount(1); table.addListener(SWT.SetData, new Listener() { @Override public void handleEvent(Event event) { TableItem item = (TableItem) event.item; int rowIndex = table.indexOf(item); // The first line is populated by filters. if (rowIndex == 0) { // TODO might need to populate if existing filters return; } // Use rowIndex - 1 since the first line is used for filters. for(int i=0; i<fields.size(); i++) { Object value = getDocumentValue(rowIndex - 1, fields.get(i)); item.setText(i, Objects.toString(value, "")); } // TODO use item.setText(String[] values) ? // TODO store status insert/update/delete using item.setData() ? } }); // Add columns for (FieldInfo field:fields) { TableColumn column = new TableColumn(table, SWT.LEFT); column.setText(field.getName()); column.pack(); // TODO needed ? might be worth to setLayout() to get rid of this } // Add filters. TableItem[] items = table.getItems(); // TODO do we need to load all items ? TableEditor editor = new TableEditor(table); for(int i=0; i<fields.size(); i++) { final CCombo combo = new CCombo(table, SWT.NONE); combo.add(""); // TODO check if map contains field ? // TODO no need to use facets for tm_body for instance FacetField facet = facets.get(fields.get(i).getName()); for(Count count:facet.getValues()) { combo.add(count.getName()); // TODO use count.getCount() too ? } combo.setData("field", facet.getName()); // Filter results when user selects a facet value. combo.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent event) { String filterName = combo.getData("field").toString(); String filterValue = combo.getText(); if (StringUtils.isEmpty(filterValue)) { filters.remove(filterName); } else { filters.put(filterName, filterValue); } clear(); } }); editor.grabHorizontal = true; editor.setEditor(combo, items[0], i); editor = new TableEditor(table); } // TODO re-use editor instead of SorlGUICellModifier ? return table; } /** * Create the TableViewer */ private TableViewer createTableViewer() { // TODO use collectionutils to transform List<FieldInfo> into List<String> List<String> columnNames = new ArrayList<String>(); for(FieldInfo field:fields) { columnNames.add(field.getName()); } // TODO cols String[] cols = new String[columnNames.size()]; columnNames.toArray(cols); TableViewer tableViewer = new TableViewer(table); tableViewer.setUseHashlookup(true); tableViewer.setColumnProperties(cols); // Create the cell editors CellEditor[] editors = new CellEditor[tableViewer.getColumnProperties().length]; TextCellEditor textEditor; for (int i=0; i < editors.length; i++) { textEditor = new TextCellEditor(table); ((Text) textEditor.getControl()).setTextLimit(60); editors[i] = textEditor; } tableViewer.setCellEditors(editors); tableViewer.setCellModifier(new SolrGUICellModifier()); return tableViewer; } // TODO allow to select multiple values for each field public void dispose() { tableViewer.getLabelProvider().dispose(); // TODO needed ? server.shutdown(); // TODO move server instantiation/shutdown into SolrGUITabItem ? } private List<FieldInfo> getRemoteFields() { LukeRequest request = new LukeRequest(); try { LukeResponse response = request.process(server); return new ArrayList<FieldInfo>(response.getFieldInfo().values()); } catch (SolrServerException e) { // TODO Auto-generated catch block e.printStackTrace(); return new ArrayList<FieldInfo>(); // TODO Collections.EMPTY_LIST } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return new ArrayList<FieldInfo>(); // TODO Collections.EMPTY_LIST } /* TODO provide option to use this in case Luke handler is not available? requires at least 1 document in the server Collection<String> fields = getAllDocuments().get(0).getFieldNames(); return fields.toArray(new String[fields.size()]); */ } private int getRemoteCount() { SolrQuery query = getBaseQuery(0, 0); try { // Solr returns a long, SWT expects an int. long count = server.query(query).getResults().getNumFound(); return Integer.parseInt(String.valueOf(count)); } catch (SolrServerException e) { // TODO Auto-generated catch block e.printStackTrace(); return 0; } } /* * Map facet name => facet field */ private Map<String, FacetField> getRemoteFacets() { SolrQuery query = getBaseQuery(0, 0); query.setFacet(true); query.setFacetSort("index"); query.setFacetLimit(-1); // TODO or set a limit ? no limit could be bad for perf for(FieldInfo field:fields) { // TODO we don't want facets on fields with too many values query.addFacetField(field.getName()); } Map<String, FacetField> facets = new HashMap<String, FacetField>(); try { for(FacetField facet:server.query(query).getFacetFields()) { facets.put(facet.getName(), facet); } } catch(SolrServerException e) { e.printStackTrace(); } return facets; } /** * Not null-safe */ private Object getDocumentValue(int rowIndex, FieldInfo field) { int page = rowIndex / PAGE_SIZE; // If page has not be fetched yet, then fetch it. if (!pages.containsKey(page)) { SolrQuery query = getBaseQuery(page * PAGE_SIZE, PAGE_SIZE); try { pages.put(page, server.query(query).getResults()); } catch(SolrServerException e) { // TODO handle exception e.printStackTrace(); } } return pages.get(page).get(rowIndex % PAGE_SIZE).getFieldValue(field.getName()); } private SolrQuery getBaseQuery(int start, int rows) { SolrQuery query = new SolrQuery("*:*"); query.setStart(start); query.setRows(rows); // Add filters. for (Entry<String, String> filter:filters.entrySet()) { query.addFilterQuery(filter.getKey()+":"+filter.getValue()); } return query; } /* * Re-populate table with remote data. */ private void clear() { pages = new HashMap<Integer, SolrDocumentList>(); table.setItemCount(getRemoteCount() + 1); // First row is for filters, the rest is for documents. table.clearAll(); } }
package com.jcwhatever.bukkit.generic.utils; import org.bukkit.entity.Entity; import org.bukkit.inventory.ItemStack; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Array utilities. */ public final class ArrayUtils { private ArrayUtils() {} public static final boolean[] EMPTY_BOOLEAN_ARRAY = new boolean[0]; public static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; public static final char[] EMPTY_CHAR_ARRAY = new char[0]; public static final short[] EMPTY_SHORT_ARRAY = new short[0]; public static final int[] EMPTY_INT_ARRAY = new int[0]; public static final long[] EMPTY_LONG_ARRAY = new long[0]; public static final float[] EMPTY_FLOAT_ARRAY = new float[0]; public static final double[] EMPTY_DOUBLE_ARRAY = new double[0]; public static final String[] EMPTY_STRING_ARRAY = new String[0]; public static final ItemStack[] EMPTY_ITEMSTACK_ARRAY = new ItemStack[0]; public static final Entity[] EMPTY_ENTITY_ARRAY = new Entity[0]; /** * Copy the source array elements to the destination array starting from the * beginning and ending when either the destination runs out of space or the * source runs out of elements. * * @param source The source array. * @param destination The destination array. * * @param <T> The array component type. * * @return The destination array. */ public static <T> T[] copyFromStart(T[] source, T[] destination) { PreCon.notNull(source); PreCon.notNull(destination); int size = Math.min(source.length, destination.length); System.arraycopy(source, 0, destination, 0, size); return destination; } /** * Copy the source array elements to the destination array starting from the * beginning and ending when either the destination runs out of space or the * source runs out of elements. * * @param source The source array. * @param destination The destination array. * * @return The destination array. */ public static boolean[] copyFromStart(boolean[] source, boolean[] destination) { PreCon.notNull(source); PreCon.notNull(destination); int size = Math.min(source.length, destination.length); System.arraycopy(source, 0, destination, 0, size); return destination; } /** * Copy the source array elements to the destination array starting from the * beginning and ending when either the destination runs out of space or the * source runs out of elements. * * @param source The source array. * @param destination The destination array. * * @return The destination array. */ public static byte[] copyFromStart(byte[] source, byte[] destination) { PreCon.notNull(source); PreCon.notNull(destination); int size = Math.min(source.length, destination.length); System.arraycopy(source, 0, destination, 0, size); return destination; } /** * Copy the source array elements to the destination array starting from the * beginning and ending when either the destination runs out of space or the * source runs out of elements. * * @param source The source array. * @param destination The destination array. * * @return The destination array. */ public static char[] copyFromStart(char[] source, char[] destination) { PreCon.notNull(source); PreCon.notNull(destination); int size = Math.min(source.length, destination.length); System.arraycopy(source, 0, destination, 0, size); return destination; } /** * Copy the source array elements to the destination array starting from the * beginning and ending when either the destination runs out of space or the * source runs out of elements. * * @param source The source array. * @param destination The destination array. * * @return The destination array. */ public static short[] copyFromStart(short[] source, short[] destination) { PreCon.notNull(source); PreCon.notNull(destination); int size = Math.min(source.length, destination.length); System.arraycopy(source, 0, destination, 0, size); return destination; } /** * Copy the source array elements to the destination array starting from the * beginning and ending when either the destination runs out of space or the * source runs out of elements. * * @param source The source array. * @param destination The destination array. * * @return The destination array. */ public static int[] copyFromStart(int[] source, int[] destination) { PreCon.notNull(source); PreCon.notNull(destination); int size = Math.min(source.length, destination.length); System.arraycopy(source, 0, destination, 0, size); return destination; } /** * Copy the source array elements to the destination array starting from the * beginning and ending when either the destination runs out of space or the * source runs out of elements. * * @param source The source array. * @param destination The destination array. * * @return The destination array. */ public static long[] copyFromStart(long[] source, long[] destination) { PreCon.notNull(source); PreCon.notNull(destination); int size = Math.min(source.length, destination.length); System.arraycopy(source, 0, destination, 0, size); return destination; } /** * Copy the source array elements to the destination array starting from the * beginning and ending when either the destination runs out of space or the * source runs out of elements. * * @param source The source array. * @param destination The destination array. * * @return The destination array. */ public static float[] copyFromStart(float[] source, float[] destination) { PreCon.notNull(source); PreCon.notNull(destination); int size = Math.min(source.length, destination.length); System.arraycopy(source, 0, destination, 0, size); return destination; } /** * Copy the source array elements to the destination array starting from the * beginning and ending when either the destination runs out of space or the * source runs out of elements. * * @param source The source array. * @param destination The destination array. * * @return The destination array. */ public static double[] copyFromStart(double[] source, double[] destination) { PreCon.notNull(source); PreCon.notNull(destination); int size = Math.min(source.length, destination.length); System.arraycopy(source, 0, destination, 0, size); return destination; } /** * Copy the source array elements to the destination array starting from the end * and finishing when either the destination runs out of space or the source runs * out of elements. * * @param source The source array. * @param destination The destination array. * * @param <T> The array component type. * * @return The destination array. */ public static <T> T[] copyFromEnd(T[] source, T[] destination) { PreCon.notNull(source); PreCon.notNull(destination); int delta = source.length - destination.length; int sourceAdjust = delta < 0 ? 0 : delta; int destAdjust = delta < 0 ? -delta : 0; System.arraycopy(source, sourceAdjust, destination, destAdjust, destination.length - destAdjust); return destination; } /** * Copy the source array elements to the destination array starting from the end * and finishing when either the destination runs out of space or the source runs * out of elements. * * @param source The source array. * @param destination The destination array. * * @return The destination array. */ public static boolean[] copyFromEnd(boolean[] source, boolean[] destination) { PreCon.notNull(source); PreCon.notNull(destination); int delta = source.length - destination.length; int sourceAdjust = delta < 0 ? 0 : delta; int destAdjust = delta < 0 ? -delta : 0; System.arraycopy(source, sourceAdjust, destination, destAdjust, destination.length - destAdjust); return destination; } /** * Copy the source array elements to the destination array starting from the end * and finishing when either the destination runs out of space or the source runs * out of elements. * * @param source The source array. * @param destination The destination array. * * @return The destination array. */ public static byte[] copyFromEnd(byte[] source, byte[] destination) { PreCon.notNull(source); PreCon.notNull(destination); int delta = source.length - destination.length; int sourceAdjust = delta < 0 ? 0 : delta; int destAdjust = delta < 0 ? -delta : 0; System.arraycopy(source, sourceAdjust, destination, destAdjust, destination.length - destAdjust); return destination; } /** * Copy the source array elements to the destination array starting from the end * and finishing when either the destination runs out of space or the source runs * out of elements. * * @param source The source array. * @param destination The destination array. * * @return The destination array. */ public static char[] copyFromEnd(char[] source, char[] destination) { PreCon.notNull(source); PreCon.notNull(destination); int delta = source.length - destination.length; int sourceAdjust = delta < 0 ? 0 : delta; int destAdjust = delta < 0 ? -delta : 0; System.arraycopy(source, sourceAdjust, destination, destAdjust, destination.length - destAdjust); return destination; } /** * Copy the source array elements to the destination array starting from the end * and finishing when either the destination runs out of space or the source runs * out of elements. * * @param source The source array. * @param destination The destination array. * * @return The destination array. */ public static short[] copyFromEnd(short[] source, short[] destination) { PreCon.notNull(source); PreCon.notNull(destination); int delta = source.length - destination.length; int sourceAdjust = delta < 0 ? 0 : delta; int destAdjust = delta < 0 ? -delta : 0; System.arraycopy(source, sourceAdjust, destination, destAdjust, destination.length - destAdjust); return destination; } /** * Copy the source array elements to the destination array starting from the end * and finishing when either the destination runs out of space or the source runs * out of elements. * * @param source The source array. * @param destination The destination array. * * @return The destination array. */ public static int[] copyFromEnd(int[] source, int[] destination) { PreCon.notNull(source); PreCon.notNull(destination); int delta = source.length - destination.length; int sourceAdjust = delta < 0 ? 0 : delta; int destAdjust = delta < 0 ? -delta : 0; System.arraycopy(source, sourceAdjust, destination, destAdjust, destination.length - destAdjust); return destination; } /** * Copy the source array elements to the destination array starting from the end * and finishing when either the destination runs out of space or the source runs * out of elements. * * @param source The source array. * @param destination The destination array. * * @return The destination array. */ public static long[] copyFromEnd(long[] source, long[] destination) { PreCon.notNull(source); PreCon.notNull(destination); int delta = source.length - destination.length; int sourceAdjust = delta < 0 ? 0 : delta; int destAdjust = delta < 0 ? -delta : 0; System.arraycopy(source, sourceAdjust, destination, destAdjust, destination.length - destAdjust); return destination; } /** * Copy the source array elements to the destination array starting from the end * and finishing when either the destination runs out of space or the source runs * out of elements. * * @param source The source array. * @param destination The destination array. * * @return The destination array. */ public static float[] copyFromEnd(float[] source, float[] destination) { PreCon.notNull(source); PreCon.notNull(destination); int delta = source.length - destination.length; int sourceAdjust = delta < 0 ? 0 : delta; int destAdjust = delta < 0 ? -delta : 0; System.arraycopy(source, sourceAdjust, destination, destAdjust, destination.length - destAdjust); return destination; } /** * Copy the source array elements to the destination array starting from the end * and finishing when either the destination runs out of space or the source runs * out of elements. * * @param source The source array. * @param destination The destination array. * * @return The destination array. */ public static double[] copyFromEnd(double[] source, double[] destination) { PreCon.notNull(source); PreCon.notNull(destination); int delta = source.length - destination.length; int sourceAdjust = delta < 0 ? 0 : delta; int destAdjust = delta < 0 ? -delta : 0; System.arraycopy(source, sourceAdjust, destination, destAdjust, destination.length - destAdjust); return destination; } /** * Reduce the size of an array by trimming from the beginning and end of the array. * * @param startAmountToRemove The number of elements to remove from the start of the array. * @param array The array to trim. * @param endAmountToRemove The number of elements to remove from the end of the array. * * @param <T> The component type. * * @return A new trimmed array. */ public static <T> T[] reduce(int startAmountToRemove, T[] array, int endAmountToRemove) { PreCon.positiveNumber(startAmountToRemove); PreCon.notNull(array); PreCon.positiveNumber(endAmountToRemove); PreCon.isValid(startAmountToRemove + endAmountToRemove <= array.length, "Amount to remove is larger than the array."); @SuppressWarnings("unchecked") Class<T> componentClass = (Class<T>) array.getClass().getComponentType(); int size = array.length - (startAmountToRemove + endAmountToRemove); if (size == 0) return newArray(componentClass, 0); T[] newArray = newArray(componentClass, size); System.arraycopy(array, startAmountToRemove - 1, newArray, 0, newArray.length); return newArray; } /** * Reduce the size of an array by trimming from the beginning and end of the array. * * @param startAmountToRemove The number of elements to remove from the start of the array. * @param array The array to trim. * @param endAmountToRemove The number of elements to remove from the end of the array. * * @return A new trimmed array. */ public static boolean[] reduce(int startAmountToRemove, boolean[] array, int endAmountToRemove) { PreCon.positiveNumber(startAmountToRemove); PreCon.notNull(array); PreCon.positiveNumber(endAmountToRemove); PreCon.isValid(startAmountToRemove + endAmountToRemove <= array.length, "Amount to remove is larger than the array."); int size = array.length - (startAmountToRemove + endAmountToRemove); if (size == 0) return EMPTY_BOOLEAN_ARRAY; boolean[] newArray = new boolean[size]; System.arraycopy(array, startAmountToRemove - 1, newArray, 0, newArray.length); return newArray; } /** * Reduce the size of an array by trimming from the beginning and end of the array. * * @param startAmountToRemove The number of elements to remove from the start of the array. * @param array The array to trim. * @param endAmountToRemove The number of elements to remove from the end of the array. * * @return A new trimmed array. */ public static byte[] reduce(int startAmountToRemove, byte[] array, int endAmountToRemove) { PreCon.positiveNumber(startAmountToRemove); PreCon.notNull(array); PreCon.positiveNumber(endAmountToRemove); PreCon.isValid(startAmountToRemove + endAmountToRemove <= array.length, "Amount to remove is larger than the array."); int size = array.length - (startAmountToRemove + endAmountToRemove); if (size == 0) return EMPTY_BYTE_ARRAY; byte[] newArray = new byte[size]; System.arraycopy(array, startAmountToRemove - 1, newArray, 0, newArray.length); return newArray; } /** * Reduce the size of an array by trimming from the beginning and end of the array. * * @param startAmountToRemove The number of elements to remove from the start of the array. * @param array The array to trim. * @param endAmountToRemove The number of elements to remove from the end of the array. * * @return A new trimmed array. */ public static char[] reduce(int startAmountToRemove, char[] array, int endAmountToRemove) { PreCon.positiveNumber(startAmountToRemove); PreCon.notNull(array); PreCon.positiveNumber(endAmountToRemove); PreCon.isValid(startAmountToRemove + endAmountToRemove <= array.length, "Amount to remove is larger than the array."); int size = array.length - (startAmountToRemove + endAmountToRemove); if (size == 0) return EMPTY_CHAR_ARRAY; char[] newArray = new char[size]; System.arraycopy(array, startAmountToRemove - 1, newArray, 0, newArray.length); return newArray; } /** * Reduce the size of an array by trimming from the beginning and end of the array. * * @param startAmountToRemove The number of elements to remove from the start of the array. * @param array The array to trim. * @param endAmountToRemove The number of elements to remove from the end of the array. * * @return A new trimmed array. */ public static short[] reduce(int startAmountToRemove, short[] array, int endAmountToRemove) { PreCon.positiveNumber(startAmountToRemove); PreCon.notNull(array); PreCon.positiveNumber(endAmountToRemove); PreCon.isValid(startAmountToRemove + endAmountToRemove <= array.length, "Amount to remove is larger than the array."); int size = array.length - (startAmountToRemove + endAmountToRemove); if (size == 0) return EMPTY_SHORT_ARRAY; short[] newArray = new short[size]; System.arraycopy(array, startAmountToRemove - 1, newArray, 0, newArray.length); return newArray; } /** * Reduce the size of an array by trimming from the beginning and end of the array. * * @param startAmountToRemove The number of elements to remove from the start of the array. * @param array The array to trim. * @param endAmountToRemove The number of elements to remove from the end of the array. * * @return A new trimmed array. */ public static int[] reduce(int startAmountToRemove, int[] array, int endAmountToRemove) { PreCon.positiveNumber(startAmountToRemove); PreCon.notNull(array); PreCon.positiveNumber(endAmountToRemove); PreCon.isValid(startAmountToRemove + endAmountToRemove <= array.length, "Amount to remove is larger than the array."); int size = array.length - (startAmountToRemove + endAmountToRemove); if (size == 0) return EMPTY_INT_ARRAY; int[] newArray = new int[size]; System.arraycopy(array, startAmountToRemove - 1, newArray, 0, newArray.length); return newArray; } /** * Reduce the size of an array by trimming from the beginning and end of the array. * * @param startAmountToRemove The number of elements to remove from the start of the array. * @param array The array to trim. * @param endAmountToRemove The number of elements to remove from the end of the array. * * @return A new trimmed array. */ public static long[] reduce(int startAmountToRemove, long[] array, int endAmountToRemove) { PreCon.positiveNumber(startAmountToRemove); PreCon.notNull(array); PreCon.positiveNumber(endAmountToRemove); PreCon.isValid(startAmountToRemove + endAmountToRemove <= array.length, "Amount to remove is larger than the array."); int size = array.length - (startAmountToRemove + endAmountToRemove); if (size == 0) return EMPTY_LONG_ARRAY; long[] newArray = new long[size]; System.arraycopy(array, startAmountToRemove - 1, newArray, 0, newArray.length); return newArray; } /** * Reduce the size of an array by trimming from the beginning and end of the array. * * @param startAmountToRemove The number of elements to remove from the start of the array. * @param array The array to trim. * @param endAmountToRemove The number of elements to remove from the end of the array. * * @return A new trimmed array. */ public static float[] reduce(int startAmountToRemove, float[] array, int endAmountToRemove) { PreCon.positiveNumber(startAmountToRemove); PreCon.notNull(array); PreCon.positiveNumber(endAmountToRemove); PreCon.isValid(startAmountToRemove + endAmountToRemove <= array.length, "Amount to remove is larger than the array."); int size = array.length - (startAmountToRemove + endAmountToRemove); if (size == 0) return EMPTY_FLOAT_ARRAY; float[] newArray = new float[size]; System.arraycopy(array, startAmountToRemove - 1, newArray, 0, newArray.length); return newArray; } /** * Reduce the size of an array by trimming from the beginning and end of the array. * * @param startAmountToRemove The number of elements to remove from the start of the array. * @param array The array to trim. * @param endAmountToRemove The number of elements to remove from the end of the array. * * @return A new trimmed array. */ public static double[] reduce(int startAmountToRemove, double[] array, int endAmountToRemove) { PreCon.positiveNumber(startAmountToRemove); PreCon.notNull(array); PreCon.positiveNumber(endAmountToRemove); PreCon.isValid(startAmountToRemove + endAmountToRemove <= array.length, "Amount to remove is larger than the array."); int size = array.length - (startAmountToRemove + endAmountToRemove); if (size == 0) return EMPTY_DOUBLE_ARRAY; double[] newArray = new double[size]; System.arraycopy(array, startAmountToRemove - 1, newArray, 0, newArray.length); return newArray; } /** * Reduce the size of an array by trimming from the beginning and end of the array. * * @param startAmountToRemove The number of elements to remove from the start of the array. * @param array The array to trim. * @param endAmountToRemove The number of elements to remove from the end of the array. * * @return A new trimmed array. */ public static String[] reduce(int startAmountToRemove, String[] array, int endAmountToRemove) { PreCon.positiveNumber(startAmountToRemove); PreCon.notNull(array); PreCon.positiveNumber(endAmountToRemove); PreCon.isValid(startAmountToRemove + endAmountToRemove <= array.length, "Amount to remove is larger than the array."); int size = array.length - (startAmountToRemove + endAmountToRemove); if (size == 0) return EMPTY_STRING_ARRAY; String[] newArray = new String[size]; System.arraycopy(array, startAmountToRemove - 1, newArray, 0, newArray.length); return newArray; } /** * Reduce the size of an array by trimming from the beginning and end of the array. * * @param startAmountToRemove The number of elements to remove from the start of the array. * @param array The array to trim. * @param endAmountToRemove The number of elements to remove from the end of the array. * * @return A new trimmed array. */ public static ItemStack[] reduce(int startAmountToRemove, ItemStack[] array, int endAmountToRemove) { PreCon.positiveNumber(startAmountToRemove); PreCon.notNull(array); PreCon.positiveNumber(endAmountToRemove); PreCon.isValid(startAmountToRemove + endAmountToRemove <= array.length, "Amount to remove is larger than the array."); int size = array.length - (startAmountToRemove + endAmountToRemove); if (size == 0) return EMPTY_ITEMSTACK_ARRAY; ItemStack[] newArray = new ItemStack[size]; System.arraycopy(array, startAmountToRemove - 1, newArray, 0, newArray.length); return newArray; } /** * Reduce the size of an array by trimming from the beginning and end of the array. * * @param startAmountToRemove The number of elements to remove from the start of the array. * @param array The array to trim. * @param endAmountToRemove The number of elements to remove from the end of the array. * * @return A new trimmed array. */ public static Entity[] reduce(int startAmountToRemove, Entity[] array, int endAmountToRemove) { PreCon.positiveNumber(startAmountToRemove); PreCon.notNull(array); PreCon.positiveNumber(endAmountToRemove); PreCon.isValid(startAmountToRemove + endAmountToRemove <= array.length, "Amount to remove is larger than the array."); int size = array.length - (startAmountToRemove + endAmountToRemove); if (size == 0) return EMPTY_ENTITY_ARRAY; Entity[] newArray = new Entity[size]; System.arraycopy(array, startAmountToRemove - 1, newArray, 0, newArray.length); return newArray; } /** * Reduce the size of an array by trimming from the beginning of the array. * * @param amountToRemove The number of elements to remove. * @param array The array to trim. * * @param <T> The component type. * * @return A new trimmed array. */ public static <T> T[] reduceStart(int amountToRemove, T[] array) { PreCon.notNull(array); PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array."); @SuppressWarnings("unchecked") Class<T> componentClass = (Class<T>) array.getClass().getComponentType(); if (array.length == amountToRemove) return newArray(componentClass, 0); int size = array.length - amountToRemove; T[] result = newArray(componentClass, size); return copyFromEnd(array, result); } /** * Reduce the size of an array by trimming from the beginning of the array. * * @param amountToRemove The number of elements to remove. * @param array The array to trim. * * @return A new trimmed array. */ public static boolean[] reduceStart(int amountToRemove, boolean[] array) { PreCon.notNull(array); PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array."); if (array.length == amountToRemove) return EMPTY_BOOLEAN_ARRAY; int size = array.length - amountToRemove; return copyFromEnd(array, new boolean[size]); } /** * Reduce the size of an array by trimming from the beginning of the array. * * @param amountToRemove The number of elements to remove. * @param array The array to trim. * * @return A new trimmed array. */ public static byte[] reduceStart(int amountToRemove, byte[] array) { PreCon.notNull(array); PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array."); if (array.length == amountToRemove) return EMPTY_BYTE_ARRAY; int size = array.length - amountToRemove; return copyFromEnd(array, new byte[size]); } /** * Reduce the size of an array by trimming from the beginning of the array. * * @param amountToRemove The number of elements to remove. * @param array The array to trim. * * @return A new trimmed array. */ public static char[] reduceStart(int amountToRemove, char[] array) { PreCon.notNull(array); PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array."); if (array.length == amountToRemove) return EMPTY_CHAR_ARRAY; int size = array.length - amountToRemove; return copyFromEnd(array, new char[size]); } /** * Reduce the size of an array by trimming from the beginning of the array. * * @param amountToRemove The number of elements to remove. * @param array The array to trim. * * @return A new trimmed array. */ public static short[] reduceStart(int amountToRemove, short[] array) { PreCon.notNull(array); PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array."); if (array.length == amountToRemove) return EMPTY_SHORT_ARRAY; int size = array.length - amountToRemove; return copyFromEnd(array, new short[size]); } /** * Reduce the size of an array by trimming from the beginning of the array. * * @param amountToRemove The number of elements to remove. * @param array The array to trim. * * @return A new trimmed array. */ public static int[] reduceStart(int amountToRemove, int[] array) { PreCon.notNull(array); PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array."); if (array.length == amountToRemove) return EMPTY_INT_ARRAY; int size = array.length - amountToRemove; return copyFromEnd(array, new int[size]); } /** * Reduce the size of an array by trimming from the beginning of the array. * * @param amountToRemove The number of elements to remove. * @param array The array to trim. * * @return A new trimmed array. */ public static long[] reduceStart(int amountToRemove, long[] array) { PreCon.notNull(array); PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array."); if (array.length == amountToRemove) return EMPTY_LONG_ARRAY; int size = array.length - amountToRemove; return copyFromEnd(array, new long[size]); } /** * Reduce the size of an array by trimming from the beginning of the array. * * @param amountToRemove The number of elements to remove. * @param array The array to trim. * * @return A new trimmed array. */ public static float[] reduceStart(int amountToRemove, float[] array) { PreCon.notNull(array); PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array."); if (array.length == amountToRemove) return EMPTY_FLOAT_ARRAY; int size = array.length - amountToRemove; return copyFromEnd(array, new float[size]); } /** * Reduce the size of an array by trimming from the beginning of the array. * * @param amountToRemove The number of elements to remove. * @param array The array to trim. * * @return A new trimmed array. */ public static double[] reduceStart(int amountToRemove, double[] array) { PreCon.notNull(array); PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array."); if (array.length == amountToRemove) return EMPTY_DOUBLE_ARRAY; int size = array.length - amountToRemove; return copyFromEnd(array, new double[size]); } /** * Reduce the size of an array by trimming from the beginning of the array. * * @param amountToRemove The number of elements to remove. * @param array The array to trim. * * @return A new trimmed array. */ public static String[] reduceStart(int amountToRemove, String[] array) { PreCon.notNull(array); PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array."); if (array.length == amountToRemove) return EMPTY_STRING_ARRAY; int size = array.length - amountToRemove; return copyFromEnd(array, new String[size]); } /** * Reduce the size of an array by trimming from the beginning of the array. * * @param amountToRemove The number of elements to remove. * @param array The array to trim. * * @return A new trimmed array. */ public static ItemStack[] reduceStart(int amountToRemove, ItemStack[] array) { PreCon.notNull(array); PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array."); if (array.length == amountToRemove) return EMPTY_ITEMSTACK_ARRAY; int size = array.length - amountToRemove; return copyFromEnd(array, new ItemStack[size]); } /** * Reduce the size of an array by trimming from the beginning of the array. * * @param amountToRemove The number of elements to remove. * @param array The array to trim. * * @return A new trimmed array. */ public static Entity[] reduceStart(int amountToRemove, Entity[] array) { PreCon.notNull(array); PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array."); if (array.length == amountToRemove) return EMPTY_ENTITY_ARRAY; int size = array.length - amountToRemove; return copyFromEnd(array, new Entity[size]); } /** * Reduce the size of an array by trimming from the end of the array. * * @param array The array to trim. * @param amountToRemove The number of elements to remove. * * @param <T> The array component type. * * @return A new trimmed array. */ public static <T> T[] reduceEnd(T[] array, int amountToRemove) { PreCon.notNull(array); PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array."); @SuppressWarnings("unchecked") Class<T> componentClass = (Class<T>) array.getClass().getComponentType(); if (array.length == amountToRemove) return newArray(componentClass, 0); int size = array.length - amountToRemove; T[] result = newArray(componentClass, size); return copyFromStart(array, result); } /** * Reduce the size of an array by trimming from the end of the array. * * @param array The array to trim. * @param amountToRemove The number of elements to remove. * * @return A new trimmed array. */ public static boolean[] reduceEnd(boolean[] array, int amountToRemove) { PreCon.notNull(array); PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array."); if (array.length == amountToRemove) return EMPTY_BOOLEAN_ARRAY; int size = array.length - amountToRemove; return copyFromStart(array, new boolean[size]); } /** * Reduce the size of an array by trimming from the end of the array. * * @param array The array to trim. * @param amountToRemove The number of elements to remove. * * @return A new trimmed array. */ public static byte[] reduceEnd(byte[] array, int amountToRemove) { PreCon.notNull(array); PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array."); if (array.length == amountToRemove) return EMPTY_BYTE_ARRAY; int size = array.length - amountToRemove; return copyFromStart(array, new byte[size]); } /** * Reduce the size of an array by trimming from the end of the array. * * @param array The array to trim. * @param amountToRemove The number of elements to remove. * * @return A new trimmed array. */ public static char[] reduceEnd(char[] array, int amountToRemove) { PreCon.notNull(array); PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array."); if (array.length == amountToRemove) return EMPTY_CHAR_ARRAY; int size = array.length - amountToRemove; return copyFromStart(array, new char[size]); } /** * Reduce the size of an array by trimming from the end of the array. * * @param array The array to trim. * @param amountToRemove The number of elements to remove. * * @return A new trimmed array. */ public static short[] reduceEnd(short[] array, int amountToRemove) { PreCon.notNull(array); PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array."); if (array.length == amountToRemove) return EMPTY_SHORT_ARRAY; int size = array.length - amountToRemove; return copyFromStart(array, new short[size]); } /** * Reduce the size of an array by trimming from the end of the array. * * @param array The array to trim. * @param amountToRemove The number of elements to remove. * * @return A new trimmed array. */ public static int[] reduceEnd(int[] array, int amountToRemove) { PreCon.notNull(array); PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array."); if (array.length == amountToRemove) return EMPTY_INT_ARRAY; int size = array.length - amountToRemove; return copyFromStart(array, new int[size]); } /** * Reduce the size of an array by trimming from the end of the array. * * @param array The array to trim. * @param amountToRemove The number of elements to remove. * * @return A new trimmed array. */ public static long[] reduceEnd(long[] array, int amountToRemove) { PreCon.notNull(array); PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array."); if (array.length == amountToRemove) return EMPTY_LONG_ARRAY; int size = array.length - amountToRemove; return copyFromStart(array, new long[size]); } /** * Reduce the size of an array by trimming from the end of the array. * * @param array The array to trim. * @param amountToRemove The number of elements to remove. * * @return A new trimmed array. */ public static float[] reduceEnd(float[] array, int amountToRemove) { PreCon.notNull(array); PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array."); if (array.length == amountToRemove) return EMPTY_FLOAT_ARRAY; int size = array.length - amountToRemove; return copyFromStart(array, new float[size]); } /** * Reduce the size of an array by trimming from the end of the array. * * @param array The array to trim. * @param amountToRemove The number of elements to remove. * * @return A new trimmed array. */ public static double[] reduceEnd(double[] array, int amountToRemove) { PreCon.notNull(array); PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array."); if (array.length == amountToRemove) return EMPTY_DOUBLE_ARRAY; int size = array.length - amountToRemove; return copyFromStart(array, new double[size]); } /** * Reduce the size of an array by trimming from the end of the array. * * @param array The array to trim. * @param amountToRemove The number of elements to remove. * * @return A new trimmed array. */ public static String[] reduceEnd(String[] array, int amountToRemove) { PreCon.notNull(array); PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array."); if (array.length == amountToRemove) return EMPTY_STRING_ARRAY; int size = array.length - amountToRemove; return copyFromStart(array, new String[size]); } /** * Reduce the size of an array by trimming from the end of the array. * * @param array The array to trim. * @param amountToRemove The number of elements to remove. * * @return A new trimmed array. */ public static ItemStack[] reduceEnd(ItemStack[] array, int amountToRemove) { PreCon.notNull(array); PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array."); if (array.length == amountToRemove) return EMPTY_ITEMSTACK_ARRAY; int size = array.length - amountToRemove; return copyFromStart(array, new ItemStack[size]); } /** * Reduce the size of an array by trimming from the end of the array. * * @param array The array to trim. * @param amountToRemove The number of elements to remove. * * @return A new trimmed array. */ public static Entity[] reduceEnd(Entity[] array, int amountToRemove) { PreCon.notNull(array); PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array."); if (array.length == amountToRemove) return EMPTY_ENTITY_ARRAY; int size = array.length - amountToRemove; return copyFromStart(array, new Entity[size]); } /** * Convert a primitive wrapper array to a primitive array. * * @param array The array to convert. * * @return A new primitive array. */ public static boolean[] toPrimitive(Boolean[] array) { PreCon.notNull(array); if (array.length == 0) return EMPTY_BOOLEAN_ARRAY; boolean[] newArray = new boolean[array.length]; for (int i=0; i < array.length; i++) { Boolean element = array[i]; newArray[i] = element == null ? false : element; } return newArray; } /** * Convert a primitive wrapper array to a primitive array. * * @param array The array to convert. * * @return A new primitive array. */ public static byte[] toPrimitive(Byte[] array) { PreCon.notNull(array); if (array.length == 0) return EMPTY_BYTE_ARRAY; byte[] newArray = new byte[array.length]; for (int i=0; i < array.length; i++) { Byte element = array[i]; newArray[i] = element == null ? 0 : element; } return newArray; } /** * Convert a primitive wrapper array to a primitive array. * * @param array The array to convert. * * @return A new primitive array. */ public static char[] toPrimitive(Character[] array) { PreCon.notNull(array); if (array.length == 0) return EMPTY_CHAR_ARRAY; char[] newArray = new char[array.length]; for (int i=0; i < array.length; i++) { Character element = array[i]; newArray[i] = element == null ? 0 : element; } return newArray; } /** * Convert a primitive wrapper array to a primitive array. * * @param array The array to convert. * * @return A new primitive array. */ public static short[] toPrimitive(Short[] array) { PreCon.notNull(array); if (array.length == 0) return EMPTY_SHORT_ARRAY; short[] newArray = new short[array.length]; for (int i=0; i < array.length; i++) { Short element = array[i]; newArray[i] = element == null ? 0 : element; } return newArray; } /** * Convert a primitive wrapper array to a primitive array. * * @param array The array to convert. * * @return A new primitive array. */ public static int[] toPrimitive(Integer[] array) { PreCon.notNull(array); if (array.length == 0) return EMPTY_INT_ARRAY; int[] newArray = new int[array.length]; for (int i=0; i < array.length; i++) { Integer element = array[i]; newArray[i] = element == null ? 0 : element; } return newArray; } /** * Convert a primitive wrapper array to a primitive array. * * @param array The array to convert. * * @return A new primitive array. */ public static long[] toPrimitive(Long[] array) { PreCon.notNull(array); if (array.length == 0) return EMPTY_LONG_ARRAY; long[] newArray = new long[array.length]; for (int i=0; i < array.length; i++) { Long element = array[i]; newArray[i] = element == null ? 0L : element; } return newArray; } /** * Convert a primitive wrapper array to a primitive array. * * @param array The array to convert. * * @return A new primitive array. */ public static float[] toPrimitive(Float[] array) { PreCon.notNull(array); if (array.length == 0) return EMPTY_FLOAT_ARRAY; float[] newArray = new float[array.length]; for (int i=0; i < array.length; i++) { Float element = array[i]; newArray[i] = element == null ? 0F : element; } return newArray; } /** * Convert a primitive wrapper array to a primitive array. * * @param array The array to convert. * * @return A new primitive array. */ public static double[] toPrimitive(Double[] array) { PreCon.notNull(array); if (array.length == 0) return EMPTY_DOUBLE_ARRAY; double[] newArray = new double[array.length]; for (int i=0; i < array.length; i++) { Double element = array[i]; newArray[i] = element == null ? 0 : element; } return newArray; } /** * Convert a primitive array to a primitive wrapper array. * * @param array The array to convert. * * @return A new primitive wrapper array. */ public static Boolean[] toWrapper(boolean[] array) { PreCon.notNull(array); Boolean[] newArray = new Boolean[array.length]; for (int i=0; i < array.length; i++) { newArray[i] = array[i]; } return newArray; } /** * Convert a primitive array to a primitive wrapper array. * * @param array The array to convert. * * @return A new primitive wrapper array. */ public static Byte[] toWrapper(byte[] array) { PreCon.notNull(array); Byte[] newArray = new Byte[array.length]; for (int i=0; i < array.length; i++) { newArray[i] = array[i]; } return newArray; } /** * Convert a primitive array to a primitive wrapper array. * * @param array The array to convert. * * @return A new primitive wrapper array. */ public static Character[] toWrapper(char[] array) { PreCon.notNull(array); Character[] newArray = new Character[array.length]; for (int i=0; i < array.length; i++) { newArray[i] = array[i]; } return newArray; } /** * Convert a primitive array to a primitive wrapper array. * * @param array The array to convert. * * @return A new primitive wrapper array. */ public static Short[] toWrapper(short[] array) { PreCon.notNull(array); Short[] newArray = new Short[array.length]; for (int i=0; i < array.length; i++) { newArray[i] = array[i]; } return newArray; } /** * Convert a primitive array to a primitive wrapper array. * * @param array The array to convert. * * @return A new primitive wrapper array. */ public static Integer[] toWrapper(int[] array) { PreCon.notNull(array); Integer[] newArray = new Integer[array.length]; for (int i=0; i < array.length; i++) { newArray[i] = array[i]; } return newArray; } /** * Convert a primitive array to a primitive wrapper array. * * @param array The array to convert. * * @return A new primitive wrapper array. */ public static Long[] toWrapper(long[] array) { PreCon.notNull(array); Long[] newArray = new Long[array.length]; for (int i=0; i < array.length; i++) { newArray[i] = array[i]; } return newArray; } /** * Convert a primitive array to a primitive wrapper array. * * @param array The array to convert. * * @return A new primitive wrapper array. */ public static Float[] toWrapper(float[] array) { PreCon.notNull(array); Float[] newArray = new Float[array.length]; for (int i=0; i < array.length; i++) { newArray[i] = array[i]; } return newArray; } /** * Convert a primitive array to a primitive wrapper array. * * @param array The array to convert. * * @return A new primitive wrapper array. */ public static Double[] toWrapper(double[] array) { PreCon.notNull(array); Double[] newArray = new Double[array.length]; for (int i=0; i < array.length; i++) { newArray[i] = array[i]; } return newArray; } /** * Get the element at the specified index of the array * or return the default value if the array is smaller * than the specified index. * * @param array The array to get an element from. * @param index The index of the element to get. * @param defaultValue The default value if the array isn't large enough. * * @param <T> The array component type. * * @return The element at the specified index or the default value. */ public static <T> T get(T[] array, int index, T defaultValue) { PreCon.notNull(array); return (index - 1 > array.length) ? defaultValue : array[index]; } /** * Get the element at the specified index of the array * or return the default value if the array is smaller * than the specified index. * * @param array The array to get an element from. * @param index The index of the element to get. * @param defaultValue The default value if the array isn't large enough. * * @return The element at the specified index or the default value. */ public static boolean get(boolean[] array, int index, boolean defaultValue) { PreCon.notNull(array); return (index - 1 > array.length) ? defaultValue : array[index]; } /** * Get the element at the specified index of the array * or return the default value if the array is smaller * than the specified index. * * @param array The array to get an element from. * @param index The index of the element to get. * @param defaultValue The default value if the array isn't large enough. * * @return The element at the specified index or the default value. */ public static byte get(byte[] array, int index, byte defaultValue) { PreCon.notNull(array); return (index - 1 > array.length) ? defaultValue : array[index]; } /** * Get the element at the specified index of the array * or return the default value if the array is smaller * than the specified index. * * @param array The array to get an element from. * @param index The index of the element to get. * @param defaultValue The default value if the array isn't large enough. * * @return The element at the specified index or the default value. */ public static short get(short[] array, int index, short defaultValue) { PreCon.notNull(array); return (index - 1 > array.length) ? defaultValue : array[index]; } /** * Get the element at the specified index of the array * or return the default value if the array is smaller * than the specified index. * * @param array The array to get an element from. * @param index The index of the element to get. * @param defaultValue The default value if the array isn't large enough. * * @return The element at the specified index or the default value. */ public static char get(char[] array, int index, char defaultValue) { PreCon.notNull(array); return (index - 1 > array.length) ? defaultValue : array[index]; } /** * Get the element at the specified index of the array * or return the default value if the array is smaller * than the specified index. * * @param array The array to get an element from. * @param index The index of the element to get. * @param defaultValue The default value if the array isn't large enough. * * @return The element at the specified index or the default value. */ public static int get(int[] array, int index, int defaultValue) { PreCon.notNull(array); return (index - 1 > array.length) ? defaultValue : array[index]; } /** * Get the element at the specified index of the array * or return the default value if the array is smaller * than the specified index. * * @param array The array to get an element from. * @param index The index of the element to get. * @param defaultValue The default value if the array isn't large enough. * * @return The element at the specified index or the default value. */ public static long get(long[] array, int index, long defaultValue) { PreCon.notNull(array); return (index - 1 > array.length) ? defaultValue : array[index]; } /** * Get the element at the specified index of the array * or return the default value if the array is smaller * than the specified index. * * @param array The array to get an element from. * @param index The index of the element to get. * @param defaultValue The default value if the array isn't large enough. * * @return The element at the specified index or the default value. */ public static float get(float[] array, int index, float defaultValue) { PreCon.notNull(array); return (index - 1 > array.length) ? defaultValue : array[index]; } /** * Get the element at the specified index of the array * or return the default value if the array is smaller * than the specified index. * * @param array The array to get an element from. * @param index The index of the element to get. * @param defaultValue The default value if the array isn't large enough. * * @return The element at the specified index or the default value. */ public static double get(double[] array, int index, double defaultValue) { PreCon.notNull(array); return (index - 1 > array.length) ? defaultValue : array[index]; } /** * Get the last element in an array. * * @param array The array. * * @param <T> The array component type. */ public static <T> T last(T[] array) { PreCon.notNull(array); PreCon.isValid(array.length > 0, "Array has no elements."); return array[array.length - 1]; } /** * Get the last element in an array. * * @param array The array. * * @param <T> The array component type. */ public static <T> T last(T[] array, T empty) { PreCon.notNull(array); if (array.length == 0) return empty; return array[array.length - 1]; } /** * Get the last element in an array. * * @param array The array. */ public static boolean last(boolean[] array) { PreCon.notNull(array); PreCon.isValid(array.length > 0, "Array has no elements."); return array[array.length - 1]; } /** * Get the last element in an array. * * @param array The array. * @param empty The value to return if the array is empty. */ public static boolean last(boolean[] array, boolean empty) { PreCon.notNull(array); if (array.length == 0) return empty; return array[array.length - 1]; } /** * Get the last element in an array. * * @param array The array. */ public static byte last(byte[] array) { PreCon.notNull(array); PreCon.isValid(array.length > 0, "Array has no elements."); return array[array.length - 1]; } /** * Get the last element in an array. * * @param array The array. * @param empty The value to return if the array is empty. */ public static byte last(byte[] array, byte empty) { PreCon.notNull(array); if (array.length == 0) return empty; return array[array.length - 1]; } /** * Get the last element in an array. * * @param array The array. */ public static char last(char[] array) { PreCon.notNull(array); PreCon.isValid(array.length > 0, "Array has no elements."); return array[array.length - 1]; } /** * Get the last element in an array. * * @param array The array. * @param empty The value to return if the array is empty. */ public static char last(char[] array, char empty) { PreCon.notNull(array); if (array.length == 0) return empty; return array[array.length - 1]; } /** * Get the last element in an array. * * @param array The array. */ public static short last(short[] array) { PreCon.notNull(array); PreCon.isValid(array.length > 0, "Array has no elements."); return array[array.length - 1]; } /** * Get the last element in an array. * * @param array The array. * @param empty The value to return if the array is empty. */ public static short last(short[] array, short empty) { PreCon.notNull(array); if (array.length == 0) return empty; return array[array.length - 1]; } /** * Get the last element in an array. * * @param array The array. */ public static int last(int[] array) { PreCon.notNull(array); PreCon.isValid(array.length > 0, "Array has no elements."); return array[array.length - 1]; } /** * Get the last element in an array. * * @param array The array. * @param empty The value to return if the array is empty. */ public static int last(int[] array, int empty) { PreCon.notNull(array); if (array.length == 0) return empty; return array[array.length - 1]; } /** * Get the last element in an array. * * @param array The array. */ public static long last(long[] array) { PreCon.notNull(array); PreCon.isValid(array.length > 0, "Array has no elements."); return array[array.length - 1]; } /** * Get the last element in an array. * * @param array The array. * @param empty The value to return if the array is empty. */ public static long last(long[] array, long empty) { PreCon.notNull(array); if (array.length == 0) return empty; return array[array.length - 1]; } /** * Get the last element in an array. * * @param array The array. */ public static float last(float[] array) { PreCon.notNull(array); PreCon.isValid(array.length > 0, "Array has no elements."); return array[array.length - 1]; } /** * Get the last element in an array. * * @param array The array. * @param empty The value to return if the array is empty. */ public static float last(float[] array, float empty) { PreCon.notNull(array); if (array.length == 0) return empty; return array[array.length - 1]; } /** * Get the last element in an array. * * @param array The array. */ public static double last(double[] array) { PreCon.notNull(array); PreCon.isValid(array.length > 0, "Array has no elements."); return array[array.length - 1]; } /** * Get the last element in an array. * * @param array The array. * @param empty The value to return if the array is empty. */ public static double last(double[] array, double empty) { PreCon.notNull(array); if (array.length == 0) return empty; return array[array.length - 1]; } /** * Convert an array to an array list. * * @param array The array to convert. * * @param <T> The array component type. */ public static <T> List<T> asList(T[] array) { PreCon.notNull(array); List<T> result = new ArrayList<T>(array.length); Collections.addAll(result, array); return result; } /** * Convert an array to an array list. * * @param array The array to convert. */ public static List<Boolean> asList(boolean[] array) { PreCon.notNull(array); List<Boolean> result = new ArrayList<>(array.length); for (boolean b : array) { result.add(b); } return result; } /** * Convert an array to an array list. * * @param array The array to convert. */ public static List<Byte> asList(byte[] array) { PreCon.notNull(array); List<Byte> result = new ArrayList<>(array.length); for (byte b : array) { result.add(b); } return result; } /** * Convert an array to an array list. * * @param array The array to convert. */ public static List<Character> asList(char[] array) { PreCon.notNull(array); List<Character> result = new ArrayList<>(array.length); for (char b : array) { result.add(b); } return result; } /** * Convert an array to an array list. * * @param array The array to convert. */ public static List<Short> asList(short[] array) { PreCon.notNull(array); List<Short> result = new ArrayList<>(array.length); for (short b : array) { result.add(b); } return result; } /** * Convert an array to an array list. * * @param array The array to convert. */ public static List<Integer> asList(int[] array) { PreCon.notNull(array); List<Integer> result = new ArrayList<>(array.length); for (int b : array) { result.add(b); } return result; } /** * Convert an array to an array list. * * @param array The array to convert. */ public static List<Long> asList(long[] array) { PreCon.notNull(array); List<Long> result = new ArrayList<>(array.length); for (long b : array) { result.add(b); } return result; } /** * Convert an array to an array list. * * @param array The array to convert. */ public static List<Float> asList(float[] array) { PreCon.notNull(array); List<Float> result = new ArrayList<>(array.length); for (float b : array) { result.add(b); } return result; } /** * Convert an array to an array list. * * @param array The array to convert. */ public static List<Double> asList(double[] array) { PreCon.notNull(array); List<Double> result = new ArrayList<>(array.length); for (double b : array) { result.add(b); } return result; } private static <T> T[] newArray(Class<T> arrayClass, int size) { @SuppressWarnings("unchecked") T[] newArray = (T[])Array.newInstance(arrayClass, size); return newArray; } }
package com.jcwhatever.bukkit.generic.utils; import org.bukkit.entity.Entity; import org.bukkit.inventory.ItemStack; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.LinkedList; /** * Array utilities. */ public final class ArrayUtils { private ArrayUtils() {} public static final boolean[] EMPTY_BOOLEAN_ARRAY = new boolean[0]; public static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; public static final char[] EMPTY_CHAR_ARRAY = new char[0]; public static final short[] EMPTY_SHORT_ARRAY = new short[0]; public static final int[] EMPTY_INT_ARRAY = new int[0]; public static final long[] EMPTY_LONG_ARRAY = new long[0]; public static final float[] EMPTY_FLOAT_ARRAY = new float[0]; public static final double[] EMPTY_DOUBLE_ARRAY = new double[0]; public static final String[] EMPTY_STRING_ARRAY = new String[0]; public static final ItemStack[] EMPTY_ITEMSTACK_ARRAY = new ItemStack[0]; public static final Entity[] EMPTY_ENTITY_ARRAY = new Entity[0]; /** * Copy the source array elements to the destination array starting from the * beginning and ending when either the destination runs out of space or the * source runs out of elements. * * @param source The source array. * @param destination The destination array. * * @param <T> The array component type. * * @return The destination array. */ public static <T> T[] copyFromStart(T[] source, T[] destination) { PreCon.notNull(source); PreCon.notNull(destination); int size = Math.min(source.length, destination.length); System.arraycopy(source, 0, destination, 0, size); return destination; } /** * Copy the source array elements to the destination array starting from the * beginning and ending when either the destination runs out of space or the * source runs out of elements. * * @param source The source array. * @param destination The destination array. * * @return The destination array. */ public static boolean[] copyFromStart(boolean[] source, boolean[] destination) { PreCon.notNull(source); PreCon.notNull(destination); int size = Math.min(source.length, destination.length); System.arraycopy(source, 0, destination, 0, size); return destination; } /** * Copy the source array elements to the destination array starting from the * beginning and ending when either the destination runs out of space or the * source runs out of elements. * * @param source The source array. * @param destination The destination array. * * @return The destination array. */ public static byte[] copyFromStart(byte[] source, byte[] destination) { PreCon.notNull(source); PreCon.notNull(destination); int size = Math.min(source.length, destination.length); System.arraycopy(source, 0, destination, 0, size); return destination; } /** * Copy the source array elements to the destination array starting from the * beginning and ending when either the destination runs out of space or the * source runs out of elements. * * @param source The source array. * @param destination The destination array. * * @return The destination array. */ public static char[] copyFromStart(char[] source, char[] destination) { PreCon.notNull(source); PreCon.notNull(destination); int size = Math.min(source.length, destination.length); System.arraycopy(source, 0, destination, 0, size); return destination; } /** * Copy the source array elements to the destination array starting from the * beginning and ending when either the destination runs out of space or the * source runs out of elements. * * @param source The source array. * @param destination The destination array. * * @return The destination array. */ public static short[] copyFromStart(short[] source, short[] destination) { PreCon.notNull(source); PreCon.notNull(destination); int size = Math.min(source.length, destination.length); System.arraycopy(source, 0, destination, 0, size); return destination; } /** * Copy the source array elements to the destination array starting from the * beginning and ending when either the destination runs out of space or the * source runs out of elements. * * @param source The source array. * @param destination The destination array. * * @return The destination array. */ public static int[] copyFromStart(int[] source, int[] destination) { PreCon.notNull(source); PreCon.notNull(destination); int size = Math.min(source.length, destination.length); System.arraycopy(source, 0, destination, 0, size); return destination; } /** * Copy the source array elements to the destination array starting from the * beginning and ending when either the destination runs out of space or the * source runs out of elements. * * @param source The source array. * @param destination The destination array. * * @return The destination array. */ public static long[] copyFromStart(long[] source, long[] destination) { PreCon.notNull(source); PreCon.notNull(destination); int size = Math.min(source.length, destination.length); System.arraycopy(source, 0, destination, 0, size); return destination; } /** * Copy the source array elements to the destination array starting from the * beginning and ending when either the destination runs out of space or the * source runs out of elements. * * @param source The source array. * @param destination The destination array. * * @return The destination array. */ public static float[] copyFromStart(float[] source, float[] destination) { PreCon.notNull(source); PreCon.notNull(destination); int size = Math.min(source.length, destination.length); System.arraycopy(source, 0, destination, 0, size); return destination; } /** * Copy the source array elements to the destination array starting from the * beginning and ending when either the destination runs out of space or the * source runs out of elements. * * @param source The source array. * @param destination The destination array. * * @return The destination array. */ public static double[] copyFromStart(double[] source, double[] destination) { PreCon.notNull(source); PreCon.notNull(destination); int size = Math.min(source.length, destination.length); System.arraycopy(source, 0, destination, 0, size); return destination; } /** * Copy the source array elements to the destination array starting from the end * and finishing when either the destination runs out of space or the source runs * out of elements. * * @param source The source array. * @param destination The destination array. * * @param <T> The array component type. * * @return The destination array. */ public static <T> T[] copyFromEnd(T[] source, T[] destination) { PreCon.notNull(source); PreCon.notNull(destination); int delta = source.length - destination.length; int sourceAdjust = delta < 0 ? 0 : delta; int destAdjust = delta < 0 ? -delta : 0; System.arraycopy(source, sourceAdjust, destination, destAdjust, destination.length - destAdjust); return destination; } /** * Copy the source array elements to the destination array starting from the end * and finishing when either the destination runs out of space or the source runs * out of elements. * * @param source The source array. * @param destination The destination array. * * @return The destination array. */ public static boolean[] copyFromEnd(boolean[] source, boolean[] destination) { PreCon.notNull(source); PreCon.notNull(destination); int delta = source.length - destination.length; int sourceAdjust = delta < 0 ? 0 : delta; int destAdjust = delta < 0 ? -delta : 0; System.arraycopy(source, sourceAdjust, destination, destAdjust, destination.length - destAdjust); return destination; } /** * Copy the source array elements to the destination array starting from the end * and finishing when either the destination runs out of space or the source runs * out of elements. * * @param source The source array. * @param destination The destination array. * * @return The destination array. */ public static byte[] copyFromEnd(byte[] source, byte[] destination) { PreCon.notNull(source); PreCon.notNull(destination); int delta = source.length - destination.length; int sourceAdjust = delta < 0 ? 0 : delta; int destAdjust = delta < 0 ? -delta : 0; System.arraycopy(source, sourceAdjust, destination, destAdjust, destination.length - destAdjust); return destination; } /** * Copy the source array elements to the destination array starting from the end * and finishing when either the destination runs out of space or the source runs * out of elements. * * @param source The source array. * @param destination The destination array. * * @return The destination array. */ public static char[] copyFromEnd(char[] source, char[] destination) { PreCon.notNull(source); PreCon.notNull(destination); int delta = source.length - destination.length; int sourceAdjust = delta < 0 ? 0 : delta; int destAdjust = delta < 0 ? -delta : 0; System.arraycopy(source, sourceAdjust, destination, destAdjust, destination.length - destAdjust); return destination; } /** * Copy the source array elements to the destination array starting from the end * and finishing when either the destination runs out of space or the source runs * out of elements. * * @param source The source array. * @param destination The destination array. * * @return The destination array. */ public static short[] copyFromEnd(short[] source, short[] destination) { PreCon.notNull(source); PreCon.notNull(destination); int delta = source.length - destination.length; int sourceAdjust = delta < 0 ? 0 : delta; int destAdjust = delta < 0 ? -delta : 0; System.arraycopy(source, sourceAdjust, destination, destAdjust, destination.length - destAdjust); return destination; } /** * Copy the source array elements to the destination array starting from the end * and finishing when either the destination runs out of space or the source runs * out of elements. * * @param source The source array. * @param destination The destination array. * * @return The destination array. */ public static int[] copyFromEnd(int[] source, int[] destination) { PreCon.notNull(source); PreCon.notNull(destination); int delta = source.length - destination.length; int sourceAdjust = delta < 0 ? 0 : delta; int destAdjust = delta < 0 ? -delta : 0; System.arraycopy(source, sourceAdjust, destination, destAdjust, destination.length - destAdjust); return destination; } /** * Copy the source array elements to the destination array starting from the end * and finishing when either the destination runs out of space or the source runs * out of elements. * * @param source The source array. * @param destination The destination array. * * @return The destination array. */ public static long[] copyFromEnd(long[] source, long[] destination) { PreCon.notNull(source); PreCon.notNull(destination); int delta = source.length - destination.length; int sourceAdjust = delta < 0 ? 0 : delta; int destAdjust = delta < 0 ? -delta : 0; System.arraycopy(source, sourceAdjust, destination, destAdjust, destination.length - destAdjust); return destination; } /** * Copy the source array elements to the destination array starting from the end * and finishing when either the destination runs out of space or the source runs * out of elements. * * @param source The source array. * @param destination The destination array. * * @return The destination array. */ public static float[] copyFromEnd(float[] source, float[] destination) { PreCon.notNull(source); PreCon.notNull(destination); int delta = source.length - destination.length; int sourceAdjust = delta < 0 ? 0 : delta; int destAdjust = delta < 0 ? -delta : 0; System.arraycopy(source, sourceAdjust, destination, destAdjust, destination.length - destAdjust); return destination; } /** * Copy the source array elements to the destination array starting from the end * and finishing when either the destination runs out of space or the source runs * out of elements. * * @param source The source array. * @param destination The destination array. * * @return The destination array. */ public static double[] copyFromEnd(double[] source, double[] destination) { PreCon.notNull(source); PreCon.notNull(destination); int delta = source.length - destination.length; int sourceAdjust = delta < 0 ? 0 : delta; int destAdjust = delta < 0 ? -delta : 0; System.arraycopy(source, sourceAdjust, destination, destAdjust, destination.length - destAdjust); return destination; } /** * Reduce the size of an array by trimming from the beginning and end of the array. * * @param startAmountToRemove The number of elements to remove from the start of the array. * @param array The array to trim. * @param endAmountToRemove The number of elements to remove from the end of the array. * * @param <T> The component type. * * @return A new trimmed array. */ public static <T> T[] reduce(int startAmountToRemove, T[] array, int endAmountToRemove) { PreCon.positiveNumber(startAmountToRemove); PreCon.notNull(array); PreCon.positiveNumber(endAmountToRemove); PreCon.isValid(startAmountToRemove + endAmountToRemove <= array.length, "Amount to remove is larger than the array."); @SuppressWarnings("unchecked") Class<T> componentClass = (Class<T>) array.getClass().getComponentType(); int size = array.length - (startAmountToRemove + endAmountToRemove); if (size == 0) return newArray(componentClass, 0); T[] newArray = newArray(componentClass, size); System.arraycopy(array, startAmountToRemove - 1, newArray, 0, newArray.length); return newArray; } /** * Reduce the size of an array by trimming from the beginning and end of the array. * * @param startAmountToRemove The number of elements to remove from the start of the array. * @param array The array to trim. * @param endAmountToRemove The number of elements to remove from the end of the array. * * @return A new trimmed array. */ public static boolean[] reduce(int startAmountToRemove, boolean[] array, int endAmountToRemove) { PreCon.positiveNumber(startAmountToRemove); PreCon.notNull(array); PreCon.positiveNumber(endAmountToRemove); PreCon.isValid(startAmountToRemove + endAmountToRemove <= array.length, "Amount to remove is larger than the array."); int size = array.length - (startAmountToRemove + endAmountToRemove); if (size == 0) return EMPTY_BOOLEAN_ARRAY; boolean[] newArray = new boolean[size]; System.arraycopy(array, startAmountToRemove - 1, newArray, 0, newArray.length); return newArray; } /** * Reduce the size of an array by trimming from the beginning and end of the array. * * @param startAmountToRemove The number of elements to remove from the start of the array. * @param array The array to trim. * @param endAmountToRemove The number of elements to remove from the end of the array. * * @return A new trimmed array. */ public static byte[] reduce(int startAmountToRemove, byte[] array, int endAmountToRemove) { PreCon.positiveNumber(startAmountToRemove); PreCon.notNull(array); PreCon.positiveNumber(endAmountToRemove); PreCon.isValid(startAmountToRemove + endAmountToRemove <= array.length, "Amount to remove is larger than the array."); int size = array.length - (startAmountToRemove + endAmountToRemove); if (size == 0) return EMPTY_BYTE_ARRAY; byte[] newArray = new byte[size]; System.arraycopy(array, startAmountToRemove - 1, newArray, 0, newArray.length); return newArray; } /** * Reduce the size of an array by trimming from the beginning and end of the array. * * @param startAmountToRemove The number of elements to remove from the start of the array. * @param array The array to trim. * @param endAmountToRemove The number of elements to remove from the end of the array. * * @return A new trimmed array. */ public static char[] reduce(int startAmountToRemove, char[] array, int endAmountToRemove) { PreCon.positiveNumber(startAmountToRemove); PreCon.notNull(array); PreCon.positiveNumber(endAmountToRemove); PreCon.isValid(startAmountToRemove + endAmountToRemove <= array.length, "Amount to remove is larger than the array."); int size = array.length - (startAmountToRemove + endAmountToRemove); if (size == 0) return EMPTY_CHAR_ARRAY; char[] newArray = new char[size]; System.arraycopy(array, startAmountToRemove - 1, newArray, 0, newArray.length); return newArray; } /** * Reduce the size of an array by trimming from the beginning and end of the array. * * @param startAmountToRemove The number of elements to remove from the start of the array. * @param array The array to trim. * @param endAmountToRemove The number of elements to remove from the end of the array. * * @return A new trimmed array. */ public static short[] reduce(int startAmountToRemove, short[] array, int endAmountToRemove) { PreCon.positiveNumber(startAmountToRemove); PreCon.notNull(array); PreCon.positiveNumber(endAmountToRemove); PreCon.isValid(startAmountToRemove + endAmountToRemove <= array.length, "Amount to remove is larger than the array."); int size = array.length - (startAmountToRemove + endAmountToRemove); if (size == 0) return EMPTY_SHORT_ARRAY; short[] newArray = new short[size]; System.arraycopy(array, startAmountToRemove - 1, newArray, 0, newArray.length); return newArray; } /** * Reduce the size of an array by trimming from the beginning and end of the array. * * @param startAmountToRemove The number of elements to remove from the start of the array. * @param array The array to trim. * @param endAmountToRemove The number of elements to remove from the end of the array. * * @return A new trimmed array. */ public static int[] reduce(int startAmountToRemove, int[] array, int endAmountToRemove) { PreCon.positiveNumber(startAmountToRemove); PreCon.notNull(array); PreCon.positiveNumber(endAmountToRemove); PreCon.isValid(startAmountToRemove + endAmountToRemove <= array.length, "Amount to remove is larger than the array."); int size = array.length - (startAmountToRemove + endAmountToRemove); if (size == 0) return EMPTY_INT_ARRAY; int[] newArray = new int[size]; System.arraycopy(array, startAmountToRemove - 1, newArray, 0, newArray.length); return newArray; } /** * Reduce the size of an array by trimming from the beginning and end of the array. * * @param startAmountToRemove The number of elements to remove from the start of the array. * @param array The array to trim. * @param endAmountToRemove The number of elements to remove from the end of the array. * * @return A new trimmed array. */ public static long[] reduce(int startAmountToRemove, long[] array, int endAmountToRemove) { PreCon.positiveNumber(startAmountToRemove); PreCon.notNull(array); PreCon.positiveNumber(endAmountToRemove); PreCon.isValid(startAmountToRemove + endAmountToRemove <= array.length, "Amount to remove is larger than the array."); int size = array.length - (startAmountToRemove + endAmountToRemove); if (size == 0) return EMPTY_LONG_ARRAY; long[] newArray = new long[size]; System.arraycopy(array, startAmountToRemove - 1, newArray, 0, newArray.length); return newArray; } /** * Reduce the size of an array by trimming from the beginning and end of the array. * * @param startAmountToRemove The number of elements to remove from the start of the array. * @param array The array to trim. * @param endAmountToRemove The number of elements to remove from the end of the array. * * @return A new trimmed array. */ public static float[] reduce(int startAmountToRemove, float[] array, int endAmountToRemove) { PreCon.positiveNumber(startAmountToRemove); PreCon.notNull(array); PreCon.positiveNumber(endAmountToRemove); PreCon.isValid(startAmountToRemove + endAmountToRemove <= array.length, "Amount to remove is larger than the array."); int size = array.length - (startAmountToRemove + endAmountToRemove); if (size == 0) return EMPTY_FLOAT_ARRAY; float[] newArray = new float[size]; System.arraycopy(array, startAmountToRemove - 1, newArray, 0, newArray.length); return newArray; } /** * Reduce the size of an array by trimming from the beginning and end of the array. * * @param startAmountToRemove The number of elements to remove from the start of the array. * @param array The array to trim. * @param endAmountToRemove The number of elements to remove from the end of the array. * * @return A new trimmed array. */ public static double[] reduce(int startAmountToRemove, double[] array, int endAmountToRemove) { PreCon.positiveNumber(startAmountToRemove); PreCon.notNull(array); PreCon.positiveNumber(endAmountToRemove); PreCon.isValid(startAmountToRemove + endAmountToRemove <= array.length, "Amount to remove is larger than the array."); int size = array.length - (startAmountToRemove + endAmountToRemove); if (size == 0) return EMPTY_DOUBLE_ARRAY; double[] newArray = new double[size]; System.arraycopy(array, startAmountToRemove - 1, newArray, 0, newArray.length); return newArray; } /** * Reduce the size of an array by trimming from the beginning and end of the array. * * @param startAmountToRemove The number of elements to remove from the start of the array. * @param array The array to trim. * @param endAmountToRemove The number of elements to remove from the end of the array. * * @return A new trimmed array. */ public static String[] reduce(int startAmountToRemove, String[] array, int endAmountToRemove) { PreCon.positiveNumber(startAmountToRemove); PreCon.notNull(array); PreCon.positiveNumber(endAmountToRemove); PreCon.isValid(startAmountToRemove + endAmountToRemove <= array.length, "Amount to remove is larger than the array."); int size = array.length - (startAmountToRemove + endAmountToRemove); if (size == 0) return EMPTY_STRING_ARRAY; String[] newArray = new String[size]; System.arraycopy(array, startAmountToRemove - 1, newArray, 0, newArray.length); return newArray; } /** * Reduce the size of an array by trimming from the beginning and end of the array. * * @param startAmountToRemove The number of elements to remove from the start of the array. * @param array The array to trim. * @param endAmountToRemove The number of elements to remove from the end of the array. * * @return A new trimmed array. */ public static ItemStack[] reduce(int startAmountToRemove, ItemStack[] array, int endAmountToRemove) { PreCon.positiveNumber(startAmountToRemove); PreCon.notNull(array); PreCon.positiveNumber(endAmountToRemove); PreCon.isValid(startAmountToRemove + endAmountToRemove <= array.length, "Amount to remove is larger than the array."); int size = array.length - (startAmountToRemove + endAmountToRemove); if (size == 0) return EMPTY_ITEMSTACK_ARRAY; ItemStack[] newArray = new ItemStack[size]; System.arraycopy(array, startAmountToRemove - 1, newArray, 0, newArray.length); return newArray; } /** * Reduce the size of an array by trimming from the beginning and end of the array. * * @param startAmountToRemove The number of elements to remove from the start of the array. * @param array The array to trim. * @param endAmountToRemove The number of elements to remove from the end of the array. * * @return A new trimmed array. */ public static Entity[] reduce(int startAmountToRemove, Entity[] array, int endAmountToRemove) { PreCon.positiveNumber(startAmountToRemove); PreCon.notNull(array); PreCon.positiveNumber(endAmountToRemove); PreCon.isValid(startAmountToRemove + endAmountToRemove <= array.length, "Amount to remove is larger than the array."); int size = array.length - (startAmountToRemove + endAmountToRemove); if (size == 0) return EMPTY_ENTITY_ARRAY; Entity[] newArray = new Entity[size]; System.arraycopy(array, startAmountToRemove - 1, newArray, 0, newArray.length); return newArray; } /** * Reduce the size of an array by trimming from the beginning of the array. * * @param amountToRemove The number of elements to remove. * @param array The array to trim. * * @param <T> The component type. * * @return A new trimmed array. */ public static <T> T[] reduceStart(int amountToRemove, T[] array) { PreCon.notNull(array); PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array."); @SuppressWarnings("unchecked") Class<T> componentClass = (Class<T>) array.getClass().getComponentType(); if (array.length == amountToRemove) return newArray(componentClass, 0); int size = array.length - amountToRemove; T[] result = newArray(componentClass, size); return copyFromEnd(array, result); } /** * Reduce the size of an array by trimming from the beginning of the array. * * @param amountToRemove The number of elements to remove. * @param array The array to trim. * * @return A new trimmed array. */ public static boolean[] reduceStart(int amountToRemove, boolean[] array) { PreCon.notNull(array); PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array."); if (array.length == amountToRemove) return EMPTY_BOOLEAN_ARRAY; int size = array.length - amountToRemove; return copyFromEnd(array, new boolean[size]); } /** * Reduce the size of an array by trimming from the beginning of the array. * * @param amountToRemove The number of elements to remove. * @param array The array to trim. * * @return A new trimmed array. */ public static byte[] reduceStart(int amountToRemove, byte[] array) { PreCon.notNull(array); PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array."); if (array.length == amountToRemove) return EMPTY_BYTE_ARRAY; int size = array.length - amountToRemove; return copyFromEnd(array, new byte[size]); } /** * Reduce the size of an array by trimming from the beginning of the array. * * @param amountToRemove The number of elements to remove. * @param array The array to trim. * * @return A new trimmed array. */ public static char[] reduceStart(int amountToRemove, char[] array) { PreCon.notNull(array); PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array."); if (array.length == amountToRemove) return EMPTY_CHAR_ARRAY; int size = array.length - amountToRemove; return copyFromEnd(array, new char[size]); } /** * Reduce the size of an array by trimming from the beginning of the array. * * @param amountToRemove The number of elements to remove. * @param array The array to trim. * * @return A new trimmed array. */ public static short[] reduceStart(int amountToRemove, short[] array) { PreCon.notNull(array); PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array."); if (array.length == amountToRemove) return EMPTY_SHORT_ARRAY; int size = array.length - amountToRemove; return copyFromEnd(array, new short[size]); } /** * Reduce the size of an array by trimming from the beginning of the array. * * @param amountToRemove The number of elements to remove. * @param array The array to trim. * * @return A new trimmed array. */ public static int[] reduceStart(int amountToRemove, int[] array) { PreCon.notNull(array); PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array."); if (array.length == amountToRemove) return EMPTY_INT_ARRAY; int size = array.length - amountToRemove; return copyFromEnd(array, new int[size]); } /** * Reduce the size of an array by trimming from the beginning of the array. * * @param amountToRemove The number of elements to remove. * @param array The array to trim. * * @return A new trimmed array. */ public static long[] reduceStart(int amountToRemove, long[] array) { PreCon.notNull(array); PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array."); if (array.length == amountToRemove) return EMPTY_LONG_ARRAY; int size = array.length - amountToRemove; return copyFromEnd(array, new long[size]); } /** * Reduce the size of an array by trimming from the beginning of the array. * * @param amountToRemove The number of elements to remove. * @param array The array to trim. * * @return A new trimmed array. */ public static float[] reduceStart(int amountToRemove, float[] array) { PreCon.notNull(array); PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array."); if (array.length == amountToRemove) return EMPTY_FLOAT_ARRAY; int size = array.length - amountToRemove; return copyFromEnd(array, new float[size]); } /** * Reduce the size of an array by trimming from the beginning of the array. * * @param amountToRemove The number of elements to remove. * @param array The array to trim. * * @return A new trimmed array. */ public static double[] reduceStart(int amountToRemove, double[] array) { PreCon.notNull(array); PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array."); if (array.length == amountToRemove) return EMPTY_DOUBLE_ARRAY; int size = array.length - amountToRemove; return copyFromEnd(array, new double[size]); } /** * Reduce the size of an array by trimming from the beginning of the array. * * @param amountToRemove The number of elements to remove. * @param array The array to trim. * * @return A new trimmed array. */ public static String[] reduceStart(int amountToRemove, String[] array) { PreCon.notNull(array); PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array."); if (array.length == amountToRemove) return EMPTY_STRING_ARRAY; int size = array.length - amountToRemove; return copyFromEnd(array, new String[size]); } /** * Reduce the size of an array by trimming from the beginning of the array. * * @param amountToRemove The number of elements to remove. * @param array The array to trim. * * @return A new trimmed array. */ public static ItemStack[] reduceStart(int amountToRemove, ItemStack[] array) { PreCon.notNull(array); PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array."); if (array.length == amountToRemove) return EMPTY_ITEMSTACK_ARRAY; int size = array.length - amountToRemove; return copyFromEnd(array, new ItemStack[size]); } /** * Reduce the size of an array by trimming from the beginning of the array. * * @param amountToRemove The number of elements to remove. * @param array The array to trim. * * @return A new trimmed array. */ public static Entity[] reduceStart(int amountToRemove, Entity[] array) { PreCon.notNull(array); PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array."); if (array.length == amountToRemove) return EMPTY_ENTITY_ARRAY; int size = array.length - amountToRemove; return copyFromEnd(array, new Entity[size]); } /** * Reduce the size of an array by trimming from the end of the array. * * @param array The array to trim. * @param amountToRemove The number of elements to remove. * * @param <T> The array component type. * * @return A new trimmed array. */ public static <T> T[] reduceEnd(T[] array, int amountToRemove) { PreCon.notNull(array); PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array."); @SuppressWarnings("unchecked") Class<T> componentClass = (Class<T>) array.getClass().getComponentType(); if (array.length == amountToRemove) return newArray(componentClass, 0); int size = array.length - amountToRemove; T[] result = newArray(componentClass, size); return copyFromStart(array, result); } /** * Reduce the size of an array by trimming from the end of the array. * * @param array The array to trim. * @param amountToRemove The number of elements to remove. * * @return A new trimmed array. */ public static boolean[] reduceEnd(boolean[] array, int amountToRemove) { PreCon.notNull(array); PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array."); if (array.length == amountToRemove) return EMPTY_BOOLEAN_ARRAY; int size = array.length - amountToRemove; return copyFromStart(array, new boolean[size]); } /** * Reduce the size of an array by trimming from the end of the array. * * @param array The array to trim. * @param amountToRemove The number of elements to remove. * * @return A new trimmed array. */ public static byte[] reduceEnd(byte[] array, int amountToRemove) { PreCon.notNull(array); PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array."); if (array.length == amountToRemove) return EMPTY_BYTE_ARRAY; int size = array.length - amountToRemove; return copyFromStart(array, new byte[size]); } /** * Reduce the size of an array by trimming from the end of the array. * * @param array The array to trim. * @param amountToRemove The number of elements to remove. * * @return A new trimmed array. */ public static char[] reduceEnd(char[] array, int amountToRemove) { PreCon.notNull(array); PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array."); if (array.length == amountToRemove) return EMPTY_CHAR_ARRAY; int size = array.length - amountToRemove; return copyFromStart(array, new char[size]); } /** * Reduce the size of an array by trimming from the end of the array. * * @param array The array to trim. * @param amountToRemove The number of elements to remove. * * @return A new trimmed array. */ public static short[] reduceEnd(short[] array, int amountToRemove) { PreCon.notNull(array); PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array."); if (array.length == amountToRemove) return EMPTY_SHORT_ARRAY; int size = array.length - amountToRemove; return copyFromStart(array, new short[size]); } /** * Reduce the size of an array by trimming from the end of the array. * * @param array The array to trim. * @param amountToRemove The number of elements to remove. * * @return A new trimmed array. */ public static int[] reduceEnd(int[] array, int amountToRemove) { PreCon.notNull(array); PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array."); if (array.length == amountToRemove) return EMPTY_INT_ARRAY; int size = array.length - amountToRemove; return copyFromStart(array, new int[size]); } /** * Reduce the size of an array by trimming from the end of the array. * * @param array The array to trim. * @param amountToRemove The number of elements to remove. * * @return A new trimmed array. */ public static long[] reduceEnd(long[] array, int amountToRemove) { PreCon.notNull(array); PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array."); if (array.length == amountToRemove) return EMPTY_LONG_ARRAY; int size = array.length - amountToRemove; return copyFromStart(array, new long[size]); } /** * Reduce the size of an array by trimming from the end of the array. * * @param array The array to trim. * @param amountToRemove The number of elements to remove. * * @return A new trimmed array. */ public static float[] reduceEnd(float[] array, int amountToRemove) { PreCon.notNull(array); PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array."); if (array.length == amountToRemove) return EMPTY_FLOAT_ARRAY; int size = array.length - amountToRemove; return copyFromStart(array, new float[size]); } /** * Reduce the size of an array by trimming from the end of the array. * * @param array The array to trim. * @param amountToRemove The number of elements to remove. * * @return A new trimmed array. */ public static double[] reduceEnd(double[] array, int amountToRemove) { PreCon.notNull(array); PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array."); if (array.length == amountToRemove) return EMPTY_DOUBLE_ARRAY; int size = array.length - amountToRemove; return copyFromStart(array, new double[size]); } /** * Reduce the size of an array by trimming from the end of the array. * * @param array The array to trim. * @param amountToRemove The number of elements to remove. * * @return A new trimmed array. */ public static String[] reduceEnd(String[] array, int amountToRemove) { PreCon.notNull(array); PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array."); if (array.length == amountToRemove) return EMPTY_STRING_ARRAY; int size = array.length - amountToRemove; return copyFromStart(array, new String[size]); } /** * Reduce the size of an array by trimming from the end of the array. * * @param array The array to trim. * @param amountToRemove The number of elements to remove. * * @return A new trimmed array. */ public static ItemStack[] reduceEnd(ItemStack[] array, int amountToRemove) { PreCon.notNull(array); PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array."); if (array.length == amountToRemove) return EMPTY_ITEMSTACK_ARRAY; int size = array.length - amountToRemove; return copyFromStart(array, new ItemStack[size]); } /** * Reduce the size of an array by trimming from the end of the array. * * @param array The array to trim. * @param amountToRemove The number of elements to remove. * * @return A new trimmed array. */ public static Entity[] reduceEnd(Entity[] array, int amountToRemove) { PreCon.notNull(array); PreCon.isValid(amountToRemove <= array.length, "Amount to remove is larger than the array."); if (array.length == amountToRemove) return EMPTY_ENTITY_ARRAY; int size = array.length - amountToRemove; return copyFromStart(array, new Entity[size]); } /** * Convert a primitive wrapper array to a primitive array. * * @param array The array to convert. * * @return A new primitive array. */ public static boolean[] toPrimitive(Boolean[] array) { PreCon.notNull(array); if (array.length == 0) return EMPTY_BOOLEAN_ARRAY; boolean[] newArray = new boolean[array.length]; for (int i=0; i < array.length; i++) { Boolean element = array[i]; newArray[i] = element == null ? false : element; } return newArray; } /** * Convert a primitive wrapper array to a primitive array. * * @param array The array to convert. * * @return A new primitive array. */ public static byte[] toPrimitive(Byte[] array) { PreCon.notNull(array); if (array.length == 0) return EMPTY_BYTE_ARRAY; byte[] newArray = new byte[array.length]; for (int i=0; i < array.length; i++) { Byte element = array[i]; newArray[i] = element == null ? 0 : element; } return newArray; } /** * Convert a primitive wrapper array to a primitive array. * * @param array The array to convert. * * @return A new primitive array. */ public static char[] toPrimitive(Character[] array) { PreCon.notNull(array); if (array.length == 0) return EMPTY_CHAR_ARRAY; char[] newArray = new char[array.length]; for (int i=0; i < array.length; i++) { Character element = array[i]; newArray[i] = element == null ? 0 : element; } return newArray; } /** * Convert a primitive wrapper array to a primitive array. * * @param array The array to convert. * * @return A new primitive array. */ public static short[] toPrimitive(Short[] array) { PreCon.notNull(array); if (array.length == 0) return EMPTY_SHORT_ARRAY; short[] newArray = new short[array.length]; for (int i=0; i < array.length; i++) { Short element = array[i]; newArray[i] = element == null ? 0 : element; } return newArray; } /** * Convert a primitive wrapper array to a primitive array. * * @param array The array to convert. * * @return A new primitive array. */ public static int[] toPrimitive(Integer[] array) { PreCon.notNull(array); if (array.length == 0) return EMPTY_INT_ARRAY; int[] newArray = new int[array.length]; for (int i=0; i < array.length; i++) { Integer element = array[i]; newArray[i] = element == null ? 0 : element; } return newArray; } /** * Convert a primitive wrapper array to a primitive array. * * @param array The array to convert. * * @return A new primitive array. */ public static long[] toPrimitive(Long[] array) { PreCon.notNull(array); if (array.length == 0) return EMPTY_LONG_ARRAY; long[] newArray = new long[array.length]; for (int i=0; i < array.length; i++) { Long element = array[i]; newArray[i] = element == null ? 0L : element; } return newArray; } /** * Convert a primitive wrapper array to a primitive array. * * @param array The array to convert. * * @return A new primitive array. */ public static float[] toPrimitive(Float[] array) { PreCon.notNull(array); if (array.length == 0) return EMPTY_FLOAT_ARRAY; float[] newArray = new float[array.length]; for (int i=0; i < array.length; i++) { Float element = array[i]; newArray[i] = element == null ? 0F : element; } return newArray; } /** * Convert a primitive wrapper array to a primitive array. * * @param array The array to convert. * * @return A new primitive array. */ public static double[] toPrimitive(Double[] array) { PreCon.notNull(array); if (array.length == 0) return EMPTY_DOUBLE_ARRAY; double[] newArray = new double[array.length]; for (int i=0; i < array.length; i++) { Double element = array[i]; newArray[i] = element == null ? 0 : element; } return newArray; } /** * Convert a primitive array to a primitive wrapper array. * * @param array The array to convert. * * @return A new primitive wrapper array. */ public static Boolean[] toWrapper(boolean[] array) { PreCon.notNull(array); Boolean[] newArray = new Boolean[array.length]; for (int i=0; i < array.length; i++) { newArray[i] = array[i]; } return newArray; } /** * Convert a primitive array to a primitive wrapper array. * * @param array The array to convert. * * @return A new primitive wrapper array. */ public static Byte[] toWrapper(byte[] array) { PreCon.notNull(array); Byte[] newArray = new Byte[array.length]; for (int i=0; i < array.length; i++) { newArray[i] = array[i]; } return newArray; } /** * Convert a primitive array to a primitive wrapper array. * * @param array The array to convert. * * @return A new primitive wrapper array. */ public static Character[] toWrapper(char[] array) { PreCon.notNull(array); Character[] newArray = new Character[array.length]; for (int i=0; i < array.length; i++) { newArray[i] = array[i]; } return newArray; } /** * Convert a primitive array to a primitive wrapper array. * * @param array The array to convert. * * @return A new primitive wrapper array. */ public static Short[] toWrapper(short[] array) { PreCon.notNull(array); Short[] newArray = new Short[array.length]; for (int i=0; i < array.length; i++) { newArray[i] = array[i]; } return newArray; } /** * Convert a primitive array to a primitive wrapper array. * * @param array The array to convert. * * @return A new primitive wrapper array. */ public static Integer[] toWrapper(int[] array) { PreCon.notNull(array); Integer[] newArray = new Integer[array.length]; for (int i=0; i < array.length; i++) { newArray[i] = array[i]; } return newArray; } /** * Convert a primitive array to a primitive wrapper array. * * @param array The array to convert. * * @return A new primitive wrapper array. */ public static Long[] toWrapper(long[] array) { PreCon.notNull(array); Long[] newArray = new Long[array.length]; for (int i=0; i < array.length; i++) { newArray[i] = array[i]; } return newArray; } /** * Convert a primitive array to a primitive wrapper array. * * @param array The array to convert. * * @return A new primitive wrapper array. */ public static Float[] toWrapper(float[] array) { PreCon.notNull(array); Float[] newArray = new Float[array.length]; for (int i=0; i < array.length; i++) { newArray[i] = array[i]; } return newArray; } /** * Convert a primitive array to a primitive wrapper array. * * @param array The array to convert. * * @return A new primitive wrapper array. */ public static Double[] toWrapper(double[] array) { PreCon.notNull(array); Double[] newArray = new Double[array.length]; for (int i=0; i < array.length; i++) { newArray[i] = array[i]; } return newArray; } /** * Get the element at the specified index of the array * or return the default value if the array is smaller * than the specified index. * * @param array The array to get an element from. * @param index The index of the element to get. * @param defaultValue The default value if the array isn't large enough. * * @param <T> The array component type. * * @return The element at the specified index or the default value. */ public static <T> T get(T[] array, int index, T defaultValue) { PreCon.notNull(array); return (index > array.length - 1) ? defaultValue : array[index]; } /** * Get the element at the specified index of the array * or return the default value if the array is smaller * than the specified index. * * @param array The array to get an element from. * @param index The index of the element to get. * @param defaultValue The default value if the array isn't large enough. * * @return The element at the specified index or the default value. */ public static boolean get(boolean[] array, int index, boolean defaultValue) { PreCon.notNull(array); return (index > array.length - 1) ? defaultValue : array[index]; } /** * Get the element at the specified index of the array * or return the default value if the array is smaller * than the specified index. * * @param array The array to get an element from. * @param index The index of the element to get. * @param defaultValue The default value if the array isn't large enough. * * @return The element at the specified index or the default value. */ public static byte get(byte[] array, int index, byte defaultValue) { PreCon.notNull(array); return (index > array.length - 1) ? defaultValue : array[index]; } /** * Get the element at the specified index of the array * or return the default value if the array is smaller * than the specified index. * * @param array The array to get an element from. * @param index The index of the element to get. * @param defaultValue The default value if the array isn't large enough. * * @return The element at the specified index or the default value. */ public static short get(short[] array, int index, short defaultValue) { PreCon.notNull(array); return (index > array.length - 1) ? defaultValue : array[index]; } /** * Get the element at the specified index of the array * or return the default value if the array is smaller * than the specified index. * * @param array The array to get an element from. * @param index The index of the element to get. * @param defaultValue The default value if the array isn't large enough. * * @return The element at the specified index or the default value. */ public static char get(char[] array, int index, char defaultValue) { PreCon.notNull(array); return (index > array.length - 1) ? defaultValue : array[index]; } /** * Get the element at the specified index of the array * or return the default value if the array is smaller * than the specified index. * * @param array The array to get an element from. * @param index The index of the element to get. * @param defaultValue The default value if the array isn't large enough. * * @return The element at the specified index or the default value. */ public static int get(int[] array, int index, int defaultValue) { PreCon.notNull(array); return (index > array.length - 1) ? defaultValue : array[index]; } /** * Get the element at the specified index of the array * or return the default value if the array is smaller * than the specified index. * * @param array The array to get an element from. * @param index The index of the element to get. * @param defaultValue The default value if the array isn't large enough. * * @return The element at the specified index or the default value. */ public static long get(long[] array, int index, long defaultValue) { PreCon.notNull(array); return (index > array.length - 1) ? defaultValue : array[index]; } /** * Get the element at the specified index of the array * or return the default value if the array is smaller * than the specified index. * * @param array The array to get an element from. * @param index The index of the element to get. * @param defaultValue The default value if the array isn't large enough. * * @return The element at the specified index or the default value. */ public static float get(float[] array, int index, float defaultValue) { PreCon.notNull(array); return (index > array.length - 1) ? defaultValue : array[index]; } /** * Get the element at the specified index of the array * or return the default value if the array is smaller * than the specified index. * * @param array The array to get an element from. * @param index The index of the element to get. * @param defaultValue The default value if the array isn't large enough. * * @return The element at the specified index or the default value. */ public static double get(double[] array, int index, double defaultValue) { PreCon.notNull(array); return (index > array.length - 1) ? defaultValue : array[index]; } /** * Get the last element in an array. * * @param array The array. * * @param <T> The array component type. */ public static <T> T last(T[] array) { PreCon.notNull(array); PreCon.isValid(array.length > 0, "Array has no elements."); return array[array.length - 1]; } /** * Get the last element in an array. * * @param array The array. * * @param <T> The array component type. */ public static <T> T last(T[] array, T empty) { PreCon.notNull(array); if (array.length == 0) return empty; return array[array.length - 1]; } /** * Get the last element in an array. * * @param array The array. */ public static boolean last(boolean[] array) { PreCon.notNull(array); PreCon.isValid(array.length > 0, "Array has no elements."); return array[array.length - 1]; } /** * Get the last element in an array. * * @param array The array. * @param empty The value to return if the array is empty. */ public static boolean last(boolean[] array, boolean empty) { PreCon.notNull(array); if (array.length == 0) return empty; return array[array.length - 1]; } /** * Get the last element in an array. * * @param array The array. */ public static byte last(byte[] array) { PreCon.notNull(array); PreCon.isValid(array.length > 0, "Array has no elements."); return array[array.length - 1]; } /** * Get the last element in an array. * * @param array The array. * @param empty The value to return if the array is empty. */ public static byte last(byte[] array, byte empty) { PreCon.notNull(array); if (array.length == 0) return empty; return array[array.length - 1]; } /** * Get the last element in an array. * * @param array The array. */ public static char last(char[] array) { PreCon.notNull(array); PreCon.isValid(array.length > 0, "Array has no elements."); return array[array.length - 1]; } /** * Get the last element in an array. * * @param array The array. * @param empty The value to return if the array is empty. */ public static char last(char[] array, char empty) { PreCon.notNull(array); if (array.length == 0) return empty; return array[array.length - 1]; } /** * Get the last element in an array. * * @param array The array. */ public static short last(short[] array) { PreCon.notNull(array); PreCon.isValid(array.length > 0, "Array has no elements."); return array[array.length - 1]; } /** * Get the last element in an array. * * @param array The array. * @param empty The value to return if the array is empty. */ public static short last(short[] array, short empty) { PreCon.notNull(array); if (array.length == 0) return empty; return array[array.length - 1]; } /** * Get the last element in an array. * * @param array The array. */ public static int last(int[] array) { PreCon.notNull(array); PreCon.isValid(array.length > 0, "Array has no elements."); return array[array.length - 1]; } /** * Get the last element in an array. * * @param array The array. * @param empty The value to return if the array is empty. */ public static int last(int[] array, int empty) { PreCon.notNull(array); if (array.length == 0) return empty; return array[array.length - 1]; } /** * Get the last element in an array. * * @param array The array. */ public static long last(long[] array) { PreCon.notNull(array); PreCon.isValid(array.length > 0, "Array has no elements."); return array[array.length - 1]; } /** * Get the last element in an array. * * @param array The array. * @param empty The value to return if the array is empty. */ public static long last(long[] array, long empty) { PreCon.notNull(array); if (array.length == 0) return empty; return array[array.length - 1]; } /** * Get the last element in an array. * * @param array The array. */ public static float last(float[] array) { PreCon.notNull(array); PreCon.isValid(array.length > 0, "Array has no elements."); return array[array.length - 1]; } /** * Get the last element in an array. * * @param array The array. * @param empty The value to return if the array is empty. */ public static float last(float[] array, float empty) { PreCon.notNull(array); if (array.length == 0) return empty; return array[array.length - 1]; } /** * Get the last element in an array. * * @param array The array. */ public static double last(double[] array) { PreCon.notNull(array); PreCon.isValid(array.length > 0, "Array has no elements."); return array[array.length - 1]; } /** * Get the last element in an array. * * @param array The array. * @param empty The value to return if the array is empty. */ public static double last(double[] array, double empty) { PreCon.notNull(array); if (array.length == 0) return empty; return array[array.length - 1]; } /** * Convert an array to an array list. * * @param array The array to convert. * * @param <T> The array component type. */ public static <T> ArrayList<T> asList(T[] array) { PreCon.notNull(array); ArrayList<T> result = new ArrayList<T>(array.length); Collections.addAll(result, array); return result; } /** * Convert an array to an array list. * * @param array The array to convert. */ public static ArrayList<Boolean> asList(boolean[] array) { PreCon.notNull(array); ArrayList<Boolean> result = new ArrayList<>(array.length); for (boolean b : array) { result.add(b); } return result; } /** * Convert an array to an array list. * * @param array The array to convert. */ public static ArrayList<Byte> asList(byte[] array) { PreCon.notNull(array); ArrayList<Byte> result = new ArrayList<>(array.length); for (byte b : array) { result.add(b); } return result; } /** * Convert an array to an array list. * * @param array The array to convert. */ public static ArrayList<Character> asList(char[] array) { PreCon.notNull(array); ArrayList<Character> result = new ArrayList<>(array.length); for (char b : array) { result.add(b); } return result; } /** * Convert an array to an array list. * * @param array The array to convert. */ public static ArrayList<Short> asList(short[] array) { PreCon.notNull(array); ArrayList<Short> result = new ArrayList<>(array.length); for (short b : array) { result.add(b); } return result; } /** * Convert an array to an array list. * * @param array The array to convert. */ public static ArrayList<Integer> asList(int[] array) { PreCon.notNull(array); ArrayList<Integer> result = new ArrayList<>(array.length); for (int b : array) { result.add(b); } return result; } /** * Convert an array to an array list. * * @param array The array to convert. */ public static ArrayList<Long> asList(long[] array) { PreCon.notNull(array); ArrayList<Long> result = new ArrayList<>(array.length); for (long b : array) { result.add(b); } return result; } /** * Convert an array to an array list. * * @param array The array to convert. */ public static ArrayList<Float> asList(float[] array) { PreCon.notNull(array); ArrayList<Float> result = new ArrayList<>(array.length); for (float b : array) { result.add(b); } return result; } /** * Convert an array to an array list. * * @param array The array to convert. */ public static ArrayList<Double> asList(double[] array) { PreCon.notNull(array); ArrayList<Double> result = new ArrayList<>(array.length); for (double b : array) { result.add(b); } return result; } /** * Convert an array to a {@code LinkedList}. * * @param array The array to convert. * * @param <T> The array component type. */ public static <T> LinkedList<T> asLinkedList(T[] array) { PreCon.notNull(array); LinkedList<T> result = new LinkedList<>(); Collections.addAll(result, array); return result; } /** * Convert an array to a {@code LinkedList}. * * @param array The array to convert. */ public static LinkedList<Boolean> asLinkedList(boolean[] array) { PreCon.notNull(array); LinkedList<Boolean> result = new LinkedList<>(); for (boolean b : array) { result.add(b); } return result; } /** * Convert an array to a {@code LinkedList}. * * @param array The array to convert. */ public static LinkedList<Byte> asLinkedList(byte[] array) { PreCon.notNull(array); LinkedList<Byte> result = new LinkedList<>(); for (byte b : array) { result.add(b); } return result; } /** * Convert an array to a {@code LinkedList}. * * @param array The array to convert. */ public static LinkedList<Character> asLinkedList(char[] array) { PreCon.notNull(array); LinkedList<Character> result = new LinkedList<>(); for (char b : array) { result.add(b); } return result; } /** * Convert an array to a {@code LinkedList}. * * @param array The array to convert. */ public static LinkedList<Short> asLinkedList(short[] array) { PreCon.notNull(array); LinkedList<Short> result = new LinkedList<>(); for (short b : array) { result.add(b); } return result; } /** * Convert an array to a {@code LinkedList}. * * @param array The array to convert. */ public static LinkedList<Integer> asLinkedList(int[] array) { PreCon.notNull(array); LinkedList<Integer> result = new LinkedList<>(); for (int b : array) { result.add(b); } return result; } /** * Convert an array to a {@code LinkedList}. * * @param array The array to convert. */ public static LinkedList<Long> asLinkedList(long[] array) { PreCon.notNull(array); LinkedList<Long> result = new LinkedList<>(); for (long b : array) { result.add(b); } return result; } /** * Convert an array to a {@code LinkedList}. * * @param array The array to convert. */ public static LinkedList<Float> asLinkedList(float[] array) { PreCon.notNull(array); LinkedList<Float> result = new LinkedList<>(); for (float b : array) { result.add(b); } return result; } /** * Convert an array to a {@code LinkedList}. * * @param array The array to convert. */ public static LinkedList<Double> asLinkedList(double[] array) { PreCon.notNull(array); LinkedList<Double> result = new LinkedList<>(); for (double b : array) { result.add(b); } return result; } /** * Convert an array to a {@code HashSet}. * * @param array The array to convert. * * @param <T> The array component type. */ public static <T> HashSet<T> asSet(T[] array) { PreCon.notNull(array); HashSet<T> result = new HashSet<>(array.length); Collections.addAll(result, array); return result; } /** * Convert an array to a {@code HashSet}. * * @param array The array to convert. */ public static HashSet<Boolean> asSet(boolean[] array) { PreCon.notNull(array); HashSet<Boolean> result = new HashSet<>(2); for (boolean b : array) { result.add(b); if (result.size() == 2) break; } return result; } /** * Convert an array to a {@code HashSet}. * * @param array The array to convert. */ public static HashSet<Byte> asSet(byte[] array) { PreCon.notNull(array); HashSet<Byte> result = new HashSet<>(array.length); for (byte b : array) { result.add(b); } return result; } /** * Convert an array to a {@code HashSet}. * * @param array The array to convert. */ public static HashSet<Character> asSet(char[] array) { PreCon.notNull(array); HashSet<Character> result = new HashSet<>(array.length); for (char b : array) { result.add(b); } return result; } /** * Convert an array to a {@code HashSet}. * * @param array The array to convert. */ public static HashSet<Short> asSet(short[] array) { PreCon.notNull(array); HashSet<Short> result = new HashSet<>(array.length); for (short b : array) { result.add(b); } return result; } /** * Convert an array to a {@code HashSet}. * * @param array The array to convert. */ public static HashSet<Integer> asSet(int[] array) { PreCon.notNull(array); HashSet<Integer> result = new HashSet<>(array.length); for (int b : array) { result.add(b); } return result; } /** * Convert an array to a {@code HashSet}. * * @param array The array to convert. */ public static HashSet<Long> asSet(long[] array) { PreCon.notNull(array); HashSet<Long> result = new HashSet<>(array.length); for (long b : array) { result.add(b); } return result; } /** * Convert an array to a {@code HashSet}. * * @param array The array to convert. */ public static HashSet<Float> asSet(float[] array) { PreCon.notNull(array); HashSet<Float> result = new HashSet<>(array.length); for (float b : array) { result.add(b); } return result; } /** * Convert an array to a {@code HashSet}. * * @param array The array to convert. */ public static HashSet<Double> asSet(double[] array) { PreCon.notNull(array); HashSet<Double> result = new HashSet<>(array.length); for (double b : array) { result.add(b); } return result; } private static <T> T[] newArray(Class<T> arrayClass, int size) { @SuppressWarnings("unchecked") T[] newArray = (T[])Array.newInstance(arrayClass, size); return newArray; } }
package com.opengamma.id; import java.io.Serializable; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Set; import org.apache.commons.lang.ObjectUtils; import org.fudgemsg.FudgeField; import org.fudgemsg.FudgeFieldContainer; import org.fudgemsg.FudgeMsg; /** * * * @author kirk */ public class DomainSpecificIdentifiersImpl implements Serializable, DomainSpecificIdentifiers { public static final String ID_FUDGE_FIELD_NAME = "ID"; private final Set<DomainSpecificIdentifier> _identifiers; private final int _hashCode; public DomainSpecificIdentifiersImpl(DomainSpecificIdentifier... identifiers) { if((identifiers == null) || (identifiers.length == 0)) { _identifiers = Collections.<DomainSpecificIdentifier>emptySet(); } else { _identifiers = new HashSet<DomainSpecificIdentifier>(identifiers.length); for(DomainSpecificIdentifier secId : identifiers) { _identifiers.add(secId); } } _hashCode = calcHashCode(); } public DomainSpecificIdentifiersImpl(Collection<? extends DomainSpecificIdentifier> identifiers) { if(identifiers == null) { _identifiers = Collections.<DomainSpecificIdentifier>emptySet(); } else { _identifiers = new HashSet<DomainSpecificIdentifier>(identifiers); } _hashCode = calcHashCode(); } public DomainSpecificIdentifiersImpl(DomainSpecificIdentifier identifier) { if(identifier == null) { _identifiers = Collections.<DomainSpecificIdentifier>emptySet(); } else { _identifiers = new HashSet<DomainSpecificIdentifier>(); _identifiers.add(identifier); } _hashCode = calcHashCode(); } public DomainSpecificIdentifiersImpl(FudgeFieldContainer fudgeMsg) { Set<DomainSpecificIdentifier> identifiers = new HashSet<DomainSpecificIdentifier>(); for(FudgeField field : fudgeMsg.getAllByName(ID_FUDGE_FIELD_NAME)) { if(!(field.getValue() instanceof FudgeFieldContainer)) { throw new IllegalArgumentException("Message provider has field named " + ID_FUDGE_FIELD_NAME + " which doesn't contain a sub-Message"); } DomainSpecificIdentifier identifier = new DomainSpecificIdentifier((FudgeFieldContainer)field.getValue()); identifiers.add(identifier); } _identifiers = identifiers; _hashCode = calcHashCode(); } @Override public Collection<DomainSpecificIdentifier> getIdentifiers() { return Collections.unmodifiableSet(_identifiers); } @Override public String getIdentifier(IdentificationDomain domain) { for(DomainSpecificIdentifier identifier : getIdentifiers()) { if(ObjectUtils.equals(domain, identifier.getDomain())) { return identifier.getValue(); } } return null; } @Override public FudgeFieldContainer toFudgeMsg() { FudgeMsg msg = new FudgeMsg(); for(DomainSpecificIdentifier identifier: getIdentifiers()) { msg.add(ID_FUDGE_FIELD_NAME, identifier.toFudgeMsg()); } return msg; } protected int calcHashCode() { final int prime = 31; int result = 1; result = prime * result + ((_identifiers == null) ? 0 : _identifiers.hashCode()); return result; } @Override public int hashCode() { return _hashCode; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; DomainSpecificIdentifiersImpl other = (DomainSpecificIdentifiersImpl) obj; if(!ObjectUtils.equals(_identifiers, other._identifiers)) { return false; } return true; } }
package com.tactfactory.harmony.command; import java.util.LinkedHashMap; import com.tactfactory.harmony.Console; import com.tactfactory.harmony.command.base.CommandBundleBase; import com.tactfactory.harmony.generator.FixtureGenerator; import com.tactfactory.harmony.meta.ApplicationMetadata; import com.tactfactory.harmony.meta.FixtureMetadata; import com.tactfactory.harmony.platform.BaseAdapter; import com.tactfactory.harmony.platform.IAdapter; import com.tactfactory.harmony.platform.TargetPlatform; import com.tactfactory.harmony.platform.android.AndroidAdapter; import com.tactfactory.harmony.platform.ios.IosAdapter; import com.tactfactory.harmony.platform.winphone.WinphoneAdapter; import com.tactfactory.harmony.utils.ConsoleUtils; import net.xeoh.plugins.base.annotations.PluginImplementation; /** * Fixture bundle command class. */ @PluginImplementation public class FixtureCommand extends CommandBundleBase<BaseAdapter> { //bundle name /** Bundle name. */ public static final String BUNDLE = "orm"; /** Fixture subject. */ public static final String SUBJECT = "fixture"; //actions /** Init action. */ public static final String ACTION_INIT = "init"; /** Load action. */ public static final String ACTION_LOAD = "load"; /** Purge action. */ public static final String ACTION_PURGE = "purge"; /** Update action. */ public static final String ACTION_UPDATE = "update"; //commands /** Command: ORM:FIXTURE:INIT. */ public static final String FIXTURE_INIT = BUNDLE + SEPARATOR + SUBJECT + SEPARATOR + ACTION_INIT; /** Command: ORM:FIXTURE:LOAD. */ public static final String FIXTURE_LOAD = BUNDLE + SEPARATOR + SUBJECT + SEPARATOR + ACTION_LOAD; /** Command: ORM:FIXTURE:PURGE. */ public static final String FIXTURE_PURGE = BUNDLE + SEPARATOR + SUBJECT + SEPARATOR + ACTION_PURGE; /** Command: ORM:FIXTURE:UPDATE. */ public static final String FIXTURE_UPDATE = BUNDLE + SEPARATOR + SUBJECT + SEPARATOR + ACTION_UPDATE; @Override public final void execute(final String action, final String[] args, final String option) { ConsoleUtils.display("> Fixture Generator"); this.setCommandArgs(Console.parseCommandArgs(args)); if (action.equals(FIXTURE_INIT)) { this.init(); } else if (action.equals(FIXTURE_LOAD)) { this.load(); } else if (action.equals(FIXTURE_PURGE)) { this.purge(); } else if (action.equals(FIXTURE_UPDATE)) { this.update(); } } /** * Init command. */ public final void init() { try { this.generateMetas(); final FixtureMetadata fixtureMeta = new FixtureMetadata(); //TODO : get type by user input fixtureMeta.setType("yml"); if (this.getCommandArgs().containsKey("format")) { final String format = this.getCommandArgs().get("format"); if (format.equals("xml") || format.equals("yml")) { fixtureMeta.setType(format); } } boolean force = false; if (this.getCommandArgs().containsKey("force")) { final String bool = this.getCommandArgs().get("force"); if (bool.equals("true")) { force = true; } } ApplicationMetadata.INSTANCE.getOptions().put( fixtureMeta.getName(), fixtureMeta); for(IAdapter adapter : this.getAdapters()) { try { new FixtureGenerator(adapter).init(force); } catch (final Exception e) { ConsoleUtils.displayError(e); } } } catch (final Exception e) { // TODO Auto-generated catch block ConsoleUtils.displayError(e); } } /** * Load command. */ public final void load() { for(IAdapter adapter : this.getAdapters()) { try { new FixtureGenerator(adapter).load(); } catch (final Exception e) { ConsoleUtils.displayError(e); } } } /** * Purge command. */ public final void purge() { this.generateMetas(); for(IAdapter adapter : this.getAdapters()) { try { new FixtureGenerator(adapter).purge(); } catch (final Exception e) { ConsoleUtils.displayError(e); } } } /** * Update command. */ public final void update() { } @Override public final void summary() { LinkedHashMap<String, String> commands = new LinkedHashMap<String, String>(); commands.put(FIXTURE_INIT, "Initialize fixtures, create loaders :\n" + "\t\t use --format=(xml|yml)" + " to specify a format (default : yml)\n" + "\t\t use --force=(true|false)" + " to overwrite existing fixture loaders (default : false)"); commands.put(FIXTURE_LOAD, "Load fixtures into the projects (overwrite)"); commands.put(FIXTURE_PURGE, "Clear fixtures on the projects"); commands.put(FIXTURE_UPDATE, "Update the fixtures in the project"); ConsoleUtils.displaySummary( SUBJECT, commands); } @Override public final boolean isAvailableCommand(final String command) { return command.equals(FIXTURE_INIT) || command.equals(FIXTURE_LOAD) || command.equals(FIXTURE_PURGE) || command.equals(FIXTURE_UPDATE); } @Override public void initBundleAdapter() { this.adapterMapping.put( TargetPlatform.ANDROID, AndroidAdapter.class); this.adapterMapping.put( TargetPlatform.WINPHONE, WinphoneAdapter.class); this.adapterMapping.put( TargetPlatform.IPHONE, IosAdapter.class); } }
package com.yidejia.app.mall.fragment; import android.os.Bundle; import android.text.format.DateUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ScrollView; import com.actionbarsherlock.app.SherlockFragment; import com.handmark.pulltorefresh.library.PullToRefreshBase; import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2; import com.handmark.pulltorefresh.library.PullToRefreshScrollView; import com.yidejia.app.mall.R; import com.yidejia.app.mall.util.AllOrderUtil; public class AllOrderFragment extends SherlockFragment { // private TextView titleTextView;// // private TextView numberTextView;// // private TextView sumPrice;// // private TextView countTextView;// // private LinearLayout mLayout;// // private View view; // private OrderDataManage orderDataManage ;// private String hello; private String defaultHello = "default hello"; private PullToRefreshScrollView mPullToRefreshScrollView; private LinearLayout relativeLayout; /** * * * @param view */ private void setupShow() { AllOrderUtil allOrderUtil = new AllOrderUtil(getSherlockActivity(), relativeLayout); allOrderUtil.loadView(fromIndex, amount); // mLayout = (LinearLayout) // view.findViewById(R.id.all_order_item_main_scrollView_linearlayout1); // orderDataManage = new OrderDataManage(getSherlockActivity()); // titleTextView = // (TextView)view.findViewById(R.id.all_order_item_main_item_detail); // numberTextView = // (TextView)view.findViewById(R.id.all_order_item_main_item_number); // sumPrice = // (TextView)view.findViewById(R.id.all_order_item_main_sum_money_deatil); // countTextView = // (TextView)view.findViewById(R.id.all_order_item_main_item_textview7); } public static AllOrderFragment newInstance(String s) { AllOrderFragment waitFragment = new AllOrderFragment(); Bundle bundle = new Bundle(); bundle.putString("Hello", s); waitFragment.setArguments(bundle); return waitFragment; } @Override public void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); Bundle args = getArguments(); hello = args != null ? args.getString("hello") : defaultHello; } private int fromIndex = 0; private int amount = 10; private OnRefreshListener2<ScrollView> listener = new OnRefreshListener2<ScrollView>() { @Override public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) { String label = getResources().getString(R.string.update_time) + DateUtils.formatDateTime(getSherlockActivity(), System.currentTimeMillis(), DateUtils.FORMAT_ABBREV_ALL | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME); refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label); setupShow(); mPullToRefreshScrollView.onRefreshComplete(); } @Override public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) { // TODO Auto-generated method stub String label = getResources().getString(R.string.update_time) + DateUtils.formatDateTime(getSherlockActivity(), System.currentTimeMillis(), DateUtils.FORMAT_ABBREV_ALL | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME); refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label); fromIndex += amount; setupShow(); mPullToRefreshScrollView.onRefreshComplete(); } }; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.all_order_item_main, null); mPullToRefreshScrollView = (PullToRefreshScrollView) view .findViewById(R.id.all_order_item_main_refresh_scrollview11); relativeLayout = (LinearLayout) view .findViewById(R.id.all_order_item_main_scrollView_linearlayout1); mPullToRefreshScrollView.setOnRefreshListener(listener); String label = getResources().getString(R.string.update_time) + DateUtils.formatDateTime(getSherlockActivity(), System.currentTimeMillis(), DateUtils.FORMAT_ABBREV_ALL | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_DATE); mPullToRefreshScrollView.getLoadingLayoutProxy().setLastUpdatedLabel(label); // Log.i("info", allOrderUtil+""); // setupShow(view); // getData(); // View produce = inflater.inflate(R.layout.all_order_item_produce, // null);// // View produce1 = inflater.inflate(R.layout.all_order_item_produce, // null);// // relativeLayout.addView(produce); // relativeLayout.addView(produce1); // produce1.setOnClickListener(new OnClickListener() { // @Override // public void onClick(View arg0) { // Intent intent = new // Intent(getSherlockActivity(),OrderDetailActivity.class); // startActivity(intent); // produce.setOnClickListener(new OnClickListener() { // @Override // public void onClick(View arg0) { // Intent intent = new // Intent(getSherlockActivity(),OrderDetailActivity.class); // startActivity(intent); return view; } @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); } // private void getData(){ // ArrayList<Order> mList = orderDataManage.getOrderArray(514492+"", "", "", // "", 0+"", 10+""); // for(int i=0;i<mList.size();i++){ // Order mOrder = mList.get(i); // titleTextView.setText(mOrder.getStatus()); // numberTextView.setText(mOrder.getOrderCode()); // mLayout.addView(view); }
package boundary.Game; import boundary.Question.QuestionResource; import boundary.Representation; import boundary.User.UserResource; import com.wordnik.swagger.annotations.ApiOperation; import com.wordnik.swagger.annotations.ApiResponse; import com.wordnik.swagger.annotations.ApiResponses; import entity.Game; import entity.User; import entity.UserRole; import provider.Secured; import javax.ejb.EJB; import javax.ejb.Stateless; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.DELETE; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.*; @Path("/games") @Stateless @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class GameRepresentation extends Representation { @EJB private GameResource gameResource; @EJB private UserResource userResource; @EJB private QuestionResource questionResource; @GET @Path("/{id}") @Secured({UserRole.CUSTOMER}) @ApiOperation(value = "Get a game by its id", notes = "Access : Owner only") @ApiResponses(value = { @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 401, message = "Unauthorized"), @ApiResponse(code = 404, message = "Not Found"), @ApiResponse(code = 500, message = "Internal server error") }) public Response get(@Context SecurityContext securityContext, @PathParam("id") String id) { Game game = gameResource.findById(id); if (game == null) flash(404, "Error : Game does not exist"); String currentEmail = securityContext.getUserPrincipal().getName(); String ownersEmail = game.getUser().getEmail(); if (!ownersEmail.equals(currentEmail)) return Response.status(Response.Status.UNAUTHORIZED).build(); return Response.ok(game, MediaType.APPLICATION_JSON).build(); } @POST @Secured({UserRole.CUSTOMER}) @ApiOperation(value = "Get a game by its id", notes = "Access : Owner only") @ApiResponses(value = { @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 401, message = "Unauthorized"), @ApiResponse(code = 404, message = "Not Found"), @ApiResponse(code = 500, message = "Internal server error") }) public Response add(@Context SecurityContext securityContext, Game game) { if (game == null) flash(400, EMPTY_JSON); if (!game.isValid()) flash(400, INVALID_JSON); User user = userResource.findByEmail(securityContext.getUserPrincipal().getName()); game.setUser(user); if (questionResource.findById(game.getQuestion().getId()) == null) flash(400, "Error : the question does not exist"); return Response.ok(gameResource.insert(game), MediaType.APPLICATION_JSON).build(); } @DELETE @Path("/{id}") @Secured({UserRole.ADMIN}) @ApiOperation(value = "Delete a game by its id", notes = "Access : Admin only") @ApiResponses(value = { @ApiResponse(code = 204, message = "No content"), @ApiResponse(code = 401, message = "Unauthorized"), @ApiResponse(code = 404, message = "Not Found"), @ApiResponse(code = 500, message = "Internal server error") }) public Response delete(@PathParam("id") String id) { Game game = gameResource.findById(id); if (game == null) flash(404, "Error : Game does not exist"); gameResource.delete(game); return Response.status(Response.Status.NO_CONTENT).build(); } }
package org.xdi.oxauth.util; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONObject; import org.xdi.oxauth.model.crypto.Key; import org.xdi.oxauth.model.crypto.KeyFactory; import org.xdi.oxauth.model.crypto.signature.*; /** * @author Javier Rojas Blum * @version 0.9, 09/23/2014 */ public class KeyGenerator { public static void main(String[] args) throws Exception { JSONArray keys = new JSONArray(); keys.put(generateRS256Keys()); keys.put(generateRS384Keys()); keys.put(generateRS512Keys()); keys.put(generateES256Keys()); keys.put(generateES384Keys()); keys.put(generateES512Keys()); JSONObject jsonObject = new JSONObject(); jsonObject.put("keys", keys); System.out.println(jsonObject.toString(4).replace("\\/", "/")); } public static JSONObject generateRS256Keys() throws Exception { KeyFactory<RSAPrivateKey, RSAPublicKey> keyFactory = new RSAKeyFactory( SignatureAlgorithm.RS256, "CN=Test CA Certificate"); Key<RSAPrivateKey, RSAPublicKey> key = keyFactory.getKey(); key.setKeyType("RSA"); key.setUse("SIGNATURE"); key.setAlgorithm("RS256"); key.setKeyId("1"); key.setCurve(JSONObject.NULL); return key.toJSONObject(); } public static JSONObject generateRS384Keys() throws Exception { KeyFactory<RSAPrivateKey, RSAPublicKey> keyFactory = new RSAKeyFactory( SignatureAlgorithm.RS384, "CN=Test CA Certificate"); Key<RSAPrivateKey, RSAPublicKey> key = keyFactory.getKey(); key.setKeyType("RSA"); key.setUse("SIGNATURE"); key.setAlgorithm("RS384"); key.setKeyId("2"); key.setCurve(JSONObject.NULL); return key.toJSONObject(); } public static JSONObject generateRS512Keys() throws Exception { KeyFactory<RSAPrivateKey, RSAPublicKey> keyFactory = new RSAKeyFactory( SignatureAlgorithm.RS512, "CN=Test CA Certificate"); Key<RSAPrivateKey, RSAPublicKey> key = keyFactory.getKey(); key.setKeyType("RSA"); key.setUse("SIGNATURE"); key.setAlgorithm("RS512"); key.setKeyId("3"); key.setCurve(JSONObject.NULL); return key.toJSONObject(); } public static JSONObject generateES256Keys() throws Exception { KeyFactory<ECDSAPrivateKey, ECDSAPublicKey> keyFactory = new ECDSAKeyFactory( SignatureAlgorithm.ES256, "CN=Test CA Certificate"); Key<ECDSAPrivateKey, ECDSAPublicKey> key = keyFactory.getKey(); key.setKeyType("EC"); key.setUse("SIGNATURE"); key.setAlgorithm("EC"); key.setKeyId("4"); key.setCurve("P-256"); return key.toJSONObject(); } public static JSONObject generateES384Keys() throws Exception { KeyFactory<ECDSAPrivateKey, ECDSAPublicKey> keyFactory = new ECDSAKeyFactory( SignatureAlgorithm.ES384, "CN=Test CA Certificate"); Key<ECDSAPrivateKey, ECDSAPublicKey> key = keyFactory.getKey(); key.setKeyType("EC"); key.setUse("SIGNATURE"); key.setAlgorithm("EC"); key.setKeyId("5"); key.setCurve("P-384"); return key.toJSONObject(); } public static JSONObject generateES512Keys() throws Exception{ KeyFactory<ECDSAPrivateKey, ECDSAPublicKey> keyFactory = new ECDSAKeyFactory( SignatureAlgorithm.ES512, "CN=Test CA Certificate"); Key<ECDSAPrivateKey, ECDSAPublicKey> key = keyFactory.getKey(); key.setKeyType("EC"); key.setUse("SIGNATURE"); key.setAlgorithm("EC"); key.setKeyId("6"); key.setCurve("P-521"); return key.toJSONObject(); } }
/** * In App Billing Plugin * * @author Guillaume Charhon - Smart Mobile Software * @modifications Brian Thurlow 10/16/13 * */ package com.mohamnag.inappbilling; import com.mohamnag.inappbilling.helper.Purchase; import org.json.JSONArray; import org.json.JSONObject; import org.json.JSONException; import java.util.List; import java.util.ArrayList; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; import com.mohamnag.inappbilling.helper.IabHelper; import com.mohamnag.inappbilling.helper.IabResult; import com.mohamnag.inappbilling.helper.Inventory; import com.mohamnag.inappbilling.helper.SkuDetails; import android.content.Intent; import android.util.Log; public class InAppBillingPlugin extends CordovaPlugin { //TODO: transfer all the logs back to JS for a better visibility. ~> window.inappbilling.log() /* Error codes. keep synchronized between: InAppPurchase.m, InAppBillingPlugin.java, android_iab.js and ios_iab.js Be carefull assiging new codes, these are meant to express the REASON of the error, not WHAT failed! */ private static final int ERROR_CODES_BASE = 4983497; private static final int ERR_LOAD = ERROR_CODES_BASE + 2; private static final int ERR_PURCHASE = ERROR_CODES_BASE + 3; private static final int ERR_LOAD_RECEIPTS = ERROR_CODES_BASE + 4; private static final int ERR_CLIENT_INVALID = ERROR_CODES_BASE + 5; private static final int ERR_PAYMENT_CANCELLED = ERROR_CODES_BASE + 6; private static final int ERR_PAYMENT_INVALID = ERROR_CODES_BASE + 7; private static final int ERR_PAYMENT_NOT_ALLOWED = ERROR_CODES_BASE + 8; private static final int ERR_UNKNOWN = ERROR_CODES_BASE + 10; // used here: private static final int ERR_SETUP = ERROR_CODES_BASE + 1; private static final int ERR_LOAD_INVENTORY = ERROR_CODES_BASE + 11; private static final int ERR_HELPER_DISPOSED = ERROR_CODES_BASE + 12; private static final int ERR_NOT_INITIALIZED = ERROR_CODES_BASE + 13; private static final int ERR_INVENTORY_NOT_LOADED = ERROR_CODES_BASE + 14; private static final int ERR_PURCHASE_FAILED = ERROR_CODES_BASE + 15; private static final int ERR_JSON_CONVERSION_FAILED = ERROR_CODES_BASE + 16; private static final int ERR_INVALID_PURCHASE_PAYLOAD = ERROR_CODES_BASE + 16; private boolean initialized = false; //TODO: set this from JS, according to what is defined in options private final Boolean ENABLE_DEBUG_LOGGING = true; private final String TAG = "CORDOVA_BILLING"; /* base64EncodedPublicKey should be YOUR APPLICATION'S PUBLIC KEY * (that you got from the Google Play developer console). This is not your * developer public key, it's the *app-specific* public key. * * Instead of just storing the entire literal string here embedded in the * program, construct the key at runtime from pieces or * use bit manipulation (for example, XOR with some other string) to hide * the actual key. The key itself is not secret information, but we don't * want to make it easy for an attacker to replace the public key with one * of their own and then fake messages from the server. */ private final String base64EncodedPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAogC9VXkak0pUlNZLpT90jKyejwrsd6ASjL1wuIJgpk3TyoOEYR3aUdthTfVEnqsEdOWNb/uc0CsFfsnGIchiQmiL3oSM7WFpC4/zWVYl8M+oe3BWczEMKSC7XR/XXjsnK7dMWvPFkProF9+4yDCHy+zpPT0HKP0UZOp0GTNGjgKP2SIye0Whx985vo6edsrKeNe7aZZS63N8X6bRIMAHKgyO4vowZJn+QYGzHh9ZSknExfJFqBKhMr5ytI2shhzFMx0tQPd76SKjIRZ8e6iQAyJkMjLnCBbhfB4FoguSXijB4PCZxTJ0fmO6OGIhWf3hz/wLRapGlRXtEuV2HVTH5QIDAQAB"; // (arbitrary) request code for the purchase flow static final int RC_REQUEST = 10001; // The helper object IabHelper mHelper; // A quite up to date inventory of available items and purchase items Inventory myInventory; //TODO: a global callbakcContext is wrong and may interfere in concurrent calls, remove this and pass it to each function! CallbackContext callbackContext; //TODO: replace all the Log.d() calls with this private void jsLog(String msg) { //TODO: msg is prone to js injection! current workaround: turn off logs in production String js = String.format("window.inappbilling.log('%s');", "[android] " + msg); webView.sendJavascript(js); } @Override /** * Called from JavaScript and dispatches the requests further to proper * functions. */ public boolean execute(String action, JSONArray data, final CallbackContext callbackContext) { this.callbackContext = callbackContext; // Check if the action has a handler Boolean isValidAction = true; // Action selector try { switch (action) { // Initialize case "init": { List<String> productIds = null; if (data.length() > 0) { productIds = jsonStringToList(data.getString(0)); } init(productIds, callbackContext); break; } // Get the list of purchases case "getPurchases": { if (isReady(callbackContext)) { getPurchases(callbackContext); } break; } // Buy an item case "buy": { if (isReady(callbackContext)) { String payload = ""; if(data.length() > 1) { payload = data.getString(1); } buy(data.getString(0), payload, callbackContext); } break; } case "subscribe": { // Subscribe to an item // Get Product Id final String sku = data.getString(0); subscribe(sku); break; } case "consumePurchase": consumePurchase(data); break; case "getAvailableProducts": { // Get the list of purchases JSONArray jsonSkuList = new JSONArray(); jsonSkuList = getAvailableProducts(); // Call the javascript back callbackContext.success(jsonSkuList); break; } case "getProductDetails": { getProductDetails(jsonStringToList(data.getString(0)), callbackContext); break; } default: // No handler for the action isValidAction = false; break; } } catch (IllegalStateException e) { callbackContext.error(e.getMessage()); } catch (JSONException e) { callbackContext.error(e.getMessage()); } // Method not found return isValidAction; } /** * Helper to convert JSON string to a List<String> * * @param data * @return */ private List<String> jsonStringToList(String data) { JSONArray jsonSkuList = new JSONArray(data); List<String> sku = new ArrayList<>(); int len = jsonSkuList.length(); jsLog("Num SKUs Found: " + len); for (int i = 0; i < len; i++) { sku.add(jsonSkuList.get(i).toString()); jsLog("Product SKU Added: " + jsonSkuList.get(i).toString()); } return sku; } /** * Initializes the plugin, will also optionally load products if some * product IDs are provided. * * @param productIds * @param callbackContext */ private void init(final List<String> productIds, final CallbackContext callbackContext) { jsLog("Initialization started."); // Some sanity checks to see if the developer (that's you!) really followed the // instructions to run this plugin if (base64EncodedPublicKey.contains("CONSTRUCT_YOUR")) { throw new RuntimeException("Please put your app's public key in InAppBillingPlugin.java. See ReadMe."); } // Create the helper, passing it our context and the public key to verify signatures with jsLog("Creating IAB helper."); mHelper = new IabHelper(cordova.getActivity().getApplicationContext(), base64EncodedPublicKey); // enable debug logging (for a production application, you should set this to false). mHelper.enableDebugLogging(ENABLE_DEBUG_LOGGING); // Start setup. This is asynchronous and the specified listener // will be called once setup completes. jsLog("Starting IAB setup."); mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() { @Override public void onIabSetupFinished(IabResult result) { if (!result.isSuccess()) { // Oh no, there was a problem. jsLog("Setup finished unsuccessfully."); callbackContext.error(ErrorEvent.buildJson( ERR_SETUP, "IAB setup was not successful", result )); } else { // Hooray, IAB is fully set up. jsLog("Setup finished successfully."); initialized = true; // Now, let's get an inventory of stuff we own. getProductDetails(productIds, callbackContext); } } }); } /** * Checks for correct initialization of plug-in and the case where helper is * disposed in mean time. * * @param result */ private boolean isReady(CallbackContext callbackContext) { if (!initialized) { callbackContext.error(ErrorEvent.buildJson( ERR_NOT_INITIALIZED, "Plugin has not been initialized.", null )); return false; } // Have we been disposed of in the meantime? If so, quit. (probably // useless but lets keep it for now!) else if (mHelper == null) { callbackContext.error(ErrorEvent.buildJson( ERR_HELPER_DISPOSED, "The billing helper has been disposed.", null )); return false; } else { return true; } } /** * Buy an already loaded item. * * @param productId * @param payload * @param callbackContext */ private void buy(final String productId, final String payload, final CallbackContext callbackContext) { this.cordova.setActivityResultCallback(this); // we create one listener for each purchase request, this guarnatiees // the concistency of data when multiple requests is launched in parallel IabHelper.OnIabPurchaseFinishedListener prchListener = new IabHelper.OnIabPurchaseFinishedListener() { @Override public void onIabPurchaseFinished(IabResult result, Purchase purchase) { jsLog("Purchase finished: " + result + ", purchase: " + purchase); if (isReady(callbackContext)) { if (result.isFailure()) { callbackContext.error(ErrorEvent.buildJson( ERR_PURCHASE_FAILED, "Purchase failed", result )); } else if (!payload.equals(purchase.getDeveloperPayload())) { callbackContext.error(ErrorEvent.buildJson( ERR_INVALID_PURCHASE_PAYLOAD, "Developer payload verification failed.", result )); } else { jsLog("Purchase successful."); // add the purchase to the inventory myInventory.addPurchase(purchase); try { callbackContext.success(new JSONObject(purchase.getOriginalJson())); } catch (JSONException e) { callbackContext.error(ErrorEvent.buildJson( ERR_JSON_CONVERSION_FAILED, "Could not create JSON object from purchase object", result )); } } } } }; mHelper.launchPurchaseFlow( cordova.getActivity(), productId, RC_REQUEST, prchListener, payload ); } // Buy an item private void subscribe(final String sku) { if (mHelper == null) { callbackContext.error("Billing plugin was not initialized"); return; } if (!mHelper.subscriptionsSupported()) { callbackContext.error("Subscriptions not supported on your device yet. Sorry!"); return; } /* TODO: for security, generate your payload here for verification. See the comments on * verifyDeveloperPayload() for more info. Since this is a sample, we just use * an empty string, but on a production app you should generate this. */ final String payload = ""; this.cordova.setActivityResultCallback(this); Log.d(TAG, "Launching purchase flow for subscription."); mHelper.launchPurchaseFlow(cordova.getActivity(), sku, IabHelper.ITEM_TYPE_SUBS, RC_REQUEST, mPurchaseFinishedListener, payload); } /** * Get list of loaded purchases * * @param callbackContext * @throws JSONException */ private void getPurchases(CallbackContext callbackContext) throws JSONException { jsLog("getPurchases called."); if (myInventory == null) { callbackContext.error(ErrorEvent.buildJson( ERR_INVENTORY_NOT_LOADED, "Inventory is not loaded.", null )); } else { List<Purchase> purchaseList = myInventory.getAllPurchases(); // Convert the java list to JSON JSONArray jsonPurchaseList = new JSONArray(); for (Purchase p : purchaseList) { jsonPurchaseList.put(new JSONObject(p.getOriginalJson())); } callbackContext.success(jsonPurchaseList); } } // Get the list of available products private JSONArray getAvailableProducts() { // Get the list of owned items if (myInventory == null) { callbackContext.error("Billing plugin was not initialized"); return new JSONArray(); } List<SkuDetails> skuList = myInventory.getAllProducts(); // Convert the java list to buildJson JSONArray jsonSkuList = new JSONArray(); try { for (SkuDetails sku : skuList) { Log.d(TAG, "SKUDetails: Title: " + sku.getTitle()); jsonSkuList.put(sku.toJson()); } } catch (JSONException e) { callbackContext.error(e.getMessage()); } return jsonSkuList; } /** * Loads products with specific IDs and gets their details. * * @param productIds * @param callbackContext */ private void getProductDetails(final List<String> productIds, final CallbackContext callbackContext) { if (isReady(callbackContext)) { IabHelper.QueryInventoryFinishedListener invListener = new IabHelper.QueryInventoryFinishedListener() { @Override public void onQueryInventoryFinished(IabResult result, Inventory inventory) { jsLog("Inventory listener called."); if (result.isFailure()) { callbackContext.error(ErrorEvent.buildJson( ERR_LOAD_INVENTORY, "Failed to query inventory.", result )); } else { //I'm not really feeling good about just copying inventory OVER old data! myInventory = inventory; jsLog("Query inventory was successful."); callbackContext.success(); } } }; if (productIds == null) { jsLog("Querying inventory without product IDs."); mHelper.queryInventoryAsync(invListener); } else { jsLog("Querying inventory with specific product IDs."); mHelper.queryInventoryAsync(true, productIds, invListener); } } } // Consume a purchase private void consumePurchase(JSONArray data) throws JSONException { if (mHelper == null) { callbackContext.error("Did you forget to initialize the plugin?"); return; } String sku = data.getString(0); // Get the purchase from the inventory Purchase purchase = myInventory.getPurchase(sku); if (purchase != null) // Consume it { mHelper.consumeAsync(purchase, mConsumeFinishedListener); } else { callbackContext.error(sku + " is not owned so it cannot be consumed"); } } // Listener that's called when we finish querying the items and subscriptions we own IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() { public void onQueryInventoryFinished(IabResult result, Inventory inventory) { Log.d(TAG, "Inside mGotInventoryListener"); if (!hasErrorsAndUpdateInventory(result, inventory)) { } Log.d(TAG, "Query inventory was successful."); callbackContext.success(); } }; // Listener that's called when we finish querying the details IabHelper.QueryInventoryFinishedListener mGotDetailsListener = new IabHelper.QueryInventoryFinishedListener() { public void onQueryInventoryFinished(IabResult result, Inventory inventory) { Log.d(TAG, "Inside mGotDetailsListener"); if (!hasErrorsAndUpdateInventory(result, inventory)) { } Log.d(TAG, "Query details was successful."); List<SkuDetails> skuList = inventory.getAllProducts(); // Convert the java list to buildJson JSONArray jsonSkuList = new JSONArray(); try { for (SkuDetails sku : skuList) { Log.d(TAG, "SKUDetails: Title: " + sku.getTitle()); jsonSkuList.put(sku.toJson()); } } catch (JSONException e) { callbackContext.error(e.getMessage()); } callbackContext.success(jsonSkuList); } }; // Check if there is any errors in the iabResult and update the inventory private Boolean hasErrorsAndUpdateInventory(IabResult result, Inventory inventory) { if (result.isFailure()) { callbackContext.error("Failed to query inventory: " + result); return true; } // Have we been disposed of in the meantime? If so, quit. if (mHelper == null) { callbackContext.error("The billing helper has been disposed"); return true; } // Update the inventory myInventory = inventory; return false; } // Callback for when a purchase is finished IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() { public void onIabPurchaseFinished(IabResult result, Purchase purchase) { Log.d(TAG, "Purchase finished: " + result + ", purchase: " + purchase); // Have we been disposed of in the meantime? If so, quit. if (mHelper == null) { callbackContext.error("The billing helper has been disposed"); } if (result.isFailure()) { callbackContext.error("Error purchasing: " + result); return; } if (!verifyDeveloperPayload(purchase)) { callbackContext.error("Error purchasing. Authenticity verification failed."); return; } Log.d(TAG, "Purchase successful."); // add the purchase to the inventory myInventory.addPurchase(purchase); try { callbackContext.success(new JSONObject(purchase.getOriginalJson())); } catch (JSONException e) { callbackContext.error("Could not create JSON object from purchase object"); } } }; // Called when consumption is complete IabHelper.OnConsumeFinishedListener mConsumeFinishedListener = new IabHelper.OnConsumeFinishedListener() { public void onConsumeFinished(Purchase purchase, IabResult result) { Log.d(TAG, "Consumption finished. Purchase: " + purchase + ", result: " + result); // We know this is the "gas" sku because it's the only one we consume, // so we don't check which sku was consumed. If you have more than one // sku, you probably should check... if (result.isSuccess()) { // successfully consumed, so we apply the effects of the item in our // game world's logic // remove the item from the inventory myInventory.erasePurchase(purchase.getSku()); Log.d(TAG, "Consumption successful. ."); callbackContext.success(purchase.getOriginalJson()); } else { callbackContext.error("Error while consuming: " + result); } } }; @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { Log.d(TAG, "onActivityResult(" + requestCode + "," + resultCode + "," + data); // Pass on the activity result to the helper for handling if (!mHelper.handleActivityResult(requestCode, resultCode, data)) { // not handled, so handle it ourselves (here's where you'd // perform any handling of activity results not related to in-app // billing... super.onActivityResult(requestCode, resultCode, data); } else { Log.d(TAG, "onActivityResult handled by IABUtil."); } } /** * Verifies the developer payload of a purchase. */ boolean verifyDeveloperPayload(Purchase p) { @SuppressWarnings("unused") String payload = p.getDeveloperPayload(); /* * TODO: verify that the developer payload of the purchase is correct. It will be * the same one that you sent when initiating the purchase. * * WARNING: Locally generating a random string when starting a purchase and * verifying it here might seem like a good approach, but this will fail in the * case where the user purchases an item on one device and then uses your app on * a different device, because on the other device you will not have access to the * random string you originally generated. * * So a good developer payload has these characteristics: * * 1. If two different users purchase an item, the payload is different between them, * so that one user's purchase can't be replayed to another user. * * 2. The payload must be such that you can verify it even when the app wasn't the * one who initiated the purchase flow (so that items purchased by the user on * one device work on other devices owned by the user). * * Using your own server to store and verify developer payloads across app * installations is recommended. */ return true; } // We're being destroyed. It's important to dispose of the helper here! @Override public void onDestroy() { super.onDestroy(); // very important: Log.d(TAG, "Destroying helper."); if (mHelper != null) { mHelper.dispose(); mHelper = null; } } }
package de.bitbrain.braingdx.apps.rpg; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.scenes.scene2d.Stage; import de.bitbrain.braingdx.apps.Assets; import de.bitbrain.braingdx.assets.SharedAssetManager; import de.bitbrain.braingdx.behavior.movement.Orientation; import de.bitbrain.braingdx.behavior.movement.RasteredMovementBehavior; import de.bitbrain.braingdx.graphics.animation.SpriteSheet; import de.bitbrain.braingdx.graphics.animation.SpriteSheetAnimation; import de.bitbrain.braingdx.graphics.animation.SpriteSheetAnimation.Direction; import de.bitbrain.braingdx.graphics.animation.types.AnimationTypes; import de.bitbrain.braingdx.graphics.lighting.PointLightBehavior; import de.bitbrain.braingdx.graphics.pipeline.RenderPipe; import de.bitbrain.braingdx.graphics.pipeline.layers.RenderPipeIds; import de.bitbrain.braingdx.graphics.pipeline.layers.TextureRenderLayer; import de.bitbrain.braingdx.graphics.renderer.SpriteSheetAnimationRenderer; import de.bitbrain.braingdx.postprocessing.effects.Bloom; import de.bitbrain.braingdx.screens.AbstractScreen; import de.bitbrain.braingdx.world.GameObject; public class RPGScreen extends AbstractScreen<RPGTest> { private static final int SOLDIER = 1; private RasteredMovementBehavior behavior; private SpriteSheetAnimation animation; public RPGScreen(RPGTest rpgTest) { super(rpgTest); } @Override protected void onCreateStage(Stage stage, int width, int height) { prepareResources(); behavior = new RasteredMovementBehavior().interval(0.2f).rasterSize(32); addSoldier(0f, 0f, 32); setupShaders(); } @Override protected void onUpdate(float delta) { if (Gdx.input.isKeyPressed(Keys.W)) { animation.type(AnimationTypes.FORWARD_YOYO); behavior.move(Orientation.UP); } else if (Gdx.input.isKeyPressed(Keys.A)) { animation.type(AnimationTypes.FORWARD_YOYO); behavior.move(Orientation.LEFT); } else if (Gdx.input.isKeyPressed(Keys.S)) { animation.type(AnimationTypes.FORWARD_YOYO); behavior.move(Orientation.DOWN); } else if (Gdx.input.isKeyPressed(Keys.D)) { animation.type(AnimationTypes.FORWARD_YOYO); behavior.move(Orientation.RIGHT); } else if (!behavior.isMoving()) { animation.type(AnimationTypes.RESET); } } private void prepareResources() { final Texture background = SharedAssetManager.getInstance().get(Assets.RPG.BACKGROUND, Texture.class); getRenderPipeline().add(RenderPipeIds.BACKGROUND, new TextureRenderLayer(background)); getLightingManager().setAmbientLight(new Color(0.06f, 0f, 0.1f, 0.1f)); Texture texture = SharedAssetManager.getInstance().get(Assets.RPG.CHARACTER_TILESET); SpriteSheet sheet = new SpriteSheet(texture, 12, 8); animation = new SpriteSheetAnimation(sheet) .origin(3, 0) .interval(0.2f) .direction(Direction.HORIZONTAL) .type(AnimationTypes.RESET) .base(1) .frames(3); getRenderManager().register(SOLDIER, new SpriteSheetAnimationRenderer(animation) .map(Orientation.DOWN, 0) .map(Orientation.LEFT, 1) .map(Orientation.RIGHT, 2) .map(Orientation.UP, 3) ); } private void setupShaders() { RenderPipe worldPipe = getRenderPipeline().getPipe(RenderPipeIds.WORLD); Bloom bloom = new Bloom(Math.round(Gdx.graphics.getWidth() / 1.5f), Math.round(Gdx.graphics.getHeight() / 1.5f)); bloom.setBlurAmount(25f); bloom.setBloomIntesity(1.4f); bloom.setBlurPasses(7); worldPipe.addEffects(bloom); } private void addSoldier(float x, float y, int size) { GameObject object = getGameWorld().addObject(); object.setPosition(x, y); object.setType(SOLDIER); object.setDimensions(size, size); getBehaviorManager().apply(new PointLightBehavior(Color.valueOf("ff5544ff"), 700f, getLightingManager()), object); getBehaviorManager().apply(behavior, object); getGameCamera().setTarget(object); getGameCamera().setSpeed(1f); getGameCamera().setZoomScale(0.001f); } }
package nl.mpi.kinnate.kindocument; import java.io.File; import java.io.IOException; import java.io.StringReader; import java.net.URI; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import nl.mpi.arbil.data.ArbilComponentBuilder; import nl.mpi.arbil.userstorage.SessionStorage; import nl.mpi.arbil.util.ArbilBugCatcher; import nl.mpi.kinnate.gedcomimport.ImportException; import nl.mpi.kinnate.kindata.EntityData; import nl.mpi.kinnate.uniqueidentifiers.UniqueIdentifier; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; public class EntityDocument { File entityFile = null; Document metadataDom = null; Node kinnateNode = null; Element metadataNode = null; Node currentDomNode = null; public EntityData entityData = null; private ImportTranslator importTranslator; public static String defaultEntityType = "individual"; private SessionStorage sessionStorage; public EntityDocument(ImportTranslator importTranslator, SessionStorage sessionStorage) { this.importTranslator = importTranslator; this.sessionStorage = sessionStorage; assignIdentiferAndFile(); } public EntityDocument(String entityType, ImportTranslator importTranslator, SessionStorage sessionStorage) throws ImportException { this.importTranslator = importTranslator; this.sessionStorage = sessionStorage; assignIdentiferAndFile(); try { // construct the metadata file URI xsdUri = new CmdiTransformer(sessionStorage).getXsdUrlString(entityType); URI addedNodeUri = new ArbilComponentBuilder().createComponentFile(entityFile.toURI(), xsdUri, false); } catch (KinXsdException exception) { new ArbilBugCatcher().logError(exception); throw new ImportException("Error: " + exception.getMessage()); } setDomNodesFromExistingFile(); } public EntityDocument(EntityDocument entityDocumentToCopy, ImportTranslator importTranslator, SessionStorage sessionStorage) throws ImportException { this.importTranslator = importTranslator; this.sessionStorage = sessionStorage; assignIdentiferAndFile(); try { // load the document that needs to be copied so that it can be saved into the new location metadataDom = ArbilComponentBuilder.getDocument(entityDocumentToCopy.entityFile.toURI()); ArbilComponentBuilder.savePrettyFormatting(metadataDom, entityFile); } catch (IOException exception) { new ArbilBugCatcher().logError(exception); throw new ImportException("Error: " + exception.getMessage()); } catch (ParserConfigurationException exception) { new ArbilBugCatcher().logError(exception); throw new ImportException("Error: " + exception.getMessage()); } catch (SAXException exception) { new ArbilBugCatcher().logError(exception); throw new ImportException("Error: " + exception.getMessage()); } // replace the entity data in the new document setDomNodesFromExistingFile(); } public EntityDocument(File destinationDirectory, String nameString, String entityType, ImportTranslator importTranslator, SessionStorage sessionStorage) throws ImportException { this.importTranslator = importTranslator; this.sessionStorage = sessionStorage; String idString; entityData = new EntityData(new UniqueIdentifier(UniqueIdentifier.IdentifierType.lid)); if (nameString != null) { idString = nameString; entityFile = new File(destinationDirectory, nameString + ".kmdi"); } else { idString = entityData.getUniqueIdentifier().getQueryIdentifier() + ".kmdi"; File subDirectory = new File(destinationDirectory, idString.substring(0, 2)); subDirectory.mkdir(); entityFile = new File(subDirectory, idString); } try { // construct the metadata file URI xsdUri = new CmdiTransformer(sessionStorage).getXsdUrlString(entityType); URI addedNodeUri = new ArbilComponentBuilder().createComponentFile(entityFile.toURI(), xsdUri, false); } catch (KinXsdException exception) { new ArbilBugCatcher().logError(exception); throw new ImportException("Error: " + exception.getMessage()); } setDomNodesFromExistingFile(); } public EntityDocument(URI entityUri, ImportTranslator importTranslator, SessionStorage sessionStorage) throws ImportException { this.importTranslator = importTranslator; this.sessionStorage = sessionStorage; entityFile = new File(entityUri); setDomNodesFromExistingFile(); } private void assignIdentiferAndFile() { String idString; entityData = new EntityData(new UniqueIdentifier(UniqueIdentifier.IdentifierType.lid)); idString = entityData.getUniqueIdentifier().getQueryIdentifier() + ".kmdi"; File subDirectory = new File(sessionStorage.getCacheDirectory(), idString.substring(0, 2)); subDirectory.mkdir(); entityFile = new File(subDirectory, idString); } private void setDomNodesFromExistingFile() throws ImportException { try { metadataDom = ArbilComponentBuilder.getDocument(entityFile.toURI()); kinnateNode = metadataDom.getDocumentElement(); final NodeList metadataNodeList = ((Element) kinnateNode).getElementsByTagName("Metadata"); if (metadataNodeList.getLength() < 1) { throw new ImportException("Metadata node not found"); } metadataNode = (Element) metadataNodeList.item(0); // remove any old entity data which will be replaced on save with the existingEntity data provided final NodeList entityNodeList = ((Element) kinnateNode).getElementsByTagNameNS("*", "Entity"); for (int entityCounter = 0; entityCounter < entityNodeList.getLength(); entityCounter++) { if (entityData == null) { JAXBContext jaxbContext = JAXBContext.newInstance(EntityData.class); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); entityData = (EntityData) unmarshaller.unmarshal(entityNodeList.item(entityCounter), EntityData.class).getValue(); } kinnateNode.removeChild(entityNodeList.item(entityCounter)); } currentDomNode = metadataNode; if (entityData == null) { throw new ImportException("Entity node not found"); } } catch (JAXBException exception) { new ArbilBugCatcher().logError(exception); throw new ImportException("Error: " + exception.getMessage()); } catch (ParserConfigurationException exception) { new ArbilBugCatcher().logError(exception); throw new ImportException("Error: " + exception.getMessage()); } catch (SAXException exception) { new ArbilBugCatcher().logError(exception); throw new ImportException("Error: " + exception.getMessage()); } catch (IOException exception) { new ArbilBugCatcher().logError(exception); throw new ImportException("Error: " + exception.getMessage()); } } public String getFileName() { return entityFile.getName(); } public UniqueIdentifier getUniqueIdentifier() { return entityData.getUniqueIdentifier(); } public URI createBlankDocument(boolean overwriteExisting) throws ImportException { if (metadataDom != null) { throw new ImportException("The document already exists"); } URI entityUri; if (!overwriteExisting && entityFile.exists()) { throw new ImportException("Skipping existing entity file"); } else { // start skip overwrite try { entityUri = entityFile.toURI(); URI xsdUri = new CmdiTransformer(sessionStorage).getXsdUrlString("individual"); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); String templateXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<Kinnate \n" + "xmlns:kin=\"http://mpi.nl/tla/kin\" \n" + "xmlns:dcr=\"http: + "xmlns:ann=\"http: + "xmlns:xsi=\"http: + "xmlns:cmd=\"http: + "xmlns=\"http: + "KmdiVersion=\"1.1\" \n" + "xsi:schemaLocation=\"http://mpi.nl/tla/kin " + xsdUri.toString() + "\n \" />"; System.out.println("templateXml: " + templateXml); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); metadataDom = documentBuilder.parse(new InputSource(new StringReader(templateXml))); metadataNode = metadataDom.createElementNS("http: currentDomNode = metadataNode; kinnateNode = metadataDom.getDocumentElement(); } catch (DOMException exception) { new ArbilBugCatcher().logError(exception); throw new ImportException("Error: " + exception.getMessage()); } catch (ParserConfigurationException exception) { new ArbilBugCatcher().logError(exception); throw new ImportException("Error: " + exception.getMessage()); } catch (IOException exception) { new ArbilBugCatcher().logError(exception); throw new ImportException("Error: " + exception.getMessage()); } catch (SAXException exception) { new ArbilBugCatcher().logError(exception); throw new ImportException("Error: " + exception.getMessage()); } catch (KinXsdException exception) { new ArbilBugCatcher().logError(exception); throw new ImportException("Error: " + exception.getMessage()); } return entityUri; } } public void insertValue(String nodeName, String valueString) { // this method will create a flat xml file and reuse any existing nodes of the target name ImportTranslator.TranslationElement translationElement = importTranslator.translate(nodeName, valueString); System.out.println("insertValue: " + translationElement.fieldName + " : " + translationElement.fieldValue); Node currentNode = metadataNode.getFirstChild(); while (currentNode != null) { if (translationElement.fieldName.equals(currentNode.getLocalName())) { if (currentNode.getTextContent() == null || currentNode.getTextContent().length() == 0) { // put the value into this node currentNode.setTextContent(translationElement.fieldValue); return; } if (currentNode.getTextContent().equals(translationElement.fieldValue)) { // if the value already exists then do not add again return; } } currentNode = currentNode.getNextSibling(); } Node valueElement = metadataDom.createElementNS("http://www.clarin.eu/cmd/", /*"cmd:" +*/ translationElement.fieldName); // todo/ ulr encode / and other chars valueElement.setTextContent(translationElement.fieldValue); metadataNode.appendChild(valueElement); } private void importNode(Node foreignNode) { Node importedNode = metadataDom.importNode(foreignNode, true); while (importedNode.hasChildNodes()) { // the metadata node already exists so just add the child nodes of it Node currentChild = importedNode.getFirstChild(); currentDomNode.appendChild(currentChild); // importedNode.removeChild(currentChild); } } public Node insertNode(String nodeName, String valueString) { ImportTranslator.TranslationElement translationElement = importTranslator.translate(nodeName, valueString); System.out.println("nodeName: " + translationElement.fieldName + " : " + translationElement.fieldValue); Node valueElement = metadataDom.createElementNS("http://www.clarin.eu/cmd/", /*"cmd:" +*/ translationElement.fieldName); valueElement.setTextContent(translationElement.fieldValue); currentDomNode.appendChild(valueElement); return valueElement; } public void assendToLevel(int nodeLevel) { int levelCount = 0; Node counterNode = currentDomNode; while (counterNode != null) { levelCount++; counterNode = counterNode.getParentNode(); } levelCount = levelCount - 3; // always keep the kinnate.metadata nodes while (levelCount > nodeLevel) { levelCount currentDomNode = currentDomNode.getParentNode(); } } public void appendValueToLast(String valueString) { System.out.println("appendValueToLast: " + valueString); currentDomNode.setTextContent(currentDomNode.getTextContent() + valueString); } public void appendValue(String nodeName, String valueString, int targetLevel) { // this method will create a structured xml file // the nodeName will be translated if required in insertNode() System.out.println("appendValue: " + nodeName + " : " + valueString + " : " + targetLevel); assendToLevel(targetLevel); NodeList childNodes = currentDomNode.getChildNodes(); if (childNodes.getLength() == 1 && childNodes.item(0).getNodeType() == Node.TEXT_NODE) { // getTextContent returns the text value of all sub nodes so make sure there is only one node which would be the text node String currentValue = currentDomNode.getTextContent(); if (currentValue != null && currentValue.trim().length() > 0) { Node spacerElement = metadataDom.createElementNS("http://www.clarin.eu/cmd/", /*"cmd:" +*/ currentDomNode.getLocalName()); Node parentNode = currentDomNode.getParentNode(); parentNode.removeChild(currentDomNode); spacerElement.appendChild(currentDomNode); parentNode.appendChild(spacerElement); currentDomNode = spacerElement; // currentDomNode.setTextContent(""); //insertNode(currentDomNode.getLocalName(), currentValue); } } currentDomNode = insertNode(nodeName, valueString); } // public void insertDefaultMetadata() { // // todo: this could be done via Arbil code and the schema when that is ready // insertValue("Gender", "unspecified"); // insertValue("Name", "unspecified"); public File getFile() { return entityFile; } public String getFilePath() { return entityFile.getAbsolutePath(); } public void setAsDeletedDocument() throws ImportException { // todo: } public void saveDocument() throws ImportException { try { JAXBContext jaxbContext = JAXBContext.newInstance(EntityData.class); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.marshal(entityData, kinnateNode); } catch (JAXBException exception) { new ArbilBugCatcher().logError(exception); throw new ImportException("Error: " + exception.getMessage()); } // try { // Node entityNode = org.apache.xpath.XPathAPI.selectSingleNode(metadataDom, "/:Kinnate/:Entity"); kinnateNode.appendChild(metadataNode); // todo: maybe insert the user selected CMDI profile into the XML declaration of the kinnate node and let arbil handle the adding of sub nodes or consider using ArbilComponentBuilder to insert a cmdi sub component into the metadata node or keep the cmdi data in a separate file // } catch (TransformerException exception) { // new ArbilBugCatcher().logError(exception); // throw new ImportException("Error: " + exception.getMessage()); ArbilComponentBuilder.savePrettyFormatting(metadataDom, entityFile); System.out.println("saved: " + entityFile.toURI().toString()); } // private EntityDocument(File destinationDirectory, String typeString, String idString, HashMap<String, ArrayList<String>> createdNodeIds, boolean overwriteExisting) { }
package be.ibridge.kettle.core.database; import be.ibridge.kettle.core.Const; import be.ibridge.kettle.core.value.Value; /** * Contains IBM UniVerse database specific information through static final members * * @author Matt * @since 16-nov-2006 */ public class UniVerseDatabaseMeta extends BaseDatabaseMeta implements DatabaseInterface { private static final int MAX_VARCHAR_LENGTH = 65535; /** * Construct a new database connection. * */ public UniVerseDatabaseMeta(String name, String access, String host, String db, String port, String user, String pass) { super(name, access, host, db, port, user, pass); } public UniVerseDatabaseMeta() { } public String getDatabaseTypeDesc() { return "UNIVERSE"; } public String getDatabaseTypeDescLong() { return "UniVerse database"; } /** * @return Returns the databaseType. */ public int getDatabaseType() { return DatabaseMeta.TYPE_DATABASE_UNIVERSE; } public int[] getAccessTypeList() { return new int[] { DatabaseMeta.TYPE_ACCESS_NATIVE, DatabaseMeta.TYPE_ACCESS_ODBC, DatabaseMeta.TYPE_ACCESS_JNDI }; } /** * @see be.ibridge.kettle.core.database.DatabaseInterface#getNotFoundTK(boolean) */ public int getNotFoundTK(boolean use_autoinc) { if ( supportsAutoInc() && use_autoinc) { return 1; } return super.getNotFoundTK(use_autoinc); } public String getDriverClass() { if (getAccessType()==DatabaseMeta.TYPE_ACCESS_NATIVE) { return "com.ibm.u2.jdbc.UniJDBCDriver"; } else { return "sun.jdbc.odbc.JdbcOdbcDriver"; // always ODBC! } } public String getURL(String hostname, String port, String databaseName) { if (getAccessType()==DatabaseMeta.TYPE_ACCESS_NATIVE) { return "jdbc:ibm-u2://"+hostname+"/"+databaseName; } else { return "jdbc:odbc:"+databaseName; } } /** * Checks whether or not the command setFetchSize() is supported by the JDBC driver... * @return true is setFetchSize() is supported! */ public boolean isFetchSizeSupported() { return false; } /** * @see be.ibridge.kettle.core.database.DatabaseInterface#getSchemaTableCombination(java.lang.String, java.lang.String) */ public String getSchemaTableCombination(String schema_name, String table_part) { return "\""+schema_name+"\".\""+table_part+"\""; } /** * @return true if the database supports bitmap indexes */ public boolean supportsBitmapIndex() { return false; } /** * @return true if Kettle can create a repository on this type of database. */ public boolean supportsRepository() { return false; } /** * @param tableName The table to be truncated. * @return The SQL statement to truncate a table: remove all rows from it without a transaction */ public String getTruncateTableStatement(String tableName) { return "DELETE FROM "+tableName; } /** * UniVerse doesn't even support timestamps. */ public boolean supportsTimeStampToDateConversion() { return false; } /** * Generates the SQL statement to add a column to the specified table * For this generic type, i set it to the most common possibility. * * @param tablename The table to add * @param v The column defined as a value * @param tk the name of the technical key field * @param use_autoinc whether or not this field uses auto increment * @param pk the name of the primary key field * @param semicolon whether or not to add a semi-colon behind the statement. * @return the SQL statement to add a column to the specified table */ public String getAddColumnStatement(String tablename, Value v, String tk, boolean use_autoinc, String pk, boolean semicolon) { return "ALTER TABLE "+tablename+" ADD "+getFieldDefinition(v, tk, pk, use_autoinc, true, false); } /** * Generates the SQL statement to modify a column in the specified table * @param tablename The table to add * @param v The column defined as a value * @param tk the name of the technical key field * @param use_autoinc whether or not this field uses auto increment * @param pk the name of the primary key field * @param semicolon whether or not to add a semi-colon behind the statement. * @return the SQL statement to modify a column in the specified table */ public String getModifyColumnStatement(String tablename, Value v, String tk, boolean use_autoinc, String pk, boolean semicolon) { return "ALTER TABLE "+tablename+" MODIFY "+getFieldDefinition(v, tk, pk, use_autoinc, true, false); } public String getFieldDefinition(Value v, String tk, String pk, boolean use_autoinc, boolean add_fieldname, boolean add_cr) { String retval=""; String fieldname = v.getName(); int length = v.getLength(); int precision = v.getPrecision(); if (add_fieldname) retval+=fieldname+" "; int type = v.getType(); switch(type) { case Value.VALUE_TYPE_DATE : retval+="DATE"; break; case Value.VALUE_TYPE_BOOLEAN: retval+="CHAR(1)"; break; case Value.VALUE_TYPE_NUMBER : case Value.VALUE_TYPE_INTEGER: case Value.VALUE_TYPE_BIGNUMBER: if (fieldname.equalsIgnoreCase(tk) || // Technical key fieldname.equalsIgnoreCase(pk) // Primary key ) { retval+="INTEGER"; } else { if (length>0) { if (precision>0 || length>18) { retval+="DECIMAL("+length+", "+precision+")"; } else { retval+="INTEGER"; } } else { retval+="DOUBLE PRECISION"; } } break; case Value.VALUE_TYPE_STRING: if (length>=MAX_VARCHAR_LENGTH || length<=0) { retval+="VARCHAR("+MAX_VARCHAR_LENGTH+")"; } else { retval+="VARCHAR("+length+")"; } break; default: retval+=" UNKNOWN"; break; } if (add_cr) retval+=Const.CR; return retval; } public String[] getReservedWords() { return new String[] { "@NEW", "@OLD", "ACTION", "ADD", "AL", "ALL", "ALTER", "AND", "AR", "AS", "ASC", "ASSOC", "ASSOCIATED", "ASSOCIATION", "AUTHORIZATION", "AVERAGE", "AVG", "BEFORE", "BETWEEN", "BIT", "BOTH", "BY", "CALC", "CASCADE", "CASCADED", "CAST", "CHAR", "CHAR_LENGTH", "CHARACTER", "CHARACTER_LENGTH", "CHECK", "COL.HDG", "COL.SPACES", "COL.SPCS", "COL.SUP", "COLUMN", "COMPILED", "CONNECT", "CONSTRAINT", "CONV", "CONVERSION", "COUNT", "COUNT.SUP", "CREATE", "CROSS", "CURRENT_DATE", "CURRENT_TIME", "DATA", "DATE", "DBA", "DBL.SPC", "DEC", "DECIMAL", "DEFAULT", "DELETE", "DESC", "DET.SUP", "DICT", "DISPLAY.NAME", "DISPLAYLIKE", "DISPLAYNAME", "DISTINCT", "DL", "DOUBLE", "DR", "DROP", "DYNAMIC", "E.EXIST", "EMPTY", "EQ", "EQUAL", "ESCAPE", "EVAL", "EVERY", "EXISTING", "EXISTS", "EXPLAIN", "EXPLICIT", "FAILURE", "FIRST", "FLOAT", "FMT", "FOOTER", "FOOTING", "FOR", "FOREIGN", "FORMAT", "FROM", "FULL", "GE", "GENERAL", "GRAND", "GRAND.TOTAL", "GRANT", "GREATER", "GROUP", "GROUP.SIZE", "GT", "HAVING", "HEADER", "HEADING", "HOME", "IMPLICIT", "IN", "INDEX", "INNER", "INQUIRING", "INSERT", "INT", "INTEGER", "INTO", "IS", "JOIN", "KEY", "LARGE.RECORD", "LAST", "LE", "LEADING", "LEFT", "LESS", "LIKE", "LOCAL", "LOWER", "LPTR", "MARGIN", "MATCHES", "MATCHING", "MAX", "MERGE.LOAD", "MIN", "MINIMIZE.SPACE", "MINIMUM.MODULUS", "MODULO", "MULTI.VALUE", "MULTIVALUED", "NATIONAL", "NCHAR", "NE", "NO", "NO.INDEX", "NO.OPTIMIZE", "NO.PAGE", "NOPAGE", "NOT", "NRKEY", "NULL", "NUMERIC", "NVARCHAR", "ON", "OPTION", "OR", "ORDER", "OUTER", "PCT", "PRECISION", "PRESERVING", "PRIMARY", "PRIVILEGES", "PUBLIC", "REAL", "RECORD.SIZE", "REFERENCES", "REPORTING", "RESOURCE", "RESTORE", "RESTRICT", "REVOKE", "RIGHT", "ROWUNIQUE", "SAID", "SAMPLE", "SAMPLED", "SCHEMA", "SELECT", "SEPARATION", "SEQ.NUM", "SET", "SINGLE.VALUE", "SINGLEVALUED", "SLIST", "SMALLINT", "SOME", "SPLIT.LOAD", "SPOKEN", "SUBSTRING", "SUCCESS", "SUM", "SUPPRESS", "SYNONYM", "TABLE", "TIME", "TO", "TOTAL", "TRAILING", "TRIM", "TYPE", "UNION", "UNIQUE", "UNNEST", "UNORDERED", "UPDATE", "UPPER", "USER", "USING", "VALUES", "VARBIT", "VARCHAR", "VARYING", "VERT", "VERTICALLY", "VIEW", "WHEN", "WHERE", "WITH", }; } public String[] getUsedLibraries() { return new String[] { "unijdbc.jar", "asjava.zip" }; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ch.unizh.ini.jaer.config.boards; import ch.unizh.ini.jaer.config.AbstractConfigValue; import ch.unizh.ini.jaer.config.cpld.CPLDConfigValue; import ch.unizh.ini.jaer.config.cpld.CPLDShiftRegister; import ch.unizh.ini.jaer.config.dac.DAC; import ch.unizh.ini.jaer.config.dac.DAC_AD5391_channel; import ch.unizh.ini.jaer.config.dac.DACchannel; import ch.unizh.ini.jaer.config.dac.DACchannelArray; import ch.unizh.ini.jaer.config.fx2.PortBit; import ch.unizh.ini.jaer.config.fx2.TriStateablePortBit; import ch.unizh.ini.jaer.config.onchip.ChipConfigChain; import ch.unizh.ini.jaer.config.onchip.OnchipConfigBit; import ch.unizh.ini.jaer.config.onchip.OutputMux; import java.math.BigInteger; import java.text.ParseException; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import net.sf.jaer.biasgen.AddressedIPot; import net.sf.jaer.biasgen.AddressedIPotArray; import net.sf.jaer.biasgen.Biasgen; import net.sf.jaer.biasgen.Biasgen.HasPreference; import net.sf.jaer.biasgen.Pot; import net.sf.jaer.biasgen.PotArray; import net.sf.jaer.biasgen.VDAC.VPot; import net.sf.jaer.biasgen.coarsefine.AddressedIPotCF; import net.sf.jaer.biasgen.coarsefine.ShiftedSourceBiasCF; import net.sf.jaer.chip.AEChip; import net.sf.jaer.chip.Chip; import net.sf.jaer.hardwareinterface.HardwareInterfaceException; import net.sf.jaer.hardwareinterface.usb.cypressfx2.CypressFX2; /** * * @author Christian */ public class LatticeMachFX2config extends Biasgen implements HasPreference{ public AEChip chip; protected ShiftedSourceBiasCF[] ssBiases = new ShiftedSourceBiasCF[2]; protected ChipConfigChain chipConfigChain = null; protected ArrayList<HasPreference> hasPreferenceList = new ArrayList<HasPreference>(); public LatticeMachFX2config(Chip chip) { super(chip); this.chip = (AEChip) chip; } /** Vendor request command understood by the firmware in connection with VENDOR_REQUEST_SEND_BIAS_BYTES */ public final Fx2ConfigCmd CMD_IPOT = new Fx2ConfigCmd(1, "IPOT"), CMD_AIPOT = new Fx2ConfigCmd(2, "AIPOT"), CMD_SCANNER = new Fx2ConfigCmd(3, "SCANNER"), CMD_CHIP_CONFIG = new Fx2ConfigCmd(4, "CHIP"), CMD_SETBIT = new Fx2ConfigCmd(5, "SETBIT"), CMD_VDAC = new Fx2ConfigCmd(6, "VDAC"), CMD_INITDAC = new Fx2ConfigCmd(7, "INITDAC"), CMD_CPLD_CONFIG = new Fx2ConfigCmd(8, "CPLD"); public final String[] CMD_NAMES = {"IPOT", "AIPOT", "SCANNER", "CHIP", "SET_BIT", "CPLD_CONFIG"}; final byte[] emptyByteArray = new byte[0]; /** List of direct port bits * */ protected ArrayList<PortBit> portBits = new ArrayList(); public static final byte VR_WRITE_CONFIG = (byte) 0xB8; /** Command sent to firmware by vendor request */ public class Fx2ConfigCmd { short code; String name; public Fx2ConfigCmd(int code, String name) { this.code = (short) code; this.name = name; } @Override public String toString() { return "ConfigCmd{" + "code=" + code + ", name=" + name + '}'; } } /** convenience method for sending configuration to hardware. Sends vendor request VR_WRITE_CONFIG with subcommand cmd, index index and bytes bytes. * * @param cmd the subcommand to set particular configuration, e.g. CMD_CPLD_CONFIG * @param index unused * @param bytes the payload * @throws HardwareInterfaceException */ protected void sendFx2ConfigCommand(Fx2ConfigCmd cmd, int index, byte[] bytes) throws HardwareInterfaceException { if (bytes == null) { bytes = emptyByteArray; } // log.info(String.format("sending command vendor request cmd=%d, index=%d, and %d bytes", cmd, index, bytes.length)); if (getHardwareInterface() != null && getHardwareInterface() instanceof CypressFX2) { ((CypressFX2) getHardwareInterface()).sendVendorRequest(VR_WRITE_CONFIG, (short) (0xffff & cmd.code), (short) (0xffff & index), bytes); // & to prevent sign extension for negative shorts } } protected void sendFx2Config(){ for (PortBit b : portBits) { update(b, null); } } /** Active container for CPLD configuration, which know how to format the data for the CPLD shift register. * */ protected CPLDShiftRegister cpldConfig = new CPLDShiftRegister(); protected void sendCPLDConfig() throws HardwareInterfaceException { if(cpldConfig.getShiftRegisterLength() > 0){ byte[] bytes = cpldConfig.getBytes(); // log.info("Send CPLD Config: "+cpldConfig.toString()); sendFx2ConfigCommand(CMD_CPLD_CONFIG, 0, bytes); } } protected DACchannelArray dacChannels = new DACchannelArray(this); protected DAC dac = null; protected void setDAC(DAC dac){ this.dac = dac; } protected void setDACchannelArray(DACchannelArray dacChannels){ this.dacChannels = dacChannels; } protected void addDACchannel(String s) throws ParseException { try { String d = ","; StringTokenizer t = new StringTokenizer(s, d); if (t.countTokens() != 2) { throw new Error("only " + t.countTokens() + " tokens in pot " + s + "; use , to separate tokens for name,tooltip"); } String name = t.nextToken(); String tip = t.nextToken(); int address = dacChannels.getNumChannels(); dacChannels.addChannel(new DACchannel(chip, name, dac, address++, 0, 0, tip)); } catch (Exception e) { throw new Error(e.toString()); } } // sends VR to init DAC public void initDAC() throws HardwareInterfaceException { sendFx2ConfigCommand(CMD_INITDAC, 0, new byte[0]); } protected boolean sendDACchannel(DACchannel channel) throws HardwareInterfaceException { int chan = channel.getChannel(); int value = channel.getBitValue(); byte[] b = new byte[6]; // 2*24=48 bits byte msb = (byte) (0xff & ((0xf00 & value) >> 8)); byte lsb = (byte) (0xff & value); byte dat1 = 0; byte dat2 = (byte) 0xC0; byte dat3 = 0; dat1 |= (0xff & ((chan % 16) & 0xf)); dat2 |= ((msb & 0xf) << 2) | ((0xff & (lsb & 0xc0) >> 6)); dat3 |= (0xff & ((lsb << 2))); if (chan < 16) { // these are first VPots in list; they need to be loaded first to isSet to the second DAC in the daisy chain b[0] = dat1; b[1] = dat2; b[2] = dat3; b[3] = 0; b[4] = 0; b[5] = 0; } else { // second DAC VPots, loaded second to end up at start of daisy chain shift register b[0] = 0; b[1] = 0; b[2] = 0; b[3] = dat1; b[4] = dat2; b[5] = dat3; } sendFx2ConfigCommand(CMD_VDAC, 0, b); // value=CMD_VDAC, index=0, bytes as above return true; } public boolean sendDACconfig(){ log.info("Send DAC Config"); if(dac == null || dacChannels == null){ return false; } Iterator i = dacChannels.getChannelIterator(); while(i.hasNext()){ DACchannel iPot = (DACchannel) i.next(); try { if(!sendDACchannel(iPot))return false; } catch (HardwareInterfaceException ex) { Logger.getLogger(LatticeMachFX2config.class.getName()).log(Level.SEVERE, null, ex); return false; } } return true; } /** Quick addConfigValue of an addressed pot from a string description, comma delimited * * @param s , e.g. "Amp,n,normal,DVS ON threshold"; separate tokens for name,sex,type,tooltip\nsex=n|p, type=normal|cascode * @throws ParseException Error */ protected void addAIPot(String s) throws ParseException { try { String d = ","; StringTokenizer t = new StringTokenizer(s, d); if (t.countTokens() != 4) { throw new Error("only " + t.countTokens() + " tokens in pot " + s + "; use , to separate tokens for name,sex,type,tooltip\nsex=n|p, type=normal|cascode"); } String name = t.nextToken(); String a; a = t.nextToken(); Pot.Sex sex = null; if (a.equalsIgnoreCase("n")) { sex = Pot.Sex.N; } else if (a.equalsIgnoreCase("p")) { sex = Pot.Sex.P; } else { throw new ParseException(s, s.lastIndexOf(a)); } a = t.nextToken(); Pot.Type type = null; if (a.equalsIgnoreCase("normal")) { type = Pot.Type.NORMAL; } else if (a.equalsIgnoreCase("cascode")) { type = Pot.Type.CASCODE; } else { throw new ParseException(s, s.lastIndexOf(a)); } String tip = t.nextToken(); int address = getPotArray().getNumPots(); getPotArray().addPot(new AddressedIPotCF(this, name, address++, type, sex, false, true, AddressedIPotCF.maxCoarseBitValue / 2, AddressedIPotCF.maxFineBitValue, address, tip)); } catch (Exception e) { throw new Error(e.toString()); } } protected boolean sendAIPot(AddressedIPot pot) throws HardwareInterfaceException{ byte[] bytes = pot.getBinaryRepresentation(); if (bytes == null) { return false; // not ready yet, called by super } String hex = String.format("%02X%02X%02X",bytes[2],bytes[1],bytes[0]); log.info("Send AIPot for "+pot.getName()+" with value "+hex); sendFx2ConfigCommand(CMD_AIPOT, 0, bytes); // the usual packing of ipots with other such as shifted sources, on-chip voltage dac, and diagnotic mux output and extra configuration return true; } /** Sends everything on the on-chip shift register * * @throws HardwareInterfaceException * @return false if not sent because bytes are not yet initialized */ protected boolean sendOnChipConfig() throws HardwareInterfaceException { log.info("Send whole OnChip Config"); //biases if(getPotArray() == null){ return false; } AddressedIPotArray ipots = (AddressedIPotArray) potArray; Iterator i = ipots.getShiftRegisterIterator(); while(i.hasNext()){ AddressedIPot iPot = (AddressedIPot) i.next(); if(!sendAIPot(iPot))return false; } //shifted sources for (ShiftedSourceBiasCF ss : ssBiases) { if(!sendAIPot(ss))return false; } //diagnose SR sendOnChipConfigChain(); return true; } public boolean sendOnChipConfigChain() throws HardwareInterfaceException{ String onChipConfigBits = chipConfigChain.getBitString(); byte[] onChipConfigBytes = bitString2Bytes(onChipConfigBits); if(onChipConfigBits == null){ return false; } else { BigInteger bi = new BigInteger(onChipConfigBits); //System.out.println("Send on chip config (length "+onChipConfigBits.length+" bytes): "+String.format("%0"+(onChipConfigBits.length<<1)+"X", bi)); log.info("Send on chip config: "+onChipConfigBits); sendFx2ConfigCommand(CMD_CHIP_CONFIG, 0, onChipConfigBytes); return true; } } /** List of configuration values * */ protected ArrayList<AbstractConfigValue> configValues = new ArrayList<AbstractConfigValue>(); /** Adds a value, adding it to the appropriate internal containers, and adding this as an observer of the value. * * @param value some configuration value */ public void addConfigValue(AbstractConfigValue value) { if (value == null) { return; } configValues.add(value); value.addToPreferenceList(hasPreferenceList); if (value instanceof CPLDConfigValue) { cpldConfig.add((CPLDConfigValue) value); } else if (value instanceof PortBit) { portBits.add((PortBit) value); } value.addObserver(this); log.info("Added " + value); } /** Clears all lists of configuration values. * @see AbstractConfigValue * */ public void clearConfigValues() { cpldConfig.clear(); configValues.clear(); portBits.clear(); } /** Sends complete configuration to hardware by calling several updates with objects * * @param biasgen this object * @throws HardwareInterfaceException on some error */ @Override public void sendConfiguration(Biasgen biasgen) throws HardwareInterfaceException { if (isBatchEditOccurring()) { log.info("batch edit occurring, not sending configuration yet"); return; } log.info("sending full configuration"); if (!sendOnChipConfig()) { return; } sendFx2Config(); sendDACconfig(); sendCPLDConfig(); sendCPLDConfig(); } @Override public void loadPreferences() { loadPreference(); } @Override public void loadPreference() { super.loadPreferences(); if (hasPreferenceList != null) { for (HasPreference hp : hasPreferenceList) { hp.loadPreference(); } } if (ssBiases != null) { for (ShiftedSourceBiasCF ss : ssBiases) { ss.loadPreferences(); } } if (dacChannels != null) { for (DACchannel channel : dacChannels.getChannels()){ channel.loadPreferences(); } } } @Override public void storePreferences() { storePreference(); } @Override public void storePreference() { super.storePreferences(); for (HasPreference hp : hasPreferenceList) { hp.storePreference(); } if (ssBiases != null) { for (ShiftedSourceBiasCF ss : ssBiases) { ss.storePreferences(); } } if (dacChannels != null) { for (DACchannel channel : dacChannels.getChannels()){ channel.storePreferences(); } } } }
package org.folio.rest; import io.vertx.core.AbstractVerticle; import io.vertx.core.AsyncResult; import io.vertx.core.Context; import io.vertx.core.Future; import io.vertx.core.Handler; import io.vertx.core.MultiMap; import io.vertx.core.Vertx; import io.vertx.core.buffer.Buffer; import io.vertx.core.eventbus.DeliveryOptions; import io.vertx.core.eventbus.EventBus; import io.vertx.core.http.HttpMethod; import io.vertx.core.http.HttpServer; import io.vertx.core.http.HttpServerFileUpload; import io.vertx.core.http.HttpServerOptions; import io.vertx.core.http.HttpServerRequest; import io.vertx.core.http.HttpServerResponse; import io.vertx.core.json.JsonArray; 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.StaticHandler; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import java.util.function.Consumer; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.mail.MessagingException; import javax.mail.internet.InternetHeaders; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMultipart; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.ValidatorFactory; import javax.ws.rs.core.Response; import org.apache.commons.lang3.StringUtils; import org.folio.rest.annotations.Stream; import org.folio.rest.jaxrs.model.JobConf; import org.folio.rest.jaxrs.model.Parameter; import org.folio.rest.jaxrs.resource.AdminResource.PersistMethod; import org.folio.rest.persist.PostgresClient; import org.folio.rest.tools.AnnotationGrabber; import org.folio.rest.tools.RTFConsts; import org.folio.rest.tools.codecs.PojoEventBusCodec; import org.folio.rest.tools.messages.MessageConsts; import org.folio.rest.tools.messages.Messages; import org.folio.rest.tools.utils.BinaryOutStream; import org.folio.rest.tools.utils.InterfaceToImpl; import org.folio.rest.tools.utils.LogUtil; import org.folio.rest.tools.utils.OutStream; import org.folio.rulez.Rules; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.rule.FactHandle; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Joiner; import com.google.common.io.ByteStreams; import org.folio.rest.tools.ClientGenerator; public class RestVerticle extends AbstractVerticle { public static final String DEFAULT_UPLOAD_BUS_ADDRS = "admin.uploaded.files"; public static final String DEFAULT_TEMP_DIR = System.getProperty("java.io.tmpdir"); public static final String JSON_URL_MAPPINGS = "API_PATH_MAPPINGS"; public static final String OKAPI_HEADER_TENANT = ClientGenerator.OKAPI_HEADER_TENANT; public static final String STREAM_ID = "STREAMED_ID"; public static final String STREAM_COMPLETE = "COMPLETE"; public static final HashMap<String, String> MODULE_SPECIFIC_ARGS = new HashMap<>(); private static final String UPLOAD_PATH_TO_HANDLE = "/admin/upload"; private static final String CORS_ALLOW_HEADER = "Access-Control-Allow-Origin"; private static final String CORS_ALLOW_ORIGIN = "Access-Control-Allow-Headers"; private static final String CORS_ALLOW_HEADER_VALUE = "*"; private static final String CORS_ALLOW_ORIGIN_VALUE = "Origin, Authorization, X-Requested-With, Content-Type, Accept"; private static final String SUPPORTED_CONTENT_TYPE_FORMDATA = "multipart/form-data"; private static final String SUPPORTED_CONTENT_TYPE_STREAMIN = "application/octet-stream"; private static final String SUPPORTED_CONTENT_TYPE_JSON_DEF = "application/json"; private static final String SUPPORTED_CONTENT_TYPE_TEXT_DEF = "text/plain"; private static final String SUPPORTED_CONTENT_TYPE_XML_DEF = "application/xml"; private static final String FILE_UPLOAD_PARAM = "javax.mail.internet.MimeMultipart"; private static ValidatorFactory validationFactory; private static KieSession droolsSession; private static String className = RestVerticle.class.getName(); private static final Logger log = LoggerFactory.getLogger(className); private static final ObjectMapper MAPPER = new ObjectMapper(); private static final String OKAPI_HEADER_PREFIX = "x-okapi"; private static final String DEFAULT_SCHEMA = "public"; private final Messages messages = Messages.getInstance(); private int port = -1; private EventBus eventBus; // this is only to run via IDE - otherwise see pom which runs the verticle and // requires passing -cluster and preferable -cluster-home args public static void main(String[] args) { Vertx vertx = Vertx.vertx(); vertx.deployVerticle(new RestVerticle()); } static { //validationFactory used to validate the pojos which are created from the json //passed in the request body in put and post requests. The constraints validated by this factory //are the ones in the json schemas accompanying the raml files validationFactory = Validation.buildDefaultValidatorFactory(); } // first match - no q val check static String acceptCheck(JsonArray l, String h) { String []hl = h.split(","); String hBest = null; for (int i = 0; i < hl.length; i++) { String mediaRange = hl[i].split(";")[0].trim(); for (int j = 0; j < l.size(); j++) { String c = l.getString(j); if (mediaRange.compareTo("*/*") == 0 || c.equalsIgnoreCase(mediaRange)) { hBest = c; break; } } } return hBest; } @Override public void start(Future<Void> startFuture) throws Exception { InputStream in = getClass().getClassLoader().getResourceAsStream("git.properties"); if (in != null) { try { Properties prop = new Properties(); prop.load(in); in.close(); log.info("git: " + prop.getProperty("git.remote.origin.url") + " " + prop.getProperty("git.commit.id")); } catch (Exception e) { log.warn(e.getMessage()); } } //process cmd line arguments cmdProcessing(); LogUtil.formatLogMessage(className, "start", "metrics enabled: " + vertx.isMetricsEnabled()); /**MetricsService metricsService = MetricsService.create(vertx);*/ // maps paths found in raml to the generated functions to route to when the paths are requested MappedClasses mappedURLs = populateConfig(); // set of exposed urls as declared in the raml Set<String> urlPaths = mappedURLs.getAvailURLs(); // create a map of regular expression to url path Map<String, Pattern> regex2Pattern = mappedURLs.buildURLRegex(); // Create a router object. Router router = Router.router(vertx); eventBus = vertx.eventBus(); //register codec to be able to pass pojos on the event bus eventBus.registerCodec(new PojoEventBusCodec()); // needed so that we get the body content of the request - note that this // will read the entire body into memory final BodyHandler handler = BodyHandler.create(); // IMPORTANT!!! // the body of the request will be read into memory for ALL PUT requests // and for POST requests with the content-types below ONLY!!! // multipart, for example will not be read by the body handler as vertx saves // multiparts and www-encoded to disk - hence multiparts will be handled differently // see uploadHandler further down router.put().handler(handler); router.post().consumes(SUPPORTED_CONTENT_TYPE_JSON_DEF).handler(handler); router.post().consumes(SUPPORTED_CONTENT_TYPE_TEXT_DEF).handler(handler); router.post().consumes(SUPPORTED_CONTENT_TYPE_XML_DEF).handler(handler); // run pluggable startup code in a class implementing the InitAPI interface // in the "org.folio.rest.impl" package runHook(vv -> { if (((Future<?>) vv).failed()) { String reason = ((Future<?>) vv).cause().getMessage(); log.error( messages.getMessage("en", MessageConsts.InitializeVerticleFail, reason)); startFuture.fail(reason); vertx.close(); System.exit(-1); } else { log.info("init succeeded......."); try { // startup periodic impl if exists runPeriodicHook(); } catch (Exception e2) { log.error(e2); } //single handler for all url calls other then documentation //which is handled separately router.routeWithRegex("^(?!.*apidocs).*$").handler(rc -> { long start = System.nanoTime(); try { //list of regex urls created from urls declared in the raml Iterator<String> iter = urlPaths.iterator(); boolean validPath = false; boolean[] validRequest = { true }; // loop over regex patterns and try to match them against the requested // URL if no match is found, then the requested url is not supported by // the ramls and we return an error - this has positive security implications as well while (iter.hasNext()) { String regexURL = iter.next(); //try to match the requested url to the each regex pattern created from the urls in the raml Matcher m = regex2Pattern.get(regexURL).matcher(rc.request().path()); if (m.find()) { validPath = true; // get the function that should be invoked for the requested // path + requested http_method pair JsonObject ret = mappedURLs.getMethodbyPath(regexURL, rc.request().method().toString()); // if a valid path was requested but no function was found if (ret == null) { // if the path is valid and the http method is options // assume a cors request if (rc.request().method() == HttpMethod.OPTIONS) { // assume cors and return header of preflight // Access-Control-Allow-Origin // REMOVE CORS SUPPORT FOR // NOW!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // rc.response().putHeader(CORS_ALLOW_ORIGIN, // CORS_ALLOW_ORIGIN_VALUE); // rc.response().putHeader(CORS_ALLOW_HEADER, // CORS_ALLOW_HEADER_VALUE); rc.response().end(); return; } // the url exists but the http method requested does not match a function // meaning url+http method != a function endRequestWithError(rc, 400, true, messages.getMessage("en", MessageConsts.HTTPMethodNotSupported), validRequest); } Class<?> aClass; try { if (validRequest[0]) { int groups = m.groupCount(); //pathParams are the place holders in the raml query string //for example /admin/{admin_id}/yyy/{yyy_id} - the content in between the {} are path params //they are replaced with actual values and are passed to the function which the url is mapped to String[] pathParams = new String[groups]; for (int i = 0; i < groups; i++) { pathParams[i] = m.group(i + 1); } //get interface mapped to this url String iClazz = ret.getString(AnnotationGrabber.CLASS_NAME); // convert from interface to an actual class implementing it, which appears in the impl package aClass = InterfaceToImpl.convert2Impl(RTFConsts.PACKAGE_OF_IMPLEMENTATIONS, iClazz, false).get(0); Object o = null; // call back the constructor of the class - gives a hook into the class not based on the apis // passing the vertx and context objects in to it. try { o = aClass.getConstructor(Vertx.class, Context.class).newInstance(vertx, vertx.getOrCreateContext()); } catch (Exception e) { // if no such constructor was implemented call the // default no param constructor to create the object to be used to call functions on o = aClass.newInstance(); } final Object instance = o; // function to invoke for the requested url String function = ret.getString(AnnotationGrabber.FUNCTION_NAME); // parameters for the function to invoke JsonObject params = ret.getJsonObject(AnnotationGrabber.METHOD_PARAMS); // all methods in the class whose function is mapped to the called url // needed so that we can get a reference to the Method object and call it via reflection Method[] methods = aClass.getMethods(); // what the api will return as output (Accept) JsonArray produces = ret.getJsonArray(AnnotationGrabber.PRODUCES); // what the api expects to get (content-type) JsonArray consumes = ret.getJsonArray(AnnotationGrabber.CONSUMES); HttpServerRequest request = rc.request(); //check that the accept and content-types passed in the header of the request //are as described in the raml checkAcceptContentType(produces, consumes, rc, validRequest); // create the array and then populate it by parsing the url parameters which are needed to invoke the function mapped //to the requested URL - array will be populated by parseParams() function Iterator<Map.Entry<String, Object>> paramList = params.iterator(); Object[] paramArray = new Object[params.size()]; parseParams(rc, paramList, validRequest, consumes, paramArray, pathParams); //create okapi headers map and inject into function Map<String, String> okapiHeaders = new HashMap<>(); String []tenantId = new String[]{null}; getOkapiHeaders(rc, okapiHeaders, tenantId); //Get method in class to be run for this requested API endpoint Method[] method2Run = new Method[]{null}; for (int i = 0; i < methods.length; i++) { if (methods[i].getName().equals(function)) { method2Run[0] = methods[i]; break; } } //is function annotated to receive data in chunks as they come in. //Note that the function controls the logic to this if this is the case boolean streamData = isStreamed(method2Run[0].getAnnotations()); if (validRequest[0]) { // check if we are dealing with a file upload , currently only multipart/form-data and application/octet //in the raml definition for such a function final boolean[] isContentUpload = new boolean[] { false }; final int[] uploadParamPosition = new int[] { -1 }; params.forEach(param -> { String cType = request.getHeader("Content-type"); if (((JsonObject) param.getValue()).getString("type").equals(FILE_UPLOAD_PARAM)) { isContentUpload[0] = true; uploadParamPosition[0] = ((JsonObject) param.getValue()).getInteger("order"); } else if(((JsonObject) param.getValue()).getString("type").equals("java.io.InputStream")){ //application/octet-stream passed - this is handled in a stream like manner //and the corresponding function called must annotate with a @Stream - and be able //to handle the function being called repeatedly on parts of the data uploadParamPosition[0] = ((JsonObject) param.getValue()).getInteger("order"); isContentUpload[0] = true; } }); /** * file upload requested (multipart/form-data) but the url is not to the /admin/upload * meaning, an implementing module is using its own upload handling, so read the content and * pass to implementing function just like any other call */ if (isContentUpload[0] && !streamData) { //if file upload - set needed handlers if (consumes != null && consumes.contains(SUPPORTED_CONTENT_TYPE_FORMDATA)) { //multipart handleMultipartUpload(rc, request, uploadParamPosition, paramArray, validRequest); request.endHandler( a -> { if (validRequest[0]) { //if request is valid - invoke it try { invoke(method2Run[0], paramArray, instance, rc, tenantId, okapiHeaders, new StreamStatus(), v -> { LogUtil.formatLogMessage(className, "start", " invoking " + function); sendResponse(rc, v, start); }); } catch (Exception e1) { log.error(e1.getMessage(), e1); rc.response().end(); } } }); } else { //assume input stream handleInputStreamUpload(method2Run[0], rc, request, instance, tenantId, okapiHeaders, uploadParamPosition, paramArray, validRequest, start); } } else if(streamData){ request.handler(new Handler<Buffer>() { @Override public void handle(Buffer buff) { try { StreamStatus stat = new StreamStatus(); stat.status = 0; paramArray[uploadParamPosition[0]] = new ByteArrayInputStream( buff.getBytes() ); invoke(method2Run[0], paramArray, instance, rc, tenantId, okapiHeaders, stat, v -> { LogUtil.formatLogMessage(className, "start", " invoking " + function); }); } catch (Exception e1) { log.error(e1.getMessage(), e1); rc.response().end(); } } }); request.endHandler( e -> { StreamStatus stat = new StreamStatus(); stat.status = 1; invoke(method2Run[0], paramArray, instance, rc, tenantId, okapiHeaders, stat, v -> { LogUtil.formatLogMessage(className, "start", " invoking " + function); //all data has been stored in memory - not necessarily all processed sendResponse(rc, v, start); }); }); request.exceptionHandler(new Handler<Throwable>(){ @Override public void handle(Throwable event) { endRequestWithError(rc, 400, true, "unable to upload file " + event.getMessage(), validRequest); }}); } else{ if (validRequest[0]) { //if request is valid - invoke it try { invoke(method2Run[0], paramArray, instance, rc, tenantId, okapiHeaders, new StreamStatus(), v -> { LogUtil.formatLogMessage(className, "start", " invoking " + function); sendResponse(rc, v, start); }); } catch (Exception e1) { log.error(e1.getMessage(), e1); rc.response().end(); } } } //real need for this is in case of bad file upload requests which dont trigger the upload end handler - so this catches is // register handler - in case of file uploads - when the body handler is used then the entire body is read // and calling the endhandler will throw an exception since there is nothing to read. so this can only be called //when no body handler is associated with the path - in our case multipart/form-data /* if (isContentUpload[0] && !handleInternally) { request.endHandler( a -> { if (validRequest[0]) { //if request is valid - invoke it try { invoke(method2Run[0], paramArray, instance, rc, tenantId, okapiHeaders, new StreamStatus(), v -> { LogUtil.formatLogMessage(className, "start", " invoking " + function); sendResponse(rc, v, start); }); } catch (Exception e1) { log.error(e1.getMessage(), e1); rc.response().end(); } } }); }*/ } else{ endRequestWithError(rc, 400, true, messages.getMessage("en", MessageConsts.UnableToProcessRequest), validRequest); } } } catch (Exception e) { log.error(e.getMessage(), e); endRequestWithError(rc, 400, true, messages.getMessage("en", MessageConsts.UnableToProcessRequest) + e.getMessage(), validRequest); } } } if (!validPath) { // invalid path endRequestWithError(rc, 400, true, messages.getMessage("en", MessageConsts.InvalidURLPath, rc.request().path()), validRequest); } } finally {/*do nothing*/} } ); /* * Set<HttpMethod> corsAllowedMethods = new HashSet<HttpMethod>(); corsAllowedMethods.add(HttpMethod.GET); * corsAllowedMethods.add(HttpMethod.OPTIONS); corsAllowedMethods.add(HttpMethod.PUT); corsAllowedMethods.add(HttpMethod.POST); * corsAllowedMethods.add(HttpMethod.DELETE); * * router.route().handler( CorsHandler.create("*").allowedMethods(corsAllowedMethods * ).allowedHeader("Authorization").allowedHeader("Content-Type") .allowedHeader("Access-Control-Request-Method").allowedHeader( * "Access-Control-Allow-Credentials") .allowedHeader("Access-Control-Allow-Origin" * ).allowedHeader("Access-Control-Allow-Headers")); */ if (port == -1) { /** we are here if port was not passed via cmd line */ port = config().getInteger("http.port", 8081); } /** in anycase set the port so it is available to others via the config() */ config().put("http.port", port); Integer p = port; //if client includes an Accept-Encoding header which includes //the supported compressions - deflate or gzip. HttpServerOptions serverOptions = new HttpServerOptions(); serverOptions.setCompressionSupported(false); HttpServer server = vertx.createHttpServer(serverOptions); server.requestHandler(router::accept) // router object (declared in the beginning of the atrt function accepts request and will pass to next handler for // specified path .listen( // Retrieve the port from the configuration file - file needs to // be passed as arg to command line, // for example: -conf src/main/conf/my-application-conf.json // default to 8181. p, result -> { if (result.failed()) { startFuture.fail(result.cause()); } else { try { runPostDeployHook( res2 -> { if(!res2.succeeded()){ log.error(res2.cause().getMessage(), res2.cause()); } }); } catch (Exception e) { log.error(e.getMessage(), e); } LogUtil.formatLogMessage(className, "start", "http server for apis and docs started on port " + p + "."); LogUtil.formatLogMessage(className, "start", "Documentation available at: " + "http://localhost:" + Integer.toString(p) + "/apidocs/"); startFuture.complete(); } }); } }); } /** * @param method2Run * @param rc * @param request * @param okapiHeaders * @param tenantId * @param instance * @param uploadParamPosition * @param paramArray * @param validRequest * @param start */ private void handleInputStreamUpload(Method method2Run, RoutingContext rc, HttpServerRequest request, Object instance, String[] tenantId, Map<String, String> okapiHeaders, int[] uploadParamPosition, Object[] paramArray, boolean[] validRequest, long start) { final Buffer content = Buffer.buffer(); request.handler(new Handler<Buffer>() { @Override public void handle(Buffer buff) { content.appendBuffer(buff); } }); request.endHandler( e -> { paramArray[uploadParamPosition[0]] = new ByteArrayInputStream(content.getBytes()); try { invoke(method2Run, paramArray, instance, rc, tenantId, okapiHeaders, new StreamStatus(), v -> { LogUtil.formatLogMessage(className, "start", " invoking " + method2Run); sendResponse(rc, v, start); }); } catch (Exception e1) { log.error(e1.getMessage(), e1); rc.response().end(); } }); request.exceptionHandler(new Handler<Throwable>(){ @Override public void handle(Throwable event) { endRequestWithError(rc, 400, true, event.getMessage(), validRequest); } }); } /** * @param request * @param uploadParamPosition * @param paramArray * @param validRequest */ private void handleMultipartUpload(RoutingContext rc, HttpServerRequest request, int[] uploadParamPosition, Object[] paramArray, boolean[] validRequest) { request.setExpectMultipart(true); MimeMultipart mmp = new MimeMultipart(); //place the mmp as an argument to the 'to be called' function - at the correct position paramArray[uploadParamPosition[0]] = mmp; request.uploadHandler(new Handler<io.vertx.core.http.HttpServerFileUpload>() { Buffer content = Buffer.buffer(); @Override public void handle(HttpServerFileUpload upload) { // called as data comes in upload.handler(new Handler<Buffer>() { @Override public void handle(Buffer buff) { if(content == null){ content = Buffer.buffer(); } content.appendBuffer(buff); } }); upload.exceptionHandler(new Handler<Throwable>() { @Override public void handle(Throwable event) { endRequestWithError(rc, 400, true, "unable to upload file " + event.getMessage(), validRequest); } }); // endHandler called when all data completed streaming to server //called for each part in the multipart - so if uploading 2 files - will be called twice upload.endHandler(new Handler<Void>() { @Override public void handle(Void event) { InternetHeaders headers = new InternetHeaders(); MimeBodyPart mbp = null; try { mbp = new MimeBodyPart(headers, content.getBytes()); mbp.setFileName(upload.filename()); mmp.addBodyPart(mbp); content = null; } catch (MessagingException e) { // TODO Auto-generated catch block log.error(e); } } }); } }); } /** * @param annotations * @return */ private boolean isStreamed(Annotation[] annotations) { for (int i = 0; i < annotations.length; i++) { if(annotations[i].annotationType().equals(Stream.class)){ return true; } } return false; } /** * Send the result as response. * * @param rc * - where to send the result * @param v * - the result to send * @param start * - request's start time, using JVM's high-resolution time source, in nanoseconds */ private void sendResponse(RoutingContext rc, AsyncResult<Response> v, long start) { Response result = ((Response) ((AsyncResult<?>) v).result()); if (result == null) { // catch all endRequestWithError(rc, 500, true, "Server error", new boolean[] { true }); return; } try { HttpServerResponse response = rc.response(); int statusCode = result.getStatus(); // 204 means no content returned in the response, so passing // a chunked Transfer header is not allowed if (statusCode != 204) { response.setChunked(true); } response.setStatusCode(statusCode); // !!!!!!!!!!!!!!!!!!!!!! CORS commented OUT!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // response.putHeader("Access-Control-Allow-Origin", "*"); for (Entry<String, List<String>> entry : result.getStringHeaders().entrySet()) { String jointValue = Joiner.on("; ").join(entry.getValue()); response.headers().add(entry.getKey(), jointValue); } //response.headers().add(HttpHeaders.ACCEPT_ENCODING, "gzip, deflate"); //forward all headers except content-type that was passed in by the client //since this may cause problems when for example application/octet-stream is //sent as part of an upload. passing this back will confuse clients as they //will think they are getting back a stream of data which may not be the case rc.request().headers().remove("Content-type"); response.headers().addAll(rc.request().headers()); Object entity = result.getEntity(); /* entity is of type OutStream - and will be written as a string */ if (entity instanceof OutStream) { response.write(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(((OutStream) entity).getData())); } /* entity is of type BinaryOutStream - and will be written as a buffer */ else if(entity instanceof BinaryOutStream){ response.write(Buffer.buffer(((BinaryOutStream) entity).getData())); } /* data is a string so just push it out, no conversion needed */ else if(entity instanceof String){ response.write(Buffer.buffer((String)entity)); } /* catch all - anything else will be assumed to be a pojo which needs converting to json */ else if (entity != null) { response.write(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(entity)); } } catch (Exception e) { log.error(e); } finally { rc.response().end(); } long end = System.nanoTime(); StringBuffer sb = new StringBuffer(); if (log.isDebugEnabled()) { sb.append(rc.getBodyAsString()); } LogUtil.formatStatsLogMessage(rc.request().remoteAddress().toString(), rc.request().method().toString(), rc.request().version().toString(), rc.response().getStatusCode(), (((end - start) / 1000000)), rc.response().bytesWritten(), rc.request().path(), rc.request().query(), rc.response().getStatusMessage(), sb.toString()); } private void endRequestWithError(RoutingContext rc, int status, boolean chunked, String message, boolean[] isValid) { if (isValid[0]) { log.error(rc.request().absoluteURI() + " [ERROR] " + message); rc.response().setChunked(chunked); rc.response().setStatusCode(status); rc.response().write(message); rc.response().end(); } // once we are here the call is not valid isValid[0] = false; } private void getOkapiHeaders(RoutingContext rc, Map<String, String> headers, String[] tenantId){ MultiMap mm = rc.request().headers(); Consumer<Map.Entry<String,String>> consumer = entry -> { String headerKey = entry.getKey().toLowerCase(); if(headerKey.startsWith(OKAPI_HEADER_PREFIX)){ if(headerKey.equalsIgnoreCase(ClientGenerator.OKAPI_HEADER_TENANT)){ tenantId[0] = entry.getValue(); } headers.put(headerKey, entry.getValue()); } }; mm.forEach(consumer); } public void invoke(Method method, Object[] params, Object o, RoutingContext rc, String[] tenantId, Map<String,String> headers, StreamStatus streamed, Handler<AsyncResult<Response>> resultHandler) { Context context = vertx.getOrCreateContext(); //if streaming is requested the status will be 0 (streaming started) //or 1 streaming data complete //otherwise it will be -1 and flags wont be set if(streamed.status == 0){ headers.put(STREAM_ID, String.valueOf(rc.hashCode())); } else if(streamed.status == 1){ headers.put(STREAM_ID, String.valueOf(rc.hashCode())); headers.put(STREAM_COMPLETE, String.valueOf(rc.hashCode())); } Object[] newArray = new Object[params.length]; for (int i = 0; i < params.length - 3; i++) { newArray[i] = params[i]; } //inject call back handler into each function newArray[params.length - 2] = resultHandler; //inject vertx context into each function newArray[params.length - 1] = getVertx().getOrCreateContext(); /* if(tenantId[0] == null){ headers.put(OKAPI_HEADER_TENANT, DEFAULT_SCHEMA); }*/ newArray[params.length - 3] = headers; context.runOnContext(v -> { try { method.invoke(o, newArray); // response.setChunked(true); // response.setStatusCode(((Response)result).getStatus()); } catch (Exception e) { log.error(e); String message; try { // catch exception for now in case of null point and show generic // message message = e.getCause().getMessage(); } catch (Throwable ee) { message = messages.getMessage("en", MessageConsts.UnableToProcessRequest); } endRequestWithError(rc, 400, true, message, new boolean[] { true }); } }); } public JsonObject loadConfig(String configFile) { try { byte[] jsonData = ByteStreams.toByteArray(getClass().getClassLoader().getResourceAsStream(configFile)); return new JsonObject(new String(jsonData)); } catch (IOException e) { log.error(e); } return new JsonObject(); } private static String replaceLast(String string, String substring, String replacement) { int index = string.lastIndexOf(substring); if (index == -1) return string; return string.substring(0, index) + replacement + string.substring(index + substring.length()); } private MappedClasses populateConfig() { MappedClasses mappedURLs = new MappedClasses(); JsonObject jObjClasses = new JsonObject(); try { jObjClasses.mergeIn(AnnotationGrabber.generateMappings()); } catch (Exception e) { log.error(e); } // loadConfig(JSON_URL_MAPPINGS); Set<String> classURLs = jObjClasses.fieldNames(); classURLs.forEach(classURL -> { System.out.println(classURL); JsonObject jObjMethods = jObjClasses.getJsonObject(classURL); Set<String> methodURLs = jObjMethods.fieldNames(); jObjMethods.fieldNames(); methodURLs.forEach(methodURL -> { Object val = jObjMethods.getValue(methodURL); if (val instanceof JsonArray) { ((JsonArray) val).forEach(entry -> { String pathRegex = ((JsonObject) entry).getString("regex2method"); ((JsonObject) entry).put(AnnotationGrabber.CLASS_NAME, jObjMethods.getString(AnnotationGrabber.CLASS_NAME)); ((JsonObject) entry).put(AnnotationGrabber.INTERFACE_NAME, jObjMethods.getString(AnnotationGrabber.INTERFACE_NAME)); mappedURLs.addPath(pathRegex, (JsonObject) entry); }); } }); }); return mappedURLs; } @Override public void stop(Future<Void> stopFuture) throws Exception { // TODO Auto-generated method stub super.stop(); PostgresClient.stopEmbeddedPostgres(); try { droolsSession.dispose(); } catch (Exception e) {/*ignore*/} // removes the .lck file associated with the log file LogUtil.closeLogger(); runShutdownHook(v -> { if (v.succeeded()) { stopFuture.complete(); } else { stopFuture.fail("shutdown hook failed...."); } }); } /** * ONLY 1 Impl is allowed currently! * implementors of the InitAPI interface must call back the handler in there init() implementation like this: * resultHandler.handle(io.vertx.core.Future.succeededFuture(true)); or this will hang */ private void runHook(Handler<AsyncResult<Boolean>> resultHandler) throws Exception { try { ArrayList<Class<?>> aClass = InterfaceToImpl.convert2Impl(RTFConsts.PACKAGE_OF_IMPLEMENTATIONS, RTFConsts.PACKAGE_OF_HOOK_INTERFACES + ".InitAPI", false); for (int i = 0; i < aClass.size(); i++) { Class<?>[] paramArray = new Class[] { Vertx.class, Context.class, Handler.class }; Method method = aClass.get(i).getMethod("init", paramArray); method.invoke(aClass.get(i).newInstance(), vertx, vertx.getOrCreateContext(), resultHandler); LogUtil.formatLogMessage(getClass().getName(), "runHook", "One time hook called with implemented class " + "named " + aClass.get(i).getName()); } } catch (ClassNotFoundException e) { // no hook implemented, this is fine, just startup normally then resultHandler.handle(io.vertx.core.Future.succeededFuture(true)); } } /** * multiple impl allowed * @throws Exception */ private void runPeriodicHook() throws Exception { try { ArrayList<Class<?>> aClass = InterfaceToImpl.convert2Impl(RTFConsts.PACKAGE_OF_IMPLEMENTATIONS, RTFConsts.PACKAGE_OF_HOOK_INTERFACES + ".PeriodicAPI", true); for (int i = 0; i < aClass.size(); i++) { Class<?>[] paramArray = new Class[] {}; Method method = aClass.get(i).getMethod("runEvery", paramArray); Object delay = method.invoke(aClass.get(i).newInstance()); LogUtil.formatLogMessage(getClass().getName(), "runPeriodicHook", "Periodic hook called with implemented class " + "named " + aClass.get(i).getName()); final int j = i; vertx.setPeriodic(((Long) delay).longValue(), new Handler<Long>() { @Override public void handle(Long aLong) { try { Class<?>[] paramArray1 = new Class[] { Vertx.class, Context.class }; Method method1 = aClass.get(j).getMethod("run", paramArray1); method1.invoke(aClass.get(j).newInstance(), vertx, vertx.getOrCreateContext()); } catch (Exception e) { log.error(e.getMessage(), e); } } }); } } catch (ClassNotFoundException e) { // no hook implemented, this is fine, just startup normally then LogUtil.formatLogMessage(getClass().getName(), "runPeriodicHook", "no periodic implementation found, continuing with deployment"); } } /** * ONE impl allowed * @throws Exception */ private void runPostDeployHook(Handler<AsyncResult<Boolean>> resultHandler) throws Exception { try { ArrayList<Class<?>> aClass = InterfaceToImpl.convert2Impl(RTFConsts.PACKAGE_OF_IMPLEMENTATIONS, RTFConsts.PACKAGE_OF_HOOK_INTERFACES + ".PostDeployVerticle", true); for (int i = 0; i < aClass.size(); i++) { Class<?>[] paramArray = new Class[] { Vertx.class, Context.class, Handler.class }; Method method = aClass.get(i).getMethod("init", paramArray); method.invoke(aClass.get(i).newInstance(), vertx, vertx.getOrCreateContext(), resultHandler); LogUtil.formatLogMessage(getClass().getName(), "runHook", "Post Deploy Hook called with implemented class " + "named " + aClass.get(i).getName()); } } catch (ClassNotFoundException e) { // no hook implemented, this is fine, just startup normally then LogUtil.formatLogMessage(getClass().getName(), "runPostDeployHook", "no Post Deploy Hook implementation found, continuing with deployment"); } } /** * only one impl allowed * @param resultHandler * @throws Exception */ private void runShutdownHook(Handler<AsyncResult<Void>> resultHandler) throws Exception { try { ArrayList<Class<?>> aClass = InterfaceToImpl.convert2Impl(RTFConsts.PACKAGE_OF_IMPLEMENTATIONS, RTFConsts.PACKAGE_OF_HOOK_INTERFACES + ".ShutdownAPI", false); for (int i = 0; i < aClass.size(); i++) { Class<?>[] paramArray = new Class[] { Vertx.class, Context.class, Handler.class }; Method method = aClass.get(i).getMethod("shutdown", paramArray); method.invoke(aClass.get(i).newInstance(), vertx, vertx.getOrCreateContext(), resultHandler); LogUtil.formatLogMessage(getClass().getName(), "runShutdownHook", "shutdown hook called with implemented class " + "named " + aClass.get(i).getName()); } } catch (ClassNotFoundException e) { // no hook implemented, this is fine, just startup normally then LogUtil.formatLogMessage(getClass().getName(), "runShutdownHook", "no shutdown hook implementation found, continuing with shutdown"); resultHandler.handle(io.vertx.core.Future.succeededFuture()); } } private void cmdProcessing() throws Exception { String importDataPath = null; String droolsPath = null; // TODO need to add a normal command line parser List<String> cmdParams = processArgs(); if (cmdParams != null) { for (Iterator iterator = cmdParams.iterator(); iterator.hasNext();) { String param = (String) iterator.next(); if (param.startsWith("-Dhttp.port=")) { port = Integer.parseInt(param.split("=")[1]); LogUtil.formatLogMessage(className, "cmdProcessing", "port to listen on " + port); } else if (param.startsWith("drools_dir=")) { droolsPath = param.split("=")[1]; LogUtil.formatLogMessage(className, "cmdProcessing", "Drools rules file dir set to " + droolsPath); } else if (param.startsWith("db_connection=")) { String dbconnection = param.split("=")[1]; PostgresClient.setConfigFilePath(dbconnection); PostgresClient.setIsEmbedded(false); LogUtil.formatLogMessage(className, "cmdProcessing", "Setting path to db config file.... " + dbconnection); } else if (param.startsWith("embed_postgres=true")) { // allow setting config() from unit test mode which runs embedded LogUtil.formatLogMessage(className, "cmdProcessing", "Using embedded postgres... starting... "); // this blocks PostgresClient.setIsEmbedded(true); PostgresClient.setConfigFilePath(null); } else if (param != null && param.startsWith("postgres_import_path=")) { try { importDataPath = param.split("=")[1]; System.out.println("Setting path to import DB file.... " + importDataPath); } catch (Exception e) { // any problems - print exception and continue log.error(e); } } else{ //assume module specific cmd line args with '=' separator String []arg = param.split("="); if(arg.length == 2){ MODULE_SPECIFIC_ARGS.put(arg[0], arg[1]); log.info("module specific argument added: " + arg[0] + " with value " + arg[1]); } else{ log.warn("The following cmd line parameter was skipped, " + param + ". Expected format key=value\nIf this is a " + "JVM argument, pass it before the jar, not after"); } } } if (PostgresClient.isEmbedded() || importDataPath != null) { PostgresClient.getInstance(vertx).startEmbeddedPostgres(); } if (importDataPath != null) { // blocks as well for now System.out.println("Import DB file.... " + importDataPath); PostgresClient.getInstance(vertx).importFileEmbedded(importDataPath); } } try { droolsSession = new Rules(droolsPath).buildSession(); } catch (Exception e) { log.error(e); } } private String removeBoundry(String contenttype) { int idx = contenttype.indexOf("boundary"); if (idx != -1) { return contenttype.substring(0, idx - 1); } return contenttype; } /** * check accept and content-type headers if no - set the request asa not valid and return error to user */ private void checkAcceptContentType(JsonArray produces, JsonArray consumes, RoutingContext rc, boolean[] validRequest) { /* * NOTE that the content type and accept headers will accept a partial match - for example: if the raml indicates a text/plain and an * application/json content-type and only one is passed - it will accept it */ // check allowed content types in the raml for this resource + method HttpServerRequest request = rc.request(); if (consumes != null && validRequest[0]) { // get the content type passed in the request // if this was left out by the client they must add for request to return // clean up simple stuff from the clients header - trim the string and remove ';' in case // it was put there as a suffix String contentType = StringUtils.defaultString(request.getHeader("Content-type")).replace(";", "").trim(); if (!consumes.contains(removeBoundry(contentType))) { endRequestWithError(rc, 400, true, messages.getMessage("en", MessageConsts.ContentTypeError, consumes, contentType), validRequest); } } // type of data expected to be returned by the server if (produces != null && validRequest[0]) { String accept = StringUtils.defaultString(request.getHeader("Accept")); if (acceptCheck(produces, accept) == null) { // use contains because multiple values may be passed here // for example json/application; text/plain mismatch of content type found endRequestWithError(rc, 400, true, messages.getMessage("en", MessageConsts.AcceptHeaderError, produces, accept), validRequest); } } } private void parseParams(RoutingContext rc, Iterator<Map.Entry<String, Object>> paramList, boolean[] validRequest, JsonArray consumes, Object[] paramArray, String[] pathParams) { HttpServerRequest request = rc.request(); MultiMap queryParams = request.params(); int []pathParamsIndex = new int[] { pathParams.length }; paramList.forEachRemaining(entry -> { if (validRequest[0]) { String valueName = ((JsonObject) entry.getValue()).getString("value"); String valueType = ((JsonObject) entry.getValue()).getString("type"); String paramType = ((JsonObject) entry.getValue()).getString("param_type"); int order = ((JsonObject) entry.getValue()).getInteger("order"); Object defaultVal = ((JsonObject) entry.getValue()).getValue("default_value"); // validation of query params (other then enums), object in body (not including drools), // and some header params validated by jsr311 (aspects) - the rest are handled in the code here // handle un-annotated parameters - this is assumed to be // entities in HTTP BODY for post and put requests or the 3 injected params // (okapi headers, vertx context and vertx handler) - file uploads are also not annotated but are not handled here due // to their async upload - so explicitly skip them if (AnnotationGrabber.NON_ANNOTATED_PARAM.equals(paramType) && !FILE_UPLOAD_PARAM.equals(valueType)) { try { // this will also validate the json against the pojo created from the schema Class<?> entityClazz = Class.forName(valueType); if (!valueType.equals("io.vertx.core.Handler") && !valueType.equals("io.vertx.core.Context") && !valueType.equals("java.util.Map") && !valueType.equals("java.io.InputStream")) { // we have special handling for the Result Handler and context, it is also assumed that //an inputsteam parameter occurs when application/octet is declared in the raml //in which case the content will be streamed to he function if("java.io.Reader".equals(valueType)){ paramArray[order] = new StringReader(rc.getBodyAsString()); } else{ paramArray[order] = MAPPER.readValue(rc.getBodyAsString(), entityClazz); } Set<? extends ConstraintViolation<?>> validationErrors = validationFactory.getValidator().validate(paramArray[order]); if (validationErrors.size() > 0) { StringBuffer sb = new StringBuffer(); for (ConstraintViolation<?> cv : validationErrors) { sb.append("\n" + cv.getPropertyPath() + " " + cv.getMessage() + ","); } endRequestWithError(rc, 400, true, "Object validation errors " + sb.toString(), validRequest); } // complex rules validation here (drools) - after simpler validation rules pass - try { // if no /rules exist then drools session will be null // TODO support adding .drl files dynamically to db / dir // and having them picked up if (droolsSession != null) { // add object to validate to session FactHandle handle = droolsSession.insert(paramArray[order]); // run all rules in session on object droolsSession.fireAllRules(); // remove the object from the session droolsSession.delete(handle); } } catch (Exception e) { log.error(e); endRequestWithError(rc, 400, true, e.getCause().getMessage(), validRequest); } } } catch (Exception e) { log.error(e); endRequestWithError(rc, 400, true, "Json content error " + e.getMessage(), validRequest); } } else if (AnnotationGrabber.HEADER_PARAM.equals(paramType)) { // handle header params - read the header field from the // header (valueName) and get its value String value = request.getHeader(valueName); // set the value passed from the header as a param to the function paramArray[order] = value; } else if (AnnotationGrabber.PATH_PARAM.equals(paramType)) { // these are placeholder values in the path - for example // /patrons/{patronid} - this would be the patronid value paramArray[order] = pathParams[pathParamsIndex[0] - 1]; pathParamsIndex[0] = pathParamsIndex[0] - 1; } else if (AnnotationGrabber.QUERY_PARAM.equals(paramType)) { String param = queryParams.get(valueName); // support enum, numbers or strings as query parameters try { if (valueType.contains("String")) { // regular string param in query string - just push value if (param == null && defaultVal != null) { // no value passed - check if there is a default value paramArray[order] = defaultVal; } else { paramArray[order] = param; } } else if (valueType.contains("int")) { // cant pass null to an int type - replace with zero if (param == null) { if (defaultVal != null) { paramArray[order] = Integer.valueOf((String) defaultVal); } else { paramArray[order] = 0; } } else { paramArray[order] = Integer.valueOf(param).intValue(); } } else if (valueType.contains("boolean")) { if (param == null) { if (defaultVal != null) { paramArray[order] = Boolean.valueOf((String)defaultVal); } } else { paramArray[order] = Boolean.valueOf(param); } } else if (valueType.contains("BigDecimal")) { // cant pass null to an int type - replace with zero if (param == null) { if (defaultVal != null) { paramArray[order] = new BigDecimal((String) defaultVal); } else { paramArray[order] = new BigDecimal(0); } } else { paramArray[order] = new BigDecimal(param.replaceAll(",", "")); // big decimal can contain "," } } else { // enum object type try { String enumClazz = replaceLast(valueType, ".", "$"); Class<?> enumClazz1 = Class.forName(enumClazz); if (enumClazz1.isEnum()) { Object defaultEnum = null; Object[] vals = enumClazz1.getEnumConstants(); for (int i = 0; i < vals.length; i++) { if (vals[i].toString().equals(defaultVal)) { defaultEnum = vals[i]; } // set default value (if there was one in the raml) // in case no value was passed in the request if (param == null && defaultEnum != null) { paramArray[order] = defaultEnum; break; } // make sure enum value is valid by converting the string to an enum else if (vals[i].toString().equals(param)) { paramArray[order] = vals[i]; break; } if (i == vals.length - 1) { // if enum passed is not valid, replace with default value paramArray[order] = defaultEnum; } } } } catch (Exception ee) { log.error(ee); validRequest[0] = false; } } } catch (Exception e) { log.error(e); validRequest[0] = false; } } } }); } private boolean handleInterally(HttpServerRequest request){ if(UPLOAD_PATH_TO_HANDLE.equals(request.path())){ return true; } return false; } private void internalUploadService(RoutingContext rc, boolean []validRequest){ HttpServerRequest request = rc.request(); if(request.getParam("file_name") == null){ //handle validation manually since not using the built in framework for validation endRequestWithError(rc, 400, true, messages.getMessage("en", MessageConsts.FileUploadError, ", file_name can not be null"), validRequest); return; } String[] instId = new String[]{rc.request().getHeader(ClientGenerator.OKAPI_HEADER_TENANT)}; if(instId[0] == null){ instId[0] = ""; } request.pause(); String[] filename = new String[]{DEFAULT_TEMP_DIR + "/"}; if(!instId[0].equals("")){ filename[0] = filename[0] + instId[0] + "/"; new File(filename[0]).mkdir(); } filename[0] = filename[0] + System.currentTimeMillis() + "_" + request.getParam("file_name"); vertx.fileSystem().open(filename[0], new io.vertx.core.file.OpenOptions(), ares -> { try { io.vertx.core.file.AsyncFile file = ares.result(); io.vertx.core.streams.Pump pump = io.vertx.core.streams.Pump.pump(request, file); request.endHandler(v1 -> file.close(v2 -> { PersistMethod persistMethod = PersistMethod.SAVE; String requestedPersistMethod = request.getParam("persist_method"); if(requestedPersistMethod != null){ if(PersistMethod.valueOf(requestedPersistMethod) != null){ persistMethod = PersistMethod.valueOf(requestedPersistMethod); } } if(persistMethod == PersistMethod.SAVE_AND_NOTIFY){ String address = request.getParam("bus_address"); if(address == null){ address = DEFAULT_UPLOAD_BUS_ADDRS; } DeliveryOptions dOps = new DeliveryOptions(); dOps.setSendTimeout(5000); dOps.setCodecName("PojoEventBusCodec"); JobConf cObj = new JobConf(); cObj.setInstId(instId[0]); cObj.setEnabled(true); cObj.setDescription("File import job"); cObj.setType(RTFConsts.SCHEDULE_TYPE_MANUAL); cObj.setName(address); cObj.setCreator("system"); cObj.setModule(RTFConsts.IMPORT_MODULE); cObj.setBulkSize(1000); cObj.setFailPercentage(5.0); //this is a hack to use the conf object //which is only one for all job instances of this type //to pass the specific file for this job instance to the //listening service Parameter p1 = new Parameter(); p1.setKey("file"); p1.setValue(filename[0]); List<Parameter> parameters = new ArrayList<>(); parameters.add(p1); cObj.setParameters(parameters); eventBus.send(address, cObj, dOps, rep -> { if(rep.succeeded()){ log.debug("Delivered Messaged of uploaded file " + filename[0]); Object returnCode = rep.result().body(); if(returnCode != null){ if(RTFConsts.OK_PROCESSING_STATUS.equals(returnCode)){ request.response().setStatusCode(204); } else{ request.response().setStatusCode(400); request.response().setStatusMessage("File uploaded but there was an error processing request"); } } request.response().end(); } else{ log.error("Unable to deliver message of uploaded file " + filename[0] + " check if notification address is correct"); request.response().setStatusCode(400); request.response().setStatusMessage("The file was saved, but unable to notify of the upload to listening services " + "check if notification address is correct"); request.response().end(); } }); } else{ request.response().setStatusCode(204); request.response().end(); } log.info("Successfully uploaded file " + filename[0]); })); pump.start(); request.resume(); } catch (Exception e) { log.error(e); endRequestWithError(rc, 400, true, messages.getMessage("en", MessageConsts.FileUploadError, e.getMessage()), validRequest); } }); } class StreamStatus { public int status = -1; } }
package com.gmail.alexellingsen.g2aospskin.hooks; import android.app.Activity; import android.content.Context; import android.content.res.XModuleResources; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.util.AttributeSet; import android.view.ContextThemeWrapper; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import com.gmail.alexellingsen.g2aospskin.Prefs; import com.gmail.alexellingsen.g2aospskin.R; import com.gmail.alexellingsen.g2aospskin.utils.SettingsHelper; import de.robv.android.xposed.XC_MethodHook; import de.robv.android.xposed.XposedBridge; import de.robv.android.xposed.XposedHelpers; import de.robv.android.xposed.callbacks.XC_InitPackageResources.InitPackageResourcesParam; import de.robv.android.xposed.callbacks.XC_LayoutInflated; import de.robv.android.xposed.callbacks.XC_LoadPackage; import java.util.ArrayList; public class LGMessenger { private static final String PACKAGE = "com.android.mms"; private static XModuleResources mModRes; private static SettingsHelper mSettings; private static int mID = -1; private static ImageView mConversationShadow; public static void init(final SettingsHelper settings, XModuleResources modRes) throws Throwable { mModRes = modRes; mSettings = settings; try { XposedHelpers.findAndHookMethod( "android.view.View", null, "setBackground", Drawable.class, new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { if (param.thisObject instanceof LinearLayout && mSettings.getBoolean(Prefs.AOSP_THEME_LG_MESSENGER, false)) { LinearLayout thiz = (LinearLayout) param.thisObject; Context context = thiz.getContext(); if (context.getClass().getName().equals("com.android.mms.ui.ComposeMessageActivity")) { if (mID != -1 && thiz.getId() == mID) { param.args[0] = null; } } } else if (param.thisObject.getClass().getName().equals("com.android.mms.pinchApi.ExEditText") && mSettings.getBoolean(Prefs.AOSP_THEME_LG_MESSENGER, false)) { param.args[0] = null; } } } ); XposedHelpers.findAndHookMethod( "android.view.View", null, "setBackgroundDrawable", Drawable.class, new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { if (param.thisObject.getClass().getName().equals("com.android.mms.pinchApi.ExEditText") && mSettings.getBoolean(Prefs.AOSP_THEME_LG_MESSENGER, false)) { param.args[0] = null; } } } ); } catch (Throwable ignored) { XposedBridge.log("Couldn't hook LinearLayout in init"); } XposedHelpers.findAndHookMethod( "android.view.ContextThemeWrapper", null, "setTheme", int.class, new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { if (param.thisObject.getClass().getPackage().getName().contains("com.android.mms.ui") && mSettings.getBoolean(Prefs.AOSP_THEME_LG_MESSENGER, false)) { param.args[0] = android.R.style.Theme_Holo_Light_DarkActionBar; } } } ); } public static void handleInitPackageResources(InitPackageResourcesParam resparam) throws Throwable { if (!resparam.packageName.equals(PACKAGE)) { return; } if (!mSettings.getBoolean(Prefs.AOSP_THEME_LG_MESSENGER, false)) return; resparam.res.hookLayout(PACKAGE, "layout", "conversation_list_screen", new XC_LayoutInflated() { @Override public void handleLayoutInflated(LayoutInflatedParam liparam) throws Throwable { mConversationShadow = (ImageView) liparam.view.findViewById( liparam.res.getIdentifier("msg_list_title_bar_shadow_img", "id", PACKAGE) ); mConversationShadow.setVisibility(View.GONE); } }); resparam.res.setReplacement(PACKAGE, "drawable", "ic_add", mModRes.fwd(R.drawable.ic_action_content_new)); resparam.res.setReplacement(PACKAGE, "drawable", "ic_menu_add", mModRes.fwd(R.drawable.ic_action_content_new)); resparam.res.setReplacement(PACKAGE, "drawable", "ic_menu_call", mModRes.fwd(R.drawable.ic_action_device_access_call)); resparam.res.setReplacement(PACKAGE, "drawable", "ic_menu_composemsg", mModRes.fwd(R.drawable.ic_action_content_new_email)); } public static void handleLoadPackage(final XC_LoadPackage.LoadPackageParam lpparam) throws Throwable { if (!lpparam.packageName.equals(PACKAGE)) { return; } if (!mSettings.getBoolean(Prefs.AOSP_THEME_LG_MESSENGER, false)) return; XposedHelpers.findAndHookMethod( PACKAGE + ".ui.ComposeMessageFragment", lpparam.classLoader, "initResourceRefs", new XC_MethodHook() { @Override protected void afterHookedMethod(MethodHookParam param) throws Throwable { ViewGroup view = (ViewGroup) XposedHelpers.getObjectField(param.thisObject, "mEditTextLayout"); mID = view.getId(); } } ); ArrayList<String> classes = new ArrayList<String>(); classes.add(PACKAGE + ".ui.ConversationList"); classes.add(PACKAGE + ".ui.ComposeMessageActivity"); classes.add(PACKAGE + ".ui.SmsPreference"); classes.add(PACKAGE + ".ui.FloatingWrapper"); for (String c : classes) { XposedHelpers.findAndHookMethod( c, lpparam.classLoader, "onCreate", Bundle.class, new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { ((Activity) param.thisObject).setTheme(android.R.style.Theme_Holo_Light_DarkActionBar); } } ); } XC_MethodHook hook = new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { param.args[0] = new ContextThemeWrapper((android.content.Context) param.args[0], android.R.style.Theme_Holo_Light_DarkActionBar); } }; XposedHelpers.findAndHookConstructor( PACKAGE + ".pinchApi.ExEditText", lpparam.classLoader, Context.class, hook ); XposedHelpers.findAndHookConstructor( PACKAGE + ".pinchApi.ExEditText", lpparam.classLoader, Context.class, AttributeSet.class, hook ); XposedHelpers.findAndHookConstructor( PACKAGE + ".pinchApi.ExEditText", lpparam.classLoader, Context.class, AttributeSet.class, int.class, hook ); XposedBridge.log("Hooked all constructors"); } }
package <%=packageName%>.web.rest; import com.codahale.metrics.annotation.Timed; import <%=packageName%>.domain.<%= entityClass %>; import <%=packageName%>.repository.<%= entityClass %>Repository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.inject.Inject;<% if (javaVersion == '7') { %> import javax.servlet.http.HttpServletResponse;<% } %> import java.util.List;<% if (javaVersion == '8') { %> import java.util.Optional;<% } %> /** * REST controller for managing <%= entityClass %>. */ @RestController @RequestMapping("/app") public class <%= entityClass %>Resource { private final Logger log = LoggerFactory.getLogger(<%= entityClass %>Resource.class); @Inject private <%= entityClass %>Repository <%= entityInstance %>Repository; /** * POST /rest/<%= entityInstance %>s -> Create a new <%= entityInstance %>. */ @RequestMapping(value = "/rest/<%= entityInstance %>s", method = RequestMethod.POST, produces = "application/json") @Timed public void create(@RequestBody <%= entityClass %> <%= entityInstance %>) { log.debug("REST request to save <%= entityClass %> : {}", <%= entityInstance %>); <%= entityInstance %>Repository.save(<%= entityInstance %>); } /** * GET /rest/<%= entityInstance %>s -> get all the <%= entityInstance %>s. */ @RequestMapping(value = "/rest/<%= entityInstance %>s", method = RequestMethod.GET, produces = "application/json") @Timed public List<<%= entityClass %>> getAll() { log.debug("REST request to get all <%= entityClass %>s"); return <%= entityInstance %>Repository.findAll(); } /** * GET /rest/<%= entityInstance %>s/:id -> get the "id" <%= entityInstance %>. */ @RequestMapping(value = "/rest/<%= entityInstance %>s/{id}", method = RequestMethod.GET, produces = "application/json") @Timed public ResponseEntity<<%= entityClass %>> get(@PathVariable <% if (databaseType == 'sql') { %>Long<% } %><% if (databaseType == 'nosql') { %>String<% } %> id<% if (javaVersion == '7') { %>, HttpServletResponse response<% } %>) { log.debug("REST request to get <%= entityClass %> : {}", id);<% if (javaVersion == '8') { %> return Optional.ofNullable(<%= entityInstance %>Repository.findOne(id)) .map(<%= entityInstance %> -> new ResponseEntity<>( <%= entityInstance %>, HttpStatus.OK)) .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));<% } else { %> <%= entityClass %> <%= entityInstance %> = <%= entityInstance %>Repository.findOne(id); if (<%= entityInstance %> == null) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } return new ResponseEntity<>(<%= entityInstance %>, HttpStatus.OK);<% } %> } /** * DELETE /rest/<%= entityInstance %>s/:id -> delete the "id" <%= entityInstance %>. */ @RequestMapping(value = "/rest/<%= entityInstance %>s/{id}", method = RequestMethod.DELETE, produces = "application/json") @Timed public void delete(@PathVariable <% if (databaseType == 'sql') { %>Long<% } %><% if (databaseType == 'nosql') { %>String<% } %> id) { log.debug("REST request to delete <%= entityClass %> : {}", id); <%= entityInstance %>Repository.delete(id); } }
package etomica.models.nitrogen; import etomica.action.AtomActionTranslateBy; import etomica.action.MoleculeActionTranslateTo; import etomica.action.MoleculeChildAtomAction; import etomica.api.IBox; import etomica.api.IMolecule; import etomica.api.IVector; import etomica.api.IVectorMutable; import etomica.atom.MoleculePair; import etomica.data.IData; import etomica.data.IDataInfo; import etomica.data.types.DataGroup; import etomica.lattice.BravaisLatticeCrystal; import etomica.lattice.IndexIterator; import etomica.lattice.IndexIteratorReflecting; import etomica.lattice.IndexIteratorTriangular; import etomica.lattice.IndexIteratorTriangularPermutations; import etomica.lattice.SpaceLattice; import etomica.paracetamol.AtomActionTransformed; import etomica.space.Tensor; import etomica.util.FunctionGeneral; /** * Lattice sum crystal for molecular model * * * @author taitan * */ public class LatticeSumCrystalMolecular{ public LatticeSumCrystalMolecular(BravaisLatticeCrystal lattice, CoordinateDefinitionNitrogen coordinateDef, IBox box) { this.lattice = lattice; this.coordinateDef = coordinateDef; this.ghostBox = box; xzOrientationTensor = coordinateDef.getXzOrientationTensor(); yOrientationTensor = coordinateDef.getyOrientationTensor(); if(coordinateDef.isBetaLatticeSum){ positionVector = coordinateDef.positionVector; } atomGroupAction = new MoleculeChildAtomAction(new AtomActionTransformed(lattice.getSpace())); spaceDim = lattice.getSpace().D(); IndexIteratorTriangularPermutations iteratorT = new IndexIteratorTriangularPermutations(spaceDim); setIterator(new IndexIteratorReflecting(iteratorT)); coreIterator = iteratorT.getCoreIterator(); kVector = lattice.getSpace().makeVector(); dr = lattice.getSpace().makeVector(); siteIndex = new int[lattice.D()];//lattice.D() should be spaceDim+1 position = lattice.getSpace().makeVector(); //get coordinates of basis at the origin basisDim = lattice.getBasis().getScaledCoordinates().length; basis0 = new IVectorMutable[basisDim]; moleculeCell0 = new IMolecule[basisDim]; for(int j=0; j<basisDim; j++) { siteIndex[spaceDim] = j; basis0[j] = lattice.getSpace().makeVector(); basis0[j].E((IVectorMutable)lattice.site(siteIndex)); moleculeCell0[j] = coordinateDef.getBasisCells()[0].molecules.getMolecule(j); } atomActionTranslateTo = new MoleculeActionTranslateTo(lattice.getSpace()); translateBy = new AtomActionTranslateBy(lattice.getSpace()); atomGroupActionTranslate = new MoleculeChildAtomAction(translateBy); } public DataGroup calculateSum(FunctionGeneral function) { IDataInfo dataInfo = function.getDataInfo(); IData work = dataInfo.makeData(); IData[][] sumR = new IData[basisDim][basisDim]; IData[][] sumI = new IData[basisDim][basisDim]; for(int jp=0; jp<basisDim; jp++) { for(int j=0; j<basisDim; j++) { sumR[jp][j] = dataInfo.makeData(); sumI[jp][j] = dataInfo.makeData(); } } MoleculePair pair; for(int jp=0; jp<basisDim; jp++) { for(int j=0; j<basisDim; j++) { if(jp==j) continue; pair = new MoleculePair(moleculeCell0[j], moleculeCell0[jp]); sumR[jp][j].PE(function.f(pair)); } } //loop over shells for(int m=1; m<=maxLatticeShell; m++) { //loop over cells in shell coreIterator.setMaxElement(m); coreIterator.setMaxElementMin(m); iterator.reset(); while(iterator.hasNext()) { System.arraycopy(iterator.next(), 0, siteIndex, 0, spaceDim); double ckr = 0; double skr = 0; //loop over sites in lattice cell for(int jp=0; jp<basisDim; jp++) { siteIndex[spaceDim] = jp; IMolecule ghostMol = ghostBox.getMoleculeList(ghostBox.getMoleculeList().getMolecule(0).getType()).getMolecule(0); ghostMol.getType().initializeConformation(ghostMol); int rotationNum = jp%4; ((AtomActionTransformed)atomGroupAction.getAtomAction()).setTransformationTensor(yOrientationTensor[rotationNum]); atomGroupAction.actionPerformed(ghostMol); ((AtomActionTransformed)atomGroupAction.getAtomAction()).setTransformationTensor(xzOrientationTensor[rotationNum]); atomGroupAction.actionPerformed(ghostMol); //Putting the molecule to its lattice site IVectorMutable site = (IVectorMutable)lattice.site(siteIndex); position.E(site); atomActionTranslateTo.setDestination(position); atomActionTranslateTo.actionPerformed(ghostMol); if(coordinateDef.isBetaLatticeSum){ translateBy.setTranslationVector(positionVector[rotationNum]); atomGroupActionTranslate.actionPerformed(ghostMol); } //loop over sites in origin cell for(int j=0; j<basisDim; j++) { dr.Ev1Mv2(site, basis0[j]); if(jp == 0 && j == 0) { //define cell distance as distance between 0th sites in cells double kDotr = kVector.dot(dr); ckr = Math.cos(kDotr); skr = Math.sin(kDotr); } MoleculePair molPair = new MoleculePair(moleculeCell0[j], ghostMol); IData value = function.f(molPair); work.E(value); work.TE(ckr); sumR[jp][j].PE(work); work.E(value); work.TE(skr); sumI[jp][j].PE(work); } } } } return new DataGroupLSC(sumR, sumI); } public void setK(IVector k) { kVector.E(k); } public IVector getK() { return kVector; } public IndexIterator getIterator() { return iterator; } private void setIterator(IndexIterator iterator) { if(iterator.getD() != lattice.getSpace().D()) { throw new IllegalArgumentException("Given iterator does not produce index arrays of a dimension consistent with the lattice: iterator.getD() = "+iterator.getD()+"; lattice.D() = "+lattice.D()); } this.iterator = iterator; } public SpaceLattice getLattice() { return lattice; } public int getMaxLatticeShell() { return maxLatticeShell; } /** * Specifies the largest index element that will be included in the lattice sum. * Default is 50. */ public void setMaxLatticeShell(int maxElement) { this.maxLatticeShell = maxElement; } private static final long serialVersionUID = 1L; private final BravaisLatticeCrystal lattice; private IndexIterator iterator; private IndexIteratorTriangular coreIterator; private final IVectorMutable kVector; private final IVectorMutable[] basis0; private final int[] siteIndex; private final IVectorMutable dr; private final int basisDim; private final int spaceDim; private int maxLatticeShell; protected final IMolecule[] moleculeCell0; protected IVectorMutable offset, position; protected final MoleculeActionTranslateTo atomActionTranslateTo; protected final AtomActionTranslateBy translateBy; protected MoleculeChildAtomAction atomGroupActionTranslate; protected CoordinateDefinitionNitrogen coordinateDef; protected IBox ghostBox; protected Tensor[] xzOrientationTensor, yOrientationTensor; protected MoleculeChildAtomAction atomGroupAction; protected IVectorMutable[] positionVector; /** * Helper class that encapsulates the complex basis-basis data in a manner that * permits easy access to real and imaginary components for a given pair of basis * elements. */ public class DataGroupLSC extends DataGroup { private DataGroupLSC(IData[][] sumR, IData[][] sumI) { super(makeDataArray(sumR, sumI)); } /** * Returns real part of complex data. * @param j index of basis element in origin cell * @param jp index of basis element in lattice cell */ public IData getDataReal(int j, int jp) { return ((DataGroup)((DataGroup)this.getData(jp)).getData(j)).getData(0); } /** * Returns imaginary part of complex data. * @param j index of basis element in origin cell * @param jp index of basis element in lattice cell */ public IData getDataImaginary(int j, int jp) { return ((DataGroup)((DataGroup)this.getData(jp)).getData(j)).getData(1); } private static final long serialVersionUID = 1L; } //used by DataGroupLSC constructor private static IData[] makeDataArray(IData[][] sumR, IData[][] sumI) { int basisDim = sumR.length; DataGroup[] dataArray = new DataGroup[basisDim]; DataGroup[] data = new DataGroup[basisDim]; for(int jp=0; jp<basisDim; jp++) { for(int j=0; j<basisDim; j++) { data[j] = new DataGroup(new IData[] {sumR[jp][j], sumI[jp][j]}); } dataArray[jp] = new DataGroup(data); } return dataArray; } }
package com.haxademic.core.media.audio.playback; import java.util.ArrayList; import java.util.HashMap; import com.haxademic.core.app.P; import com.haxademic.core.file.FileUtil; import com.haxademic.core.math.MathUtil; import com.haxademic.core.media.audio.interphase.Scales; public class DroneSampler { protected String audioDir; protected String[] audioFiles; protected WavPlayer activePlayer; protected HashMap<String, DroneSamplerLoop> droneLoops = new HashMap<String, DroneSamplerLoop>(); protected int soundIndex = -1; protected int loopInterval = 15000; protected int loopLastStartTime = -loopInterval; public DroneSampler(String audioDir, float loopIntervalSeconds) { this.audioDir = audioDir; this.loopInterval = P.round(loopIntervalSeconds * 1000); P.out("DroneSampler loading sounds from:", this.audioDir); loadSounds(); } protected void loadSounds() { // load audio directory ArrayList<String> sounds = FileUtil.getFilesInDirOfTypes(FileUtil.getPath(audioDir), "wav,aif"); audioFiles = new String[sounds.size()]; for (int i = 0; i < sounds.size(); i++) { audioFiles[i] = sounds.get(i); P.out("Loading...", audioFiles[i]); } } protected void startNextSound() { // go to next index & play next sound! soundIndex = (soundIndex < audioFiles.length - 1) ? soundIndex + 1 : 0; String nextSoundId = audioFiles[soundIndex]; startPlayer(nextSoundId); } protected void releaseOldPlayers() { for (HashMap.Entry<String, DroneSamplerLoop> entry : droneLoops.entrySet()) { // ramp down old players halfway through interval DroneSamplerLoop synthLoop = entry.getValue(); if(synthLoop.active() && P.p.millis() - synthLoop.startTime() > loopInterval/2) { synthLoop.release(); } } } protected void startPlayer(String id) { // lazy-init DroneSampler if(droneLoops.containsKey(id) == false) { droneLoops.put(id, new DroneSamplerLoop(id)); } // get random pitch and play int newPitch = Scales.SCALES[0][MathUtil.randRange(0, Scales.SCALES[0].length - 1)]; droneLoops.get(id).start(newPitch); } protected void checkNextSoundInterval() { if(P.p.millis() > loopLastStartTime + loopInterval) { loopLastStartTime = P.p.millis(); startNextSound(); } } protected void updateLoops() { for (HashMap.Entry<String, DroneSamplerLoop> entry : droneLoops.entrySet()) { DroneSamplerLoop droneLoop = entry.getValue(); droneLoop.update(); } } public void update() { releaseOldPlayers(); checkNextSoundInterval(); updateLoops(); } }
package com.itmill.toolkit.terminal.gwt.client.ui; import java.util.Date; import com.google.gwt.user.client.ui.FlowPanel; import com.itmill.toolkit.terminal.gwt.client.ApplicationConnection; import com.itmill.toolkit.terminal.gwt.client.DateTimeService; import com.itmill.toolkit.terminal.gwt.client.LocaleNotLoadedException; import com.itmill.toolkit.terminal.gwt.client.Paintable; import com.itmill.toolkit.terminal.gwt.client.UIDL; public class IDateField extends FlowPanel implements Paintable { public static final String CLASSNAME = "i-datefield"; protected String id; protected ApplicationConnection client; protected boolean immediate; public static int RESOLUTION_YEAR = 0; public static int RESOLUTION_MONTH = 1; public static int RESOLUTION_DAY = 2; public static int RESOLUTION_HOUR = 3; public static int RESOLUTION_MIN = 4; public static int RESOLUTION_SEC = 5; public static int RESOLUTION_MSEC = 6; protected int currentResolution = RESOLUTION_YEAR; protected String currentLocale; protected boolean readonly; protected boolean enabled; protected Date date = null; // e.g when paging a calendar, before actually selecting protected Date showingDate = new Date(); protected DateTimeService dts; public IDateField() { setStyleName(CLASSNAME); dts = new DateTimeService(); } public void updateFromUIDL(UIDL uidl, ApplicationConnection client) { // Ensure correct implementation and let layout manage caption if (client.updateComponent(this, uidl, true)) { return; } // Save details this.client = client; id = uidl.getId(); immediate = uidl.getBooleanAttribute("immediate"); readonly = uidl.getBooleanAttribute("readonly"); enabled = !uidl.getBooleanAttribute("disabled"); if (uidl.hasAttribute("locale")) { final String locale = uidl.getStringAttribute("locale"); try { dts.setLocale(locale); currentLocale = locale; } catch (final LocaleNotLoadedException e) { currentLocale = dts.getLocale(); // TODO redirect this to console System.out.println("Tried to use an unloaded locale \"" + locale + "\". Using default locale (" + currentLocale + ")."); } } int newResolution; if (uidl.hasVariable("msec")) { newResolution = RESOLUTION_MSEC; } else if (uidl.hasVariable("sec")) { newResolution = RESOLUTION_SEC; } else if (uidl.hasVariable("min")) { newResolution = RESOLUTION_MIN; } else if (uidl.hasVariable("hour")) { newResolution = RESOLUTION_HOUR; } else if (uidl.hasVariable("day")) { newResolution = RESOLUTION_DAY; } else if (uidl.hasVariable("month")) { newResolution = RESOLUTION_MONTH; } else { newResolution = RESOLUTION_YEAR; } currentResolution = newResolution; final int year = uidl.getIntVariable("year"); final int month = (currentResolution >= RESOLUTION_MONTH) ? uidl .getIntVariable("month") : -1; final int day = (currentResolution >= RESOLUTION_DAY) ? uidl .getIntVariable("day") : -1; final int hour = (currentResolution >= RESOLUTION_HOUR) ? uidl .getIntVariable("hour") : 0; final int min = (currentResolution >= RESOLUTION_MIN) ? uidl .getIntVariable("min") : 0; final int sec = (currentResolution >= RESOLUTION_SEC) ? uidl .getIntVariable("sec") : 0; final int msec = (currentResolution >= RESOLUTION_MSEC) ? uidl .getIntVariable("msec") : 0; // Construct new date for this datefield (only if not null) if (year > -1) { date = new Date((long) getTime(year, month, day, hour, min, sec, msec)); showingDate.setTime(date.getTime()); } else { date = null; showingDate = new Date(); } } /* * We need this redundant native function because Java's Date object doesn't * have a setMilliseconds method. */ private static native double getTime(int y, int m, int d, int h, int mi, int s, int ms) /*-{ try { var date = new Date(); if(y && y >= 0) date.setFullYear(y); if(m && m >= 1) date.setMonth(m-1); if(d && d >= 0) date.setDate(d); if(h >= 0) date.setHours(h); if(mi >= 0) date.setMinutes(mi); if(s >= 0) date.setSeconds(s); if(ms >= 0) date.setMilliseconds(ms); return date.getTime(); } catch (e) { // TODO print some error message on the console //console.log(e); return (new Date()).getTime(); } }-*/; public int getMilliseconds() { return (int) (date.getTime() - date.getTime() / 1000 * 1000); } public void setMilliseconds(int ms) { date.setTime(date.getTime() / 1000 * 1000 + ms); } public int getCurrentResolution() { return currentResolution; } public void setCurrentResolution(int currentResolution) { this.currentResolution = currentResolution; } public String getCurrentLocale() { return currentLocale; } public void setCurrentLocale(String currentLocale) { this.currentLocale = currentLocale; } public Date getCurrentDate() { return date; } public void setCurrentDate(Date date) { this.date = date; } public Date getShowingDate() { return showingDate; } public void setShowingDate(Date date) { showingDate = date; } public boolean isImmediate() { return immediate; } public boolean isReadonly() { return readonly; } public boolean isEnabled() { return enabled; } public DateTimeService getDateTimeService() { return dts; } public String getId() { return id; } public ApplicationConnection getClient() { return client; } }
import org.junit.Rule; import org.junit.Test; import org.openqa.selenium.WebElement; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import org.testcontainers.containers.BrowserWebDriverContainer; import java.io.File; import java.util.List; import static org.rnorth.visibleassertions.VisibleAssertions.assertTrue; import static org.testcontainers.containers.BrowserWebDriverContainer.VncRecordingMode.RECORD_ALL; /** * Simple example of plain Selenium usage. */ public class SeleniumContainerTest { @Rule public BrowserWebDriverContainer chrome = new BrowserWebDriverContainer() .withDesiredCapabilities(DesiredCapabilities.chrome()) .withRecordingMode(RECORD_ALL, new File("target")); @Test public void simplePlainSeleniumTest() { RemoteWebDriver driver = chrome.getWebDriver(); driver.get("https://wikipedia.org"); List<WebElement> searchInput = driver.findElementsByName("search"); assertTrue("The search input box is found", searchInput != null && searchInput.size() > 0); } }
package com.jcwhatever.bukkit.storefront.regions; import com.jcwhatever.bukkit.generic.mixins.IDisposable; import com.jcwhatever.bukkit.generic.regions.BasicRegion; import com.jcwhatever.bukkit.generic.regions.IRegionEventHandler; import com.jcwhatever.bukkit.generic.regions.ReadOnlyRegion; import com.jcwhatever.bukkit.generic.regions.Region.EnterRegionReason; import com.jcwhatever.bukkit.generic.regions.Region.LeaveRegionReason; import com.jcwhatever.bukkit.generic.utils.PreCon; import com.jcwhatever.bukkit.storefront.Msg; import com.jcwhatever.bukkit.storefront.Storefront; import com.jcwhatever.bukkit.storefront.stores.IStore; import org.bukkit.Location; import org.bukkit.entity.Player; import javax.annotation.Nullable; public class StoreRegion implements IDisposable{ private final IStore _store; private final MessageHandler _messageHandler; private ReadOnlyRegion _region; private String _entryMessage; private String _exitMessage; private boolean _hasOwnRegion; /** * Constructor */ public StoreRegion(IStore store, ReadOnlyRegion region) { _store = store; _messageHandler = new MessageHandler(); setRegion(region); } public StoreRegion(IStore store) { PreCon.notNull(store); _store = store; _messageHandler = new MessageHandler(); setOwnRegion(); } public boolean hasOwnRegion() { return _hasOwnRegion; } public ReadOnlyRegion getRegion() { return _region; } public void setRegion(ReadOnlyRegion region) { PreCon.notNull(region); if (_region != null) { dispose(); } _hasOwnRegion = false; _region = region; _region.addEventHandler(_messageHandler); _region.setMeta(IStore.class.getName(), _store); } public void setOwnRegion() { if (_region != null) { dispose(); } _hasOwnRegion = true; BasicRegion region = new BasicRegion(Storefront.getInstance(), _store.getName(), _store.getDataNode().getNode("region")); region.setMeta(BasicRegion.class.getName() + ".Storefront", region); _region = new ReadOnlyRegion(region); _region.addEventHandler(_messageHandler); _region.setMeta(IStore.class.getName(), _store); } public void setCoords(Location p1, Location p2) { if (!hasOwnRegion()) setOwnRegion(); BasicRegion region = _region.getMeta(BasicRegion.class.getName() + ".Storefront"); if (region == null) throw new AssertionError(); region.setCoords(p1, p2); } @Nullable public String getEntryMessage() { return _entryMessage; } @Nullable public String getExitMessage() { return _exitMessage; } public void setEntryMessage(@Nullable String message) { _entryMessage = message; } public void setExitMessage(@Nullable String message) { _exitMessage = message; } @Override public void dispose() { _region.removeEventHandler(_messageHandler); _region.setMeta(IStore.class.getName(), null); BasicRegion internalRegion = _region.getMeta(BasicRegion.class.getName() + ".Storefront"); if (internalRegion != null) { internalRegion.dispose(); } } private class MessageHandler implements IRegionEventHandler { @Override public boolean canDoPlayerEnter(Player player, EnterRegionReason reason) { return _entryMessage != null; } @Override public boolean canDoPlayerLeave(Player player, LeaveRegionReason reason) { return _exitMessage != null; } @Override public void onPlayerEnter(Player player, EnterRegionReason reason) { Msg.tell(player, _entryMessage); } @Override public void onPlayerLeave(Player player, LeaveRegionReason reason) { Msg.tell(player, _exitMessage); } } }
package com.jwetherell.algorithms.data_structures; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Deque; import java.util.List; import com.jwetherell.algorithms.data_structures.interfaces.IHeap; @SuppressWarnings("unchecked") public interface BinaryHeap<T extends Comparable<T>> extends IHeap<T> { public enum HeapType { Tree, Array } public enum Type { MIN, MAX } /** * Get the heap in array form. * * @return array representing the heap. */ public T[] getHeap(); /** * A binary heap using an array to hold the nodes. * * @author Justin Wetherell <phishman3579@gmail.com> */ public static class BinaryHeapArray<T extends Comparable<T>> implements BinaryHeap<T> { private static final int MINIMUM_SIZE = 10; private Type type = Type.MIN; private int size = 0; private T[] array = (T[]) new Comparable[MINIMUM_SIZE]; /** * Get the parent index of this index, will return Integer.MIN_VALUE if * no parent is possible. * * @param index * of the node to find a parent for. * @return index of parent node or Integer.MIN_VALUE if no parent. */ private static final int getParentIndex(int index) { if (index > 0) return (int) Math.floor((index - 1) / 2); return Integer.MIN_VALUE; } /** * Get the left child index of this index. * * @param index * of the node to find a left child for. * @return index of left child node. */ private static final int getLeftIndex(int index) { return 2 * index + 1; } /** * Get the right child index of this index. * * @param index * of the node to find a right child for. * @return index of right child node. */ private static final int getRightIndex(int index) { return 2 * index + 2; } /** * Constructor for heap, defaults to a min-heap. */ public BinaryHeapArray() { size = 0; } /** * Constructor for heap. * * @param type * Heap type. */ public BinaryHeapArray(Type type) { this(); this.type = type; } /** * {@inheritDoc} */ @Override public int size() { return size; } /** * {@inheritDoc} */ @Override public boolean add(T value) { int growSize = this.size; if (size >= array.length) { array = Arrays.copyOf(array, (growSize + (growSize>>1))); } array[size] = value; heapUp(size++); return true; } protected void heapUp(int nodeIndex) { T value = this.array[nodeIndex]; while (nodeIndex >= 0) { int parentIndex = getParentIndex(nodeIndex); if (parentIndex < 0) break; T parent = this.array[parentIndex]; if ((type == Type.MIN && parent != null && value.compareTo(parent) < 0) || (type == Type.MAX && parent != null && value.compareTo(parent) > 0) ) { // Node is greater/lesser than parent, switch node with parent this.array[parentIndex] = value; this.array[nodeIndex] = parent; } else { nodeIndex = parentIndex; } } } /** * {@inheritDoc} */ @Override public T remove(T value) { if (array.length == 0) return null; for (int i = 0; i < size; i++) { T node = array[i]; if (node.equals(value)) return remove(i); } return null; } private T remove(int index) { if (index<0 || index>=size) return null; T t = array[index]; array[index] = array[--size]; array[size] = null; heapDown(index); int shrinkSize = size; if (size >= MINIMUM_SIZE && size < (shrinkSize + (shrinkSize<<1))) { System.arraycopy(array, 0, array, 0, size); } return t; } /** * {@inheritDoc} */ @Override public void clear() { size = 0; } /** * {@inheritDoc} */ @Override public boolean contains(T value) { if (array.length == 0) return false; for (int i = 0; i < size; i++) { T t = array[i]; if (t.equals(value)) return true; } return false; } /** * {@inheritDoc} */ @Override public boolean validate() { if (array.length == 0) return true; return validateNode(0); } /** * Validate the node for the heap invariants. * * @param node * to validate for. * @return True if node is valid. */ private boolean validateNode(int index) { T value = this.array[index]; int leftIndex = getLeftIndex(index); int rightIndex = getRightIndex(index); // We shouldn't ever have a right node without a left in a heap if (rightIndex != Integer.MIN_VALUE && leftIndex == Integer.MIN_VALUE) return false; if (leftIndex != Integer.MIN_VALUE && leftIndex < size) { T left = this.array[leftIndex]; if ((type == Type.MIN && value.compareTo(left) < 0) || (type == Type.MAX && value.compareTo(left) > 0)) { return validateNode(leftIndex); } return false; } if (rightIndex != Integer.MIN_VALUE && rightIndex < size) { T right = this.array[rightIndex]; if ((type == Type.MIN && value.compareTo(right) < 0) || (type == Type.MAX && value.compareTo(right) > 0)) { return validateNode(rightIndex); } return false; } return true; } /** * {@inheritDoc} */ @Override public T[] getHeap() { T[] nodes = (T[]) new Comparable[size]; if (array.length == 0) return nodes; for (int i = 0; i < size; i++) { T node = this.array[i]; nodes[i] = node; } return nodes; } /** * {@inheritDoc} */ @Override public T getHeadValue() { if (array.length == 0) return null; return array[0]; } /** * {@inheritDoc} */ @Override public T removeHead() { return remove(getHeadValue()); } protected void heapDown(int index) { T value = this.array[index]; int leftIndex = getLeftIndex(index); int rightIndex = getRightIndex(index); T left = (leftIndex != Integer.MIN_VALUE && leftIndex < this.size) ? this.array[leftIndex] : null; T right = (rightIndex != Integer.MIN_VALUE && rightIndex < this.size) ? this.array[rightIndex] : null; if (left == null && right == null) { // Nothing to do here return; } T nodeToMove = null; int nodeToMoveIndex = -1; if ((type == Type.MIN && left != null && right != null && value.compareTo(left) > 0 && value.compareTo(right) > 0) || (type == Type.MAX && left != null && right != null && value.compareTo(left) < 0 && value.compareTo(right) < 0)) { // Both children are greater/lesser than node if ((type == Type.MIN && right.compareTo(left) < 0) || (type == Type.MAX && right.compareTo(left) > 0)) { // Right is greater/lesser than left nodeToMove = right; nodeToMoveIndex = rightIndex; } else if ((type == Type.MIN && left.compareTo(right) < 0) || (type == Type.MAX && left.compareTo(right) > 0) ) { // Left is greater/lesser than right nodeToMove = left; nodeToMoveIndex = leftIndex; } else { // Both children are equal, use right nodeToMove = right; nodeToMoveIndex = rightIndex; } } else if ((type == Type.MIN && right != null && value.compareTo(right) > 0) || (type == Type.MAX && right != null && value.compareTo(right) < 0) ) { // Right is greater/lesser than node nodeToMove = right; nodeToMoveIndex = rightIndex; } else if ((type == Type.MIN && left != null && value.compareTo(left) > 0) || (type == Type.MAX && left != null && value.compareTo(left) < 0) ) { // Left is greater/lesser than node nodeToMove = left; nodeToMoveIndex = leftIndex; } // No node to move, stop recursion if (nodeToMove == null) return; // Re-factor heap sub-tree this.array[nodeToMoveIndex] = value; this.array[index] = nodeToMove; heapDown(nodeToMoveIndex); } /** * {@inheritDoc} */ @Override public java.util.Collection<T> toCollection() { return (new JavaCompatibleBinaryHeapArray<T>(this)); } /** * {@inheritDoc} */ @Override public String toString() { return HeapPrinter.getString(this); } protected static class HeapPrinter { public static <T extends Comparable<T>> String getString(BinaryHeapArray<T> tree) { if (tree.array.length == 0) return "Tree has no nodes."; T root = tree.array[0]; if (root == null) return "Tree has no nodes."; return getString(tree, 0, "", true); } private static <T extends Comparable<T>> String getString(BinaryHeapArray<T> tree, int index, String prefix, boolean isTail) { StringBuilder builder = new StringBuilder(); T value = tree.array[index]; builder.append(prefix + (isTail ? " " : " ") + value + "\n"); List<Integer> children = null; int leftIndex = getLeftIndex(index); int rightIndex = getRightIndex(index); if (leftIndex != Integer.MIN_VALUE || rightIndex != Integer.MIN_VALUE) { children = new ArrayList<Integer>(2); if (leftIndex != Integer.MIN_VALUE && leftIndex < tree.size) { children.add(leftIndex); } if (rightIndex != Integer.MIN_VALUE && rightIndex < tree.size) { children.add(rightIndex); } } if (children != null) { for (int i = 0; i < children.size() - 1; i++) { builder.append(getString(tree, children.get(i), prefix + (isTail ? " " : " "), false)); } if (children.size() >= 1) { builder.append(getString(tree, children.get(children.size() - 1), prefix + (isTail ? " " : " "), true)); } } return builder.toString(); } } } public static class BinaryHeapTree<T extends Comparable<T>> implements BinaryHeap<T> { private Type type = Type.MIN; private int size = 0; private Node<T> root = null; /** * Constructor for heap, defaults to a min-heap. */ public BinaryHeapTree() { root = null; size = 0; } /** * Constructor for heap. * * @param type * Heap type. */ public BinaryHeapTree(Type type) { this(); this.type = type; } /** * {@inheritDoc} */ @Override public int size() { return size; } /** * Get the navigation directions through the tree to the index. * * @param index * of the Node to get directions for. * @return Integer array representing the directions to the index. */ private int[] getDirections(int index) { int directionsSize = (int) (Math.log10(index + 1) / Math.log10(2)) - 1; int[] directions = null; if (directionsSize > 0) { directions = new int[directionsSize]; int i = directionsSize - 1; while (i >= 0) { index = (index - 1) / 2; directions[i--] = (index > 0 && index % 2 == 0) ? 1 : 0; // 0=left, 1=right } } return directions; } /** * {@inheritDoc} */ @Override public boolean add(T value) { return add(new Node<T>(null, value)); } private boolean add(Node<T> newNode) { if (root == null) { root = newNode; size++; return true; } Node<T> node = root; int[] directions = getDirections(size); // size == index of new node if (directions != null && directions.length > 0) { for (int d : directions) { if (d == 0) { // Go left node = node.left; } else { // Go right node = node.right; } } } if (node.left == null) { node.left = newNode; } else { node.right = newNode; } newNode.parent = node; size++; heapUp(newNode); return true; } /** * Remove the root node. */ private void removeRoot() { replaceNode(root); } private Node<T> getLastNode() { // Find the last node int[] directions = getDirections(size-1); // Directions to the last node Node<T> lastNode = root; if (directions != null && directions.length > 0) { for (int d : directions) { if (d == 0) { // Go left lastNode = lastNode.left; } else { // Go right lastNode = lastNode.right; } } } if (lastNode.right != null) { lastNode = lastNode.right; } else if (lastNode.left != null) { lastNode = lastNode.left; } return lastNode; } /** * Replace the node with the last node and heap down. * * @param node to replace. */ private void replaceNode(Node<T> node) { Node<T> lastNode = getLastNode(); // Remove lastNode from tree Node<T> lastNodeParent = lastNode.parent; if (lastNodeParent!=null) { if (lastNodeParent.right != null) { lastNodeParent.right = null; } else { lastNodeParent.left = null; } lastNode.parent = null; } if (node.parent!=null) { if (node.parent.left.equals(node)) { node.parent.left = lastNode; } else { node.parent.right = lastNode; } } lastNode.parent = node.parent; lastNode.left = node.left; if (node.left!=null) node.left.parent = lastNode; lastNode.right = node.right; if (node.right!=null) node.right.parent = lastNode; if (node.equals(root)) { if (!lastNode.equals(root)) root = lastNode; else root = null; } size // Last node is the node to remove if (lastNode.equals(node)) return; if (lastNode.equals(root)) { heapDown(lastNode); } else { heapDown(lastNode); heapUp(lastNode); } } /** * Get the node in the startingNode sub-tree which has the value. * * @param startingNode * node rooted sub-tree to search in. * @param value * to search for. * @return Node<T> which equals value in sub-tree or NULL if not found. */ private Node<T> getNode(Node<T> startingNode, T value) { Node<T> result = null; if (startingNode != null && startingNode.value.equals(value)) { result = startingNode; } else if (startingNode != null && !startingNode.value.equals(value)) { Node<T> left = startingNode.left; Node<T> right = startingNode.right; Type type = this.type; if (left != null && ((type==Type.MIN && left.value.compareTo(value)<=0)||(type==Type.MAX && left.value.compareTo(value)>=0)) ) { result = getNode(left, value); if (result != null) return result; } if (right != null && ((type==Type.MIN && right.value.compareTo(value)<=0)||(type==Type.MAX && right.value.compareTo(value)>=0)) ) { result = getNode(right, value); if (result != null) return result; } } return result; } /** * {@inheritDoc} */ @Override public void clear() { root = null; size = 0; } /** * {@inheritDoc} */ @Override public boolean contains(T value) { if (root == null) return false; Node<T> node = getNode(root,value); return (node != null); } /** * {@inheritDoc} */ @Override public T remove(T value) { if (root == null) return null; Node<T> node = getNode(root,value); if (node!=null) { T t = node.value; replaceNode(node); return t; } return null; } /** * Heap up the heap from this node. * * @param node * to heap up. */ protected void heapUp(Node<T> node) { while (node != null) { Node<T> heapNode = node; Node<T> parent = heapNode.parent; if ((type == Type.MIN && parent != null && node.value.compareTo(parent.value) < 0) || (type == Type.MAX && parent != null && node.value.compareTo(parent.value) > 0)) { // Node is less than parent, switch node with parent Node<T> grandParent = parent.parent; Node<T> parentLeft = parent.left; Node<T> parentRight = parent.right; parent.left = heapNode.left; if (parent.left != null) parent.left.parent = parent; parent.right = heapNode.right; if (parent.right != null) parent.right.parent = parent; if (parentLeft != null && parentLeft.equals(node)) { heapNode.left = parent; heapNode.right = parentRight; if (parentRight != null) parentRight.parent = heapNode; } else { heapNode.right = parent; heapNode.left = parentLeft; if (parentLeft != null) parentLeft.parent = heapNode; } parent.parent = heapNode; if (grandParent == null) { // New root. heapNode.parent = null; root = heapNode; } else { Node<T> grandLeft = grandParent.left; if (grandLeft != null && grandLeft.equals(parent)) { grandParent.left = heapNode; } else { grandParent.right = heapNode; } heapNode.parent = grandParent; } } else { node = heapNode.parent; } } } /** * Heap down the heap from this node. * * @param node * to heap down. */ protected void heapDown(Node<T> node) { if (node==null) return; Node<T> heapNode = node; Node<T> left = heapNode.left; Node<T> right = heapNode.right; if (left == null && right == null) { // Nothing to do here return; } Node<T> nodeToMove = null; if ((type == Type.MIN && left != null && right != null && node.value.compareTo(left.value) > 0 && node.value.compareTo(right.value) > 0) || (type == Type.MAX && left != null && right != null && node.value.compareTo(left.value) < 0 && node.value.compareTo(right.value) < 0)) { // Both children are greater/lesser than node if ((type == Type.MIN && right.value.compareTo(left.value) < 0) || (type == Type.MAX && right.value.compareTo(left.value) > 0)) { // Right is greater/lesser than left nodeToMove = right; } else if ((type == Type.MIN && left.value.compareTo(right.value) < 0) || (type == Type.MAX && left.value.compareTo(right.value) > 0)) { // Left is greater/lesser than right nodeToMove = left; } else { // Both children are equal, use right nodeToMove = right; } } else if ((type == Type.MIN && right != null && node.value.compareTo(right.value) > 0) || (type == Type.MAX && right != null && node.value.compareTo(right.value) < 0)) { // Right is greater than node nodeToMove = right; } else if ((type == Type.MIN && left != null && node.value.compareTo(left.value) > 0) || (type == Type.MAX && left != null && node.value.compareTo(left.value) < 0)) { // Left is greater than node nodeToMove = left; } // No node to move, stop recursion if (nodeToMove == null) return; // Re-factor heap sub-tree Node<T> nodeParent = heapNode.parent; if (nodeParent == null) { // heap down the root root = nodeToMove; root.parent = null; } else { if (nodeParent.left!=null && nodeParent.left.equals(node)) { // heap down a left nodeParent.left = nodeToMove; nodeToMove.parent = nodeParent; } else { // heap down a right nodeParent.right = nodeToMove; nodeToMove.parent = nodeParent; } } Node<T> nodeLeft = heapNode.left; Node<T> nodeRight = heapNode.right; Node<T> nodeToMoveLeft = nodeToMove.left; Node<T> nodeToMoveRight = nodeToMove.right; if (nodeLeft!=null && nodeLeft.equals(nodeToMove)) { nodeToMove.right = nodeRight; if (nodeRight != null) nodeRight.parent = nodeToMove; nodeToMove.left = heapNode; } else { nodeToMove.left = nodeLeft; if (nodeLeft != null) nodeLeft.parent = nodeToMove; nodeToMove.right = heapNode; } heapNode.parent = nodeToMove; heapNode.left = nodeToMoveLeft; if (nodeToMoveLeft != null) nodeToMoveLeft.parent = heapNode; heapNode.right = nodeToMoveRight; if (nodeToMoveRight != null) nodeToMoveRight.parent = heapNode; heapDown(node); } /** * {@inheritDoc} */ @Override public boolean validate() { if (root == null) return true; return validateNode(root); } /** * Validate node for heap invariants. * * @param node * to validate for. * @return True if node is valid. */ private boolean validateNode(Node<T> node) { Node<T> left = node.left; Node<T> right = node.right; // We shouldn't ever have a right node without a left in a heap if (right != null && left == null) return false; if (left != null) { if ((type == Type.MIN && node.value.compareTo(left.value) < 0) || (type == Type.MAX && node.value.compareTo(left.value) > 0)) { return validateNode(left); } return false; } if (right != null) { if ((type == Type.MIN && node.value.compareTo(right.value) < 0) || (type == Type.MAX && node.value.compareTo(right.value) > 0)) { return validateNode(right); } return false; } return true; } /** * Populate the node in the array at the index. * * @param node * to populate. * @param index * of node in array. * @param array * where the node lives. */ private void getNodeValue(Node<T> node, int index, T[] array) { array[index] = node.value; index = (index * 2) + 1; Node<T> left = node.left; if (left != null) getNodeValue(left, index, array); Node<T> right = node.right; if (right != null) getNodeValue(right, index + 1, array); } /** * {@inheritDoc} */ @Override public T[] getHeap() { T[] nodes = (T[]) new Comparable[size]; if (root != null) getNodeValue(root, 0, nodes); return nodes; } /** * {@inheritDoc} */ @Override public T getHeadValue() { T result = null; if (root != null) result = root.value; return result; } /** * {@inheritDoc} */ @Override public T removeHead() { T result = null; if (root != null) { result = root.value; removeRoot(); } return result; } /** * {@inheritDoc} */ @Override public java.util.Collection<T> toCollection() { return (new JavaCompatibleBinaryHeapTree<T>(this)); } /** * {@inheritDoc} */ @Override public String toString() { return HeapPrinter.getString(this); } protected static class HeapPrinter { public static <T extends Comparable<T>> void print(BinaryHeapTree<T> tree) { System.out.println(getString(tree.root, "", true)); } public static <T extends Comparable<T>> String getString(BinaryHeapTree<T> tree) { if (tree.root == null) return "Tree has no nodes."; return getString(tree.root, "", true); } private static <T extends Comparable<T>> String getString(Node<T> node, String prefix, boolean isTail) { StringBuilder builder = new StringBuilder(); builder.append(prefix + (isTail ? " " : " ") + node.value + "\n"); List<Node<T>> children = null; if (node.left != null || node.right != null) { children = new ArrayList<Node<T>>(2); if (node.left != null) children.add(node.left); if (node.right != null) children.add(node.right); } if (children != null) { for (int i = 0; i < children.size() - 1; i++) { builder.append(getString(children.get(i), prefix + (isTail ? " " : " "), false)); } if (children.size() >= 1) { builder.append(getString(children.get(children.size() - 1), prefix + (isTail ? " " : " "), true)); } } return builder.toString(); } } private static class Node<T extends Comparable<T>> { private T value = null; private Node<T> parent = null; private Node<T> left = null; private Node<T> right = null; private Node(Node<T> parent, T value) { this.value = value; this.parent = parent; } /** * {@inheritDoc} */ @Override public String toString() { return "value=" + value + " parent=" + ((parent != null) ? parent.value : "NULL") + " left=" + ((left != null) ? left.value : "NULL") + " right=" + ((right != null) ? right.value : "NULL"); } } } public static class JavaCompatibleBinaryHeapArray<T extends Comparable<T>> extends java.util.AbstractCollection<T> { private BinaryHeapArray<T> heap = null; public JavaCompatibleBinaryHeapArray() { heap = new BinaryHeapArray<T>(); } public JavaCompatibleBinaryHeapArray(BinaryHeapArray<T> heap) { this.heap = heap; } /** * {@inheritDoc} */ public boolean add(T value) { return heap.add(value); } /** * {@inheritDoc} */ public boolean remove(Object value) { return (heap.remove((T)value)!=null); } /** * {@inheritDoc} */ public boolean contains(Object value) { return heap.contains((T)value); } /** * {@inheritDoc} */ @Override public int size() { return heap.size(); } /** * {@inheritDoc} */ @Override public java.util.Iterator<T> iterator() { return (new BinaryHeapArrayIterator<T>(this.heap)); } private static class BinaryHeapArrayIterator<T extends Comparable<T>> implements java.util.Iterator<T> { private BinaryHeapArray<T> heap = null; private int last = -1; private int index = -1; protected BinaryHeapArrayIterator(BinaryHeapArray<T> heap) { this.heap = heap; } /** * {@inheritDoc} */ @Override public boolean hasNext() { if (index+1>=heap.size) return false; return (heap.array[index+1]!=null); } /** * {@inheritDoc} */ @Override public T next() { if (++index>=heap.size) return null; last = index; return heap.array[index]; } /** * {@inheritDoc} */ @Override public void remove() { heap.remove(last); } } } public static class JavaCompatibleBinaryHeapTree<T extends Comparable<T>> extends java.util.AbstractCollection<T> { private BinaryHeapTree<T> heap = null; public JavaCompatibleBinaryHeapTree() { heap = new BinaryHeapTree<T>(); } public JavaCompatibleBinaryHeapTree(BinaryHeapTree<T> heap) { this.heap = heap; } /** * {@inheritDoc} */ @Override public boolean add(T value) { return heap.add(value); } /** * {@inheritDoc} */ public boolean remove(Object value) { return (heap.remove((T)value)!=null); } /** * {@inheritDoc} */ public boolean contains(Object value) { return heap.contains((T)value); } /** * {@inheritDoc} */ @Override public int size() { return heap.size(); } /** * {@inheritDoc} */ @Override public java.util.Iterator<T> iterator() { return (new BinaryHeapTreeIterator<T>(this.heap)); } private static class BinaryHeapTreeIterator<C extends Comparable<C>> implements java.util.Iterator<C> { private BinaryHeapTree<C> heap = null; private BinaryHeapTree.Node<C> last = null; private Deque<BinaryHeapTree.Node<C>> toVisit = new ArrayDeque<BinaryHeapTree.Node<C>>(); protected BinaryHeapTreeIterator(BinaryHeapTree<C> heap) { this.heap = heap; if (heap.root!=null) toVisit.add(heap.root); } /** * {@inheritDoc} */ @Override public boolean hasNext() { if (toVisit.size()>0) return true; return false; } /** * {@inheritDoc} */ @Override public C next() { while (toVisit.size()>0) { // Go thru the current nodes BinaryHeapTree.Node<C> n = toVisit.pop(); // Add non-null children if (n.left!=null) toVisit.add(n.left); if (n.right!=null) toVisit.add(n.right); // Update last node (used in remove method) last = n; return n.value; } return null; } /** * {@inheritDoc} */ @Override public void remove() { heap.replaceNode(last); } } } }
package com.servegame.abendstern.tunnelblick.game; public class Projectile extends ModelledObject { public static final float RADIUS = 0.015f; private static final float R = RADIUS; private static final float[] MODEL = { 1, 1, 1, 0, 0, 0,+R, 0, 0,+R, 0, 0, 0, 0, 0,+R, 0, 0,+R, 0, 0,+R, 0, 0, 0, 0, 0,-R, 0, 0,+R, 0, 0,-R, 0, 0, 0, 0, 0,+R, 0, 0,+R, 0, 0,-R, 0, 0, 0, 0, 0,-R, 0, 0,-R, 0, 0,+R, 0, 0, 0, 0, 0,+R, 0, 0,-R, 0, 0,+R, 0, 0, 0, 0, 0,-R, 0, 0,-R, 0, 0,-R, 0, 0, 0, 0, 0,+R, 0, 0,-R, 0, 0,-R, 0, 0, 0, 0, 0,-R, }; private static final float SPEED = 10; private static final float LIFETIME = 5; private GameObject owner; private float vz, lifetime; public Projectile(GameField field, GameObject owner, float x, float y, float z, float ownerSpeed, float direction, Distortion distortion) { super(field, x, y, z, MODEL, distortion); this.owner = owner; vz = direction * SPEED + ownerSpeed; lifetime = 0; } public void update(float et) { moveTo(x, y, z + vz*et, true); lifetime += et; if (-z > Tunnel.GRID_LENGTH*Tunnel.GSQ_LEN/2 || lifetime > LIFETIME) alive = false; } public void collideWith(GameObject other) { if (!alive) return; //Don't affect more than one object if (other == owner) return; //Don't hit the object that launched us other.collideWithProjectile(this); alive = false; } }
package com.vectrace.MercurialEclipse.commands; import com.vectrace.MercurialEclipse.exception.HgException; import com.vectrace.MercurialEclipse.model.HgRoot; import com.vectrace.MercurialEclipse.preferences.MercurialPreferenceConstants; import com.vectrace.MercurialEclipse.team.cache.MercurialStatusCache; public class HgMergeClient extends AbstractClient { public static String merge(HgRoot hgRoot, String revision, boolean forced) throws HgException { HgCommand command = new HgCommand("merge", hgRoot, false); command.setExecutionRule(new AbstractShellCommand.ExclusiveExecutionRule(hgRoot)); command.setUsePreferenceTimeout(MercurialPreferenceConstants.IMERGE_TIMEOUT); addMergeToolPreference(command); if (revision != null) { command.addOptions("-r", revision); //$NON-NLS-1$ } if (forced) { command.addOptions("-f"); //$NON-NLS-1$ } MercurialStatusCache.getInstance().setMergeViewDialogShown(false); try { String result = command.executeToString(); return result; } catch (HgException e) { // if conflicts aren't resolved and no merge tool is started, hg // exits with 1 if (e.getStatus().getCode() != 1) { throw e; } return e.getMessage(); } } }
package me.nallar.tickthreading.minecraft; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.concurrent.locks.Lock; import me.nallar.tickthreading.Log; import me.nallar.tickthreading.collections.ConcurrentIterableArrayList; import me.nallar.tickthreading.minecraft.commands.TPSCommand; import me.nallar.tickthreading.minecraft.profiling.EntityTickProfiler; import me.nallar.tickthreading.minecraft.tickregion.EntityTickRegion; import me.nallar.tickthreading.minecraft.tickregion.TickRegion; import me.nallar.tickthreading.minecraft.tickregion.TileEntityTickRegion; import me.nallar.tickthreading.util.TableFormatter; import me.nallar.unsafe.UnsafeUtil; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.server.MinecraftServer; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.WorldServer; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.gen.ChunkProviderServer; import org.omg.CORBA.IntHolder; public final class TickManager { private static final byte lockXPlus = 1 << 1; private static final byte lockXMinus = 1 << 2; private static final byte lockZPlus = 1 << 3; private static final byte lockZMinus = 1 << 4; public final int regionSize; public boolean variableTickRate; public boolean profilingEnabled = false; private double averageTickLength = 0; private long lastTickLength = 0; private long lastStartTime = 0; private static final int shuffleInterval = 800; private int shuffleCount; private final boolean waitForCompletion; public final EntityTickProfiler entityTickProfiler = new EntityTickProfiler(); private final WorldServer world; public final ArrayList<TileEntity> tileEntityList = new ArrayList<TileEntity>(); public final ArrayList<Entity> entityList = new ArrayList<Entity>(); public Object tileEntityLock = new Object(); public Object entityLock = new Object(); private final Map<Integer, TileEntityTickRegion> tileEntityCallables = new HashMap<Integer, TileEntityTickRegion>(); private final Map<Integer, EntityTickRegion> entityCallables = new HashMap<Integer, EntityTickRegion>(); private final ConcurrentIterableArrayList<TickRegion> tickRegions = new ConcurrentIterableArrayList<TickRegion>(); private final ThreadManager threadManager; private final Map<Class<?>, Integer> entityClassToCountMap = new HashMap<Class<?>, Integer>(); public TickManager(WorldServer world, int regionSize, int threads, boolean waitForCompletion) { this.waitForCompletion = waitForCompletion; threadManager = new ThreadManager(threads, "Entities in " + Log.name(world)); this.world = world; this.regionSize = regionSize; shuffleCount = world.rand.nextInt(shuffleInterval); } public void setVariableTickRate(boolean variableTickRate) { this.variableTickRate = variableTickRate; } public TickRegion getTileEntityRegion(int hashCode) { return tileEntityCallables.get(hashCode); } @SuppressWarnings ("NumericCastThatLosesPrecision") private TileEntityTickRegion getOrCreateRegion(TileEntity tileEntity) { int hashCode = getHashCode(tileEntity); TileEntityTickRegion callable = tileEntityCallables.get(hashCode); if (callable == null) { synchronized (tickRegions) { callable = tileEntityCallables.get(hashCode); if (callable == null) { callable = new TileEntityTickRegion(world, this, tileEntity.xCoord / regionSize, tileEntity.zCoord / regionSize); tileEntityCallables.put(hashCode, callable); tickRegions.add(callable); } } } return callable; } public TickRegion getEntityRegion(int hashCode) { return entityCallables.get(hashCode); } @SuppressWarnings ("NumericCastThatLosesPrecision") private EntityTickRegion getOrCreateRegion(Entity entity) { int regionX = (int) entity.posX / regionSize; int regionZ = (int) entity.posZ / regionSize; int hashCode = getHashCodeFromRegionCoords(regionX, regionZ); EntityTickRegion callable = entityCallables.get(hashCode); if (callable == null) { synchronized (tickRegions) { callable = entityCallables.get(hashCode); if (callable == null) { callable = new EntityTickRegion(world, this, regionX, regionZ); entityCallables.put(hashCode, callable); tickRegions.add(callable); } } } return callable; } int getHashCode(TileEntity tileEntity) { return getHashCode(tileEntity.xCoord, tileEntity.zCoord); } @SuppressWarnings ("NumericCastThatLosesPrecision") public int getHashCode(Entity entity) { return getHashCode((int) entity.posX, (int) entity.posZ); } public int getHashCode(int x, int z) { return getHashCodeFromRegionCoords(x / regionSize, z / regionSize); } public static int getHashCodeFromRegionCoords(int x, int z) { return x + (z << 16); } private void processChanges() { try { synchronized (tickRegions) { Iterator<TickRegion> iterator = tickRegions.iterator(); while (iterator.hasNext()) { TickRegion tickRegion = iterator.next(); tickRegion.processChanges(); if (tickRegion.isEmpty()) { iterator.remove(); if (tickRegion instanceof EntityTickRegion) { entityCallables.remove(tickRegion.hashCode); } else { tileEntityCallables.remove(tickRegion.hashCode); } tickRegion.die(); } } if (shuffleCount++ % shuffleInterval == 0) { Collections.shuffle(tickRegions); } } } catch (Exception e) { Log.severe("Exception occurred while processing entity changes: ", e); } } public boolean add(TileEntity tileEntity) { return add(tileEntity, true); } public boolean add(TileEntity tileEntity, boolean newEntity) { TileEntityTickRegion tileEntityTickRegion = getOrCreateRegion(tileEntity); if (tileEntityTickRegion.add(tileEntity)) { tileEntity.tickRegion = tileEntityTickRegion; if (newEntity) { synchronized (tileEntityLock) { tileEntityList.add(tileEntity); } } return true; } return false; } public boolean add(Entity entity) { return add(entity, true); } public boolean add(Entity entity, boolean newEntity) { EntityTickRegion entityTickRegion = getOrCreateRegion(entity); if (entityTickRegion.add(entity)) { entity.tickRegion = entityTickRegion; if (newEntity) { synchronized (entityLock) { entityList.add(entity); } synchronized (entityClassToCountMap) { Class entityClass = entity.getClass(); Integer count = entityClassToCountMap.get(entityClass); if (count == null) { count = 0; } entityClassToCountMap.put(entityClass, count + 1); } } return true; } return false; } public void batchRemoveEntities(Collection<Entity> entities) { ChunkProviderServer chunkProviderServer = (ChunkProviderServer) world.getChunkProvider(); synchronized (entityLock) { entityList.removeAll(entities); } for (Entity entity : entities) { int x = entity.chunkCoordX; int z = entity.chunkCoordZ; if (entity.addedToChunk) { Chunk chunk = chunkProviderServer.getChunkIfExists(x, z); if (chunk != null) { chunk.removeEntity(entity); } } world.releaseEntitySkin(entity); if (entity.tickRegion != null) { entity.tickRegion.remove(entity); entity.tickRegion = null; Class entityClass = entity.getClass(); synchronized (entityClassToCountMap) { Integer count = entityClassToCountMap.get(entityClass); if (count == null) { throw new IllegalStateException("Removed an entity which should not have been in the entityList"); } entityClassToCountMap.put(entityClass, count - 1); } } } } public void batchRemoveTileEntities(Collection<TileEntity> tileEntities) { for (TileEntity tileEntity : tileEntities) { if (tileEntity.tickRegion != null) { tileEntity.tickRegion.remove(tileEntity); tileEntity.tickRegion = null; tileEntity.onChunkUnload(); } unlock(tileEntity); } synchronized (tileEntityLock) { tileEntityList.removeAll(tileEntities); } } public void remove(TileEntity tileEntity) { TileEntityTickRegion tileEntityTickRegion = tileEntity.tickRegion; if (tileEntityTickRegion == null) { tileEntityTickRegion = getOrCreateRegion(tileEntity); } tileEntityTickRegion.remove(tileEntity); removed(tileEntity); } public void remove(Entity entity) { EntityTickRegion entityTickRegion = entity.tickRegion; if (entityTickRegion == null) { entityTickRegion = getOrCreateRegion(entity); } entityTickRegion.remove(entity); removed(entity); } public void removed(TileEntity tileEntity) { tileEntity.tickRegion = null; synchronized (tileEntityLock) { tileEntityList.remove(tileEntity); } unlock(tileEntity); } public void removed(Entity entity) { boolean removed; entity.tickRegion = null; synchronized (entityLock) { removed = entityList.remove(entity); } if (removed) { Class entityClass = entity.getClass(); synchronized (entityClassToCountMap) { Integer count = entityClassToCountMap.get(entityClass); if (count == null) { throw new IllegalStateException("Removed an entity which should not have been in the entityList"); } entityClassToCountMap.put(entityClass, count - 1); } } } /* Oh, Java. Explicit MONITORENTER/EXIT should really be part of the language, there are just some cases like this where synchronized blocks get too messy, and performance is bad if using other locks. .lock/unlock calls here are replaced with MONITORENTER/EXIT. */ void unlock(TileEntity tE) { Lock lock = tE.lockManagementLock; lock.lock(); byte locks = tE.usedLocks; boolean xM = ((locks & lockXMinus) != 0) || tE.xMinusLock != null; boolean xP = ((locks & lockXPlus) != 0) || tE.xPlusLock != null; boolean zM = ((locks & lockZMinus) != 0) || tE.zMinusLock != null; boolean zP = ((locks & lockZPlus) != 0) || tE.zPlusLock != null; tE.xPlusLock = null; tE.xMinusLock = null; tE.zPlusLock = null; tE.zMinusLock = null; tE.usedLocks = 0; if (tE.thisLock == null) { lock.unlock(); return; } int xPos = tE.lastTTX; int yPos = tE.lastTTY; int zPos = tE.lastTTZ; TileEntity xMTE = xM ? world.getTEWithoutLoad(xPos - 1, yPos, zPos) : null; TileEntity xPTE = xP ? world.getTEWithoutLoad(xPos + 1, yPos, zPos) : null; TileEntity zMTE = zM ? world.getTEWithoutLoad(xPos, yPos, zPos - 1) : null; TileEntity zPTE = zP ? world.getTEWithoutLoad(xPos, yPos, zPos + 1) : null; if (xMTE == null) { xM = false; } if (xPTE == null) { xP = false; } if (zMTE == null) { zM = false; } if (zPTE == null) { zP = false; } lock.unlock(); if (!(xM || xP || zM || zP)) { return; } if (xP) { xPTE.lockManagementLock.lock(); } if (zP) { zPTE.lockManagementLock.lock(); } lock.lock(); if (zM) { zMTE.lockManagementLock.lock(); } if (xM) { xMTE.lockManagementLock.lock(); } if (xM) { xMTE.usedLocks &= ~lockXPlus; xMTE.xPlusLock = null; } if (xP) { xPTE.usedLocks &= ~lockXMinus; xPTE.xMinusLock = null; } if (zM) { zMTE.usedLocks &= ~lockZPlus; zMTE.zPlusLock = null; } if (zP) { zPTE.usedLocks &= ~lockZMinus; zPTE.zMinusLock = null; } if (xM) { xMTE.lockManagementLock.unlock(); } if (zM) { zMTE.lockManagementLock.unlock(); } lock.unlock(); if (zP) { zPTE.lockManagementLock.unlock(); } if (xP) { xPTE.lockManagementLock.unlock(); } } /* .lock/unlock calls here are replaced with MONITORENTER/EXIT. */ public final void lock(TileEntity tE) { unlock(tE); Lock lock = tE.lockManagementLock; lock.lock(); int maxPosition = (regionSize / 2) - 1; int xPos = tE.xCoord; int yPos = tE.yCoord; int zPos = tE.zCoord; tE.lastTTX = xPos; tE.lastTTY = yPos; tE.lastTTZ = zPos; int relativeXPos = (xPos % regionSize) / 2; int relativeZPos = (zPos % regionSize) / 2; boolean onMinusX = relativeXPos == 0; boolean onMinusZ = relativeZPos == 0; boolean onPlusX = relativeXPos == maxPosition; boolean onPlusZ = relativeZPos == maxPosition; boolean xM = onMinusX || onMinusZ || onPlusZ; boolean xP = onPlusX || onMinusZ || onPlusZ; boolean zM = onMinusZ || onMinusX || onPlusX; boolean zP = onPlusZ || onMinusX || onPlusX; TileEntity xMTE = xM ? world.getTEWithoutLoad(xPos - 1, yPos, zPos) : null; TileEntity xPTE = xP ? world.getTEWithoutLoad(xPos + 1, yPos, zPos) : null; TileEntity zMTE = zM ? world.getTEWithoutLoad(xPos, yPos, zPos - 1) : null; TileEntity zPTE = zP ? world.getTEWithoutLoad(xPos, yPos, zPos + 1) : null; if (xMTE == null) { xM = false; } if (xPTE == null) { xP = false; } if (zMTE == null) { zM = false; } if (zPTE == null) { zP = false; } lock.unlock(); if (!(xM || xP || zM || zP)) { return; } Lock thisLock = tE.thisLock; if (xP) { xPTE.lockManagementLock.lock(); } if (zP) { zPTE.lockManagementLock.lock(); } lock.lock(); if (zM) { zMTE.lockManagementLock.lock(); } if (xM) { xMTE.lockManagementLock.lock(); } byte usedLocks = tE.usedLocks; if (xM) { Lock otherLock = xMTE.thisLock; if (otherLock != null) { xMTE.usedLocks |= lockXPlus; tE.xMinusLock = otherLock; } if (thisLock != null) { usedLocks |= lockXMinus; xMTE.xPlusLock = thisLock; } } if (xP) { Lock otherLock = xPTE.thisLock; if (otherLock != null) { xPTE.usedLocks |= lockXMinus; tE.xPlusLock = otherLock; } if (thisLock != null) { usedLocks |= lockXPlus; xPTE.xMinusLock = thisLock; } } if (zM) { Lock otherLock = zMTE.thisLock; if (otherLock != null) { zMTE.usedLocks |= lockZPlus; tE.zMinusLock = otherLock; } if (thisLock != null) { usedLocks |= lockZMinus; zMTE.zPlusLock = thisLock; } } if (zP) { Lock otherLock = zPTE.thisLock; if (otherLock != null) { zPTE.usedLocks |= lockZMinus; tE.zPlusLock = otherLock; } if (thisLock != null) { usedLocks |= lockZPlus; zPTE.zMinusLock = thisLock; } } tE.usedLocks = usedLocks; if (xM) { xMTE.lockManagementLock.unlock(); } if (zM) { zMTE.lockManagementLock.unlock(); } lock.unlock(); if (zP) { zPTE.lockManagementLock.unlock(); } if (xP) { xPTE.lockManagementLock.unlock(); } } public void doTick() { boolean previousProfiling = world.theProfiler.profilingEnabled; lastStartTime = System.nanoTime(); threadManager.waitForCompletion(); if (previousProfiling) { world.theProfiler.profilingEnabled = false; } threadManager.runList(tickRegions); if (previousProfiling || waitForCompletion) { lastTickLength = (threadManager.waitForCompletion() - lastStartTime); averageTickLength = ((averageTickLength * 127) + lastTickLength) / 128; threadManager.run(new Runnable() { @Override public void run() { processChanges(); } }); } if (previousProfiling) { world.theProfiler.profilingEnabled = true; } if (profilingEnabled) { entityTickProfiler.tick(); } } public void tickEnd() { if (!waitForCompletion) { lastTickLength = (threadManager.waitForCompletion() - lastStartTime); averageTickLength = ((averageTickLength * 127) + lastTickLength) / 128; threadManager.run(new Runnable() { @Override public void run() { processChanges(); } }); } } public void unload() { threadManager.stop(); synchronized (tickRegions) { for (TickRegion tickRegion : tickRegions) { tickRegion.die(); } } tickRegions.clear(); entityList.clear(); entityClassToCountMap.clear(); UnsafeUtil.clean(this); } public void fixDiscrepancies(TableFormatter tableFormatter) { final IntHolder intHolder = new IntHolder(); { Set<Entity> contained = new HashSet<Entity>(); Set<Entity> toRemove = new HashSet<Entity>(); synchronized (entityList) { for (Entity e : entityList) { if (add(e, false)) { intHolder.value++; } if (!contained.add(e)) { toRemove.add(e); intHolder.value++; } } entityList.removeAll(toRemove); } } { Set<TileEntity> contained = new HashSet<TileEntity>(); Set<TileEntity> toRemove = new HashSet<TileEntity>(); synchronized (tileEntityList) { for (TileEntity te : tileEntityList) { if (add(te, false)) { intHolder.value++; } if (!contained.add(te)) { toRemove.add(te); intHolder.value++; } } tileEntityList.removeAll(toRemove); } } if (intHolder.value != 0) { tableFormatter.sb.append("Fixed ").append(intHolder.value).append(" discrepancies in tile/entity lists."); } } public void writeStats(TableFormatter tf, final TPSCommand.StatsHolder statsHolder) { long timeTotal = 0; double time = Double.NaN; try { long[] tickTimes = MinecraftServer.getServer().getTickTimes(world); for (long tick : tickTimes) { timeTotal += tick; } time = (timeTotal) / (double) tickTimes.length; if (time == 0) { time = 0.1; } } catch (NullPointerException ignored) { } int entities = entityList.size(); statsHolder.entities += entities; int tileEntities = tileEntityList.size(); statsHolder.tileEntities += tileEntities; int chunks = world.theChunkProviderServer.getLoadedChunkCount(); statsHolder.chunks += chunks; tf .row(Log.name(world)) .row(entities) .row(tileEntities) .row(chunks) .row(world.playerEntities.size()) .row(TableFormatter.formatDoubleWithPrecision((time * 100f) / MinecraftServer.getTargetTickTime(), 2) + '%'); } public TableFormatter writeDetailedStats(TableFormatter tf) { @SuppressWarnings ("MismatchedQueryAndUpdateOfStringBuilder") StringBuilder stats = tf.sb; stats.append("World: ").append(Log.name(world)).append('\n'); stats.append(" // TODO: Rewrite this float averageAverageTickTime = 0; float maxTickTime = 0; SortedMap<Float, TickRegion> sortedTickCallables = new TreeMap<Float, TickRegion>(); synchronized (tickRegions) { for (TickRegion tickRegion : tickRegions) { float averageTickTime = tickRegion.getAverageTickTime(); averageAverageTickTime += averageTickTime; sortedTickCallables.put(averageTickTime, tickRegion); if (averageTickTime > maxTickTime) { maxTickTime = averageTickTime; } } Collection<TickRegion> var = sortedTickCallables.values(); TickRegion[] sortedTickCallablesArray = var.toArray(new TickRegion[var.size()]); tf .heading("") .heading("X") .heading("Z") .heading("N") .heading("Time"); for (int i = sortedTickCallablesArray.length - 1; i >= sortedTickCallablesArray.length - 7; i if (i >= 0 && sortedTickCallablesArray[i].getAverageTickTime() > 0.2) { sortedTickCallablesArray[i].writeStats(tf); } } tf.finishTable(); stats.append('\n'); averageAverageTickTime /= tickRegions.size(); stats.append(" stats.append('\n').append(world.getChunkProvider().makeString()); stats.append("\nAverage tick time: ").append(averageAverageTickTime).append("ms"); stats.append("\nMax tick time: ").append(maxTickTime).append("ms"); stats.append("\nEffective tick time: ").append(lastTickLength / 1000000f).append("ms"); stats.append("\nAverage effective tick time: ").append((float) averageTickLength / 1000000).append("ms"); } return tf; } public TableFormatter writeEntityStats(TableFormatter tf) { tf .heading("Main") .heading("Map") .heading("Region") .heading("Player"); tf .row(entityList.size()) .row(getTotalEntityCountFromMap()) .row(getTotalEntityCountFromRegions()) .row(getEntityCount(EntityPlayer.class)); tf.finishTable(); return tf; } private int getTotalEntityCountFromRegions() { int count = 0; for (EntityTickRegion entityTickRegion : entityCallables.values()) { count += entityTickRegion.size(); } return count; } private int getTotalEntityCountFromMap() { int count = 0; for (Map.Entry<Class<?>, Integer> entry : entityClassToCountMap.entrySet()) { count += entry.getValue(); } return count; } public int getEntityCount(Class<?> clazz) { int count = 0; for (Map.Entry<Class<?>, Integer> entry : entityClassToCountMap.entrySet()) { if (clazz.isAssignableFrom(entry.getKey())) { count += entry.getValue(); } } return count; } }
/** * We are given n guests to be allocated to m equally sized tables (where n % m = 0) at a banquest. * There are constraint of the form together(i,j) and apart(i,j) where * together(i,j) means that guests i and j must sit at the same table and * apart(i,j) means that guests i and j must sit at different tables. * By default, guests can sit at any table with any other guest */ import java.io.File; import java.io.IOException; import java.util.Scanner; import java.util.stream.IntStream; import org.chocosolver.solver.*; import org.chocosolver.solver.variables.*; import org.chocosolver.solver.search.strategy.*; import org.chocosolver.solver.constraints.*; public class BanquetPlanner { Solver solver; int nGuests; int mTables; int tableSize; IntVar[] tables; // An array of table allocation for each guest IntVar[] count; // An array of the counts of guests at each table // TODO: Outline algorithm here BanquetPlanner(String fname) throws IOException { try (Scanner sc = new Scanner(new File(fname))) { nGuests = sc.nextInt(); // number of guests mTables = sc.nextInt(); // number of tables tableSize = nGuests / mTables; solver = new Solver("banquet planner"); // Create an bounded array of length nGuests, each location a guest tables = VariableFactory.enumeratedArray("tables", nGuests, 0, nGuests, solver); // The count of how many guests are at each table count = VariableFactory.integerArray("count", mTables, 0, tableSize, solver); while (sc.hasNext()) { String s = sc.next(); int i = sc.nextInt(); int j = sc.nextInt(); // guarantee that two "together" guests have the same table number, and not equal for "apart" if (s.equals("together")) { solver.post(IntConstraintFactory.arithm(tables[i], "=", tables[j])); } else { // s.equals("apart") solver.post(IntConstraintFactory.arithm(tables[i], "!=", tables[j])); } } } int[] values = IntStream.rangeClosed(0,mTables-1).toArray(); IntVar[] OCC = VF.enumeratedArray("occurences", mTables, tableSize, tableSize, solver); solver.post(ICF.global_cardinality(tables, values, OCC, false)); // set a custom variable ordering solver.set(ISF.lexico_LB(tables)); //solver.set(ISF.custom(ISF.minDomainSize_var_selector(), ISF.min_value_selector(), tables)); } boolean solve() { return solver.findSolution(); } void result() { // print out solution in specified format (see readme.txt) // so that results can be verified StringBuffer[] outputLines = new StringBuffer[mTables]; for (int tableNumber = 0; tableNumber < mTables; tableNumber++) { outputLines[tableNumber] = new StringBuffer(Integer.toString(tableNumber) + " "); } for (int guestIndex = 0; guestIndex < nGuests; guestIndex++) { int guestTable = tables[guestIndex].getValue(); outputLines[guestTable].append(Integer.toString(guestIndex) + " "); } for (StringBuffer line : outputLines) { System.out.println(line.toString()); } } void stats() { System.out.println("nodes: " + solver.getMeasures().getNodeCount() + " cpu: " + solver.getMeasures().getTimeCount()); } public static void main(String[] args) throws IOException { BanquetPlanner bp = new BanquetPlanner(args[0]); if (bp.solve()) { bp.result(); } else { System.out.println(false); } bp.stats(); } }
package com.opensymphony.workflow.designer; import java.util.Iterator; import java.util.List; import com.opensymphony.workflow.designer.proxy.StepProxy; import com.opensymphony.workflow.loader.ActionDescriptor; import com.opensymphony.workflow.loader.ConditionalResultDescriptor; import com.opensymphony.workflow.loader.ResultDescriptor; import com.opensymphony.workflow.loader.StepDescriptor; import org.jgraph.graph.GraphConstants; public class StepCell extends WorkflowCell implements ResultAware { private StepDescriptor descriptor; // Construct Cell for Userobject public StepCell(StepDescriptor userObject) { super(new StepProxy(userObject)); GraphConstants.setEditable(attributes, true); descriptor = userObject; id = descriptor.getId(); name = descriptor.getName(); } public String toString() { return descriptor.getName();// + " " + descriptor.getId(); } public String getName() { return descriptor.getName(); } public StepDescriptor getDescriptor() { return descriptor; } public boolean removeResult(ResultDescriptor result) { Iterator iter = descriptor.getActions().iterator(); boolean removed = false; while(iter.hasNext()) { ActionDescriptor action = (ActionDescriptor)iter.next(); if(result instanceof ConditionalResultDescriptor) { List list = action.getConditionalResults(); if(list != null) { for(int i = 0; i < list.size(); i++) { if(list.get(i) == result) { list.remove(i); if(action.getUnconditionalResult()==null) { iter.remove(); } removed = true; } } } } else { if(action.getUnconditionalResult() == result) { action.setUnconditionalResult(null); if(action.getConditionalResults().size()==0) { iter.remove(); } removed = true; } } } if(descriptor.getActions().size() == 0 && descriptor.getCommonActions().size() == 0) { descriptor.removeActions(); } return removed; } }
package com.simsilica.lemur; import com.jme3.material.RenderState.BlendMode; import com.jme3.math.ColorRGBA; import com.jme3.math.Vector3f; import com.jme3.scene.Node; import com.jme3.scene.Spatial; import com.simsilica.lemur.component.AbstractGuiComponent; import com.simsilica.lemur.component.BorderLayout; import com.simsilica.lemur.component.QuadBackgroundComponent; import com.simsilica.lemur.core.GuiControl; import com.simsilica.lemur.core.VersionedList; import com.simsilica.lemur.core.VersionedReference; import com.simsilica.lemur.event.CursorButtonEvent; import com.simsilica.lemur.event.CursorEventControl; import com.simsilica.lemur.event.DefaultCursorListener; import com.simsilica.lemur.grid.GridModel; import com.simsilica.lemur.list.CellRenderer; import com.simsilica.lemur.list.DefaultCellRenderer; import com.simsilica.lemur.list.SelectionModel; import com.simsilica.lemur.style.Attributes; import com.simsilica.lemur.style.ElementId; import com.simsilica.lemur.style.StyleDefaults; import com.simsilica.lemur.style.Styles; import java.util.Set; /** * * @author Paul Speed */ public class ListBox<T> extends Panel { public static final String ELEMENT_ID = "list"; public static final String CONTAINER_ID = "container"; public static final String ITEMS_ID = "items"; public static final String SLIDER_ID = "slider"; public static final String SELECTOR_ID = "selector"; private BorderLayout layout; private VersionedList<T> model; private CellRenderer<T> cellRenderer; private SelectionModel selection; private VersionedReference<Set<Integer>> selectionRef; private ClickListener clickListener = new ClickListener(); private GridPanel grid; private Slider slider; private Node selectorArea; private Panel selector; private Vector3f selectorAreaOrigin = new Vector3f(); private Vector3f selectorAreaSize = new Vector3f(); private RangedValueModel baseIndex; // upside down actually private VersionedReference<Double> indexRef; private int maxIndex; public ListBox() { this(true, new VersionedList<T>(), null, new SelectionModel(), new ElementId(ELEMENT_ID), null); } public ListBox( VersionedList<T> model ) { this(true, model, null, new SelectionModel(), new ElementId(ELEMENT_ID), null); } public ListBox( VersionedList<T> model, CellRenderer<T> renderer, String style ) { this(true, model, renderer, new SelectionModel(), new ElementId(ELEMENT_ID), style); } public ListBox( VersionedList<T> model, String style ) { this(true, model, null, new SelectionModel(), new ElementId(ELEMENT_ID), style); } public ListBox( VersionedList<T> model, ElementId elementId, String style ) { this(true, model, null, new SelectionModel(), elementId, null); } public ListBox( VersionedList<T> model, CellRenderer<T> renderer, ElementId elementId, String style ) { this(true, model, renderer, new SelectionModel(), elementId, null); } protected ListBox( boolean applyStyles, VersionedList<T> model, CellRenderer<T> cellRenderer, SelectionModel selection, ElementId elementId, String style ) { super(false, elementId.child(CONTAINER_ID), style); if( cellRenderer == null ) { // Create a default one cellRenderer = new DefaultCellRenderer(elementId.child("item"), style); } this.cellRenderer = cellRenderer; this.layout = new BorderLayout(); getControl(GuiControl.class).setLayout(layout); grid = new GridPanel(new GridModelDelegate(), elementId.child(ITEMS_ID), style); //CursorEventControl.addListenersToSpatial(grid, new GridListener()); grid.setVisibleColumns(1); layout.addChild(grid, BorderLayout.Position.Center); // Add a special component to the grid so that we get resize // events. Kind of a hack but I'm not sure I want to create // a whole event framework just for this. int sizerIndex = grid.getControl(GuiControl.class).getComponentIndex(KEY_INSETS) + 1; grid.getControl(GuiControl.class).addComponent( sizerIndex, "sizer", new AbstractGuiComponent() { @Override public void calculatePreferredSize(Vector3f size) { } @Override public void reshape(Vector3f pos, Vector3f size) { gridResized(pos, size); } }); baseIndex = new DefaultRangedValueModel(); indexRef = baseIndex.createReference(); slider = new Slider(baseIndex, Axis.Y, elementId.child(SLIDER_ID), style); layout.addChild(slider, BorderLayout.Position.East); if( applyStyles ) { Styles styles = GuiGlobals.getInstance().getStyles(); styles.applyStyles(this, elementId.getId(), style); } // Need a spacer so that the 'selector' panel doesn't think // it's being managed by this panel. // Have to set this up after applying styles so that the default // styles are properly initialized the first time. selectorArea = new Node("selectorArea"); attachChild(selectorArea); selector = new Panel(elementId.child(SELECTOR_ID), style); setModel(model); resetModelRange(); setSelectionModel(selection); } @StyleDefaults(ELEMENT_ID) public static void initializeDefaultStyles( Styles styles, Attributes attrs ) { ElementId parent = new ElementId(ELEMENT_ID); //QuadBackgroundComponent quad = new QuadBackgroundComponent(new ColorRGBA(0.5f, 0.5f, 0.5f, 1)); QuadBackgroundComponent quad = new QuadBackgroundComponent(new ColorRGBA(0.8f, 0.9f, 0.1f, 1)); quad.getMaterial().getMaterial().getAdditionalRenderState().setBlendMode(BlendMode.Exclusion); styles.getSelector(parent.child(SELECTOR_ID), null).set("background", quad, false); } @Override public void updateLogicalState( float tpf ) { super.updateLogicalState(tpf); if( indexRef.update() ) { int index = (int)(maxIndex - baseIndex.getValue()); grid.setRow(index); refreshSelector(); } if( selectionRef.update() ) { refreshSelector(); } } protected void gridResized( Vector3f pos, Vector3f size ) { if( pos.equals(selectorAreaOrigin) && size.equals(selectorAreaSize) ) { return; } selectorAreaOrigin.set(pos); selectorAreaSize.set(size); refreshSelector(); } public void setModel( VersionedList<T> model ) { if( this.model == model ) { return; } if( this.model != null ) { // Clean up the old one detachItemListeners(); } if( model == null ) { // Easier to create a default one than to handle a null model // everywhere model = new VersionedList<T>(); } this.model = model; grid.setLocation(0,0); grid.setModel(new GridModelDelegate()); // need a new one for a new version resetModelRange(); baseIndex.setValue(maxIndex); refreshSelector(); } public VersionedList<T> getModel() { return model; } public Slider getSlider() { return slider; } public GridPanel getGridPanel() { return grid; } public void setSelectionModel( SelectionModel selection ) { if( this.selection == selection ) { return; } this.selection = selection; this.selectionRef = selection.createReference(); refreshSelector(); } public SelectionModel getSelectionModel() { return selection; } public void setVisibleItems( int count ) { grid.setVisibleRows(count); resetModelRange(); refreshSelector(); } public int getVisibleItems() { return grid.getVisibleRows(); } protected void refreshSelector() { Panel selectedCell = null; if( selection != null && !selection.isEmpty() ) { // For now just one item... otherwise we have to loop // over visible items int selected = selection.iterator().next(); selectedCell = grid.getCell(selected, 0); } if( selectedCell == null ) { selectorArea.detachChild(selector); } else { Vector3f size = selectedCell.getSize().clone(); Vector3f loc = selectedCell.getLocalTranslation(); Vector3f pos = selectorAreaOrigin.add(loc.x, loc.y, loc.z + size.z); selector.setLocalTranslation(pos); selector.setSize(size); selectorArea.attachChild(selector); selectorArea.setLocalTranslation(grid.getLocalTranslation()); } } protected void resetModelRange() { int count = model.size(); int visible = grid.getVisibleRows(); maxIndex = Math.max(0, count - visible); baseIndex.setMinimum(0); baseIndex.setMaximum(maxIndex); } protected Panel getListCell( int row, int col, Panel existing ) { T value = model.get(row); Panel cell = cellRenderer.getView(value, false, existing); if( cell != existing ) { // Transfer the click listener CursorEventControl.addListenersToSpatial(cell, clickListener); CursorEventControl.removeListenersFromSpatial(existing, clickListener); } return cell; } /** * Used when the list model is swapped out. */ protected void detachItemListeners() { int base = grid.getRow(); for( int i = 0; i < grid.getVisibleRows(); i++ ) { Panel cell = grid.getCell(base + i, 0); if( cell != null ) { CursorEventControl.removeListenersFromSpatial(cell, clickListener); } } } @Override public String toString() { return getClass().getName() + "[elementId=" + getElementId() + "]"; } private class ClickListener extends DefaultCursorListener { @Override public void cursorButtonEvent( CursorButtonEvent event, Spatial target, Spatial capture ) { // Find the element we clicked on int base = grid.getRow(); for( int i = 0; i < grid.getVisibleRows(); i++ ) { Panel cell = grid.getCell( base + i, 0 ); if( cell == target ) { selection.add(base + i); } } } } protected class GridModelDelegate implements GridModel<Panel> { @Override public int getRowCount() { if( model == null ) { return 0; } return model.size(); } @Override public int getColumnCount() { return 1; } @Override public Panel getCell( int row, int col, Panel existing ) { return getListCell(row, col, existing); } @Override public void setCell( int row, int col, Panel value ) { throw new UnsupportedOperationException("ListModel is read only."); } @Override public long getVersion() { return model == null ? 0 : model.getVersion(); } @Override public GridModel<Panel> getObject() { return this; } @Override public VersionedReference<GridModel<Panel>> createReference() { return new VersionedReference<GridModel<Panel>>(this); } } }
package org.fakekoji.api.http.rest; import io.javalin.Javalin; import io.javalin.http.Context; import io.javalin.http.Handler; import org.fakekoji.core.AccessibleSettings; import org.fakekoji.jobmanager.ConfigManager; import org.fakekoji.jobmanager.JenkinsJobUpdater; import org.fakekoji.jobmanager.JobUpdater; import org.fakekoji.jobmanager.ManagementException; import org.fakekoji.jobmanager.ManagementResult; import org.fakekoji.jobmanager.manager.BuildProviderManager; import org.fakekoji.jobmanager.manager.PlatformManager; import org.fakekoji.jobmanager.manager.JDKVersionManager; import org.fakekoji.jobmanager.manager.TaskManager; import org.fakekoji.jobmanager.manager.TaskVariantManager; import org.fakekoji.jobmanager.model.JDKProject; import org.fakekoji.jobmanager.model.JDKTestProject; import org.fakekoji.jobmanager.model.JobUpdateResults; import org.fakekoji.jobmanager.project.JDKProjectManager; import org.fakekoji.jobmanager.project.JDKTestProjectManager; import org.fakekoji.model.Platform; import org.fakekoji.model.Task; import org.fakekoji.storage.StorageException; import static io.javalin.apibuilder.ApiBuilder.path; import static io.javalin.apibuilder.ApiBuilder.get; public class OToolService { private static final String ID = "id"; private static final String CONFIG_ID = "/:" + ID; private static final String BUILD_PROVIDERS = "/buildProviders"; private static final String BUILD_PROVIDER = BUILD_PROVIDERS + CONFIG_ID; private static final String JDK_VERSIONS = "/jdkVersions"; private static final String JDK_VERSION = JDK_VERSIONS + CONFIG_ID; private static final String PLATFORMS = "/platforms"; private static final String PLATFORM = PLATFORMS + CONFIG_ID; private static final String TASKS = "/tasks"; private static final String TASK = TASKS + CONFIG_ID; private static final String TASK_VARIANTS = "/taskVariants"; private static final String TASK_VARIANT = TASK_VARIANTS + CONFIG_ID; private static final String JDK_PROJECTS = "/jdkProjects"; private static final String JDK_PROJECT = JDK_PROJECTS + CONFIG_ID; private static final String JDK_TEST_PROJECTS = "/jdkTestProjects"; private static final String JDK_TEST_PROJECT = JDK_TEST_PROJECTS + CONFIG_ID; private static final String MISC = "misc"; private static final String REGENERATE_ALL_JOBS = "regenerateAllJobs"; private static final String MATRIX = "matrix"; private static final String MATRIX_COMPRESSED = "matrixCompressed" + ""; private final int port; private final Javalin app; private final JobUpdater jenkinsJobUpdater; public OToolService(AccessibleSettings settings) { this.port = settings.getWebappPort(); app = Javalin.create(config -> config .addStaticFiles("/webapp") ); jenkinsJobUpdater = new JenkinsJobUpdater(settings); final ConfigManager configManager = ConfigManager.create(settings.getConfigRoot().getAbsolutePath()); final OToolHandlerWrapper wrapper = oToolHandler -> context -> { try { oToolHandler.handle(context); } catch (ManagementException e) { context.status(400).result(e.getMessage()); } catch (StorageException e) { context.status(500).result(e.getMessage()); } }; app.routes(() -> { final JDKTestProjectManager jdkTestProjectManager = new JDKTestProjectManager( configManager.getJdkTestProjectStorage(), jenkinsJobUpdater ); final JDKProjectManager jdkProjectManager = new JDKProjectManager( configManager, jenkinsJobUpdater, settings.getLocalReposRoot(), settings.getScriptsRoot() ); path(MISC, () -> { path(REGENERATE_ALL_JOBS, () -> get(ctx -> { final JobUpdateResults[] r = new JobUpdateResults[]{new JobUpdateResults()}; wrapper.wrap(context -> { JobUpdateResults r1 = jdkTestProjectManager.regenerateAll(); r[0] = r[0].add(r1); }); wrapper.wrap(context -> { JobUpdateResults r2 = jdkProjectManager.regenerateAll(); r[0] = r[0].add(r2); if (ctx.status() < 400) { ctx.status(200).json(r[0]); } }); })); path(MATRIX, () -> get(ctx -> { wrapper.wrap(context -> { Platform }); })); }); app.post(JDK_TEST_PROJECTS, wrapper.wrap(context -> { final JDKTestProject jdkTestProject = context.bodyValidator(JDKTestProject.class).get(); final ManagementResult result = jdkTestProjectManager.create(jdkTestProject); context.status(200).json(result); })); app.get(JDK_TEST_PROJECTS, wrapper.wrap(context -> context.json(jdkTestProjectManager.readAll()))); app.put(JDK_TEST_PROJECT, wrapper.wrap(context -> { final JDKTestProject jdkTestProject = context.bodyValidator(JDKTestProject.class).get(); final String id = context.pathParam(ID); final ManagementResult result = jdkTestProjectManager.update(id, jdkTestProject); context.status(200).json(result); })); app.delete(JDK_TEST_PROJECT, wrapper.wrap(context -> { final String id = context.pathParam(ID); final ManagementResult result = jdkTestProjectManager.delete(id); context.status(200).json(result); })); final BuildProviderManager buildProviderManager = new BuildProviderManager(configManager.getBuildProviderStorage()); app.get(BUILD_PROVIDERS, context -> context.json(buildProviderManager.readAll())); final JDKVersionManager JDKVersionManager = new JDKVersionManager(configManager.getJdkVersionStorage()); app.get(JDK_VERSIONS, context -> context.json(JDKVersionManager.readAll())); final PlatformManager platformManager = new PlatformManager(configManager.getPlatformStorage(), jenkinsJobUpdater); app.get(PLATFORMS, context -> context.json(platformManager.readAll())); app.post(PLATFORMS, context -> { try { final Platform platform = context.bodyValidator(Platform.class).get(); final ManagementResult<Platform> result = platformManager.create(platform); context.status(200).json(result); } catch (ManagementException e) { context.status(400).result(e.toString()); } catch (StorageException e) { context.status(500).result(e.toString()); } }); app.put(PLATFORM, context -> { try { final String id = context.pathParam(ID); final Platform platform = context.bodyValidator(Platform.class).get(); final ManagementResult<Platform> result = platformManager.update(id, platform); context.status(200).json(result); } catch (ManagementException e) { context.status(400).result(e.toString()); } catch (StorageException e) { context.status(500).result(e.toString()); } }); app.delete(PLATFORM, context -> { try { final String id = context.pathParam(ID); final ManagementResult<Platform> result = platformManager.delete(id); context.status(200).json(result); } catch (ManagementException e) { context.status(400).result(e.toString()); } catch (StorageException e) { context.status(500).result(e.toString()); } }); final TaskManager taskManager = new TaskManager(configManager.getTaskStorage(), jenkinsJobUpdater); app.post(TASKS, context -> { try { final Task task = context.bodyValidator(Task.class).get(); final ManagementResult<Task> result = taskManager.create(task); context.status(200).json(result); } catch (ManagementException e) { context.status(400).result(e.toString()); } catch (StorageException e) { context.status(500).result(e.toString()); } }); app.get(TASKS, context -> context.json(taskManager.readAll())); app.put(TASK, context -> { try { final String id = context.pathParam(ID); final Task task = context.bodyValidator(Task.class).get(); final ManagementResult<Task> result = taskManager.update(id, task); context.json(result).status(200); } catch (ManagementException e) { context.status(400).result(e.toString()); } catch (StorageException e) { context.status(500).result(e.toString()); } }); app.delete(TASK, context -> { try { final String id = context.pathParam(ID); final ManagementResult<Task> result = taskManager.delete(id); context.status(200).json(result); } catch (ManagementException e) { context.status(400).result(e.toString()); } catch (StorageException e) { context.status(500).result(e.toString()); } }); final TaskVariantManager taskVariantManager = new TaskVariantManager(configManager.getTaskVariantStorage()); app.get(TASK_VARIANTS, context -> context.json(taskVariantManager.readAll())); app.post(JDK_PROJECTS, context -> { try { final JDKProject jdkProject = context.bodyValidator(JDKProject.class).get(); final ManagementResult<JDKProject> result = jdkProjectManager.create(jdkProject); context.status(200).json(result); } catch (ManagementException e) { context.status(400).result(e.toString()); } catch (StorageException e) { context.status(500).result(e.toString()); } }); app.get(JDK_PROJECTS, context -> context.json(jdkProjectManager.readAll())); app.put(JDK_PROJECT, context -> { try { final JDKProject jdkProject = context.bodyValidator(JDKProject.class).get(); final String id = context.pathParam(ID); final ManagementResult<JDKProject> result = jdkProjectManager.update(id, jdkProject); context.status(200).json(result); } catch (ManagementException e) { context.status(400).result(e.toString()); } catch (StorageException e) { context.status(500).result(e.toString()); } }); app.delete(JDK_PROJECT, context -> { try { final String id = context.pathParam(ID); final ManagementResult<JDKProject> result = jdkProjectManager.delete(id); context.status(200).json(result); } catch (ManagementException e) { context.status(400).result(e.toString()); } catch (StorageException e) { context.status(500).result(e.toString()); } }); }); } public void start() { app.start(port); } public void stop() { app.stop(); } public int getPort() { return port; } interface OToolHandler { void handle(Context context) throws ManagementException, StorageException; } interface OToolHandlerWrapper { Handler wrap(OToolHandler oToolHandler); } }
package net.openl10n.flies.action; import java.io.Serializable; import net.openl10n.flies.ApplicationConfiguration; import net.openl10n.flies.dao.PersonDAO; import net.openl10n.flies.model.HAccount; import net.openl10n.flies.model.HPerson; import net.openl10n.flies.security.FliesIdentity; import net.openl10n.flies.security.FliesJpaIdentityStore; import net.openl10n.flies.service.RegisterService; import net.openl10n.flies.service.impl.EmailChangeActivationService; import org.hibernate.validator.Email; import org.jboss.seam.ScopeType; import org.jboss.seam.annotations.Create; import org.jboss.seam.annotations.In; import org.jboss.seam.annotations.Logger; import org.jboss.seam.annotations.Name; import org.jboss.seam.annotations.Scope; import org.jboss.seam.annotations.Transactional; import org.jboss.seam.faces.FacesMessages; import org.jboss.seam.faces.Renderer; import org.jboss.seam.log.Log; import org.jboss.seam.security.management.JpaIdentityStore; @Name("profileAction") @Scope(ScopeType.PAGE) public class ProfileAction implements Serializable { private static final long serialVersionUID = 1L; private String name; private String email; private String username; private String activationKey; public String getActivationKey() { return activationKey; } public void setActivationKey(String keyHash) { this.activationKey = keyHash; } @In ApplicationConfiguration applicationConfiguration; @Logger Log log; @In FliesIdentity identity; @In FliesJpaIdentityStore identityStore; @In(create = true) private Renderer renderer; @In(required = false, value = JpaIdentityStore.AUTHENTICATED_USER) HAccount authenticatedAccount; @In PersonDAO personDAO; @In RegisterService registerServiceImpl; @Create public void onCreate() { username = identity.getCredentials().getUsername(); if (identityStore.isNewUser(username)) { name = identity.getCredentials().getUsername(); String domain = applicationConfiguration.getDomainName(); email = identity.getCredentials().getUsername() + "@" + domain; identity.unAuthenticate(); }else{ HPerson person = personDAO.findById(authenticatedAccount.getPerson().getId(), false); name = person.getName(); email = person.getEmail(); authenticatedAccount.getPerson().setName(this.name); authenticatedAccount.getPerson().setEmail(this.email); } } public String getName() { return name; } public void setName(String name) { this.name = name; } @Email public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Transactional public String edit() { if (!identityStore.isNewUser(username)) { HPerson person = personDAO.findById(authenticatedAccount.getPerson().getId(), true); person.setName(this.name); personDAO.makePersistent(person); personDAO.flush(); authenticatedAccount.getPerson().setName(this.name); log.debug("updated successfully"); if (!authenticatedAccount.getPerson().getEmail().equals(this.email)) { activationKey = EmailChangeActivationService.generateActivationKey(authenticatedAccount.getPerson().getId().toString(), this.email); renderer.render("/WEB-INF/facelets/email/email_validation.xhtml"); FacesMessages.instance().add("You will soon receive an email with a link to activate your email account change."); } return "updated"; } else { final String user = this.username; String key = registerServiceImpl.register(user, "", this.name, this.email); setActivationKey(key); renderer.render("/WEB-INF/facelets/email/email_activation.xhtml"); FacesMessages.instance().add("You will soon receive an email with a link to activate your account."); return "/home.xhtml"; } } public String cancel(){ if (identityStore.isNewUser(username)) { return "home"; } return "view"; } }
package br.net.mirante.singular; import br.net.mirante.singular.flow.core.MUser; import br.net.mirante.singular.flow.core.service.IUserService; import br.net.mirante.singular.persistence.entity.Actor; import org.hibernate.SessionFactory; import org.hibernate.criterion.Restrictions; import javax.inject.Inject; import javax.inject.Named; @Named public class TestUserService implements IUserService { @Inject private TestDAO testDAO; @Override public MUser getUserIfAvailable() { return (MUser)testDAO.getSomeUser(1); } @Override public boolean canBeAllocated(MUser user) { return false; } @Override public MUser findUserByCod(String username) { return (MUser)testDAO.getSomeUser(1); } }
package org.apache.flume.core; import org.apache.flume.lifecycle.LifecycleAware; import org.apache.flume.lifecycle.LifecycleException; import org.apache.flume.lifecycle.LifecycleState; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Preconditions; public class ChannelDriver implements LifecycleAware { private static final Logger logger = LoggerFactory .getLogger(ChannelDriver.class); private String name; private EventSource source; private EventSink sink; private ChannelDriverThread driverThread; private LifecycleState lifecycleState; public ChannelDriver(String name) { this.name = name; lifecycleState = LifecycleState.IDLE; } @Override public void start(Context context) throws LifecycleException { logger.debug("Channel driver starting:{}", this); driverThread = new ChannelDriverThread(name); driverThread.setSource(source); driverThread.setSink(sink); driverThread.start(); lifecycleState = LifecycleState.START; } @Override public void stop(Context context) throws LifecycleException { logger.debug("Channel driver stopping:{}", this); driverThread.setShouldStop(true); while (driverThread.isAlive()) { try { logger.debug("Waiting for driver to stop"); driverThread.join(1000); } catch (InterruptedException e) { logger .debug("Interrupted while waiting for driver thread to shutdown. Interrupting it and stopping."); driverThread.interrupt(); } } lifecycleState = LifecycleState.STOP; } @Override public LifecycleState getLifecycleState() { return lifecycleState; } @Override public void transitionTo(LifecycleState state) { } @Override public String toString() { return "{ source:" + source + " sink:" + sink + " }"; } public EventSource getSource() { return source; } public void setSource(EventSource source) { this.source = source; } public EventSink getSink() { return sink; } public void setSink(EventSink sink) { this.sink = sink; } private static class ChannelDriverThread extends Thread { private EventSource source; private EventSink sink; private Context context; private long totalEvents; private long discardedEvents; private long nullEvents; private long successfulEvents; volatile private boolean shouldStop; public ChannelDriverThread(String name) { super(name); totalEvents = 0; discardedEvents = 0; nullEvents = 0; successfulEvents = 0; shouldStop = false; } @Override public void run() { logger.debug("Channel driver thread running"); Preconditions.checkState(source != null, "Source can not be null"); Preconditions.checkState(sink != null, "Sink can not be null"); try { sink.open(context); source.open(context); } catch (InterruptedException e) { logger.debug("Interrupted while opening source / sink.", e); shouldStop = true; } catch (LifecycleException e) { logger.error("Failed to open source / sink. Exception follows.", e); shouldStop = true; } while (!shouldStop) { Event<?> event = null; try { event = source.next(context); if (event != null) { sink.append(context, event); successfulEvents++; } else { nullEvents++; } } catch (InterruptedException e) { logger.debug("Received an interrupt while moving events - stopping"); shouldStop = true; } catch (MessageDeliveryException e) { logger.debug("Unable to deliver event:{} (may be null)", event); discardedEvents++; /* FIXME: Handle dead messages. */ } totalEvents++; } try { source.close(context); sink.close(context); } catch (InterruptedException e) { logger.debug( "Interrupted while closing source / sink. Just going to continue.", e); } catch (LifecycleException e) { logger.error("Failed to open source / sink. Exception follows.", e); } logger.debug("Channel driver thread exiting cleanly"); logger .info( "Event metrics - totalEvents:{} successfulEvents:{} nullEvents:{} discardedEvents:{}", new Object[] { totalEvents, successfulEvents, nullEvents, discardedEvents }); } public void setSource(EventSource source) { this.source = source; } public void setSink(EventSink sink) { this.sink = sink; } public void setShouldStop(boolean shouldStop) { this.shouldStop = shouldStop; } } }
package logiclayer; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.sql.Blob; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.imageio.ImageIO; import objectlayer.Car; import persistlayer.CarPersistImpl; public class RentalLogicImpl() { private RentalPersistImpl rpi; public RentalLogicImpl() { rpi = new RentalPersistImpl(); } public String viewUnavailable(int carID, String d1, String d2) { //ResultSet rs = rpi.verifyDate(int carID, String d1, String d2); ResultRest rs = null; String dateVar = "["; rs =rpi.viewAvailable(); //returns all taken dates. if (rs != null) { //if there are dates taken iterate and create js variable to be parsed. while(rs.next()) { String day1 = rs.getString("startDate"); String day2 = rs.getString("endDate"); dateVar = dateVar + "{start:\"" + startDate + "\", end:\"" + endDate + "\"}, "; //dateVar = dateVar + startDate + "\", end:\"" + endDate } dateVar = dateVar + "]"; } else dateVar = "undefined"; return dateVar; }
package apps.matts.contextlearning; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; 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 com.squareup.picasso.Picasso; import java.util.ArrayList; import java.util.Random; import java.util.Stack; public class Level extends AppCompatActivity { gameLevel gm; private DatabaseReference database; Stack<Button> disabledButtons; DatabaseReference qnumref; DatabaseReference qinforef; ImageView img; Random r; String imageUrl = ""; QNum qnum = new QNum(); ArrayList<QuestionInfo> questions = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_level); database = FirebaseDatabase.getInstance().getReference(); qnumref = database.child("Count"); qinforef = database.child("Questions"); img = (ImageView)findViewById(R.id.Pic) ; disabledButtons = new Stack<Button>(); gm = new gameLevel(); } @Override public void onStart() { super.onStart(); qinforef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for(DataSnapshot ds : dataSnapshot.getChildren()){ QuestionInfo q = ds.getValue(QuestionInfo.class); Log.d("Level", q.getWord()); questions.add(q); } showQuestion(); } @Override public void onCancelled(DatabaseError databaseError) { } }); // [END post_value_event_listener] } public void showQuestion() { r = new Random(); int rq = r.nextInt(questions.size()); imageUrl = "http: Picasso.with(this).load(imageUrl).into(img); gm.setLevel(questions.get(rq).getWord().toUpperCase()); enableAllButton(); updateScreen(); } public void checkClick(View view) { if(gm.makeGuess()) { Toast.makeText(this, "Congratulations, You did it!", Toast.LENGTH_LONG).show(); showQuestion(); } else { Toast.makeText(this, "Sorry, try agian", Toast.LENGTH_LONG).show(); } } public void eraseClick(View view) { if(!disabledButtons.empty()) { gm.removeGuessLetter(); Button b = disabledButtons.pop(); b.setEnabled(true); } updateText(); } public void enableAllButton(){ while(!disabledButtons.empty()) { Button b = disabledButtons.pop(); b.setEnabled(true); } } public void letterClick(View view) { Button b = (Button)view; Character buttonText = b.getText().charAt(0); gm.guessLetter(buttonText); b.setEnabled(false); disabledButtons.add(b); updateScreen(); } public void updateScreen() { updateButtons(); updateText(); } public void updateText() { TextView textView = (TextView) findViewById(R.id.textview); textView.setText(gm.getGuessShown()); } public void updateButtons() { char[] let = gm.getGuessLettersChar(); ViewGroup layout = (ViewGroup)findViewById(R.id.layout_top_container_buttons); for (int i = 0; i < 4; i++) { View child = layout.getChildAt(i); if(child instanceof Button) { Button button = (Button) child; button.setText(let[i] + ""); } } layout = (ViewGroup)findViewById(R.id.layout_bottom_container_buttons); for (int x = 0; x < 4; x++) { View child = layout.getChildAt(x); if(child instanceof Button) { Button button = (Button) child; button.setText(let[x+4] + ""); } } } }
package com.k3nx.taskit; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; public class TaskListActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_task_list); Task[] items = new Task[3]; items[0] = new Task(); items[0].setName("Task 1"); items[1] = new Task(); items[1].setName("Task 2"); items[2] = new Task(); items[2].setName("Task 3"); ListView listView = (ListView)findViewById(R.id.task_list); listView.setAdapter(new TaskAdapter(items)); } private class TaskAdapter extends ArrayAdapter<Task> { TaskAdapter(Task[] tasks) { // Using a custom layout requires the TextView id super(TaskListActivity.this, R.layout.task_list_row, R.id.task_item_name, tasks); } @Override public View getView(int position, View convertView, ViewGroup parent) { convertView = super.getView(position, convertView, parent); Task task = getItem(position); TextView taskName = (TextView)convertView.findViewById(R.id.task_item_name); taskName.setText(task.getName()); return convertView; } } @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_task_list, 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(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
package com.muzima.view; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.RatingBar; import android.widget.Toast; import com.muzima.domain.Credentials; import com.muzima.R; import com.muzima.utils.StringUtils; import com.muzima.utils.ThemeUtils; public class FeedbackActivity extends BaseActivity { private Button sendButton; private Button cancelButton; private EditText feedbackText; private RatingBar feedbackRatingBar; private static final String EMAIL_TO = "help@muzima.org"; private static final String SUBJECT = "Feedback"; private final ThemeUtils themeUtils = new ThemeUtils(); @Override protected void onCreate(Bundle savedInstanceState) { themeUtils.onCreate(this); super.onCreate(savedInstanceState); setContentView(R.layout.activity_interactive_feedback); initViews(); setupListeners(); } @Override protected void onResume() { super.onResume(); themeUtils.onResume(this); } private void setupListeners() { sendButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String message = feedbackText.getText().toString(); if (!StringUtils.isEmpty(message)) { sendEmail(); } else { feedbackText.setHint(getString(R.string.hint_feedback_prompt)); feedbackText.setHintTextColor(getResources().getColor(R.color.error_text_color)); } } private String composeMessage() { String sender = "Sender: " + getUserName(); String rating = "Rating: " + String.valueOf(feedbackRatingBar.getRating()); String feedback = "Message: " + feedbackText.getText().toString(); String message = sender + "\n" + rating+ "\n" + feedback; return message; } private void sendEmail() { Intent emailIntent = new Intent(Intent.ACTION_SEND); emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{EMAIL_TO}); emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, SUBJECT); emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, composeMessage()); emailIntent.setData(Uri.parse("mailto:")); emailIntent.setType("message/rfc822"); if (emailIntent.resolveActivity(getPackageManager()) != null) { startActivityForResult(emailIntent, 1); } else { Toast.makeText(getApplicationContext(), R.string.no_email_client, Toast.LENGTH_SHORT).show(); } } }); cancelButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { FeedbackActivity.this.onBackPressed(); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 1) { AlertDialog.Builder builder = new AlertDialog.Builder(FeedbackActivity.this); builder .setCancelable(true) .setMessage(R.string.message_feedback_sent) .setPositiveButton(getResources().getText(R.string.general_ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { FeedbackActivity.this.onBackPressed(); } }).create().show(); } } private void initViews() { sendButton = findViewById(R.id.send); cancelButton = findViewById(R.id.cancel); feedbackText = findViewById(R.id.feedback_message); feedbackRatingBar = findViewById(R.id.question_rating); } private String getUserName() { Credentials credentials = new Credentials(this); return credentials.getUserName(); } }
package com.noprestige.kanaquiz; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.inputmethod.EditorInfo; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import java.text.DecimalFormat; public class MainQuiz extends AppCompatActivity { private int totalQuestions; private int totalCorrect; private KanaQuestionBank questionBank; private TextView lblResponse; private EditText txtAnswer; private TextView lblDisplayKana; private Button btnSubmit; private int oldTextColour; private static final DecimalFormat PERCENT_FORMATTER = new DecimalFormat(" private Handler delayHandler = new Handler(); private boolean isRetrying = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_quiz); lblResponse = (TextView) findViewById(R.id.lblResponse); txtAnswer = (EditText) findViewById(R.id.txtAnswer); lblDisplayKana = (TextView) findViewById(R.id.lblDisplayKana); btnSubmit = (Button) findViewById(R.id.btnSubmit); oldTextColour = lblResponse.getCurrentTextColor(); //kludge for reverting text colour OptionsControl.initialize(this); txtAnswer.setOnEditorActionListener( new TextView.OnEditorActionListener() { public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (((actionId == EditorInfo.IME_ACTION_GO) || (actionId == EditorInfo.IME_NULL)) && btnSubmit.isEnabled()) submitAnswer(); return true; } } ); resetQuiz(); nextQuestion(); } private void resetQuiz() { totalQuestions = 0; totalCorrect = 0; lblDisplayKana.setText(""); lblResponse.setText(""); if (!OptionsControl.compareStrings(R.string.prefid_on_incorrect, R.string.prefid_on_incorrect_default)) lblResponse.setMinLines(2); questionBank = Hiragana.QUESTIONS.getQuestionBank(); questionBank.addQuestions(Katakana.QUESTIONS.getQuestionBank()); } private void nextQuestion() { try { questionBank.newQuestion(); lblDisplayKana.setText(questionBank.getCurrentKana()); // txtAnswer.setEnabled(true); isRetrying = false; ReadyForAnswer(); } catch (NoQuestionsException ex) { lblDisplayKana.setText(""); lblResponse.setText(R.string.no_questions); txtAnswer.setEnabled(false); btnSubmit.setEnabled(false); lblResponse.setTextColor(oldTextColour); //kludge for reverting text colours txtAnswer.setText(""); } TextView lblScore = (TextView) findViewById(R.id.lblScore); if (totalQuestions > 0) { lblScore.setText(R.string.score_label); lblScore.append(": "); lblScore.append(PERCENT_FORMATTER.format((float) totalCorrect / (float) totalQuestions)); lblScore.append(System.getProperty("line.separator")); lblScore.append(Integer.toString(totalCorrect)); lblScore.append(" / "); lblScore.append(Integer.toString(totalQuestions)); } else lblScore.setText(""); } private void checkAnswer(String answer) { boolean isNewQuestion = true; btnSubmit.setEnabled(false); if (questionBank.checkCurrentAnswer(answer)) { lblResponse.setText(R.string.correct_answer); lblResponse.setTextColor(ContextCompat.getColor(this, R.color.correct)); if (!isRetrying) totalCorrect++; } else { lblResponse.setText(R.string.incorrect_answer); lblResponse.setTextColor(ContextCompat.getColor(this, R.color.incorrect)); if (OptionsControl.compareStrings(R.string.prefid_on_incorrect, R.string.prefid_on_incorrect_show_answer)) { lblResponse.append(System.getProperty("line.separator")); lblResponse.append(getResources().getText(R.string.show_correct_answer)); lblResponse.append(": "); lblResponse.append(questionBank.fetchCorrectAnswer()); } else if (OptionsControl.compareStrings(R.string.prefid_on_incorrect, R.string.prefid_on_incorrect_retry)) { txtAnswer.setText(""); lblResponse.append(System.getProperty("line.separator")); lblResponse.append(getResources().getText(R.string.try_again)); isRetrying = true; isNewQuestion = false; delayHandler.postDelayed( new Runnable() { public void run() { ReadyForAnswer(); } }, 1000 ); } } if (isNewQuestion) { totalQuestions++; //txtAnswer.setEnabled(false); //TODO: Find a way to disable a textbox without closing the touch keyboard delayHandler.postDelayed( new Runnable() { public void run() { nextQuestion(); } }, 1000 ); } } private void ReadyForAnswer() { lblResponse.setText(R.string.request_answer); btnSubmit.setEnabled(true); txtAnswer.requestFocus(); lblResponse.setTextColor(oldTextColour); //kludge for reverting text colours txtAnswer.setText(""); } public void submitAnswer(View view) { submitAnswer(); } private void submitAnswer() { String answer = txtAnswer.getText().toString().trim(); if (!answer.isEmpty()) //ignore if blank checkAnswer(answer); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { Class destination; switch (item.getItemId()) { case R.id.mnuSelection: destination = KanaSelection.class; break; case R.id.mnuReference: destination = ReferenceScreen.class; break; case R.id.mnuOptions: destination = OptionsScreen.class; break; case R.id.mnuAbout: destination = AboutScreen.class; break; default: return super.onOptionsItemSelected(item); } startActivityForResult(new Intent(MainQuiz.this, destination), 1); return true; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 1) { resetQuiz(); nextQuestion(); } } }
package com.samourai.wallet; import android.app.ActionBar; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ActivityInfo; import android.os.Bundle; import android.os.Looper; import android.support.v4.content.LocalBroadcastManager; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.ArrayAdapter; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.Switch; import android.widget.TextView; import android.widget.Toast; //import android.util.Log; import org.bitcoinj.core.Transaction; import org.bitcoinj.core.TransactionOutput; import org.bitcoinj.crypto.MnemonicException; import com.dm.zbar.android.scanner.ZBarConstants; import com.dm.zbar.android.scanner.ZBarScannerActivity; import com.samourai.wallet.api.APIFactory; import com.samourai.wallet.bip47.BIP47Activity; import com.samourai.wallet.bip47.BIP47Meta; import com.samourai.wallet.bip47.BIP47Util; import com.samourai.wallet.bip47.rpc.PaymentAddress; import com.samourai.wallet.bip47.rpc.PaymentCode; import com.samourai.wallet.hd.HD_WalletFactory; import com.samourai.wallet.ricochet.RicochetMeta; import com.samourai.wallet.send.FeeUtil; import com.samourai.wallet.send.MyTransactionOutPoint; import com.samourai.wallet.send.SendFactory; import com.samourai.wallet.send.UTXO; import com.samourai.wallet.util.AppUtil; import com.samourai.wallet.util.ExchangeRateFactory; import com.samourai.wallet.util.FormatsUtil; import com.samourai.wallet.util.MonetaryUtil; import com.samourai.wallet.util.PrefsUtil; import com.samourai.wallet.util.PushTx; import com.samourai.wallet.util.SendAddressUtil; import java.io.IOException; import java.math.BigInteger; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.text.DecimalFormatSymbols; import android.text.Editable; import android.text.TextWatcher; import android.widget.Button; import net.sourceforge.zbar.Symbol; import org.bitcoinj.core.Coin; import org.bitcoinj.params.MainNetParams; import org.bitcoinj.script.Script; import org.json.JSONException; import org.json.JSONObject; import org.spongycastle.util.encoders.Hex; public class SendActivity extends Activity { private final static int SCAN_QR = 2012; private final static int RICOCHET = 2013; private TextView tvMaxPrompt = null; private TextView tvMax = null; private long balance = 0L; private EditText edAddress = null; private String strDestinationBTCAddress = null; private TextWatcher textWatcherAddress = null; private EditText edAmountBTC = null; private EditText edAmountFiat = null; private TextWatcher textWatcherBTC = null; private TextWatcher textWatcherFiat = null; private String defaultSeparator = null; private Button btFee = null; private TextView tvFeeAmount = null; private EditText edCustomFee = null; private final static int FEE_LOW = 0; private final static int FEE_NORMAL = 1; private final static int FEE_PRIORITY = 2; // private final static int FEE_CUSTOM = 3; private int FEE_TYPE = 0; public final static int SPEND_SIMPLE = 0; public final static int SPEND_BIP126 = 1; public final static int SPEND_RICOCHET = 2; private int SPEND_TYPE = SPEND_BIP126; // private CheckBox cbSpendType = null; private Switch swRicochet = null; private String strFiat = null; private double btc_fx = 286.0; private TextView tvFiatSymbol = null; private Button btSend = null; private int selectedAccount = 0; private String strPCode = null; private boolean bViaMenu = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_send); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); SendActivity.this.getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); if(SamouraiWallet.getInstance().getShowTotalBalance()) { if(SamouraiWallet.getInstance().getCurrentSelectedAccount() == 2) { selectedAccount = 1; } else { selectedAccount = 0; } } else { selectedAccount = 0; } tvMaxPrompt = (TextView)findViewById(R.id.max_prompt); tvMax = (TextView)findViewById(R.id.max); try { balance = APIFactory.getInstance(SendActivity.this).getXpubAmounts().get(HD_WalletFactory.getInstance(SendActivity.this).get().getAccount(selectedAccount).xpubstr()); } catch(IOException ioe) { balance = 0L; } catch(MnemonicException.MnemonicLengthException mle) { balance = 0L; } catch(java.lang.NullPointerException npe) { balance = 0L; } final String strAmount; DecimalFormat df = new DecimalFormat(" df.setMinimumIntegerDigits(1); df.setMinimumFractionDigits(1); df.setMaximumFractionDigits(8); int unit = PrefsUtil.getInstance(SendActivity.this).getValue(PrefsUtil.BTC_UNITS, MonetaryUtil.UNIT_BTC); switch(unit) { case MonetaryUtil.MICRO_BTC: strAmount = df.format(((double)(balance * 1000000L)) / 1e8); break; case MonetaryUtil.MILLI_BTC: strAmount = df.format(((double)(balance * 1000L)) / 1e8); break; default: strAmount = Coin.valueOf(balance).toPlainString(); break; } tvMax.setText(strAmount + " " + getDisplayUnits()); tvMaxPrompt.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { edAmountBTC.setText(strAmount); return false; } }); tvMax.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { edAmountBTC.setText(strAmount); return false; } }); DecimalFormat format = (DecimalFormat)DecimalFormat.getInstance(new Locale("en", "US")); DecimalFormatSymbols symbols = format.getDecimalFormatSymbols(); defaultSeparator = Character.toString(symbols.getDecimalSeparator()); strFiat = PrefsUtil.getInstance(SendActivity.this).getValue(PrefsUtil.CURRENT_FIAT, "USD"); btc_fx = ExchangeRateFactory.getInstance(SendActivity.this).getAvgPrice(strFiat); tvFiatSymbol = (TextView)findViewById(R.id.fiatSymbol); tvFiatSymbol.setText(getDisplayUnits() + "-" + strFiat); edAddress = (EditText)findViewById(R.id.destination); textWatcherAddress = new TextWatcher() { public void afterTextChanged(Editable s) { validateSpend(); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { ; } public void onTextChanged(CharSequence s, int start, int before, int count) { ; } }; edAddress.addTextChangedListener(textWatcherAddress); edAddress.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { //final int DRAWABLE_LEFT = 0; //final int DRAWABLE_TOP = 1; final int DRAWABLE_RIGHT = 2; //final int DRAWABLE_BOTTOM = 3; if(event.getAction() == MotionEvent.ACTION_UP && event.getRawX() >= (edAddress.getRight() - edAddress.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) { final List<String> entries = new ArrayList<String>(); entries.addAll(BIP47Meta.getInstance().getSortedByLabels(false)); final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(SendActivity.this, android.R.layout.select_dialog_singlechoice); for(int i = 0; i < entries.size(); i++) { arrayAdapter.add(BIP47Meta.getInstance().getDisplayLabel(entries.get(i))); } AlertDialog.Builder dlg = new AlertDialog.Builder(SendActivity.this); dlg.setIcon(R.drawable.ic_launcher); dlg.setTitle(R.string.app_name); dlg.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Toast.makeText(SendActivity.this, BIP47Meta.getInstance().getDisplayLabel(entries.get(which)), Toast.LENGTH_SHORT).show(); // Toast.makeText(SendActivity.this, entries.get(which), Toast.LENGTH_SHORT).show(); processPCode(entries.get(which)); } }); dlg.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); dlg.show(); return true; } return false; } }); edAmountBTC = (EditText)findViewById(R.id.amountBTC); edAmountFiat = (EditText)findViewById(R.id.amountFiat); textWatcherBTC = new TextWatcher() { public void afterTextChanged(Editable s) { edAmountBTC.removeTextChangedListener(this); edAmountFiat.removeTextChangedListener(textWatcherFiat); int unit = PrefsUtil.getInstance(SendActivity.this).getValue(PrefsUtil.BTC_UNITS, MonetaryUtil.UNIT_BTC); int max_len = 8; NumberFormat btcFormat = NumberFormat.getInstance(new Locale("en", "US")); switch (unit) { case MonetaryUtil.MICRO_BTC: max_len = 2; break; case MonetaryUtil.MILLI_BTC: max_len = 4; break; default: max_len = 8; break; } btcFormat.setMaximumFractionDigits(max_len + 1); btcFormat.setMinimumFractionDigits(0); double d = 0.0; try { d = NumberFormat.getInstance(new Locale("en", "US")).parse(s.toString()).doubleValue(); String s1 = btcFormat.format(d); if (s1.indexOf(defaultSeparator) != -1) { String dec = s1.substring(s1.indexOf(defaultSeparator)); if (dec.length() > 0) { dec = dec.substring(1); if (dec.length() > max_len) { edAmountBTC.setText(s1.substring(0, s1.length() - 1)); edAmountBTC.setSelection(edAmountBTC.getText().length()); s = edAmountBTC.getEditableText(); } } } } catch (NumberFormatException nfe) { ; } catch (ParseException pe) { ; } switch (unit) { case MonetaryUtil.MICRO_BTC: d = d / 1000000.0; break; case MonetaryUtil.MILLI_BTC: d = d / 1000.0; break; default: break; } if(d > 21000000.0) { edAmountFiat.setText("0.00"); edAmountFiat.setSelection(edAmountFiat.getText().length()); edAmountBTC.setText("0"); edAmountBTC.setSelection(edAmountBTC.getText().length()); Toast.makeText(SendActivity.this, R.string.invalid_amount, Toast.LENGTH_SHORT).show(); } else { edAmountFiat.setText(MonetaryUtil.getInstance().getFiatFormat(strFiat).format(d * btc_fx)); edAmountFiat.setSelection(edAmountFiat.getText().length()); } edAmountFiat.addTextChangedListener(textWatcherFiat); edAmountBTC.addTextChangedListener(this); validateSpend(); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { ; } public void onTextChanged(CharSequence s, int start, int before, int count) { ; } }; edAmountBTC.addTextChangedListener(textWatcherBTC); textWatcherFiat = new TextWatcher() { public void afterTextChanged(Editable s) { edAmountFiat.removeTextChangedListener(this); edAmountBTC.removeTextChangedListener(textWatcherBTC); int max_len = 2; NumberFormat fiatFormat = NumberFormat.getInstance(new Locale("en", "US")); fiatFormat.setMaximumFractionDigits(max_len + 1); fiatFormat.setMinimumFractionDigits(0); double d = 0.0; try { d = NumberFormat.getInstance(new Locale("en", "US")).parse(s.toString()).doubleValue(); String s1 = fiatFormat.format(d); if(s1.indexOf(defaultSeparator) != -1) { String dec = s1.substring(s1.indexOf(defaultSeparator)); if(dec.length() > 0) { dec = dec.substring(1); if(dec.length() > max_len) { edAmountFiat.setText(s1.substring(0, s1.length() - 1)); edAmountFiat.setSelection(edAmountFiat.getText().length()); } } } } catch(NumberFormatException nfe) { ; } catch(ParseException pe) { ; } int unit = PrefsUtil.getInstance(SendActivity.this).getValue(PrefsUtil.BTC_UNITS, MonetaryUtil.UNIT_BTC); switch (unit) { case MonetaryUtil.MICRO_BTC: d = d * 1000000.0; break; case MonetaryUtil.MILLI_BTC: d = d * 1000.0; break; default: break; } if((d / btc_fx) > 21000000.0) { edAmountFiat.setText("0.00"); edAmountFiat.setSelection(edAmountFiat.getText().length()); edAmountBTC.setText("0"); edAmountBTC.setSelection(edAmountBTC.getText().length()); Toast.makeText(SendActivity.this, R.string.invalid_amount, Toast.LENGTH_SHORT).show(); } else { edAmountBTC.setText(MonetaryUtil.getInstance().getBTCFormat().format(d / btc_fx)); edAmountBTC.setSelection(edAmountBTC.getText().length()); } edAmountBTC.addTextChangedListener(textWatcherBTC); edAmountFiat.addTextChangedListener(this); validateSpend(); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { ; } public void onTextChanged(CharSequence s, int start, int before, int count) { ; } }; edAmountFiat.addTextChangedListener(textWatcherFiat); /* cbSpendType = (CheckBox)findViewById(R.id.simple); cbSpendType.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CheckBox cb = (CheckBox)v; if(swRicochet.isChecked()) { SPEND_TYPE = SPEND_RICOCHET; } else { SPEND_TYPE = cb.isChecked() ? SPEND_SIMPLE : SPEND_BIP126; } } }); */ SPEND_TYPE = PrefsUtil.getInstance(SendActivity.this).getValue(PrefsUtil.SPEND_TYPE, SPEND_BIP126); if(SPEND_TYPE > SPEND_BIP126) { SPEND_TYPE = SPEND_BIP126; } swRicochet = (Switch)findViewById(R.id.ricochet); swRicochet.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked) { SPEND_TYPE = SPEND_RICOCHET; if (BIP47Meta.getInstance().getOutgoingStatus(BIP47Meta.strSamouraiDonationPCode) != BIP47Meta.STATUS_SENT_CFM) { AlertDialog.Builder dlg = new AlertDialog.Builder(SendActivity.this) .setTitle(R.string.app_name) .setMessage(R.string.ricochet_fee_via_bip47) .setCancelable(false) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); Intent intent = new Intent(SendActivity.this, BIP47Activity.class); startActivity(intent); } }).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }); if(!isFinishing()) { dlg.show(); } } } else { SPEND_TYPE = PrefsUtil.getInstance(SendActivity.this).getValue(PrefsUtil.SPEND_TYPE, SPEND_BIP126); } } }); tvFeeAmount = (TextView)findViewById(R.id.feeAmount); edCustomFee = (EditText)findViewById(R.id.customFeeAmount); edCustomFee.setText("0.00015"); edCustomFee.setVisibility(View.GONE); FEE_TYPE = FEE_NORMAL; btFee = (Button)findViewById(R.id.fee); btFee.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { switch(FEE_TYPE) { case FEE_NORMAL: FEE_TYPE = FEE_LOW; btFee.setText(getString(R.string.low_fee)); edCustomFee.setVisibility(View.GONE); tvFeeAmount.setVisibility(View.VISIBLE); tvFeeAmount.setText(""); break; case FEE_LOW: FEE_TYPE = FEE_PRIORITY; btFee.setText(getString(R.string.priority_fee)); edCustomFee.setVisibility(View.GONE); tvFeeAmount.setVisibility(View.VISIBLE); tvFeeAmount.setText(""); break; case FEE_PRIORITY: /* FEE_TYPE = FEE_CUSTOM; btFee.setText(getString(R.string.custom_fee)); tvFeeAmount.setVisibility(View.GONE); edCustomFee.setVisibility(View.VISIBLE); edCustomFee.setSelection(edCustomFee.getText().length()); break; */ FEE_TYPE = FEE_NORMAL; btFee.setText(getString(R.string.auto_fee)); edCustomFee.setVisibility(View.GONE); tvFeeAmount.setVisibility(View.VISIBLE); tvFeeAmount.setText(""); break; // case FEE_CUSTOM: default: FEE_TYPE = FEE_NORMAL; btFee.setText(getString(R.string.auto_fee)); edCustomFee.setVisibility(View.GONE); tvFeeAmount.setVisibility(View.VISIBLE); tvFeeAmount.setText(""); break; } } }); tvFeeAmount.setText(""); btSend = (Button)findViewById(R.id.send); btSend.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { btSend.setClickable(false); btSend.setActivated(false); // store current change index to restore value in case of sending fail int change_index = 0; try { change_index = HD_WalletFactory.getInstance(SendActivity.this).get().getAccount(0).getChange().getAddrIdx(); // Log.d("SendActivity", "storing change index:" + change_index); } catch(IOException ioe) { ; } catch(MnemonicException.MnemonicLengthException mle) { ; } double btc_amount = 0.0; try { btc_amount = NumberFormat.getInstance(new Locale("en", "US")).parse(edAmountBTC.getText().toString().trim()).doubleValue(); // Log.i("SendFragment", "amount entered:" + btc_amount); } catch (NumberFormatException nfe) { btc_amount = 0.0; } catch (ParseException pe) { btc_amount = 0.0; } double dAmount; int unit = PrefsUtil.getInstance(SendActivity.this).getValue(PrefsUtil.BTC_UNITS, MonetaryUtil.UNIT_BTC); switch (unit) { case MonetaryUtil.MICRO_BTC: dAmount = btc_amount / 1000000.0; break; case MonetaryUtil.MILLI_BTC: dAmount = btc_amount / 1000.0; break; default: dAmount = btc_amount; break; } long amount = (long)(Math.round(dAmount * 1e8));; // Log.i("SendActivity", "amount:" + amount); final String address = strDestinationBTCAddress == null ? edAddress.getText().toString() : strDestinationBTCAddress; final int accountIdx = selectedAccount; final HashMap<String, BigInteger> receivers = new HashMap<String, BigInteger>(); receivers.put(address, BigInteger.valueOf(amount)); // get all UTXO List<UTXO> utxos = APIFactory.getInstance(SendActivity.this).getUtxos(); final List<UTXO> selectedUTXO = new ArrayList<UTXO>(); long totalValueSelected = 0L; long change = 0L; BigInteger fee = null; // Log.d("SendActivity", "amount:" + amount); // Log.d("SendActivity", "balance:" + balance); // insufficient funds if(amount > balance) { Toast.makeText(SendActivity.this, R.string.insufficient_funds, Toast.LENGTH_SHORT).show(); } // entire balance (can only be simple spend) else if(amount == balance) { // make sure we are using simple spend SPEND_TYPE = SPEND_SIMPLE; // Log.d("SendActivity", "amount == balance"); // take all utxos, deduct fee selectedUTXO.addAll(utxos); for(UTXO u : selectedUTXO) { totalValueSelected += u.getValue(); } // Log.d("SendActivity", "balance:" + balance); // Log.d("SendActivity", "total value selected:" + totalValueSelected); } else { ; } switch(FEE_TYPE) { case FEE_LOW: FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getLowFee()); break; case FEE_PRIORITY: FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getHighFee()); break; /* case FEE_CUSTOM: String strCustomFee = edCustomFee.getText().toString(); SuggestedFee suggestedFee = new SuggestedFee(); suggestedFee.setDefaultPerKB(); suggestedFee.setStressed(false); suggestedFee.setOK(true); FeeUtil.getInstance().setSuggestedFee(suggestedFee); break; */ default: FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getNormalFee()); break; } org.apache.commons.lang3.tuple.Pair<ArrayList<MyTransactionOutPoint>, ArrayList<TransactionOutput>> pair = null; if(SPEND_TYPE == SPEND_RICOCHET) { boolean samouraiFeeViaBIP47 = false; if(BIP47Meta.getInstance().getOutgoingStatus(BIP47Meta.strSamouraiDonationPCode) == BIP47Meta.STATUS_SENT_CFM) { samouraiFeeViaBIP47 = true; } final JSONObject jObj = RicochetMeta.getInstance(SendActivity.this).script(amount, FeeUtil.getInstance().getSuggestedFee().getDefaultPerKB().longValue(), address, 4, strPCode, samouraiFeeViaBIP47); if(jObj != null) { try { long totalAmount = jObj.getLong("total_spend"); if(totalAmount > balance) { Toast.makeText(SendActivity.this, R.string.insufficient_funds, Toast.LENGTH_SHORT).show(); return; } String msg = getText(R.string.ricochet_spend1) + " " + address + " " + getText(R.string.ricochet_spend2) + " " + Coin.valueOf(totalAmount).toPlainString() + " " + getText(R.string.ricochet_spend3); AlertDialog.Builder dlg = new AlertDialog.Builder(SendActivity.this) .setTitle(R.string.app_name) .setMessage(msg) .setCancelable(false) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { RicochetMeta.getInstance(SendActivity.this).add(jObj); dialog.dismiss(); Intent intent = new Intent(SendActivity.this, RicochetActivity.class); startActivityForResult(intent, RICOCHET); } }).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }); if(!isFinishing()) { dlg.show(); } return; } catch(JSONException je) { return; } } return; } // if BIP126 try both hetero/alt, if fails change type to SPEND_SIMPLE else if(SPEND_TYPE == SPEND_BIP126) { List<UTXO> _utxos = utxos; Collections.shuffle(_utxos); // hetero pair = SendFactory.getInstance(SendActivity.this).heterogeneous(_utxos, BigInteger.valueOf(amount), address); if(pair == null) { Collections.sort(_utxos, new UTXO.UTXOComparator()); // alt pair = SendFactory.getInstance(SendActivity.this).altHeterogeneous(_utxos, BigInteger.valueOf(amount), address); } if(pair == null) { // can't do BIP126, revert to SPEND_SIMPLE SPEND_TYPE = SPEND_SIMPLE; } } else { ; } // simple spend (less than balance) if(SPEND_TYPE == SPEND_SIMPLE) { List<UTXO> _utxos = utxos; // sort in ascending order by value Collections.sort(_utxos, new UTXO.UTXOComparator()); Collections.reverse(_utxos); // get smallest 1 UTXO > than spend + fee + dust for(UTXO u : _utxos) { if(u.getValue() >= (amount + SamouraiWallet.bDust.longValue() + FeeUtil.getInstance().estimatedFee(1, 2).longValue())) { selectedUTXO.add(u); totalValueSelected += u.getValue(); // Log.d("SendActivity", "spend type:" + SPEND_TYPE); // Log.d("SendActivity", "single output"); // Log.d("SendActivity", "amount:" + amount); // Log.d("SendActivity", "value selected:" + u.getValue()); // Log.d("SendActivity", "total value selected:" + totalValueSelected); // Log.d("SendActivity", "nb inputs:" + u.getOutpoints().size()); break; } } if(selectedUTXO.size() == 0) { // sort in descending order by value Collections.sort(_utxos, new UTXO.UTXOComparator()); int selected = 0; // get largest UTXOs > than spend + fee + dust for(UTXO u : _utxos) { selectedUTXO.add(u); totalValueSelected += u.getValue(); selected += u.getOutpoints().size(); // Log.d("SendActivity", "value selected:" + u.getValue()); // Log.d("SendActivity", "total value selected/threshold:" + totalValueSelected + "/" + (amount + SamouraiWallet.bDust.longValue() + FeeUtil.getInstance().estimatedFee(selected, 2).longValue())); if(totalValueSelected >= (amount + SamouraiWallet.bDust.longValue() + FeeUtil.getInstance().estimatedFee(selected, 2).longValue())) { // Log.d("SendActivity", "spend type:" + SPEND_TYPE); // Log.d("SendActivity", "multiple outputs"); // Log.d("SendActivity", "amount:" + amount); // Log.d("SendActivity", "total value selected:" + totalValueSelected); // Log.d("SendActivity", "nb inputs:" + selected); break; } } } } else if(pair != null) { selectedUTXO.clear(); receivers.clear(); long inputAmount = 0L; long outputAmount = 0L; for(MyTransactionOutPoint outpoint : pair.getLeft()) { UTXO u = new UTXO(); List<MyTransactionOutPoint> outs = new ArrayList<MyTransactionOutPoint>(); outs.add(outpoint); u.setOutpoints(outs); totalValueSelected += u.getValue(); selectedUTXO.add(u); inputAmount += u.getValue(); } for(TransactionOutput output : pair.getRight()) { try { Script script = new Script(output.getScriptBytes()); receivers.put(script.getToAddress(MainNetParams.get()).toString(), BigInteger.valueOf(output.getValue().longValue())); outputAmount += output.getValue().longValue(); } catch(Exception e) { Toast.makeText(SendActivity.this, R.string.error_bip126_output, Toast.LENGTH_SHORT).show(); return; } } change = outputAmount - amount; fee = BigInteger.valueOf(inputAmount - outputAmount); } else { Toast.makeText(SendActivity.this, R.string.cannot_select_utxo, Toast.LENGTH_SHORT).show(); return; } // do spend here if(selectedUTXO.size() > 0) { // estimate fee for simple spend, already done if BIP126 if(SPEND_TYPE == SPEND_SIMPLE) { fee = FeeUtil.getInstance().estimatedFee(selectedUTXO.size(), 2); } // Log.d("SendActivity", "spend type:" + SPEND_TYPE); // Log.d("SendActivity", "amount:" + amount); // Log.d("SendActivity", "total value selected:" + totalValueSelected); // Log.d("SendActivity", "fee:" + fee.longValue()); // Log.d("SendActivity", "nb inputs:" + selectedUTXO.size()); change = totalValueSelected - (amount + fee.longValue()); // Log.d("SendActivity", "change:" + change); boolean changeIsDust = false; if(change < SamouraiWallet.bDust.longValue() && SPEND_TYPE == SPEND_SIMPLE) { change = 0L; fee = fee.add(BigInteger.valueOf(change)); amount = totalValueSelected - fee.longValue(); // Log.d("SendActivity", "fee:" + fee.longValue()); // Log.d("SendActivity", "change:" + change); // Log.d("SendActivity", "amount:" + amount); receivers.put(address, BigInteger.valueOf(amount)); changeIsDust = true; } final long _change = change; final BigInteger _fee = fee; final int _change_index = change_index; String dest = null; if(strPCode != null && strPCode.length() > 0) { dest = BIP47Meta.getInstance().getDisplayLabel(strPCode); } else { dest = address; } String strPrivacyWarning = null; if(SendAddressUtil.getInstance().get(address) == 1) { strPrivacyWarning = getString(R.string.send_privacy_warning) + "\n\n"; } else { strPrivacyWarning = ""; } String strChangeIsDust = null; if(changeIsDust) { strChangeIsDust = getString(R.string.change_is_dust) + "\n\n"; } else { strChangeIsDust = ""; } String message = strChangeIsDust + strPrivacyWarning + "Send " + Coin.valueOf(amount).toPlainString() + " to " + dest + " (fee:" + Coin.valueOf(_fee.longValue()).toPlainString() + ")?"; final long _amount = amount; AlertDialog.Builder builder = new AlertDialog.Builder(SendActivity.this); builder.setTitle(R.string.app_name); builder.setMessage(message); builder.setCancelable(false); builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, int whichButton) { final ProgressDialog progress = new ProgressDialog(SendActivity.this); progress.setCancelable(false); progress.setTitle(R.string.app_name); progress.setMessage(getString(R.string.please_wait_sending)); progress.show(); List<MyTransactionOutPoint> outPoints = new ArrayList<MyTransactionOutPoint>(); for(UTXO u : selectedUTXO) { outPoints.addAll(u.getOutpoints()); } // add change if(_change > 0L) { if(SPEND_TYPE == SPEND_SIMPLE) { try { String change_address = HD_WalletFactory.getInstance(SendActivity.this).get().getAccount(0).getChange().getAddressAt(HD_WalletFactory.getInstance(SendActivity.this).get().getAccount(0).getChange().getAddrIdx()).getAddressString(); receivers.put(change_address, BigInteger.valueOf(_change)); } catch(IOException ioe) { ; } catch(MnemonicException.MnemonicLengthException mle) { ; } } else if (SPEND_TYPE == SPEND_BIP126) { // do nothing, change addresses included } else { ; } } // make tx Transaction tx = SendFactory.getInstance(SendActivity.this).makeTransaction(0, outPoints, receivers); if(tx != null) { tx = SendFactory.getInstance(SendActivity.this).signTransaction(tx); final String hexTx = new String(Hex.encode(tx.bitcoinSerialize())); // Log.d("SendActivity", hexTx); new Thread(new Runnable() { @Override public void run() { Looper.prepare(); boolean isOK = false; String response = null; try { // response = WebUtil.getInstance(null).postURL(WebUtil.BLOCKCHAIN_DOMAIN + "pushtx", "tx=" + hexTx); // Log.d("SendActivity", "pushTx:" + response); response = PushTx.getInstance(SendActivity.this).samourai(hexTx); // Log.d("SendActivity", "pushTx:" + response); org.json.JSONObject jsonObject = new org.json.JSONObject(response); if(jsonObject.has("status")) { if(jsonObject.getString("status").equals("ok")) { isOK = true; } } if(isOK) { Toast.makeText(SendActivity.this, R.string.tx_sent, Toast.LENGTH_SHORT).show(); if(_change > 0L && SPEND_TYPE == SPEND_SIMPLE) { try { HD_WalletFactory.getInstance(SendActivity.this).get().getAccount(0).getChange().incAddrIdx(); } catch(IOException ioe) { ; } catch(MnemonicException.MnemonicLengthException mle) { ; } } // increment counter if BIP47 spend if(strPCode != null && strPCode.length() > 0) { BIP47Meta.getInstance().getPCode4AddrLookup().put(address, strPCode); BIP47Meta.getInstance().inc(strPCode); SimpleDateFormat sd = new SimpleDateFormat("dd MMM"); String strTS = sd.format(System.currentTimeMillis()); String event = strTS + " " + SendActivity.this.getString(R.string.sent) + " " + MonetaryUtil.getInstance().getBTCFormat().format((double) _amount / 1e8) + " BTC"; BIP47Meta.getInstance().setLatestEvent(strPCode, event); strPCode = null; } SendAddressUtil.getInstance().add(address, true); Intent intent = new Intent("com.samourai.wallet.BalanceFragment.REFRESH"); intent.putExtra("notifTx", false); intent.putExtra("fetch", true); LocalBroadcastManager.getInstance(SendActivity.this).sendBroadcast(intent); View view = SendActivity.this.getCurrentFocus(); if (view != null) { InputMethodManager imm = (InputMethodManager)SendActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(view.getWindowToken(), 0); } if(bViaMenu) { SendActivity.this.finish(); } else { Intent _intent = new Intent(SendActivity.this, BalanceActivity.class); _intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP); startActivity(_intent); } } else { Toast.makeText(SendActivity.this, R.string.tx_failed, Toast.LENGTH_SHORT).show(); // reset change index upon tx fail HD_WalletFactory.getInstance(SendActivity.this).get().getAccount(0).getChange().setAddrIdx(_change_index); } } catch(Exception e) { // Log.d("SendActivity", e.getMessage()); Toast.makeText(SendActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); } finally { SendActivity.this.runOnUiThread(new Runnable() { @Override public void run() { btSend.setActivated(true); btSend.setClickable(true); progress.dismiss(); dialog.dismiss(); } }); } Looper.loop(); } }).start(); } else { // Log.d("SendActivity", "tx error"); Toast.makeText(SendActivity.this, "tx error", Toast.LENGTH_SHORT).show(); } } }); builder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, int whichButton) { try { // reset change index upon 'NO' HD_WalletFactory.getInstance(SendActivity.this).get().getAccount(0).getChange().setAddrIdx(_change_index); // Log.d("SendActivity", "resetting change index:" + _change_index); } catch(Exception e) { // Log.d("SendActivity", e.getMessage()); Toast.makeText(SendActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); } finally { SendActivity.this.runOnUiThread(new Runnable() { @Override public void run() { btSend.setActivated(true); btSend.setClickable(true); dialog.dismiss(); } }); } } }); AlertDialog alert = builder.create(); alert.show(); } } }); Bundle extras = getIntent().getExtras(); if(extras != null) { bViaMenu = extras.getBoolean("via_menu", false); String strUri = extras.getString("uri"); strPCode = extras.getString("pcode"); if(strUri != null && strUri.length() > 0) { processScan(strUri); } if(strPCode != null && strPCode.length() > 0) { processPCode(strPCode); } } validateSpend(); } @Override public void onResume() { super.onResume(); AppUtil.getInstance(SendActivity.this).checkTimeOut(); } @Override public void onPause() { super.onPause(); } @Override public void onDestroy() { SendActivity.this.getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); super.onDestroy(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); menu.findItem(R.id.action_settings).setVisible(false); menu.findItem(R.id.action_sweep).setVisible(false); menu.findItem(R.id.action_backup).setVisible(false); menu.findItem(R.id.action_refresh).setVisible(false); menu.findItem(R.id.action_share_receive).setVisible(false); menu.findItem(R.id.action_tor).setVisible(false); return super.onCreateOptionsMenu(menu); } @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(); // noinspection SimplifiableIfStatement if (id == R.id.action_scan_qr) { doScan(); } else if (id == R.id.action_ricochet) { Intent intent = new Intent(SendActivity.this, RicochetActivity.class); startActivity(intent); } else { ; } return super.onOptionsItemSelected(item); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if(resultCode == Activity.RESULT_OK && requestCode == SCAN_QR) { if(data != null && data.getStringExtra(ZBarConstants.SCAN_RESULT) != null) { final String strResult = data.getStringExtra(ZBarConstants.SCAN_RESULT); processScan(strResult); } } else if(resultCode == Activity.RESULT_CANCELED && requestCode == SCAN_QR) { ; } else if(resultCode == Activity.RESULT_OK && requestCode == RICOCHET) { ; } else if(resultCode == Activity.RESULT_CANCELED && requestCode == RICOCHET) { ; } else { ; } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK) { if(bViaMenu) { SendActivity.this.finish(); } else { Intent _intent = new Intent(SendActivity.this, BalanceActivity.class); _intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP); startActivity(_intent); } return true; } else { ; } return false; } private void doScan() { Intent intent = new Intent(SendActivity.this, ZBarScannerActivity.class); intent.putExtra(ZBarConstants.SCAN_MODES, new int[]{ Symbol.QRCODE } ); startActivityForResult(intent, SCAN_QR); } private void processScan(String data) { if(FormatsUtil.getInstance().isValidPaymentCode(data)) { processPCode(data); return; } if(data.indexOf("?") != -1) { String pcode = data.substring(0, data.indexOf("?")); if(FormatsUtil.getInstance().isValidPaymentCode(pcode)) { processPCode(data); return; } } if(FormatsUtil.getInstance().isBitcoinUri(data)) { String address = FormatsUtil.getInstance().getBitcoinAddress(data); String amount = FormatsUtil.getInstance().getBitcoinAmount(data); edAddress.setText(address); if(amount != null) { try { NumberFormat btcFormat = NumberFormat.getInstance(new Locale("en", "US")); btcFormat.setMaximumFractionDigits(8); btcFormat.setMinimumFractionDigits(1); edAmountBTC.setText(btcFormat.format(Double.parseDouble(amount) / 1e8)); } catch (NumberFormatException nfe) { edAmountBTC.setText("0.0"); } } PrefsUtil.getInstance(SendActivity.this).setValue(PrefsUtil.BTC_UNITS, MonetaryUtil.UNIT_BTC); tvFiatSymbol.setText(getDisplayUnits() + "-" + strFiat); final String strAmount; DecimalFormat df = new DecimalFormat(" df.setMinimumIntegerDigits(1); df.setMinimumFractionDigits(1); df.setMaximumFractionDigits(8); strAmount = Coin.valueOf(balance).toPlainString(); tvMax.setText(strAmount + " " + getDisplayUnits()); try { if(amount != null && Double.parseDouble(amount) != 0.0) { edAddress.setEnabled(false); edAmountBTC.setEnabled(false); edAmountFiat.setEnabled(false); // Toast.makeText(SendActivity.this, R.string.no_edit_BIP21_scan, Toast.LENGTH_SHORT).show(); } } catch (NumberFormatException nfe) { edAmountBTC.setText("0.0"); } } else if(FormatsUtil.getInstance().isValidBitcoinAddress(data)) { edAddress.setText(data); } else { Toast.makeText(SendActivity.this, R.string.scan_error, Toast.LENGTH_SHORT).show(); } validateSpend(); } private void processPCode(String data) { if(FormatsUtil.getInstance().isValidPaymentCode(data)) { if(BIP47Meta.getInstance().getOutgoingStatus(data) == BIP47Meta.STATUS_SENT_CFM) { try { PaymentCode pcode = new PaymentCode(data); PaymentAddress paymentAddress = BIP47Util.getInstance(SendActivity.this).getSendAddress(pcode, BIP47Meta.getInstance().getOutgoingIdx(data)); strDestinationBTCAddress = paymentAddress.getSendECKey().toAddress(MainNetParams.get()).toString(); strPCode = pcode.toString(); edAddress.setText(BIP47Meta.getInstance().getDisplayLabel(pcode.toString())); edAddress.setEnabled(false); } catch(Exception e) { Toast.makeText(SendActivity.this, R.string.error_payment_code, Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(SendActivity.this, "Payment must be added and notification tx sent", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(SendActivity.this, R.string.invalid_payment_code, Toast.LENGTH_SHORT).show(); } } private void validateSpend() { boolean isValid = false; boolean insufficientFunds = false; double btc_amount = 0.0; try { btc_amount = NumberFormat.getInstance(new Locale("en", "US")).parse(edAmountBTC.getText().toString().trim()).doubleValue(); // Log.i("SendFragment", "amount entered:" + btc_amount); } catch (NumberFormatException nfe) { btc_amount = 0.0; } catch (ParseException pe) { btc_amount = 0.0; } final double dAmount; int unit = PrefsUtil.getInstance(SendActivity.this).getValue(PrefsUtil.BTC_UNITS, MonetaryUtil.UNIT_BTC); switch (unit) { case MonetaryUtil.MICRO_BTC: dAmount = btc_amount / 1000000.0; break; case MonetaryUtil.MILLI_BTC: dAmount = btc_amount / 1000.0; break; default: dAmount = btc_amount; break; } // Log.i("SendFragment", "amount entered (converted):" + dAmount); final long amount = (long)(Math.round(dAmount * 1e8)); // Log.i("SendFragment", "amount entered (converted to long):" + amount); // Log.i("SendFragment", "balance:" + balance); if(amount > balance) { insufficientFunds = true; } // Log.i("SendFragment", "insufficient funds:" + insufficientFunds); if(btc_amount > 0.00 && FormatsUtil.getInstance().isValidBitcoinAddress(edAddress.getText().toString())) { isValid = true; } else if(btc_amount > 0.00 && strDestinationBTCAddress != null && FormatsUtil.getInstance().isValidBitcoinAddress(strDestinationBTCAddress)) { isValid = true; } else { isValid = false; } if(!isValid || insufficientFunds) { btSend.setVisibility(View.INVISIBLE); } else { btSend.setVisibility(View.VISIBLE); } } public String getDisplayUnits() { return (String) MonetaryUtil.getInstance().getBTCUnits()[PrefsUtil.getInstance(SendActivity.this).getValue(PrefsUtil.BTC_UNITS, MonetaryUtil.UNIT_BTC)]; } }
package com.support.design; import android.app.Application; import com.facebook.drawee.backends.pipeline.Fresco; import com.facebook.imagepipeline.backends.okhttp.OkHttpImagePipelineConfigFactory; import com.facebook.imagepipeline.core.ImagePipelineConfig; import com.squareup.okhttp.OkHttpClient; import com.support.design.common.Flog; public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); // FlogLog if (BuildConfig.DEBUG) { Flog.DebugTree tree = new Flog.DebugTree(); tree.setShowLine(false); Flog.plant(tree); } //Fresco ImagePipelineConfig config = OkHttpImagePipelineConfigFactory .newBuilder(this, new OkHttpClient()) .build(); Fresco.initialize(this, config); } }
package com.surgenews.surge; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; 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.ViewPager; import android.view.View; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { DemoCollectionPagerAdapter mDemoCollectionPagerAdapter; ViewPager mViewPager; TabLayout mTabLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.setDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); mDemoCollectionPagerAdapter = new DemoCollectionPagerAdapter(getSupportFragmentManager()); // Set up the ViewPager, attaching the adapter. mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(mDemoCollectionPagerAdapter); mTabLayout = (TabLayout) findViewById(R.id.tabs); mTabLayout.setupWithViewPager(mViewPager); } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @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. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.nav_camera) { // Handle the camera action } else if (id == R.id.nav_gallery) { } else if (id == R.id.nav_slideshow) { } else if (id == R.id.nav_manage) { } else if (id == R.id.nav_share) { } else if (id == R.id.nav_send) { } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } /** * A {@link android.support.v4.app.FragmentStatePagerAdapter} that returns a fragment * representing an object in the collection. */ public static class DemoCollectionPagerAdapter extends FragmentStatePagerAdapter { public DemoCollectionPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int i) { Fragment fragment; if(i == 0){ fragment = new ListenFragment(); Bundle args = new Bundle(); args.putInt(ListenFragment.ARG_OBJECT, i + 1); fragment.setArguments(args); } else { fragment = new ReadFragment(); Bundle args = new Bundle(); args.putInt(ReadFragment.ARG_OBJECT, i + 1); fragment.setArguments(args); } return fragment; } @Override public int getCount() { return 2; } @Override public CharSequence getPageTitle(int position) { if(position == 0){ return "Listen"; } else { return "Read"; } } } }
package cz.tmapy.android.trex; import android.app.ActivityManager; import android.app.AlertDialog; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.res.Configuration; import android.location.Location; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.content.LocalBroadcastManager; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.CompoundButton; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import android.widget.ToggleButton; import org.acra.ACRA; import java.text.SimpleDateFormat; import cz.tmapy.android.trex.database.TrackDataSource; import cz.tmapy.android.trex.database.dobs.TrackDob; import cz.tmapy.android.trex.drawer.DrawerItemCustomAdapter; import cz.tmapy.android.trex.drawer.ObjectDrawerItem; import cz.tmapy.android.trex.service.BackgroundLocationService; import cz.tmapy.android.trex.update.Updater; public class MainScreen extends AppCompatActivity implements SharedPreferences.OnSharedPreferenceChangeListener { private static final String TAG = MainScreen.class.getName(); private String[] mNavigationDrawerItemTitles; private ListView mNavigationDrawerList; private DrawerLayout mNavigationDrawerLayout; private ArrayAdapter<String> mAdapter; private ActionBarDrawerToggle mDrawerToggle; private String mActivityTitle; private String mTargetServerURL; private String mDeviceId; private Boolean mKeepScreenOn; //members for state saving private Boolean mLocalizationIsRunning = false; private String mLastLocationTime; private String mAccuracy; private String mLastLocationAlt; private String mLastLocationSpeed; private String mAddress; private String mLastServerResponse; private String mDistance; private String mDuration; TrackDataSource trackDataSource; SharedPreferences sharedPref; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_screen); trackDataSource = new TrackDataSource(MainScreen.this); sharedPref = PreferenceManager.getDefaultSharedPreferences(this); sharedPref.registerOnSharedPreferenceChangeListener(this); //to get pref changes to onSharePreferenceChanged mDeviceId = sharedPref.getString(Const.PREF_KEY_DEVICE_ID, ""); mTargetServerURL = sharedPref.getString(Const.PREF_KEY_TARGET_SERVUER_URL, ""); mKeepScreenOn = sharedPref.getBoolean(Const.PREF_KEY_KEEP_SCREEN_ON, false); HandleKeepScreenOn(); mNavigationDrawerItemTitles = getResources().getStringArray(R.array.drawer_menu); mNavigationDrawerList = (ListView) findViewById(R.id.navList); mNavigationDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mActivityTitle = getTitle().toString(); addDrawerItems(); setupDrawer(); final ToggleButton toggle = (ToggleButton) findViewById(R.id.toggle_start); toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { if (!mLocalizationIsRunning) { Boolean startSuccess = startSending(); if (!startSuccess) //cancel toggle switch when service' start is not successful toggle.setChecked(false); } } else stopSending(); } }); //Registrace broadcastreceiveru komunikaci se sluzbou (musi byt tady, aby fungoval i po nove inicializaci aplikace z notifikace // The filter's action is BROADCAST_ACTION IntentFilter mIntentFilter = new IntentFilter(Const.LOCATION_BROADCAST); // Instantiates a new mPositionReceiver NewPositionReceiver mPositionReceiver = new NewPositionReceiver(); // Registers the mPositionReceiver and its intent filters LocalBroadcastManager.getInstance(this).registerReceiver(mPositionReceiver, mIntentFilter); mLocalizationIsRunning = isServiceRunning(BackgroundLocationService.class); if (mLocalizationIsRunning) { RestoreGUIFromPreferences(); toggle.setChecked(true); } // 1) localization is not running - activity was not executed from service // 2) savedInstanceState is null - it is not change of device orientation (saved bundle doesn't exists) // 3) automatic check for update is enabled if (!mLocalizationIsRunning && savedInstanceState == null && sharedPref.getBoolean("pref_check4update", true)) new Updater(MainScreen.this).execute(); //ACRA.getErrorReporter().putCustomData("myKey", "myValue"); //ACRA.getErrorReporter().handleException(new Exception("Test exception")); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); } /** * Check service is running * * @param serviceClass * @return */ private boolean isServiceRunning(Class<?> serviceClass) { ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { if (serviceClass.getName().equals(service.service.getClassName())) { return true; } } return false; } private void addDrawerItems() { ObjectDrawerItem[] drawerItem = new ObjectDrawerItem[4]; drawerItem[0] = new ObjectDrawerItem(R.drawable.ic_action_settings, mNavigationDrawerItemTitles[0]); drawerItem[1] = new ObjectDrawerItem(R.drawable.ic_action_help, mNavigationDrawerItemTitles[1]); drawerItem[2] = new ObjectDrawerItem(R.drawable.ic_action_refresh, mNavigationDrawerItemTitles[2]); drawerItem[3] = new ObjectDrawerItem(R.drawable.ic_action_about, mNavigationDrawerItemTitles[3]); DrawerItemCustomAdapter adapter = new DrawerItemCustomAdapter(this, R.layout.listview_item_row, drawerItem); mNavigationDrawerList.setAdapter(adapter); mNavigationDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // Highlight the selected item mNavigationDrawerList.setItemChecked(position, true); DrawerItemClick(position); mNavigationDrawerList.setSelection(position); //and close the drawer mNavigationDrawerLayout.closeDrawer(mNavigationDrawerList); } }); } /** * Handle clik on navigation drawer item * * @param position */ private void DrawerItemClick(int position) { switch (position) { case 0: Intent intent = new Intent(getApplicationContext(), Settings.class); startActivity(intent); break; case 1: startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(Const.HELP_SITE_URL))); break; case 2: new Updater(MainScreen.this).execute(); break; case 3: showAbout(); break; default: Toast.makeText(MainScreen.this, "I'm sorry - not implemented!", Toast.LENGTH_SHORT).show(); break; } } /** * Shows about dialog */ protected void showAbout() { // Inflate the about message contents View messageView = getLayoutInflater().inflate(R.layout.about_dialog, null, false); messageView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { new AlertDialog.Builder(MainScreen.this) .setTitle(R.string.test_exception) .setMessage(R.string.test_exception_message) .setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { ACRA.getErrorReporter().handleException(new Exception("TEST EXCEPTION")); } }) .setNegativeButton(android.R.string.no, null).show(); return true; } }); PackageInfo pInfo = null; try { pInfo = getPackageManager().getPackageInfo(getApplicationContext().getPackageName(), 0); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setIcon(R.drawable.trainers); builder.setTitle(getResources().getString(R.string.app_name) + " " + pInfo.versionName); builder.setView(messageView); builder.create(); builder.show(); } catch (PackageManager.NameNotFoundException e) { Log.e(TAG, "Package name not found", e); } } private void setupDrawer() { mDrawerToggle = new ActionBarDrawerToggle(this, mNavigationDrawerLayout, R.string.drawer_open, R.string.drawer_close) { /** Called when a drawer has settled in a completely open state. */ public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); getSupportActionBar().setTitle(R.string.drawer_title); invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } /** Called when a drawer has settled in a completely closed state. */ public void onDrawerClosed(View view) { super.onDrawerClosed(view); getSupportActionBar().setTitle(mActivityTitle); invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } }; mDrawerToggle.setDrawerIndicatorEnabled(true); mNavigationDrawerLayout.setDrawerListener(mDrawerToggle); } @Override public void onSharedPreferenceChanged(SharedPreferences prefs, String key) { switch (key) { case Const.PREF_KEY_DEVICE_ID: mDeviceId = prefs.getString(key, ""); break; case Const.PREF_KEY_TARGET_SERVUER_URL: mTargetServerURL = prefs.getString(key, ""); break; case Const.PREF_KEY_KEEP_SCREEN_ON: mKeepScreenOn = prefs.getBoolean(key, false); HandleKeepScreenOn(); break; } } /** * Handle "keep screen on" flag */ private void HandleKeepScreenOn() { if (mKeepScreenOn) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } else //remove flag, if any getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } @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(); // Pass the event to ActionBarDrawerToggle, if it returns // true, then it has handled the app icon touch event if (mDrawerToggle.onOptionsItemSelected(item)) { return true; } return super.onOptionsItemSelected(item); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the drawer toggle state after onRestoreInstanceState has occurred. mDrawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); mDrawerToggle.onConfigurationChanged(newConfig); } /** * Start localizing and sending */ public Boolean startSending() { if (!mTargetServerURL.isEmpty()) { if (!mDeviceId.isEmpty()) { if (!mLocalizationIsRunning) { //Nastartovani sluzby ComponentName comp = new ComponentName(getApplicationContext().getPackageName(), BackgroundLocationService.class.getName()); ComponentName service = getApplicationContext().startService(new Intent().setComponent(comp)); if (null != service) { resetGUI(); mLocalizationIsRunning = true; return true; } // something really wrong here Toast.makeText(this, R.string.localiz_could_not_start, Toast.LENGTH_SHORT).show(); if (Const.LOG_BASIC) Log.e(TAG, "Could not start localization service " + comp.toString()); } else { Toast.makeText(this, R.string.localiz_run, Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(this, R.string.set_device_id, Toast.LENGTH_LONG).show(); if (Const.LOG_BASIC) Log.e(TAG, "Device identifier is not setted"); } } else { Toast.makeText(this, R.string.set_target_url, Toast.LENGTH_LONG).show(); if (Const.LOG_BASIC) Log.e(TAG, "Target server URL is not setted"); } mLocalizationIsRunning = false; return false; } /** * Switch off sending */ public void stopSending() { if (mLocalizationIsRunning) { ComponentName comp = new ComponentName(getApplicationContext().getPackageName(), BackgroundLocationService.class.getName()); getApplicationContext().stopService(new Intent().setComponent(comp)); } else Toast.makeText(this, R.string.localiz_not_run, Toast.LENGTH_SHORT).show(); mLocalizationIsRunning = false; } private void resetGUI() { TextView dateText = (TextView) findViewById(R.id.text_position_date); dateText.setText(null); TextView durationText = (TextView) findViewById(R.id.text_duration); durationText.setText(null); TextView accuText = (TextView) findViewById(R.id.text_position_accuracy); accuText.setText(null); TextView distText = (TextView) findViewById(R.id.text_distance); distText.setText(null); TextView altText = (TextView) findViewById(R.id.text_position_alt); altText.setText(null); TextView speedText = (TextView) findViewById(R.id.text_position_speed); speedText.setText(null); TextView addressText = (TextView) findViewById(R.id.text_address); addressText.setText(null); TextView respText = (TextView) findViewById(R.id.text_http_response); respText.setText(null); } /** * This class uses the BroadcastReceiver framework to detect and handle new postition messages from * the service */ private class NewPositionReceiver extends BroadcastReceiver { // prevents instantiation by other packages. private NewPositionReceiver() { } /** * This method is called by the system when a broadcast Intent is matched by this class' * intent filters * * @param context * @param intent */ @Override public void onReceive(Context context, Intent intent) { Location location = (Location) intent.getExtras().get(Const.POSITION); if (location != null) { //2014-06-28T15:07:59 mLastLocationTime = new SimpleDateFormat("HH:mm:ss").format(location.getTime()); mLastLocationAlt = String.format("%.0f", location.getAltitude()); mLastLocationSpeed = String.format("%.0f", (location.getSpeed() / 1000) * 3600); mAccuracy = String.format("%.1f", location.getAccuracy()); } if (intent.hasExtra(Const.ADDRESS)) { String adr = intent.getStringExtra(Const.ADDRESS); if (adr != null) mAddress = adr; } if (intent.hasExtra(Const.DURATION)) { Long d = intent.getLongExtra(Const.DURATION, 0l) / 1000; mDuration = String.format("%d:%02d:%02d", d / 3600, (d % 3600) / 60, (d % 60)); } if (intent.hasExtra(Const.DISTANCE)) mDistance = String.format("%.2f", (intent.getFloatExtra(Const.DISTANCE, 0.0f) / 1000)); mLastServerResponse = intent.getStringExtra(Const.SERVER_RESPONSE); UpdateGUI(); //if this is final broadcast if (intent.hasExtra(Const.FINISH_TIME)) { TrackDob trackDob = new TrackDob(); trackDob.setStartTime(intent.getLongExtra(Const.START_TIME, 0l)); trackDob.setStartLat(intent.getDoubleExtra(Const.START_LAT, 0d)); trackDob.setStartLon(intent.getDoubleExtra(Const.START_LON, 0d)); trackDob.setStartAddress(intent.getStringExtra(Const.ADDRESS)); trackDob.setFinishTime(intent.getLongExtra(Const.FINISH_TIME, 0l)); trackDob.setFinishLat(intent.getDoubleExtra(Const.FINISH_LAT, 0d)); trackDob.setFinishLon(intent.getDoubleExtra(Const.FINISH_LON, 0d)); trackDob.setFinishAddress(intent.getStringExtra(Const.FINISH_ADDRESS)); trackDob.setDistance(intent.getFloatExtra(Const.DISTANCE, 0f)); trackDob.setMaxSpeed(intent.getFloatExtra(Const.MAX_SPEED, 0f)); trackDob.setAveSpeed(intent.getFloatExtra(Const.AVE_SPEED, 0f)); trackDob.setMinAlt(intent.getDoubleExtra(Const.MIN_ALT, 0d)); trackDob.setMaxAlt(intent.getDoubleExtra(Const.MAX_ALT, 0d)); trackDob.setElevDiffUp(intent.getFloatExtra(Const.ELEV_DIFF_UP, 0f)); trackDob.setElevDiffDown(intent.getFloatExtra(Const.ELEV_DIFF_DOWN, 0f)); trackDob.setNote("ěščřžýáíé"); trackDataSource.saveTrack(trackDob); } } } private void UpdateGUI() { TextView dateText = (TextView) findViewById(R.id.text_position_date); dateText.setText(mLastLocationTime); if (mDuration != null) { TextView durationText = (TextView) findViewById(R.id.text_duration); durationText.setText(mDuration); } if (mAccuracy != null) { TextView accuracy = (TextView) findViewById(R.id.text_position_accuracy); accuracy.setText(mAccuracy + " m"); } if (mDistance != null) { TextView estDist = (TextView) findViewById(R.id.text_distance); estDist.setText(mDistance + " km"); } if (mLastLocationSpeed != null) { TextView speedText = (TextView) findViewById(R.id.text_position_speed); speedText.setText(mLastLocationSpeed + " km/h"); } if (mLastLocationAlt != null) { TextView altText = (TextView) findViewById(R.id.text_position_alt); altText.setText(mLastLocationAlt + " m"); } if (mAddress != null) { TextView address = (TextView) findViewById(R.id.text_address); address.setText(mAddress); } if (mLastServerResponse != null) { TextView httpRespText = (TextView) findViewById(R.id.text_http_response); httpRespText.setText(mLastServerResponse); } } @Override public void onSaveInstanceState(Bundle savedInstanceState) { super.onSaveInstanceState(savedInstanceState); if (mLocalizationIsRunning) { // Save the user's current state if (mLastLocationTime != null) savedInstanceState.putString(Const.LOCATION_TIME, mLastLocationTime); if (mAccuracy != null) savedInstanceState.putString(Const.ACCURACY, mAccuracy); if (mDuration != null) savedInstanceState.putString(Const.DURATION, mDuration); if (mDistance != null) savedInstanceState.putString(Const.DISTANCE, mDistance); if (mLastLocationAlt != null) savedInstanceState.putString(Const.ALTITUDE, mLastLocationAlt); if (mLastLocationSpeed != null) savedInstanceState.putString(Const.SPEED, mLastLocationSpeed); if (mAddress != null) savedInstanceState.putString(Const.ADDRESS, mAddress); if (mLastServerResponse != null) savedInstanceState.putString(Const.SERVER_RESPONSE, mLastServerResponse); } } /** * Used when app is restarted with passed state bundle * * @param savedInstanceState */ @Override public void onRestoreInstanceState(Bundle savedInstanceState) { // Restore state members from saved instance mLastLocationTime = savedInstanceState.getString(Const.LOCATION_TIME); mAccuracy = savedInstanceState.getString(Const.ACCURACY); mDuration = savedInstanceState.getString(Const.DURATION); mDistance = savedInstanceState.getString(Const.DISTANCE); mLastLocationAlt = savedInstanceState.getString(Const.ALTITUDE); mLastLocationSpeed = savedInstanceState.getString(Const.SPEED); mAddress = savedInstanceState.getString(Const.ADDRESS); mLastServerResponse = savedInstanceState.getString(Const.SERVER_RESPONSE); UpdateGUI(); super.onRestoreInstanceState(savedInstanceState); //restore after set mLocalizationIsRunning (because of button state) } @Override public void onStop() { super.onStop(); // Always call the superclass method first //store last know position sharedPref.edit().putString(Const.LOCATION_TIME, mLastLocationTime).apply(); sharedPref.edit().putString(Const.ACCURACY, mAccuracy).apply(); sharedPref.edit().putString(Const.DURATION, mDuration).apply(); sharedPref.edit().putString(Const.DISTANCE, mDistance).apply(); sharedPref.edit().putString(Const.ALTITUDE, mLastLocationAlt).apply(); sharedPref.edit().putString(Const.SPEED, mLastLocationSpeed).apply(); sharedPref.edit().putString(Const.ADDRESS, mAddress).apply(); sharedPref.edit().putString(Const.SERVER_RESPONSE, mLastServerResponse).apply(); } /** * Load last state from preferences */ public void RestoreGUIFromPreferences() { mLastLocationTime = sharedPref.getString(Const.LOCATION_TIME, ""); mAccuracy = sharedPref.getString(Const.ACCURACY, ""); mDuration = sharedPref.getString(Const.DURATION, ""); mDistance = sharedPref.getString(Const.DISTANCE, ""); mLastLocationAlt = sharedPref.getString(Const.ALTITUDE, ""); mLastLocationSpeed = sharedPref.getString(Const.SPEED, ""); mAddress = sharedPref.getString(Const.ADDRESS, ""); mLastServerResponse = sharedPref.getString(Const.SERVER_RESPONSE, ""); UpdateGUI(); } }
package mn.devfest.api; import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.util.DiffUtil; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.firebase.auth.AuthCredential; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.GoogleAuthProvider; 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 java.util.ArrayList; import java.util.HashMap; import java.util.List; import mn.devfest.api.model.Conference; import mn.devfest.api.model.Session; import mn.devfest.api.model.Speaker; import mn.devfest.persistence.UserScheduleRepository; import timber.log.Timber; public class DevFestDataSource { private static final String DEVFEST_2017_KEY = "devfest2017"; private static final String SESSIONS_CHILD_KEY = "schedule"; private static final String SPEAKERS_CHILD_KEY = "speakers"; private static final String AGENDAS_KEY = "agendas"; private static DevFestDataSource mOurInstance; private UserScheduleRepository mScheduleRepository; private DatabaseReference mFirebaseDatabaseReference; private FirebaseAuth mFirebaseAuth; private GoogleSignInAccount mGoogleAccount; private Conference mConference = new Conference(); //TODO move to an array of listeners? private DataSourceListener mDataSourceListener; private UserScheduleListener mUserScheduleListener; private ValueEventListener mFirebaseUserScheduleListener; public static DevFestDataSource getInstance(Context context) { if (mOurInstance == null) { mOurInstance = new DevFestDataSource(context); } return mOurInstance; } public DevFestDataSource(Context context) { mScheduleRepository = new UserScheduleRepository(context); //TODO move all firebase access into a separate class and de-duplicate code mFirebaseAuth = FirebaseAuth.getInstance(); mFirebaseDatabaseReference = FirebaseDatabase.getInstance().getReference(); //Get sessions mFirebaseDatabaseReference.child(DEVFEST_2017_KEY) .child(SESSIONS_CHILD_KEY).addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { //Clear the old schedule data out HashMap map = new HashMap<String, Session>(); //Add each new session into the schedule for (DataSnapshot snapshot : dataSnapshot.getChildren()) { Timber.d("Session snapshot is: %s", snapshot.toString()); Session session = snapshot.getValue(Session.class); session.setId(snapshot.getKey()); map.put(session.getId(), session); } mConference.setSchedule(map); if (mDataSourceListener != null) { mDataSourceListener.onSessionsUpdate(new ArrayList<>(map.values())); } } @Override public void onCancelled(DatabaseError databaseError) { // TODO handle failing to read value Timber.e(databaseError.toException(), "Failed to read sessions value."); } }); //Get speakers mFirebaseDatabaseReference.child(DEVFEST_2017_KEY).child(SPEAKERS_CHILD_KEY) .addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { //Clear the old speaker data out HashMap map = new HashMap<String, Session>(); //Add each new speaker into the schedule for (DataSnapshot snapshot : dataSnapshot.getChildren()) { Timber.d("Speaker snapshot is: %s", snapshot.toString()); Speaker speaker = snapshot.getValue(Speaker.class); speaker.setId(snapshot.getKey()); map.put(speaker.getId(), speaker); } mConference.setSpeakers(map); if (mDataSourceListener != null) { mDataSourceListener.onSpeakersUpdate(new ArrayList<>(map.values())); } } @Override public void onCancelled(DatabaseError databaseError) { // TODO handle failing to read value Timber.e(databaseError.toException(), "Failed to read speakers value."); } }); } @NonNull public List<Session> getSessions() { if (mConference == null) { return new ArrayList<>(); } if (mConference.getSchedule() == null) { return new ArrayList<>(); } return new ArrayList<>(mConference.getSchedule().values()); } @Nullable public Session getSessionById(String id) { if (mConference == null) { return null; } return mConference.getSchedule().get(id); } @NonNull public List<Speaker> getSpeakers() { if (mConference == null) { return new ArrayList<>(); } if (mConference.getSpeakers() == null) { return new ArrayList<>(); } return new ArrayList<>(mConference.getSpeakers().values()); } @Nullable public Speaker getSpeakerById(String id) { if (mConference == null) { return null; } return mConference.getSpeakers().get(id); } @NonNull public List<Session> getUserSchedule() { // Find sessions with an ID matching the user's saved session IDs List<Session> sessions = getSessions(); List<Session> userSessions = new ArrayList<>(); if (sessions.size() == 0) { return sessions; } if (mScheduleRepository != null) { // We use a loop that goes backwards so we can remove items as we iterate over the list without // running into a concurrent modification issue or altering the indices of items for (int i = sessions.size() - 1; i >= 0; i Session session = sessions.get(i); if (mScheduleRepository.getScheduleIds().contains(session.getId())) { userSessions.add(session); } } } return userSessions; } /** * Adds the session with the given ID to the user's schedule * * @param sessionId ID of the session to be added */ public void addToUserSchedule(String sessionId) { mScheduleRepository.addSession(sessionId); mDataSourceListener.onUserScheduleUpdate(getUserSchedule()); attemptAddingSessionToFirebase(sessionId); } private void attemptAddingSessionToFirebase(String sessionId) { //We can't sync to Firebase if we aren't logged in if (!haveGoogleAccountAndId()) { //TODO prompt the user intermittently to allow schedule sync return; } //Add the session to the user's schedule in Firebase mFirebaseDatabaseReference.child(DEVFEST_2017_KEY).child(AGENDAS_KEY) .child(mFirebaseAuth.getCurrentUser().getUid()).setValue(sessionId); } /** * Removes the session with the given ID from the user's schedule * * @param sessionId ID of the session to be removed */ public void removeFromUserSchedule(String sessionId) { mScheduleRepository.removeSession(sessionId); mDataSourceListener.onUserScheduleUpdate(getUserSchedule()); attemptRemovingSessionFromFirebase(sessionId); } private void attemptRemovingSessionFromFirebase(String sessionId) { //We can't sync to Firebase if we aren't logged in if (!haveGoogleAccountAndId()) { //TODO prompt the user intermittently to allow schedule sync return; } //Add the session to the user's schedule in Firebase mFirebaseDatabaseReference.child(DEVFEST_2017_KEY).child(AGENDAS_KEY) .child(mFirebaseAuth.getCurrentUser().getUid()).child(sessionId).removeValue(); } private boolean haveGoogleAccountAndId() { return mGoogleAccount != null && mGoogleAccount.getId() != null; } /** * Checks if a given session is in the user's schedule * * @param sessionId ID of the session to check for inclusion in the list * @return true if the session is in the user's schedule; otherwise false */ public boolean isInUserSchedule(String sessionId) { return mScheduleRepository.isInSchedule(sessionId); } public void setDataSourceListener(DataSourceListener listener) { mDataSourceListener = listener; } public void setUserScheduleListener(UserScheduleListener listener) { mUserScheduleListener = listener; } private void onConferenceUpdated() { //Notify listener mDataSourceListener.onSessionsUpdate(getSessions()); mDataSourceListener.onSpeakersUpdate(getSpeakers()); mDataSourceListener.onUserScheduleUpdate(getUserSchedule()); } //TODO de-duplicate diff methods public DiffUtil.DiffResult calculateSessionDiff(final List<Session> oldList, List<Session> newList) { return DiffUtil.calculateDiff(new DiffUtil.Callback() { @Override public int getOldListSize() { return oldList.size(); } @Override public int getNewListSize() { return newList.size(); } @Override public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) { return oldList.get(oldItemPosition).getId().equals(newList.get(newItemPosition).getId()); } @Override public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) { return oldList.get(oldItemPosition).equals(newList.get(newItemPosition)); } }); } public DiffUtil.DiffResult calculateScheduleDiff(final List<Session> sessions, List<Session> oldSchedule, List<Session> newSchedule) { return DiffUtil.calculateDiff(new DiffUtil.Callback() { @Override public int getOldListSize() { return sessions.size(); } @Override public int getNewListSize() { return sessions.size(); } @Override public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) { return oldItemPosition == newItemPosition; } @Override public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) { Session session = sessions.get(oldItemPosition); return oldSchedule.contains(session) == newSchedule.contains(session); } }); } public DiffUtil.DiffResult calculateSpeakerDiff(final List<Speaker> oldList, List<Speaker> newList) { return DiffUtil.calculateDiff(new DiffUtil.Callback() { @Override public int getOldListSize() { return oldList.size(); } @Override public int getNewListSize() { return newList.size(); } @Override public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) { return oldList.get(oldItemPosition).equals(newList.get(newItemPosition)); } @Override public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) { return oldList.get(oldItemPosition).equals(newList.get(newItemPosition)); } }); } public GoogleSignInAccount getGoogleAccount() { return mGoogleAccount; } public void setGoogleAccount(GoogleSignInAccount googleAccount) { //TODO if we're logging into an account, use the schedule if we were logged out and reconcile the schedule if we //If we are removing the Google account, stop listening if (googleAccount == null) { if (mFirebaseUserScheduleListener != null && haveGoogleAccountAndId()) { mFirebaseDatabaseReference.child(DEVFEST_2017_KEY).child(AGENDAS_KEY) .child(mGoogleAccount.getId()) .removeEventListener(mFirebaseUserScheduleListener); } mGoogleAccount = null; return; } if (googleAccount.getId() == null) { throw new IllegalArgumentException("#setGoogleAccount() called without ID. googleAccount = " + googleAccount.toString()); } //If we had no account, or if this new account isn't already being tracked, store in Firebase and track it if (!haveGoogleAccountAndId() || !googleAccount.getId().equals(mGoogleAccount.getId())) { storeAuthInFirebase(googleAccount); mFirebaseUserScheduleListener = mFirebaseDatabaseReference.child(DEVFEST_2017_KEY).child(AGENDAS_KEY) .child(googleAccount.getId()).addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { //Gather all of the session IDs from the user's schedule ArrayList<String> scheduleIds = new ArrayList<>(); for (DataSnapshot snapshot : dataSnapshot.getChildren()) { Timber.d("User schedule snapshot is: %s", snapshot.toString()); String id = snapshot.getValue(String.class); scheduleIds.add(id); } //Update the schedule IDs and send the new user schedule to the listener mScheduleRepository.setScheduleIdStringSet(scheduleIds); if (mUserScheduleListener != null) { mUserScheduleListener.onScheduleUpdate(getUserSchedule()); } } @Override public void onCancelled(DatabaseError databaseError) { Timber.e(databaseError.toException(), "Failed to read user agenda value."); } }); } mGoogleAccount = googleAccount; } private void storeAuthInFirebase(GoogleSignInAccount account) { AuthCredential authCredential = GoogleAuthProvider.getCredential(account.getIdToken(), null); mFirebaseAuth.signInWithCredential(authCredential) .addOnFailureListener(e -> Timber.d(e, "FirebaseAuth login failed")) .addOnCompleteListener(task -> { if (task.isSuccessful()) { Timber.d("FirebaseAuth login successfully completed"); } else { Timber.d("FirebaseAuth login failed"); } }); } public interface UserScheduleListener { void onScheduleUpdate(List<Session> schedule); } //TODO break this into separate listeners /** * Listener for updates from the data source */ public interface DataSourceListener { //These methods are for updating the listener void onSessionsUpdate(List<Session> sessions); void onSpeakersUpdate(List<Speaker> speakers); void onUserScheduleUpdate(List<Session> userSchedule); } }
/* * I2P - An anonymous, secure, and fully-distributed communication network. * * SysTray.java * 2004 The I2P Project * This code is public domain. */ package net.i2p.apps.systray; import java.awt.Frame; import snoozesoft.systray4j.SysTrayMenu; import snoozesoft.systray4j.SysTrayMenuEvent; import snoozesoft.systray4j.SysTrayMenuIcon; import snoozesoft.systray4j.SysTrayMenuItem; import snoozesoft.systray4j.SysTrayMenuListener; /** * A system tray control for launching the I2P router console. * * @author hypercubus */ public class SysTray implements SysTrayMenuListener { private BrowserChooser _browserChooser; private String _browserString; private ConfigFile _configFile = new ConfigFile(); private Frame _frame; private SysTrayMenuItem _itemOpenConsole = new SysTrayMenuItem("Open router console", "openconsole"); private SysTrayMenuItem _itemSelectBrowser = new SysTrayMenuItem("Select browser...", "selectbrowser"); private SysTrayMenuItem _itemShutdown = new SysTrayMenuItem("Shut down I2P router", "shutdown"); private SysTrayMenuIcon _sysTrayMenuIcon = new SysTrayMenuIcon("icons/iggy"); private SysTrayMenu _sysTrayMenu = new SysTrayMenu(_sysTrayMenuIcon, "I2P Control"); private UrlLauncher _urlLauncher = new UrlLauncher(); public SysTray() { if (!_configFile.init("systray.config")) _configFile.setProperty("browser", "default"); _browserString = _configFile.getProperty("browser", "default"); _sysTrayMenuIcon.addSysTrayMenuListener(this); createSysTrayMenu(); } public static void main(String[] args) { if (System.getProperty("os.name").startsWith("Windows")) new SysTray(); } public void iconLeftClicked(SysTrayMenuEvent e) {} public void iconLeftDoubleClicked(SysTrayMenuEvent e) { openRouterConsole(); } public void menuItemSelected(SysTrayMenuEvent e) { String browser = null; if (e.getActionCommand().equals("shutdown")) { _browserChooser = null; _frame = null; _itemShutdown = null; _itemSelectBrowser = null; _sysTrayMenuIcon = null; _sysTrayMenu = null; _browserChooser = null; _frame = null; System.exit(0); } else if (e.getActionCommand().equals("selectbrowser")) { if (!(browser = promptForBrowser("Select browser")).equals("nullnull")) setBrowser(browser); } else if (e.getActionCommand().equals("openconsole")) { openRouterConsole(); } } private void createSysTrayMenu() { _itemShutdown.addSysTrayMenuListener(this); _itemSelectBrowser.addSysTrayMenuListener(this); _itemOpenConsole.addSysTrayMenuListener(this); _sysTrayMenu.addItem(_itemShutdown); _sysTrayMenu.addSeparator(); _sysTrayMenu.addItem(_itemSelectBrowser); _sysTrayMenu.addItem(_itemOpenConsole); } private void openRouterConsole() { String browser = null; if (_browserString == null || _browserString.equals("default")) { try { if (_urlLauncher.openUrl("http://localhost:7657/")) return; } catch (Exception ex) { // Fall through. } } else { try { if (_urlLauncher.openUrl("http://localhost:7657/", _browserString)) return; } catch (Exception ex) { // Fall through. } } if (!(browser = promptForBrowser("Please select another browser")).equals("nullnull")) setBrowser(browser); } private String promptForBrowser(String windowTitle) { String browser = null; _frame = new Frame(); _browserChooser = new BrowserChooser(_frame, windowTitle); browser = _browserChooser.getDirectory() + _browserChooser.getFile(); _browserChooser = null; _frame = null; return browser; } private void setBrowser(String browser) { _browserString = browser; _configFile.setProperty("browser", browser); } }
package cz.muni.fi.pa165.entity; import java.util.Collections; import java.util.Date; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.Temporal; @Entity public class Loan { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(nullable = false) @Temporal(javax.persistence.TemporalType.DATE) private Date loanDate; @Column(nullable = false) private Boolean returned; @Column(nullable = false) @Temporal(javax.persistence.TemporalType.DATE) private Date returnDate; @Column(nullable = false) private BookState returnBookState; @Column(nullable = false) @ManyToOne private Book book; public void setBook(Book book) { this.book = book; } public Book getBook() { return book; } public void setId(Long id){ this.id=id; } public Long getId(){ return this.id; } public void setDate(Date loanDate){ this.loanDate=loanDate; } public Date getDate(){ return this.loanDate; } public Boolean isReturned(){ return this.returned; } public void returnLoan(){ this.returned=true; } public Date getReturnDate(){ return this.returnDate; } public void setReturnDate(Date returnDate){ this.returnDate=returnDate; } public BookState getReturnBookState(){ return this.returnBookState; } public void setReturnBookState(Date returnBookState){ this.returnDate=returnBookState; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((loanDate == null) ? 0 : loanDate.hashCode()); result = prime * result + ((returned == null) ? 0 : returned.hashCode()); result = prime * result + ((returnDate == null) ? 0 : returnDate.hashCode()); result = prime * result + ((returnBookState == null) ? 0 : returnBookState.hashCode()); result = prime * result + ((book == null) ? 0 : book.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof Loan)) { return false; } Loan other = (Loan) obj; if (loanDate == null && other.loanDate != null) { return false; } else if (!loanDate.equals(other.loanDate)){ return false; } if (returned == null && other.returned != null) { return false; } else if(returned!=other.returned){ return false; } if (returnDate == null && other.returnDate != null) { return false; } else if(!returnDate.equals(other.returnDate)){ return false; } if (returnBookState == null && other.returnBookState != null) { return false; } else if(!returnBookState.equals(other.returnBookState)){ return false; } if (book == null && other.book != null) { return false; } else if(!book.equals(other.book)){ return false; } return true; } }
package org.basex.data; import static org.basex.core.Text.*; import static org.basex.data.DataText.*; import java.io.*; import java.util.*; import org.basex.io.in.DataInput; import org.basex.io.out.DataOutput; import org.basex.util.*; import org.basex.util.hash.*; import org.basex.util.list.*; public final class Namespaces { /** Namespace prefixes. */ private final TokenSet prefixes; /** Namespace URIs. */ private final TokenSet uris; /** Root node. */ private final NSNode root; /** Stack with references to current default namespaces. */ private final IntList defaults = new IntList(2); /** Current level. Index starts at 1 (required by XQUF operations). */ private int level = 1; /** Current namespace node. */ private NSNode cursor; /** * Empty constructor. */ public Namespaces() { prefixes = new TokenSet(); uris = new TokenSet(); root = new NSNode(-1); cursor = root; } /** * Constructor, specifying an input stream. * @param in input stream * @throws IOException I/O exception */ Namespaces(final DataInput in) throws IOException { prefixes = new TokenSet(in); uris = new TokenSet(in); root = new NSNode(in, null); cursor = root; } /** * Writes the namespaces to disk. * @param out output stream * @throws IOException I/O exception */ void write(final DataOutput out) throws IOException { prefixes.write(out); uris.write(out); root.write(out); } /** * Returns if no namespaces exist. * Note that the container size does not change if namespaces are deleted. * This function is mainly used to decide namespaces need to be considered in query optimizations. * @return result of check */ public boolean isEmpty() { return uris.isEmpty(); } /** * Returns the number of namespaces that have been stored so far. * @return number of entries */ public int size() { return uris.size(); } /** * Returns a prefix for the specified id. * @param id id of prefix * @return prefix */ public byte[] prefix(final int id) { return prefixes.key(id); } /** * Returns a namespace uri for the specified id. * @param id id of namespace uri * @return namespace uri */ public byte[] uri(final int id) { return uris.key(id); } /** * Returns the default namespace uri for all documents of the database. * @return global default namespace, or {@code null} if there is more than one such namespace */ public byte[] globalUri() { // no namespaces defined: default namespace is empty final int ch = root.children(); if(ch == 0) return Token.EMPTY; // give up if more than one namespace is defined if(ch > 1) return null; // give up if child node has more children or more than one namespace final NSNode child = root.child(0); final int[] values = child.values(); if(child.children() > 0 || child.pre() != 1 || values.length != 2) return null; // give up if namespace has a non-empty prefix if(prefix(values[0]).length != 0) return null; // return default namespace return uri(values[1]); } /** * Returns the id of the specified namespace uri. * @param uri namespace URI * @return id, or {@code 0} if the uri is empty or if no entry is found */ public int uriId(final byte[] uri) { return uri.length == 0 ? 0 : uris.id(uri); } /** * Returns the id of a namespace uri for the specified element/attribute name. * @param name element/attribute name * @param element indicates if this is an element or attribute name * @return id of namespace uri, or {@code 0} if no entry is found */ public int uriId(final byte[] name, final boolean element) { if(isEmpty()) return 0; final byte[] pref = Token.prefix(name); return pref.length != 0 ? uriId(pref, cursor) : element ? defaults.get(level) : 0; } /** * Returns the id of a namespace uri for an element/attribute name and a specific pre value. * @param name element/attribute name * @param pre pre value * @param data data reference * @return id of namespace uri, or {@code 0} if no entry is found */ public int uriId(final byte[] name, final int pre, final Data data) { return uriId(Token.prefix(name), cursor.find(pre, data)); } /** * Returns the id of a namespace uri for the specified prefix and node, * or {@code 0} if no namespace is found. * @param pref prefix * @param node node to start with * @return id of the namespace uri */ private int uriId(final byte[] pref, final NSNode node) { final int prefId = prefixes.id(pref); if(prefId == 0) return 0; NSNode nd = node; while(nd != null) { final int uriId = nd.uri(prefId); if(uriId != 0) return uriId; nd = nd.parent(); } return 0; } /** * Returns all namespace prefixes and uris that are defined for the specified pre value. * Should only be called for element nodes. * @param pre pre value * @param data data reference * @return key and value ids */ public Atts values(final int pre, final Data data) { final Atts as = new Atts(); final int[] values = cursor.find(pre, data).values(); final int nl = values.length; for(int n = 0; n < nl; n += 2) { as.add(prefix(values[n]), uri(values[n + 1])); } return as; } /** * Returns a map with all namespaces that are valid for the specified pre value. * @param pre pre value * @param data data reference * @return scope */ TokenMap scope(final int pre, final Data data) { final TokenMap nsScope = new TokenMap(); NSNode node = cursor; do { final int[] values = node.values(); final int vl = values.length; for(int v = 0; v < vl; v += 2) { nsScope.put(prefix(values[v]), uri(values[v + 1])); } final int pos = node.find(pre); if(pos < 0) break; node = node.child(pos); } while(pre < node.pre() + data.size(node.pre(), Data.ELEM)); return nsScope; } /** * Finds the nearest namespace node on the ancestor axis of the insert * location and sets it as new root. Possible candidates for this node are collected * and the match with the highest pre value between ancestors and candidates * is determined. * @param pre pre value * @param data data reference */ void root(final int pre, final Data data) { // collect possible candidates for namespace root final List<NSNode> cand = new LinkedList<>(); NSNode node = root; cand.add(node); for(int p; (p = node.find(pre)) > -1;) { // add candidate to stack node = node.child(p); cand.add(0, node); } node = root; if(cand.size() > 1) { // compare candidates to ancestors of pre value int ancPre = pre; // take first candidate from stack NSNode curr = cand.remove(0); while(ancPre > -1 && node == root) { // this is the new root if(curr.pre() == ancPre) node = curr; // if the current candidate's pre value is lower than the current // ancestor of par or par itself, we have to look for a potential // match for this candidate. therefore we iterate through ancestors // until we find one with a lower than or the same pre value as the // current candidate. else if(curr.pre() < ancPre) { while((ancPre = data.parent(ancPre, data.kind(ancPre))) > curr.pre()); if(curr.pre() == ancPre) node = curr; } // no potential for infinite loop, because dummy root is always a match, // in this case ancPre ends iteration if(!cand.isEmpty()) curr = cand.remove(0); } } final int uri = uriId(Token.EMPTY, pre, data); defaults.set(level, uri); // remind uri before insert of first node n to connect siblings of n to // according namespace defaults.set(level - 1, uri); cursor = node; } /** * Returns all namespace nodes in the namespace structure with a minimum pre value. * @param pre minimum pre value of a namespace node. * @return list of namespace nodes */ List<NSNode> cache(final int pre) { final List<NSNode> list = new ArrayList<>(); addNsNodes(root, list, pre); return list; } /** * Recursively adds namespace nodes to the given list, starting at the children of the given node. * @param curr current namespace node * @param list list with namespace nodes * @param pre pre value */ private static void addNsNodes(final NSNode curr, final List<NSNode> list, final int pre) { final int sz = curr.children(); int i = find(curr, pre); while(i > 0 && (i == sz || curr.child(i).pre() >= pre)) i for(; i < sz; i++) { final NSNode ch = curr.child(i); if(ch.pre() >= pre) list.add(ch); addNsNodes(ch, list, pre); } } /** * Returns the index of the specified pre value. * @param curr current namespace node * @param pre int pre value * @return index, or possible insertion position */ private static int find(final NSNode curr, final int pre) { // binary search int l = 0, h = curr.children() - 1; while(l <= h) { final int m = l + h >>> 1, c = curr.child(m).pre() - pre; if(c == 0) return m; if(c < 0) l = m + 1; else h = m - 1; } return l; } /** * Sets a namespace cursor. * @param node namespace node */ void current(final NSNode node) { cursor = node; } /** * Returns the current namespace cursor. * @return current namespace node */ NSNode cursor() { return cursor; } /** * Initializes an update operation by increasing the level counter. */ public void open() { final int nu = defaults.get(level); defaults.set(++level, nu); } /** * Adds namespaces to a new namespace node. * @param pre pre value * @param atts namespaces */ public void open(final int pre, final Atts atts) { open(); if(!atts.isEmpty()) { final NSNode node = new NSNode(pre); cursor.add(node); cursor = node; final int as = atts.size(); for(int a = 0; a < as; a++) { final byte[] pref = atts.name(a), uri = atts.value(a); final int prefId = prefixes.put(pref), uriId = uris.put(uri); node.add(prefId, uriId); if(pref.length == 0) defaults.set(level, uriId); } } } /** * Closes a namespace node. * @param pre current pre value */ public void close(final int pre) { while(cursor.pre() >= pre) { final NSNode par = cursor.parent(); if(par == null) break; cursor = par; } --level; } /** * Deletes the specified namespace URI from the root node. * @param uri namespace URI reference */ public void delete(final byte[] uri) { final int id = uris.id(uri); if(id != 0) cursor.delete(id); } /** * Deletes the specified number of entries from the namespace structure. * @param pre pre value of the first node to delete * @param data data reference * @param size number of entries to be deleted */ void delete(final int pre, final int size, final Data data) { NSNode nd = cursor.find(pre, data); if(nd.pre() == pre) nd = nd.parent(); while(nd != null) { nd.delete(pre, size); nd = nd.parent(); } root.decrementPre(pre, size); } /** * Adds a namespace for the specified pre value. * @param pre pre value * @param par parent value * @param pref prefix * @param uri namespace uri * @param data data reference * @return namespace uri id */ public int add(final int pre, final int par, final byte[] pref, final byte[] uri, final Data data) { // don't store XML namespace if(Token.eq(pref, Token.XML)) return 0; final int prefId = prefixes.put(pref), uriId = uris.put(uri); NSNode nd = cursor.find(par, data); if(nd.pre() != pre) { final NSNode child = new NSNode(pre); nd.add(child); nd = child; } nd.add(prefId, uriId); return uriId; } /** * Returns a tabular representation of the namespace entries. * @param start first pre value * @param end last pre value * @return namespaces */ public byte[] table(final int start, final int end) { if(root.children() == 0) return Token.EMPTY; final Table t = new Table(); t.header.add(TABLEID); t.header.add(TABLEPRE); t.header.add(TABLEDIST); t.header.add(TABLEPREF); t.header.add(TABLEURI); for(int i = 0; i < 3; ++i) t.align.add(true); root.table(t, start, end, this); return t.contents.isEmpty() ? Token.EMPTY : t.finish(); } /** * Returns namespace information. * @return info string */ public byte[] info() { final TokenObjMap<TokenList> map = new TokenObjMap<>(); root.info(map, this); final TokenBuilder tb = new TokenBuilder(); for(final byte[] key : map) { tb.add(" "); final TokenList values = map.get(key); values.sort(false); final int ks = values.size(); if(ks > 1 || values.get(0).length != 0) { if(values.size() != 1) tb.add("("); for(int k = 0; k < ks; ++k) { if(k != 0) tb.add(", "); tb.add(values.get(k)); } if(ks != 1) tb.add(")"); tb.add(" = "); } tb.addExt("\"%\"" + NL, key); } return tb.finish(); } /** * Returns a string representation of the namespaces. * @param start start pre value * @param end end pre value * @return string */ public String toString(final int start, final int end) { return root.toString(this, start, end); } @Override public String toString() { return toString(0, Integer.MAX_VALUE); } }
package foam.lib.json; import foam.lib.parse.*; import java.util.Date; /** * Create a second date parser specifically for Properties of type Object that * get set to a Date. We use a "long form" structure like so: * * { * class: '__Timestamp__', * value: 1533135788921 * } * * Instead of simply sending the timestamp: * * 1533135788921 * * or date string: * * "2018-08-01T15:04:31.467Z" * * which would be much more efficient. The reason we can't do that here is * because if you're the server trying to parse the value of an Object property, * you don't know if a long is a timestamp or just a long, or if a string is a * date string or just a string. It's ambiguous. Therefore we have to sacrifice * performance to avoid ambiguity. * * The reason we can use the more efficient formats in other places is that the * server knows that those properties are of type Date and therefore it's not * ambiguous. * * Now that we've proven the need for an unambiguous date parser, why wouldn't * we just replace the original date parser with this one? Why have two? We do * so in the name of performance. The original date parser uses less space, * meaning less bandwidth is used and less time is spent serializing and * deserializing. */ public class ObjectDateParser extends ProxyParser { public ObjectDateParser() { super(new Seq0( new Whitespace(), new Literal("{"), new Whitespace(), new KeyParser("class"), new Whitespace(), new Literal(":"), new Whitespace(), new Literal("\"__Timestamp__\""), new Whitespace(), new Literal(","), new Whitespace(), new KeyParser("value"), new Whitespace(), new Literal(":"), new Whitespace(), new Parser() { private Parser delegate = new LongParser(); public PStream parse(PStream ps, ParserContext x) { ps = ps.apply(delegate, x); if ( ps != null ) x.set("value", ps.value()); return ps; } }, new Whitespace(), new Literal("}"))); } public PStream parse(PStream ps, ParserContext x) { try { if ((ps = super.parse(ps, x)) == null) return null; long timestamp = (long) x.get("value"); return ps.setValue(new Date(timestamp)); } catch ( Throwable t ) { return null; } } }
package org.voltdb; import static org.voltdb.common.Constants.AUTH_HANDSHAKE; import static org.voltdb.common.Constants.AUTH_HANDSHAKE_VERSION; import static org.voltdb.common.Constants.AUTH_SERVICE_NAME; import java.io.EOFException; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.PrivilegedAction; 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 javax.security.auth.Subject; import javax.security.auth.login.AccountExpiredException; import javax.security.auth.login.CredentialExpiredException; import javax.security.auth.login.FailedLoginException; import javax.security.auth.login.LoginContext; import javax.security.auth.login.LoginException; import org.ietf.jgss.GSSContext; import org.ietf.jgss.GSSCredential; import org.ietf.jgss.GSSException; import org.ietf.jgss.GSSManager; import org.mindrot.BCrypt; import org.voltcore.logging.Level; import org.voltcore.logging.VoltLogger; import org.voltdb.catalog.Connector; import org.voltdb.catalog.Database; import org.voltdb.catalog.Procedure; import org.voltdb.security.AuthenticationRequest; import org.voltdb.utils.Encoder; import org.voltdb.utils.LogKeys; import com.google_voltpatches.common.base.Charsets; import com.google_voltpatches.common.base.Throwables; import com.google_voltpatches.common.collect.ImmutableList; import com.google_voltpatches.common.collect.ImmutableMap; import com.google_voltpatches.common.collect.ImmutableSet; import java.util.EnumSet; import org.voltdb.catalog.Group; import org.voltdb.common.Permission; public class AuthSystem { private static final VoltLogger authLogger = new VoltLogger("AUTH"); /** * JASS Login configuration entry designator */ public static final String VOLTDB_SERVICE_LOGIN_MODULE = System.getProperty("VOLTDB_SERVICE_LOGIN_MODULE", "VoltDBService"); /** * Authentication provider enumeration. It serves also as mapping mechanism * for providers, which are configured in the deployment file, and the login * packet service field. */ public enum AuthProvider { HASH("hash","database"), KERBEROS("kerberos","kerberos"); private final static Map<String,AuthProvider> providerMap; private final static Map<String,AuthProvider> serviceMap; static { ImmutableMap.Builder<String, AuthProvider> pbldr = ImmutableMap.builder(); ImmutableMap.Builder<String, AuthProvider> sbldr = ImmutableMap.builder(); for (AuthProvider ap: values()) { pbldr.put(ap.provider,ap); sbldr.put(ap.service,ap); } providerMap = pbldr.build(); serviceMap = sbldr.build(); } final String provider; final String service; AuthProvider(String provider, String service) { this.provider = provider; this.service = service; } /** * @return its security provider equivalent */ public String provider() { return provider; } /** * @return its login packet service equivalent */ public String service() { return service; } public static AuthProvider fromProvider(String provider) { AuthProvider ap = providerMap.get(provider); if (ap == null) { throw new IllegalArgumentException("No provider mapping for " + provider); } return ap; } public static AuthProvider fromService(String service) { AuthProvider ap = serviceMap.get(service); if (ap == null) { throw new IllegalArgumentException("No service mapping for " + service); } return ap; } } class AuthGroup { /** * Name of the group */ private final String m_name; /** * Set of users that are a member of this group */ private Set<AuthUser> m_users = new HashSet<AuthUser>(); private final EnumSet<Permission> m_permissions = EnumSet.noneOf(Permission.class); private AuthGroup(String name, EnumSet<Permission> permissions) { m_name = name.intern(); m_permissions.addAll(permissions); } private void finish() { m_users = ImmutableSet.copyOf(m_users); } } public static class AuthUser { /** * SHA-1 double hashed copy of the users clear text password */ private final byte[] m_sha1ShadowPassword; /** * SHA-1 hashed and then bcrypted copy of the users clear text password */ private final String m_bcryptShadowPassword; /** * Name of the user */ public final String m_name; /** * Fast iterable list of groups this user is a member of. */ private List<AuthGroup> m_groups = new ArrayList<AuthGroup>(); private Set<Procedure> m_authorizedProcedures = new HashSet<Procedure>(); /** * Set of export connectors this user is authorized to access. */ private Set<Connector> m_authorizedConnectors = new HashSet<Connector>(); /** * The constructor accepts the password as either sha1 or bcrypt. In practice * there will be only one passed in depending on the format of the password in the catalog. * The other will be null and that is used to determine how to hash the supplied password * for auth * @param shadowPassword SHA-1 double hashed copy of the users clear text password * @param name Name of the user */ private AuthUser(byte[] sha1ShadowPassword, String bcryptShadowPassword, String name) { m_sha1ShadowPassword = sha1ShadowPassword; m_bcryptShadowPassword = bcryptShadowPassword; if (name != null) { m_name = name.intern(); } else { m_name = null; } } public boolean hasUserDefinedProcedurePermission(Procedure proc) { if (proc == null) { return false; } return m_authorizedProcedures.contains(proc); } public boolean hasPermission(Permission... perms) { for (int i = 0; i < perms.length;i++) { for (AuthGroup group : m_groups) { if (group.m_permissions.contains(perms[i])) { return true; } } } return false; } /** * Get group names. * @return group name array */ public final String[] getGroupNames() { String[] groupNames = new String[m_groups.size()]; for (int i = 0; i < m_groups.size(); ++i) { groupNames[i] = m_groups.get(i).m_name; } return groupNames; } public boolean authorizeConnector(String connectorClass) { if (connectorClass == null) { return false; } for (Connector c : m_authorizedConnectors) { if (c.getLoaderclass().equals(connectorClass)) { return true; } } return false; } private void finish() { m_groups = ImmutableList.copyOf(m_groups); m_authorizedProcedures = ImmutableSet.copyOf(m_authorizedProcedures); m_authorizedConnectors = ImmutableSet.copyOf(m_authorizedConnectors); } } private Map<String, AuthUser> m_users = new HashMap<String, AuthUser>(); private Map<String, AuthGroup> m_groups = new HashMap<String, AuthGroup>(); /** * Indicates whether security is enabled. If security is disabled all authentications will succede and all returned * AuthUsers will allow everything. */ private final boolean m_enabled; /** * The configured authentication provider */ private final AuthProvider m_authProvider; /** * VoltDB Kerberos service login context */ private final LoginContext m_loginCtx; /** * VoltDB service principal name */ private final byte [] m_principalName; private final GSSManager m_gssManager; AuthSystem(final Database db, boolean enabled) { AuthProvider ap = null; LoginContext loginContext = null; GSSManager gssManager = null; byte [] principal = null; m_enabled = enabled; if (!m_enabled) { m_authProvider = ap; m_loginCtx = loginContext; m_principalName = principal; m_gssManager = null; return; } m_authProvider = AuthProvider.fromProvider(db.getSecurityprovider()); if (m_authProvider == AuthProvider.KERBEROS) { try { loginContext = new LoginContext(VOLTDB_SERVICE_LOGIN_MODULE); } catch (LoginException|SecurityException ex) { VoltDB.crashGlobalVoltDB( "Cannot initialize JAAS LoginContext", true, ex); } try { loginContext.login(); principal = loginContext .getSubject() .getPrincipals() .iterator().next() .getName() .getBytes(Charsets.UTF_8) ; gssManager = GSSManager.getInstance(); } catch (AccountExpiredException ex) { VoltDB.crashGlobalVoltDB( "VoltDB assigned service principal has expired", true, ex); } catch(CredentialExpiredException ex) { VoltDB.crashGlobalVoltDB( "VoltDB assigned service principal credentials have expired", true, ex); } catch(FailedLoginException ex) { VoltDB.crashGlobalVoltDB( "VoltDB failed to authenticate against kerberos", true, ex); } catch (LoginException ex) { VoltDB.crashGlobalVoltDB( "VoltDB service principal failed to login", true, ex); } catch (Exception ex) { VoltDB.crashGlobalVoltDB( "Unexpected exception occured during service authentication", true, ex); } } m_loginCtx = loginContext; m_principalName = principal; m_gssManager = gssManager; /* * First associate all users with groups and vice versa */ for (org.voltdb.catalog.User catalogUser : db.getUsers()) { String shadowPassword = catalogUser.getShadowpassword(); byte sha1ShadowPassword[] = null; if (shadowPassword.length() == 40) { /* * This is an old catalog with a SHA-1 password * Need to hex decode it */ sha1ShadowPassword = Encoder.hexDecode(shadowPassword); } else if (shadowPassword.length() != 60) { /* * If not 40 should be 60 since it is bcrypt */ VoltDB.crashGlobalVoltDB( "Found a shadowPassword in the catalog that was in an unrecogized format", true, null); } final AuthUser user = new AuthUser( sha1ShadowPassword, shadowPassword, catalogUser.getTypeName()); m_users.put(user.m_name, user); for (org.voltdb.catalog.GroupRef catalogGroupRef : catalogUser.getGroups()) { final org.voltdb.catalog.Group catalogGroup = catalogGroupRef.getGroup(); AuthGroup group = null; if (!m_groups.containsKey(catalogGroup.getTypeName())) { group = new AuthGroup(catalogGroup.getTypeName(), Permission.getPermissionSetForGroup(catalogGroup)); m_groups.put(group.m_name, group); } else { group = m_groups.get(catalogGroup.getTypeName()); } group.m_users.add(user); user.m_groups.add(group); } } for (org.voltdb.catalog.Group catalogGroup : db.getGroups()) { AuthGroup group = null; if (!m_groups.containsKey(catalogGroup.getTypeName())) { group = new AuthGroup(catalogGroup.getTypeName(), Permission.getPermissionSetForGroup(catalogGroup)); m_groups.put(group.m_name, group); //A group not associated with any users? Weird stuff. } else { group = m_groups.get(catalogGroup.getTypeName()); } } /* * Then iterate through each procedure and and add it * to the set of procedures for each specified user and for the members of * each specified group. */ for (org.voltdb.catalog.Procedure catalogProcedure : db.getProcedures()) { for (org.voltdb.catalog.UserRef catalogUserRef : catalogProcedure.getAuthusers()) { final org.voltdb.catalog.User catalogUser = catalogUserRef.getUser(); final AuthUser user = m_users.get(catalogUser.getTypeName()); if (user == null) { //Error case. Procedure has a user listed as authorized but no such user exists } else { user.m_authorizedProcedures.add(catalogProcedure); } } for (org.voltdb.catalog.GroupRef catalogGroupRef : catalogProcedure.getAuthgroups()) { final org.voltdb.catalog.Group catalogGroup = catalogGroupRef.getGroup(); final AuthGroup group = m_groups.get(catalogGroup.getTypeName()); if (group == null) { //Error case. Procedure has a group listed as authorized but no such user exists } else { for (AuthUser user : group.m_users) { user.m_authorizedProcedures.add(catalogProcedure); } } } } m_users = ImmutableMap.copyOf(m_users); m_groups = ImmutableMap.copyOf(m_groups); for (AuthUser user : m_users.values()) { user.finish(); } for (AuthGroup group : m_groups.values()) { group.finish(); } } boolean authenticate(String username, byte[] password) { if (!m_enabled) { return true; } final AuthUser user = m_users.get(username); if (user == null) { authLogger.l7dlog(Level.INFO, LogKeys.auth_AuthSystem_NoSuchUser.name(), new String[] {username}, null); return false; } boolean matched = true; if (user.m_sha1ShadowPassword != null) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { VoltDB.crashLocalVoltDB(e.getMessage(), true, e); } byte passwordHash[] = md.digest(password); /* * A n00bs attempt at constant time comparison */ for (int ii = 0; ii < passwordHash.length; ii++) { if (passwordHash[ii] != user.m_sha1ShadowPassword[ii]){ matched = false; } } } else { matched = BCrypt.checkpw(Encoder.hexEncode(password), user.m_bcryptShadowPassword); } if (matched) { authLogger.l7dlog(Level.INFO, LogKeys.auth_AuthSystem_AuthenticatedUser.name(), new Object[] {username}, null); return true; } else { authLogger.l7dlog(Level.INFO, LogKeys.auth_AuthSystem_AuthFailedPasswordMistmatch.name(), new String[] {username}, null); return false; } } public static class AuthDisabledUser extends AuthUser { public AuthDisabledUser() { super(null, null, null); } @Override public boolean hasUserDefinedProcedurePermission(Procedure proc) { return true; } @Override public boolean hasPermission(Permission... p) { return true; } @Override public boolean authorizeConnector(String connectorName) { return true; } } private final AuthUser m_authDisabledUser = new AuthDisabledUser(); AuthUser getUser(String name) { if (!m_enabled) { return m_authDisabledUser; } return m_users.get(name); } public String[] getGroupNamesForUser(String userName) { if (userName == null) { return new String[] {}; } AuthUser user = getUser(userName); if (user == null) { return new String[] {}; } return user.getGroupNames(); } public class HashAuthenticationRequest extends AuthenticationRequest { private final String m_user; private final byte [] m_password; public HashAuthenticationRequest(final String user, final byte [] hash) { m_user = user; m_password = hash; } @Override protected boolean authenticateImpl() throws Exception { if (!m_enabled) { m_authenticatedUser = m_user; return true; } else if (m_authProvider != AuthProvider.HASH) { return false; } final AuthUser user = m_users.get(m_user); if (user == null) { authLogger.l7dlog(Level.INFO, LogKeys.auth_AuthSystem_NoSuchUser.name(), new String[] {m_user}, null); return false; } boolean matched = true; if (user.m_sha1ShadowPassword != null) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { VoltDB.crashLocalVoltDB(e.getMessage(), true, e); } byte passwordHash[] = md.digest(m_password); /* * A n00bs attempt at constant time comparison */ for (int ii = 0; ii < passwordHash.length; ii++) { if (passwordHash[ii] != user.m_sha1ShadowPassword[ii]){ matched = false; } } } else { matched = BCrypt.checkpw(Encoder.hexEncode(m_password), user.m_bcryptShadowPassword); } if (matched) { authLogger.l7dlog(Level.INFO, LogKeys.auth_AuthSystem_AuthenticatedUser.name(), new Object[] {m_user}, null); m_authenticatedUser = m_user; return true; } else { authLogger.l7dlog(Level.INFO, LogKeys.auth_AuthSystem_AuthFailedPasswordMistmatch.name(), new String[] {m_user}, null); return false; } } } public class KerberosAuthenticationRequest extends AuthenticationRequest { private SocketChannel m_socket; public KerberosAuthenticationRequest(final SocketChannel socket) { m_socket = socket; } @Override protected boolean authenticateImpl() throws Exception { if (!m_enabled) { m_authenticatedUser = "_^_pinco_pallo_^_"; return true; } else if (m_authProvider != AuthProvider.KERBEROS) { return false; } int msgSize = 4 // message size header + 1 // protocol version + 1 // result code + 4 // service name length + m_principalName.length; final ByteBuffer bb = ByteBuffer.allocate(4096); /* * write the service principal response. This gives the connecting client * the service principal name form which it constructs the GSS context * used in the client/service authentication handshake */ bb.putInt(msgSize-4).put(AUTH_HANDSHAKE_VERSION).put(AUTH_SERVICE_NAME); bb.putInt(m_principalName.length); bb.put(m_principalName); bb.flip(); while (bb.hasRemaining()) { m_socket.write(bb); } String authenticatedUser = Subject.doAs(m_loginCtx.getSubject(), new PrivilegedAction<String>() { @Override public String run() { GSSContext context = null; try { // derive the credentials from the authenticated service subject context = m_gssManager.createContext((GSSCredential)null); byte [] token; while (!context.isEstablished()) { // read in the next packet size bb.clear().limit(4); while (bb.hasRemaining()) { if (m_socket.read(bb) == -1) throw new EOFException(); } bb.flip(); int msgSize = bb.getInt(); if (msgSize > bb.capacity()) { authLogger.warn("Authentication packet exceeded alloted size"); return null; } // read the initiator (client) context token bb.clear().limit(msgSize); while (bb.hasRemaining()) { if (m_socket.read(bb) == -1) throw new EOFException(); } bb.flip(); byte version = bb.get(); if (version != AUTH_HANDSHAKE_VERSION) { authLogger.warn("Encountered unexpected authentication protocol version " + version); return null; } byte tag = bb.get(); if (tag != AUTH_HANDSHAKE) { authLogger.warn("Encountered unexpected authentication protocol tag " + tag); return null; } // process the initiator (client) context token. If it returns a non empty token // transmit it to the initiator token = context.acceptSecContext(bb.array(), bb.arrayOffset() + bb.position(), bb.remaining()); if (token != null) { msgSize = 4 + 1 + 1 + token.length; bb.clear().limit(msgSize); bb.putInt(msgSize-4).put(AUTH_HANDSHAKE_VERSION).put(AUTH_HANDSHAKE); bb.put(token); bb.flip(); while (bb.hasRemaining()) { m_socket.write(bb); } } } // at this juncture we an established security context between // the client and this service String authenticateUserName = context.getSrcName().toString(); // check if both ends are authenticated if (!context.getMutualAuthState()) { return null; } context.dispose(); context = null; return authenticateUserName; } catch (IOException|GSSException ex) { Throwables.propagate(ex); } finally { if (context != null) try { context.dispose(); } catch (Exception ignoreIt) {} } return null; } }); if (authenticatedUser != null) { final AuthUser user = m_users.get(authenticatedUser); if (user == null) { authLogger.l7dlog(Level.INFO, LogKeys.auth_AuthSystem_NoSuchUser.name(), new String[] {authenticatedUser}, null); return false; } m_authenticatedUser = authenticatedUser; authLogger.l7dlog(Level.INFO, LogKeys.auth_AuthSystem_AuthenticatedUser.name(), new Object[] {authenticatedUser}, null); } return true; } } }
package intermediate; import static com.sandwich.koan.constant.KoanConstants.__; import static com.sandwich.util.Assert.assertEquals; import com.sandwich.koan.Koan; public class AboutInnerClasses { interface Ignoreable { String ignoreAll(); } class Inner { public String doStuff() { return "stuff"; } public int returnOuter() { return x; } } @Koan public void creatingInnerClassInstance() { Inner someObject = new Inner(); assertEquals(someObject.doStuff(), "stuff"); } @Koan public void creatingInnerClassInstanceWithOtherSyntax() { AboutInnerClasses.Inner someObject = this.new Inner(); assertEquals(someObject.doStuff(), "stuff"); } private int x = 10; @Koan public void accessingOuterClassMembers() { Inner someObject = new Inner(); assertEquals(someObject.returnOuter(),10); } @Koan public void innerClassesInMethods() { class MethodInnerClass { int oneHundred() { return 100; } } assertEquals(new MethodInnerClass().oneHundred(), 100); // Where can you use this class? } class AnotherInnerClass { int thousand() { return 1000; } AnotherInnerClass crazyReturn() { class SpecialInnerClass extends AnotherInnerClass { int thousand() { return 2000; } }; return new SpecialInnerClass(); } } @Koan public void innerClassesInMethodsThatEscape() { AnotherInnerClass ic = new AnotherInnerClass(); assertEquals(ic.thousand(), 1000); AnotherInnerClass theCrazyIC = ic.crazyReturn(); assertEquals(theCrazyIC.thousand(), 2000); } int theAnswer() { return 42; } @Koan public void creatingAnonymousInnerClasses() { AboutInnerClasses anonymous = new AboutInnerClasses() { int theAnswer() { return 23; } };// <- Why do you need a semicolon here? assertEquals(anonymous.theAnswer(), 23); } @Koan public void creatingAnonymousInnerClassesToImplementInterface() { Ignoreable ignoreable = new Ignoreable(){ public String ignoreAll() { return null; } }; // Complete the code so that the statement below is correct. // Look at the koan above for inspiration assertEquals(ignoreable.ignoreAll(), null); // Did you just created an object of an interface type? // Or did you create a class that implemented this interface and // an object of that type? } @Koan public void innerClassAndInheritance() { Inner someObject = new Inner(); // The statement below is obvious... // Try to change the 'Inner' below to "AboutInnerClasses' // Why do you get an error? // What does that imply for inner classes and inheritance? assertEquals(someObject instanceof Inner, true); } class OtherInner extends AboutInnerClasses { } @Koan public void innerClassAndInheritanceOther() { OtherInner someObject = new OtherInner(); // What do you expect here? // Compare this result with the last koan. What does that mean? assertEquals(someObject instanceof AboutInnerClasses, true); } static class StaticInnerClass { public int importantNumber() { return 3; } } @Koan public void staticInnerClass() { StaticInnerClass someObject = new StaticInnerClass(); assertEquals(someObject.importantNumber(), 3); // What happens if you try to access 'x' or 'theAnswer' from the outer class? // What does this mean for static inner classes? // Try to create a sub package of this package which is named 'StaticInnerClass' // Does it work? Why not? } @Koan public void staticInnerClassFullyQualified() { AboutInnerClasses.StaticInnerClass someObject = new AboutInnerClasses.StaticInnerClass(); assertEquals(someObject.importantNumber(), 3); } }
package net.sf.jabref; import net.sf.jabref.export.FieldFormatter; import java.beans.PropertyChangeEvent; import java.beans.PropertyVetoException; import java.beans.VetoableChangeListener; import java.beans.VetoableChangeSupport; import java.util.*; import java.io.*; public class BibtexEntry { private String _id; private BibtexEntryType _type; private Map _fields = new HashMap(); VetoableChangeSupport _changeSupport = new VetoableChangeSupport(this); public BibtexEntry(String id) { this(id, BibtexEntryType.OTHER); } public BibtexEntry(String id, BibtexEntryType type) { if (id == null) { throw new NullPointerException("Every BibtexEntry must have an ID"); } _id = id; setType(type); } /** * Returns an array describing the optional fields for this entry. */ public String[] getOptionalFields() { return _type.getOptionalFields(); } /** * Returns an array describing the required fields for this entry. */ public String[] getRequiredFields() { return _type.getRequiredFields(); } /** * Returns an array describing general fields. */ public String[] getGeneralFields() { return _type.getGeneralFields(); } /** * Returns an array containing the names of all fields that are * set for this particular entry. */ public Object[] getAllFields() { return _fields.keySet().toArray(); } /** * Returns a string describing the required fields for this entry. */ public String describeRequiredFields() { return _type.describeRequiredFields(); } /** * Returns true if this entry contains the fields it needs to be * complete. */ public boolean hasAllRequiredFields() { return _type.hasAllRequiredFields(this); } /** * Returns this entry's type. */ public BibtexEntryType getType() { return _type; } /** * Sets this entry's type. */ public void setType(BibtexEntryType type) { if (type == null) { throw new NullPointerException( "Every BibtexEntry must have a type. Instead of null, use type OTHER"); } _type = type; } /** * Prompts the entry to call BibtexEntryType.getType(String) with * its current type name as argument, and sets its type according * to what is returned. This method is called when a user changes * the type customization, to make sure all entries are set with * current types. * @return true if the entry could find a type, false if not (in * this case the type will have been set to * BibtexEntryType.TYPELESS). */ public boolean updateType() { BibtexEntryType newType = BibtexEntryType.getType(_type.getName()); if (newType != null) { _type = newType; return true; } _type = BibtexEntryType.TYPELESS; return false; } /** * Sets this entry's ID, provided the database containing it * doesn't veto the change. */ public void setId(String id) throws KeyCollisionException { if (id == null) { throw new NullPointerException("Every BibtexEntry must have an ID"); } try { firePropertyChangedEvent("id", _id, id); } catch (PropertyVetoException pv) { throw new KeyCollisionException("Couldn't change ID: " + pv); } _id = id; } /** * Returns this entry's ID. */ public String getId() { return _id; } /** * Returns the contents of the given field, or null if it is not set. */ public Object getField(String name) { return _fields.get(name); } public String getCiteKey() { return (_fields.containsKey(Globals.KEY_FIELD) ? (String)_fields.get(Globals.KEY_FIELD) : null); } /** * Sets the given field to the given value. */ public void setField(HashMap fields){ _fields.putAll(fields); //_fields=fields.clone(); // clone slows up things but... // if you don't clone then client has pointer to _field and can change it behind the scenes } public void setField(String name, Object value) { if ("id".equals(name)) { throw new IllegalArgumentException("The field name '" + name + "' is reserved"); } // This mechanism is probably not really necessary. //Object normalValue = FieldTypes.normalize(name, value); try { firePropertyChangedEvent(name, _fields.get(name), value); } catch (PropertyVetoException pve) { throw new IllegalArgumentException("Change rejected: " + pve); } //Object oldValue = _fields.put(name, value); } /** * Removes the mapping for the field name. */ public void clearField(String name) { if ("id".equals(name)) { throw new IllegalArgumentException("The field name '" + name + "' is reserved"); } try { firePropertyChangedEvent(name, _fields.get(name), ""); } catch (PropertyVetoException pve) { throw new IllegalArgumentException("Change rejected: " + pve); } _fields.remove(name); } protected boolean allFieldsPresent(String[] fields) { for (int i = 0; i < fields.length; i++) { if (getField(fields[i]) == null) { return false; } } return true; } private void firePropertyChangedEvent(String fieldName, Object oldValue, Object newValue) throws PropertyVetoException { _changeSupport.fireVetoableChange(new PropertyChangeEvent(this, fieldName, oldValue, newValue)); } /** * Adds a VetoableChangeListener, which is notified of field * changes. This is useful for an object that needs to update * itself each time a field changes. */ public void addPropertyChangeListener(VetoableChangeListener listener) { _changeSupport.addVetoableChangeListener(listener); } /** * Removes a property listener. */ public void removePropertyChangeListener(VetoableChangeListener listener) { _changeSupport.removeVetoableChangeListener(listener); } /** * Write this entry to the given Writer, with the given FieldFormatter. * @param write True if this is a write, false if it is a display. The write will * not include non-writeable fields if it is a write, otherwise non-displayable fields * will be ignored. Refer to GUIGlobals for isWriteableField(String) and * isDisplayableField(String). */ public void write(Writer out, FieldFormatter ff, boolean write) throws IOException { // Write header with type and bibtex-key. out.write("@"+_type.getName().toUpperCase()+"{"); String str = Util.shaveString((String)getField(GUIGlobals.KEY_FIELD)); out.write(((str == null) ? "" : str.toString())+",\n"); HashMap written = new HashMap(); written.put(GUIGlobals.KEY_FIELD, null); // Write required fields first. String[] s = getRequiredFields(); if (s != null) for (int i=0; i<s.length; i++) { writeField(s[i], out, ff); written.put(s[i], null); } // Then optional fields. s = getOptionalFields(); if (s != null) for (int i=0; i<s.length; i++) { writeField(s[i], out, ff); written.put(s[i], null); } // Then write remaining fields in alphabetic order. TreeSet remainingFields = new TreeSet(); for (Iterator i = _fields.keySet().iterator(); i.hasNext(); ) { String key = (String)i.next(); boolean writeIt = (write ? GUIGlobals.isWriteableField(key) : GUIGlobals.isDisplayableField(key)); if (!written.containsKey(key) && writeIt) remainingFields.add(key); } for (Iterator i = remainingFields.iterator(); i.hasNext(); ) writeField((String)i.next(),out,ff); // Finally, end the entry. out.write("}\n"); } private void writeField(String name, Writer out, FieldFormatter ff) throws IOException { Object o = getField(name); if (o != null) { out.write(" "+name+" = "); try { out.write(ff.format(o.toString(), GUIGlobals.isStandardField(name))); } catch (Throwable ex) { throw new IOException (Globals.lang("Error in field")+" '"+name+"': "+ex.getMessage()); } //Util.writeField(name, o, out); out.write(",\n"); } } /** * Returns a clone of this entry. Useful for copying. */ public Object clone() { BibtexEntry clone = new BibtexEntry(_id, _type); clone._fields = (Map)((HashMap)_fields).clone(); return clone; } }
package javaPrg.feb; public class PalindromicNumbers { public static void main(String args[]) { //since java get arguments as String. convert it System.out.println("Is Palindromic:\n" + "\n121 " + isPalindromic(121l) + "\n1221 " + isPalindromic(1221l) + "\n12343 " +isPalindromic(12343l) + "\n12213 " + isPalindromic(12213l) + "\n64277 " + isPalindromic(64277l) + "\n121.121 " + isPalindromic(121.121) + "\n121.21 " + isPalindromic(121.21) + "\n0.1 " + isPalindromic(0.1) + "\n1.0 " + isPalindromic(1.0) + "\n1.1 " + isPalindromic(1.1) + "\n10.01 " + isPalindromic(10.01) + "\n92.2945 " + isPalindromic(92.2945) + "\n2213312.22 " + isPalindromic(2213312.22) + "\n12343.21 " + isPalindromic(12343.21) + "\n12.34321 " + isPalindromic(12.34321)); } private static boolean isPalindromic(double inp) { long tmp= (long)inp; double num = inp; while(tmp > 0 && num != (long)num) { tmp/=10; num*=10; } if(tmp == 0 && num == (long)num) { return isPalindromic((long)num); } return false; } private static boolean isPalindromic(long inp) { inp = inp<0?-inp:inp; long tmp = 0,tmp2 = inp; while(inp > 0) { tmp = tmp*10+inp%10; inp /= 10; } return tmp==tmp2; } }
package com.psddev.dari.db; import com.psddev.dari.util.ObjectUtils; import com.psddev.dari.util.PaginatedResult; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentHashMap; /** * Caches the results of read operations. * * <p>For example, given:</p> * * <blockquote><pre>{@literal CachingDatabase caching = new CachingDatabase(); caching.setDelegate(Database.Static.getDefault()); PaginatedResult<Article> result = Query.from(Article.class).using(caching).select(0, 5); * }</pre></blockquote> * * <p>These are some of the queries that won't trigger additional * reads in the delegate database:</p> * * <ul> * <li>{@code Query.from(Article.class).using(caching).count()}</li> * <li>{@code Query.from(Article.class).using(caching).where("_id = ?", result.getItems().get(0));}</li> * </ul> * * <p>All methods are thread-safe.</p> */ public class CachingDatabase extends ForwardingDatabase { private static final Object MISSING = new Object(); private final ConcurrentMap<UUID, Object> objectCache = new ConcurrentHashMap<UUID, Object>(); private final ConcurrentMap<UUID, Object> referenceCache = new ConcurrentHashMap<UUID, Object>(); private final ConcurrentMap<Query<?>, List<?>> readAllCache = new ConcurrentHashMap<Query<?>, List<?>>(); private final ConcurrentMap<Query<?>, Long> readCountCache = new ConcurrentHashMap<Query<?>, Long>(); private final ConcurrentMap<Query<?>, Object> readFirstCache = new ConcurrentHashMap<Query<?>, Object>(); private final ConcurrentMap<Query<?>, Map<Range, PaginatedResult<?>>> readPartialCache = new ConcurrentHashMap<Query<?>, Map<Range, PaginatedResult<?>>>(); private static class Range { public final long offset; public final int limit; public Range(long offset, int limit) { this.offset = offset; this.limit = limit; } @Override public boolean equals(Object other) { if (this == other) { return true; } else if (other instanceof Range) { Range otherRange = (Range) other; return offset == otherRange.offset && limit == otherRange.limit; } else { return false; } } @Override public int hashCode() { return ObjectUtils.hashCode(offset, limit); } } /** * Returns the map of all objects cached so far. * * @return Never {@code null}. Mutable. Thread-safe. */ public Map<UUID, Object> getObjectCache() { return objectCache; } /** * Returns the map of all object references cached so far. * * @return Never {@code null}. Mutable. Thread-safe. */ public Map<UUID, Object> getReferenceCache() { return referenceCache; } private List<Object> findIdOnlyQueryValues(Query<?> query) { if (query.getSorters().isEmpty()) { Predicate predicate = query.getPredicate(); if (predicate instanceof ComparisonPredicate) { ComparisonPredicate comparison = (ComparisonPredicate) predicate; if (Query.ID_KEY.equals(comparison.getKey()) && PredicateParser.EQUALS_ANY_OPERATOR.equals(comparison.getOperator()) && comparison.findValueQuery() == null) { return comparison.getValues(); } } } return null; } private Object findCachedObject(UUID id, Query<?> query) { Object object = objectCache.get(id); if (object == null && query.isReferenceOnly()) { return referenceCache != null ? referenceCache.get(id) : null; } else { return object; } } private void cacheObject(Object object) { State state = ((Recordable) object).getState(); UUID id = state.getId(); if (state.isReferenceOnly()) { referenceCache.put(id, object); } else if (!state.isResolveToReferenceOnly()) { objectCache.put(id, object); } } @Override @SuppressWarnings("unchecked") public <T> List<T> readAll(Query<T> query) { if (query.as(QueryOptions.class).isDisabled()) { return super.readAll(query); } List<Object> all = new ArrayList<Object>(); List<Object> values = findIdOnlyQueryValues(query); if (values != null) { List<Object> newValues = null; for (Object value : values) { UUID valueId = ObjectUtils.to(UUID.class, value); if (valueId != null) { Object object = findCachedObject(valueId, query); if (object != null) { all.add(object); continue; } } if (newValues == null) { newValues = new ArrayList<Object>(); } newValues.add(value); } if (newValues == null) { return (List<T>) all; } else { query = query.clone(); query.setPredicate(PredicateParser.Static.parse("_id = ?", newValues)); } } List<?> list = readAllCache.get(query); if (list == null) { list = super.readAll(query); readAllCache.put(query, list); for (Object item : list) { cacheObject(item); } } all.addAll(list); return (List<T>) all; } @Override public long readCount(Query<?> query) { if (query.as(QueryOptions.class).isDisabled()) { return super.readCount(query); } Long count = readCountCache.get(query); if (count == null) { COUNT: { if (readAllCache != null) { List<?> list = readAllCache.get(query); if (list != null) { count = (long) list.size(); break COUNT; } } if (readPartialCache != null) { Map<Range, PaginatedResult<?>> subCache = readPartialCache.get(query); if (subCache != null && !subCache.isEmpty()) { count = subCache.values().iterator().next().getCount(); break COUNT; } } count = super.readCount(query); } readCountCache.put(query, count); } return count; } @Override @SuppressWarnings("unchecked") public <T> T readFirst(Query<T> query) { if (query.as(QueryOptions.class).isDisabled()) { return super.readFirst(query); } List<Object> values = findIdOnlyQueryValues(query); if (values != null) { for (Object value : values) { UUID valueId = ObjectUtils.to(UUID.class, value); if (valueId != null) { Object object = findCachedObject(valueId, query); if (object != null) { return (T) object; } } } } Object first = readFirstCache.get(query); if (first == null) { first = super.readFirst(query); if (first == null) { first = MISSING; } else { cacheObject(first); } readFirstCache.put(query, first); } return first != MISSING ? (T) first : null; } @Override @SuppressWarnings("unchecked") public <T> PaginatedResult<T> readPartial(Query<T> query, long offset, int limit) { if (query.as(QueryOptions.class).isDisabled()) { return super.readPartial(query, offset, limit); } Map<Range, PaginatedResult<?>> subCache = readPartialCache.get(query); if (subCache == null) { Map<Range, PaginatedResult<?>> newSubCache = new ConcurrentHashMap<Range, PaginatedResult<?>>(); subCache = readPartialCache.putIfAbsent(query, newSubCache); if (subCache == null) { subCache = newSubCache; } } Range range = new Range(offset, limit); PaginatedResult<?> result = subCache.get(range); if (result == null) { result = super.readPartial(query, offset, limit); subCache.put(range, result); for (Object item : result.getItems()) { cacheObject(item); } } return (PaginatedResult<T>) result; } /** {@link Query} options for {@link CachingDatabase}. */ @Modification.FieldInternalNamePrefix("caching.") public static class QueryOptions extends Modification<Query<?>> { private boolean disabled; /** * Returns {@code true} if the caching should be disabled when * running the query. */ public boolean isDisabled() { Boolean old = ObjectUtils.to(Boolean.class, getOriginalObject().getOptions().get(IS_DISABLED_QUERY_OPTION)); return old != null ? old : disabled; } /** * Sets whether the caching should be disabled when running * the query. */ public void setDisabled(boolean disabled) { this.disabled = disabled; } } /** @deprecated Use {@link QueryOptions} instead. */ @Deprecated public static final String IS_DISABLED_QUERY_OPTION = "caching.isDisabled"; @Deprecated @Override public <T> List<T> readList(Query<T> query) { return readAll(query); } }
package com.psddev.dari.db; import java.util.AbstractList; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.UUID; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.nodes.Node; import org.jsoup.nodes.TextNode; import org.jsoup.parser.Tag; import com.psddev.dari.util.ErrorUtils; import com.psddev.dari.util.ObjectUtils; /** Contains strings and references to other objects. */ public class ReferentialText extends AbstractList<Object> { private static final Tag BR_TAG = Tag.valueOf("br"); private static final Tag P_TAG = Tag.valueOf("p"); private final List<Object> list = new ArrayList<Object>(); /** * Creates an empty instance. */ public ReferentialText() { } private static void addByBoundary( List<Object> list, String html, String boundary, List<Reference> references) { int previousBoundaryAt = 0; for (int boundaryAt = previousBoundaryAt; (boundaryAt = html.indexOf(boundary, previousBoundaryAt)) >= 0; previousBoundaryAt = boundaryAt + boundary.length()) { list.add(html.substring(previousBoundaryAt, boundaryAt)); list.add(references.get(list.size() / 2)); } list.add(html.substring(previousBoundaryAt)); } /** * Creates an instance from the given {@code html}. * * @param html If {@code null}, creates an empty instance. */ public ReferentialText(String html, boolean finalDraft) { if (html == null) { return; } Document document = Jsoup.parseBodyFragment(html); Element body = document.body(); document.outputSettings().prettyPrint(false); for (Element element : body.select("*")) { String tagName = element.tagName(); if (tagName.startsWith("o:")) { element.unwrap(); } else if (tagName.equals("span")) { if (element.attributes().size() == 0 || element.attr("class").contains("Mso") || element.hasAttr("color")) { element.unwrap(); } } } // Remove editorial markups. if (finalDraft) { body.getElementsByTag("del").remove(); body.getElementsByTag("ins").unwrap(); } // Convert '<p>text</p>' to 'text<br><br>'. for (Element p : body.getElementsByTag("p")) { if (p.hasText()) { p.appendChild(new Element(BR_TAG, "")); p.appendChild(new Element(BR_TAG, "")); p.unwrap(); // Remove empty paragraphs. } else { p.remove(); } } // Find object references. List<Reference> references = new ArrayList<Reference>(); String boundary = UUID.randomUUID().toString(); for (Element enhancement : body.getElementsByClass("enhancement")) { if (!enhancement.hasClass("state-removing")) { Reference reference = new Reference(); for (Map.Entry<String, String> entry : enhancement.dataset().entrySet()) { String key = entry.getKey(); if (!key.startsWith("_")) { reference.put(key, entry.getValue()); } } UUID referenceId = ObjectUtils.to(UUID.class, reference.remove("id")); if (referenceId != null) { reference.put("record", Query.findById(Object.class, referenceId)); references.add(reference); enhancement.before(boundary); } } enhancement.remove(); } StringBuilder cleaned = new StringBuilder(); for (Node child : body.childNodes()) { cleaned.append(child.toString()); } addByBoundary(this, cleaned.toString(), boundary, references); } /** * Returns a mixed list of well-formed HTML strings and object references * that have been converted to publishable forms. * * @return Never {@code null}. */ public List<Object> toPublishables() { // Concatenate the items so that it can be fed into an HTML parser. StringBuilder html = new StringBuilder(); String boundary = UUID.randomUUID().toString(); List<Reference> references = new ArrayList<Reference>(); for (Object item : this) { if (item != null) { if (item instanceof Reference) { html.append(boundary); references.add((Reference) item); } else { html.append(item.toString()); } } } // Convert 'text<br><br>' to '<p>text</p>'. Document document = Jsoup.parseBodyFragment(html.toString()); Element body = document.body(); document.outputSettings().prettyPrint(false); for (Element br : body.getElementsByTag("br")) { Element previousBr = null; // Find the closest previous <br> without any intervening content. for (Node previousNode = br; (previousNode = previousNode.previousSibling()) != null; ) { if (previousNode instanceof Element) { Element previousElement = (Element) previousNode; if (BR_TAG.equals(previousElement.tag())) { previousBr = previousElement; } break; } if (previousNode instanceof TextNode && !ObjectUtils.isBlank(((TextNode) previousNode).text())) { break; } } if (previousBr == null) { continue; } List<Node> paragraphChildren = new ArrayList<Node>(); for (Node previous = previousBr; (previous = previous.previousSibling()) != null; ) { if (previous instanceof Element && ((Element) previous).isBlock()) { break; } else { paragraphChildren.add(previous); } } Element paragraph = new Element(P_TAG, ""); for (Node child : paragraphChildren) { child.remove(); paragraph.prependChild(child.clone()); } br.before(paragraph); br.remove(); previousBr.remove(); } // Remove editorial markups. body.getElementsByTag("del").remove(); body.getElementsByTag("ins").unwrap(); // Remove empty paragraphs and stringify. StringBuilder cleaned = new StringBuilder(); for (Node child : body.childNodes()) { if (child instanceof Element) { Element childElement = (Element) child; if (P_TAG.equals(childElement.tag()) && !childElement.hasText()) { continue; } } cleaned.append(child.toString()); } List<Object> publishables = new ArrayList<Object>(); addByBoundary(publishables, cleaned.toString(), boundary, references); return publishables; } private Object checkItem(Object item) { ErrorUtils.errorIfNull(item, "item"); if (item instanceof Reference) { return item; } else if (item instanceof Map) { Reference ref = new Reference(); for (Map.Entry<?, ?> entry : ((Map<?, ?>) item).entrySet()) { Object key = entry.getKey(); ref.put(key != null ? key.toString() : null, entry.getValue()); } return ref; } else { return item.toString(); } } @Override public void add(int index, Object item) { list.add(index, checkItem(item)); } @Override public Object get(int index) { return list.get(index); } @Override public Object remove(int index) { return list.remove(index); } @Override public Object set(int index, Object item) { return list.set(index, checkItem(item)); } @Override public int size() { return list.size(); } }
package BulletinBoard; import Domain.Message; import java.sql.SQLException; import java.util.HashMap; import java.util.List; import spark.ModelAndView; import spark.Spark; import static spark.Spark.get; import static spark.Spark.post; import spark.TemplateEngine; import spark.template.thymeleaf.ThymeleafTemplateEngine; import Domain.Thread; import Domain.User; import java.util.ArrayList; public class SparkInterface { private final BulletinBoard board; private final TemplateEngine templateEngine; public SparkInterface(BulletinBoard board) { this.board = board; this.templateEngine = new ThymeleafTemplateEngine(); } public void createDb() throws Exception { board.createTable("Subforum", "forumId integer PRIMARY KEY, name text, postcount integer"); board.createTable("Thread", "threadId integer PRIMARY KEY, forumId integer, sender integer, " + "lastMessage integer, name text, dateTime Timestamp, postcount integer, " + "FOREIGN KEY(forumId) REFERENCES Subforum(forumId), FOREIGN KEY(sender) REFERENCES User(userId), " + "FOREIGN KEY(lastMessage) REFERENCES Message(messageId)"); board.createTable("Message", "messageId integer PRIMARY KEY, threadId integer, sender integer, " + "'order' integer, dateTime Timestamp, content text, FOREIGN KEY(threadId) REFERENCES Thread(threadId), " + "FOREIGN KEY(sender) REFERENCES User(userId)"); board.createTable("User", "userId integer PRIMARY KEY, username text, joinDate Timestamp, postcount integer"); board.addUser("Arto"); board.addUser("Matti"); board.addUser("Ada"); board.addSubforum("Ohjelmointi"); board.addSubforum("Lemmikit"); board.addSubforum("Lentokoneet"); board.addThread(1, 1, "Java on jees"); board.addThread(1, 1, "Python on jeesimpi"); board.addThread(1, 2, "LISP on parempi kuin"); board.addThread(1, 3, "Ohjelmointikielet on turhia"); board.addMessage(1, 1, "Mun mielestä Java on just hyvä kieli."); board.addMessage(1, 2, "No eipäs, Ruby on parempi."); board.addMessage(1, 3, "Ada on selkeästi parempi kuin kumpikin noista."); board.addMessage(1, 1, "Mun mielestä Java on just hyvä kieli."); board.addMessage(2, 1, "Python rulaa :)"); board.addMessage(3, 3, "LISP<3"); board.addMessage(3, 3, "LISP<3"); board.addMessage(4, 3, "LISP<<<<<<"); } public void start() throws Exception { get("/", (req, res) -> { HashMap map = new HashMap<>(); map.put("subforums", board.getSubforums()); return new ModelAndView(map, "index"); }, templateEngine); get("/subforum", (req, res) -> { // /subforum?id=1 HashMap map = new HashMap<>(); try { int forumId = Integer.parseInt(req.queryParams("id")); map.put("subforum", board.getSubforum(forumId)); List<Thread> threads = board.getThreadsIn(forumId); map.put("threads", threads); List<Integer> lastMsgs = new ArrayList<>(); threads.forEach(t -> lastMsgs.add(((Thread) t).getLastMessage())); map.put("lastMessages", board.getMessagesIn(lastMsgs)); //useful to have Message for future } catch (NumberFormatException | SQLException e) { res.status(404); } return new ModelAndView(map, "subforum"); }, templateEngine); get("/thread", (req, res) -> { // /thread?id=1 HashMap map = new HashMap<>(); try { int threadId = Integer.parseInt(req.queryParams("id")); map.put("thread", board.getThread(threadId)); map.put("messages", board.getMessagesIn(threadId)); } catch (NumberFormatException | SQLException e) { res.status(404); } return new ModelAndView(map, "thread"); }, templateEngine); post("/thread", (req, res) -> { try { int threadId = Integer.parseInt(req.queryParams("id")); String username = req.queryParams("name"); String comment = req.queryParams("comment"); int userId = board.getUserId(username); if (userId == -1) { userId = board.addUser(username); } board.addMessage(threadId, userId, comment); res.redirect("/thread?id=" + threadId); } catch (NumberFormatException | SQLException e) { res.status(404); } return null; }); get("/addthread", (req, res) -> { // /addthread HashMap map = new HashMap<>(); try { int forumId = Integer.parseInt(req.queryParams("id")); map.put("subforum", board.getSubforum(forumId)); } catch (NumberFormatException | SQLException e) { res.status(404); } return new ModelAndView(map, "addthread"); }, templateEngine); post("/addthread", (req, res) -> { try { int forumId = Integer.parseInt(req.queryParams("id")); String title = req.queryParams("title"); String username = req.queryParams("username"); String message = req.queryParams("message"); int userId = board.getUserId(username); if (userId == -1) { userId = board.addUser(username); } int threadId = board.addThread(forumId, userId, title); board.addMessage(threadId, userId, message); res.redirect("/thread?id=" + threadId); } catch (NumberFormatException | SQLException e) { res.status(404); } return null; }); } }
package com.ammonf.game.desktop; import com.badlogic.gdx.backends.lwjgl.LwjglApplication; import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration; import com.ammonf.game.FAAB; public class DesktopLauncher { public static void main (String[] arg) { LwjglApplicationConfiguration config = new LwjglApplicationConfiguration(); config.width = FAAB.WIDTH; config.height = FAAB.HEIGHT; config.title = FAAB.TITLE; new LwjglApplication(new FAAB(), config); } }
package org.glob3.mobile.generated; // GFont.cpp // G3MiOSSDK // GFont.hpp // G3MiOSSDK public class GFont { private static final String SERIF = "serif"; private static final String SANS_SERIF = "sans-serif"; private static final String MONOSPACED = "monospaced"; private final String _name; private final float _size; private final boolean _bold; private final boolean _italic; private GFont(String name, float size, boolean bold, boolean italic) { _name = name; _size = size; _bold = bold; _italic = italic; } public static GFont serif(float size, boolean bold) { return serif(size, bold, false); } public static GFont serif(float size) { return serif(size, false, false); } public static GFont serif() { return serif(20, false, false); } public static GFont serif(float size, boolean bold, boolean italic) { return new GFont(GFont.SERIF, size, bold, italic); } public static GFont sansSerif(float size, boolean bold) { return sansSerif(size, bold, false); } public static GFont sansSerif(float size) { return sansSerif(size, false, false); } public static GFont sansSerif() { return sansSerif(20, false, false); } public static GFont sansSerif(float size, boolean bold, boolean italic) { return new GFont(GFont.SANS_SERIF, size, bold, italic); } public static GFont monospaced(float size, boolean bold) { return monospaced(size, bold, false); } public static GFont monospaced(float size) { return monospaced(size, false, false); } public static GFont monospaced() { return monospaced(20, false, false); } public static GFont monospaced(float size, boolean bold, boolean italic) { return new GFont(GFont.MONOSPACED, size, bold, italic); } public GFont(GFont that) { _name = that._name; _size = that._size; _bold = that._bold; _italic = that._italic; } public void dispose() { } public final boolean isSerif() { return (_name.compareTo(GFont.SERIF) == 0); } public final boolean isSansSerif() { return (_name.compareTo(GFont.SANS_SERIF) == 0); } public final boolean isMonospaced() { return (_name.compareTo(GFont.MONOSPACED) == 0); } public final float getSize() { return _size; } public final boolean isBold() { return _bold; } public final boolean isItalic() { return _italic; } public final String description() { IStringBuilder isb = IStringBuilder.newStringBuilder(); isb.addString("(GFont name=\""); isb.addString(_name); isb.addString("\", size="); isb.addFloat(_size); if (_bold) { isb.addString(", bold"); } if (_italic) { isb.addString(", italic"); } isb.addString(")"); final String s = isb.getString(); if (isb != null) isb.dispose(); return s; } }
package abc.player; import java.io.IOException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import javax.print.PrintException; import javax.swing.JDialog; import org.antlr.v4.gui.Trees; import org.antlr.v4.runtime.*; import org.antlr.v4.runtime.misc.Utils; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.ParseTreeWalker; import org.junit.Test; import abc.parser.HeaderLexer; import abc.parser.HeaderParser; public class ParseTest { @Test(expected=AssertionError.class) public void testAssertionsEnabled() { assert false; // make sure assertions are enabled with VM argument: -ea } // HeaderParser // Testing partitions: // Valid index (first field and digit(s)) // Invalid index (missing X:, not first field, not digit(s)) // Valid title (second field any text) // Invalid title (missing T:, not second field) // Valid composer (any text) // Invalid composer (missing C:) // Valid meter (digit(s)/digit(s) or C or C|) // Invalid meter (missing M:, invalid characters) // Valid length (digit(s)/digit(s)) // Invalid length (missing L:, invalid characters) // Valid tempo (digit(s)/digit(s) = digit(s)) // Invalid tempo (missing T:, invalid characters) // Valid voice (any text) // Invalid voice (missing V:) // Valid key (last field and case-insensitive note + optional accidental + optional minor) // Invalid key (missing K:, not last field, note does not exist, accidental does not exist) // Valid comment (% followed by any text, not treated as a field) // Invalid comment (missing %, treated as separate field) // Valid whitespace (all whitespace should be ignored/skipped) // Invalid field (no newline at end of field) // covers valid index, valid title, valid key @Test public void testHeaderParser(){ CharStream stream = new ANTLRInputStream("X:1\nT:hello world\nK:A\n"); HeaderLexer lexer = new HeaderLexer(stream); TokenStream tokens = new CommonTokenStream(lexer); HeaderParser parser = new HeaderParser(tokens); ParseTree tree = parser.root(); Future<JDialog> inspect = Trees.inspect(tree, parser); try { Utils.waitForClose(inspect.get()); } catch (Exception e) { e.printStackTrace(); } } //test body parse }
package be.bendem.bot; import be.bendem.bot.commands.LoadCommand; import be.bendem.bot.commands.SaveCommand; import be.bendem.bot.commands.StartCommand; import fr.ribesg.alix.api.Client; import fr.ribesg.alix.api.Log; import fr.ribesg.alix.api.Server; import fr.ribesg.alix.api.bot.command.Command; import fr.ribesg.alix.api.bot.command.CommandManager; import fr.ribesg.alix.api.bot.config.AlixConfiguration; import fr.ribesg.alix.api.bot.util.PasteUtil; import org.apache.log4j.Level; import org.apache.log4j.Logger; import java.io.IOException; import java.util.Collections; /** * @author bendem */ public class RpgBot extends Client { private final AlixConfiguration config; private final CommandManager commandManager; public RpgBot() { super("RpgBot"); logger.info("Starting up..."); PasteUtil.setMode(null); config = new AlixConfiguration(""); if(!config.exists()) { try { config.save(); } catch(IOException e) { getLogger().error("Error while loading config", e); } } commandManager = createCommandManager("!", Collections.emptySet()); loadItMyself(); getServers().forEach(Server::connect); } private void loadItMyself() { getServers().addAll(config.getServers()); register(new StartCommand()); register(new SaveCommand()); register(new LoadCommand()); } private void register(Command command) { commandManager.registerCommand(command); } @Override protected boolean load() { return true; } public static void main(final String args[]) { Log.get().setLevel(Level.INFO); RpgBot bot = new RpgBot(); while(!System.console().readLine().equalsIgnoreCase("stop")); bot.kill(); } private static final Logger logger = Logger.getLogger("Georges"); static { logger.setLevel(Level.ALL); } public static Logger getLogger() { return logger; } }
package com.codeski.nbt; import java.awt.GraphicsEnvironment; import java.io.Console; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import javax.swing.JFileChooser; import javax.swing.filechooser.FileFilter; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import com.codeski.nbt.tags.NBTCompound; /** * Class allows for GUI and CLI interaction for converting files from NBT to NBT, JSON, or XML. */ public class Main { public static void main(String[] args) throws FileNotFoundException, IOException { Console console = System.console(); if (console != null) if (args.length == 2) { // Read in a user specified file File in = new File(args[0]); System.out.println("Reading " + in.getCanonicalPath() + "..."); NBTCompound root = NBTReader.read(in); // Write the file to NBT, JSON, or XML File out = new File(args[1]); String extension = args[1].substring(args[1].lastIndexOf('.') + 1); System.out.println("Writing " + out.getCanonicalPath() + "..."); if (extension.equalsIgnoreCase("dat")) NBTWriter.writeNBT(root, out); else if (extension.equalsIgnoreCase("json")) NBTWriter.writeJSON(root, out); else if (extension.equalsIgnoreCase("xml")) NBTWriter.writeXML(root, out); else { System.out.println("File extension was not dat, json, or xml. Writing NBT by default."); NBTWriter.writeNBT(root, out); } } else System.out.println("Usage: java -jar " + new File(Main.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getName() + " <file-to-read> <file-to-write>"); else if (!GraphicsEnvironment.isHeadless()) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) { e.printStackTrace(); } JFileChooser fc = new JFileChooser(); FileFilter nbt = new FileNameExtensionFilter("Named Binary Tag (.dat)", "dat"); fc.addChoosableFileFilter(nbt); // Show an open file dialog int ret = fc.showOpenDialog(null); if (ret == JFileChooser.APPROVE_OPTION) { File in = fc.getSelectedFile(); NBTCompound root = NBTReader.read(in); FileFilter json = new FileNameExtensionFilter("JavaScript Object Notation (.json)", "json"); fc.addChoosableFileFilter(json); FileFilter xml = new FileNameExtensionFilter("Extensible Markup Language (.xml)", "xml"); fc.addChoosableFileFilter(xml); fc.setFileFilter(fc.getAcceptAllFileFilter()); // Show a save file dialog ret = fc.showSaveDialog(null); if (ret == JFileChooser.APPROVE_OPTION) { File out = fc.getSelectedFile(); if (fc.getFileFilter().equals(nbt)) NBTWriter.writeNBT(root, out); else if (fc.getFileFilter().equals(json)) NBTWriter.writeJSON(root, out); else if (fc.getFileFilter().equals(xml)) NBTWriter.writeXML(root, out); else { String ext = out.getName().substring(out.getName().lastIndexOf('.') + 1, out.getName().length()); if (ext.equalsIgnoreCase("dat")) NBTWriter.writeNBT(root, out); else if (ext.equalsIgnoreCase("json")) NBTWriter.writeJSON(root, out); else if (ext.equalsIgnoreCase("xml")) NBTWriter.writeXML(root, out); else NBTWriter.writeNBT(root, out); // Default case is to write NBT data } } } } } }
package example; import nom.bdezonia.zorbage.algebra.G; import nom.bdezonia.zorbage.algorithm.ApproxStdDev; import nom.bdezonia.zorbage.algorithm.ApproxVariance; import nom.bdezonia.zorbage.algorithm.Mean; import nom.bdezonia.zorbage.algorithm.StdDev; import nom.bdezonia.zorbage.algorithm.Sum; import nom.bdezonia.zorbage.algorithm.Variance; import nom.bdezonia.zorbage.datasource.IndexedDataSource; import nom.bdezonia.zorbage.datasource.ReadOnlyHighPrecisionDataSource; import nom.bdezonia.zorbage.type.float64.real.Float64Member; import nom.bdezonia.zorbage.type.highprec.real.HighPrecisionAlgebra; import nom.bdezonia.zorbage.type.highprec.real.HighPrecisionMember; import nom.bdezonia.zorbage.type.int32.UnsignedInt32Algebra; import nom.bdezonia.zorbage.type.int32.UnsignedInt32Member; /** * @author Barry DeZonia */ class DataAnalysis { // Zorbage has a few nice wrinkles for accurately calculating numbers from data. // When you are summing a lot of numbers most programs are susceptible to overflow. // However Zorbage can work around limitations like these. void example1() { IndexedDataSource<UnsignedInt32Member> uints = nom.bdezonia.zorbage.storage.Storage.allocate(Integer.MAX_VALUE, G.UINT32.construct()); // elsewhere: fill the list with values // now sum all the numbers in the list UnsignedInt32Member sum = G.UINT32.construct(); Sum.compute(G.UINT32, uints, sum); // sum may have overflowed // so this is how we avoid overflow if we're worried about it HighPrecisionMember sum2 = G.HP.construct(); ReadOnlyHighPrecisionDataSource<UnsignedInt32Algebra,UnsignedInt32Member> filteredData = new ReadOnlyHighPrecisionDataSource<>(G.UINT32, uints); Sum.compute(G.HP, filteredData, sum2); // sum2 cannot overflow } // Zorbage can also avoid roundoff errors, especially when using large amounts of data void example2() { HighPrecisionAlgebra.setPrecision(150); IndexedDataSource<UnsignedInt32Member> uints = nom.bdezonia.zorbage.storage.Storage.allocate(Integer.MAX_VALUE, G.UINT32.construct()); // elsewhere: fill the list with values // now sum all the numbers in the list avoiding overflow and rounding errors HighPrecisionMember sum = G.HP.construct(); ReadOnlyHighPrecisionDataSource<UnsignedInt32Algebra,UnsignedInt32Member> filteredData = new ReadOnlyHighPrecisionDataSource<>(G.UINT32, uints); Sum.compute(G.HP, filteredData, sum); // sum cannot have lost precision within 150 places } // This approach also makes sure means, variances, and stddevs are perfectly accurate void example3() { HighPrecisionAlgebra.setPrecision(150); IndexedDataSource<UnsignedInt32Member> uints = nom.bdezonia.zorbage.storage.Storage.allocate(Integer.MAX_VALUE, G.UINT32.construct()); // elsewhere: fill the list with values // now sum all the numbers in the list avoiding overflow and rounding errors HighPrecisionMember mean = G.HP.construct(); HighPrecisionMember variance = G.HP.construct(); HighPrecisionMember stddev = G.HP.construct(); ReadOnlyHighPrecisionDataSource<UnsignedInt32Algebra,UnsignedInt32Member> filteredData = new ReadOnlyHighPrecisionDataSource<>(G.UINT32, uints); Mean.compute(G.HP, filteredData, mean); // accurate to 150 decimal places Variance.compute(G.HP, filteredData, variance); // accurate to 150 decimal places StdDev.compute(G.HP, filteredData, stddev); // accurate to 150 decimal places } // The exact calculations use naive mathematically correct implementations. When using the // high precision infrastructure you get accurate results. This comes at a cost of increased // processing time. If you need to trade off accuracy for speed you can use the approximate // algorithms. They guard against overflow and roundoff errors but their results are as a // consequence less precise. In fact some values simply cannot be calculated using these // methods (for instance doing math with numbers that approach max float values etc.). void example4() { IndexedDataSource<Float64Member> data = nom.bdezonia.zorbage.storage.Storage.allocate(1000000, G.DBL.construct()); // elsewhere fill list with data // now calc approximate results Float64Member variance = G.DBL.construct(); Float64Member stddev = G.DBL.construct(); ApproxVariance.compute(G.DBL, data, variance); // close to correct. faster than exact. ApproxStdDev.compute(G.DBL, data, stddev); // close to correct. faster than exact. } }
package i5.las2peer.p2p; import i5.las2peer.api.Service; import i5.las2peer.communication.Message; import i5.las2peer.communication.MessageException; import i5.las2peer.communication.RMIExceptionContent; import i5.las2peer.communication.RMIResultContent; import i5.las2peer.communication.RMIUnlockContent; import i5.las2peer.execution.L2pServiceException; import i5.las2peer.execution.L2pThread; import i5.las2peer.execution.NoSuchServiceException; import i5.las2peer.execution.NotFinishedException; import i5.las2peer.execution.RMITask; import i5.las2peer.execution.ServiceInvocationException; import i5.las2peer.execution.UnlockNeededException; import i5.las2peer.logging.NodeObserver; import i5.las2peer.logging.NodeObserver.Event; import i5.las2peer.logging.NodeStreamLogger; import i5.las2peer.logging.monitoring.MonitoringObserver; import i5.las2peer.p2p.pastry.PastryStorageException; import i5.las2peer.persistency.DecodingFailedException; import i5.las2peer.persistency.EncodingFailedException; import i5.las2peer.persistency.Envelope; import i5.las2peer.persistency.EnvelopeException; import i5.las2peer.security.Agent; import i5.las2peer.security.AgentException; import i5.las2peer.security.AgentStorage; import i5.las2peer.security.Context; import i5.las2peer.security.DuplicateEmailException; import i5.las2peer.security.DuplicateLoginNameException; import i5.las2peer.security.GroupAgent; import i5.las2peer.security.L2pSecurityException; import i5.las2peer.security.Mediator; import i5.las2peer.security.MessageReceiver; import i5.las2peer.security.MonitoringAgent; import i5.las2peer.security.ServiceAgent; import i5.las2peer.security.UserAgent; import i5.las2peer.security.UserAgentList; import i5.las2peer.testing.MockAgentFactory; import i5.las2peer.tools.CryptoException; import i5.las2peer.tools.CryptoTools; import i5.las2peer.tools.SerializationException; import java.io.File; import java.io.FileNotFoundException; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.security.KeyPair; import java.security.PublicKey; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashSet; import java.util.Hashtable; import java.util.Vector; import rice.pastry.NodeHandle; /** * Base class for nodes in the LAS2peer environment. * * A Node represents one enclosed unit in the network hosting an arbitrary number of * agents willing to participate in the P2P networking. * * @author Holger Jan&szlig;en * */ public abstract class Node implements AgentStorage { private static final String MAINLIST_ID = "mainlist"; /** * The Sending mode for outgoing messages. * * @author Holger Jan&szlig;en * */ public enum SendMode { ANYCAST, BROADCAST }; /** * Enum with the possible states of a node. * * @author Holger Jan&szlig;en * */ public enum NodeStatus { UNCONFIGURED, CONFIGURED, STARTING, RUNNING, CLOSING, CLOSED } /** * observers to be notified of all occurring events */ private HashSet<NodeObserver> observers = new HashSet<NodeObserver>(); /** * contexts for local method invocation */ private Hashtable <Long, Context> htLocalExecutionContexts = new Hashtable<Long, Context>(); /** * status of this node */ private NodeStatus status = NodeStatus.UNCONFIGURED; /** * hashtable with all {@link i5.las2peer.security.MessageReceiver}s registered at this node */ private Hashtable<Long,MessageReceiver> htRegisteredReceivers = new Hashtable<Long, MessageReceiver>(); private ClassLoader baseClassLoader = null; private Hashtable<Long, MessageResultListener> htAnswerListeners = new Hashtable <Long, MessageResultListener>(); /** * a simple prefix for a logfile to be generated on node startup */ private String sLogFilePrefix = "log/l2p_node_"; private final static String DEFAULT_INFORMATION_FILE = "config/nodeInfo.xml"; private String sInformationFileName = DEFAULT_INFORMATION_FILE; private KeyPair nodeKeyPair; /** * the list of users containing email an login name tables */ private Envelope activeUserList = null; /** * a set of updates on user Agents to perform, if an update storage of {@link activeUserList} fails */ private HashSet<UserAgent> hsUserUpdates = new HashSet<UserAgent> (); /** * Creates a new node, if the standardObserver flag is true, an observer logging all events to a * simple plain text log file will be generated. * If not, no observer will be used at startup. * * @param standardObserver */ public Node ( boolean standardObserver ) { this ( null, standardObserver ); } /** * Creates a new node with a standard plain text log file observer. */ public Node () { this ( true ); } /** * * @param baseClassLoader * */ public Node ( ClassLoader baseClassLoader ) { this ( baseClassLoader, true); } /** * * @param baseClassLoader * @param standardObserver * */ public Node ( ClassLoader baseClassLoader, boolean standardObserver ) { this (baseClassLoader, standardObserver, false); } /** * * Generates a new Node with the given baseClassLoader. * The Observer-flags determine, which observers will be registered at startup. * * @param baseClassLoader * @param standardObserver * @param monitoringObserver * */ public Node(ClassLoader baseClassLoader, boolean standardObserver, boolean monitoringObserver){ if ( standardObserver ){ initStandardLogfile (); } if(monitoringObserver){ addObserver(new MonitoringObserver(50, this)); } this.baseClassLoader = baseClassLoader; if ( baseClassLoader == null) this.baseClassLoader = this.getClass().getClassLoader(); nodeKeyPair = CryptoTools.generateKeyPair(); } /** * Gets the public key of this node. * * @return a public key */ public PublicKey getPublicNodeKey () { return nodeKeyPair.getPublic(); } /** * Creates an observer for a standard log-file. * The name of the log-file will contain the id of the node to prevent conflicts if * running multiple nodes on the same machine. */ private void initStandardLogfile () { try { if ( this instanceof LocalNode ) addObserver( new NodeStreamLogger("log/l2p_local_" + ((LocalNode) this).getNodeId() + ".log")); else if ( this instanceof PastryNodeImpl ) addObserver ( new NodeStreamLogger () ); else addObserver ( new NodeStreamLogger ( "log/l2p_node.log")); } catch (FileNotFoundException e) { System.err.println ( "Error opening standard node log: " + e + "\n\n\n"); addObserver ( new NodeStreamLogger ( System.out)); } } /** * Handles a request from the (p2p) net to unlock the private key of a remote Agent. * * @throws L2pSecurityException * @throws AgentNotKnownException * @throws CryptoException * @throws SerializationException */ public void unlockRemoteAgent (long agentId, byte[] enctryptedPass ) throws L2pSecurityException, AgentNotKnownException, SerializationException, CryptoException { String passphrase= (String) CryptoTools.decryptAsymmetric(enctryptedPass, nodeKeyPair.getPrivate()); Context context = getAgentContext(agentId); if ( ! context.getMainAgent().isLocked()) return; context.unlockMainAgent ( passphrase ); observerNotice(Event.AGENT_UNLOCKED, ""+agentId); } /** * Sends a request to unlock the agent's private key to the target node. * * @param agentId * @param passphrase * @param targetNode * @param nodeEncryptionKey * @throws L2pSecurityException */ public abstract void sendUnlockRequest ( long agentId, String passphrase, Object targetNode, PublicKey nodeEncryptionKey ) throws L2pSecurityException; /** * Adds an observer to this node. * * @param observer */ public void addObserver ( NodeObserver observer ) { observers.add ( observer ); } /** * Removes an observer from this node. * * @param observer */ public void removeObserver ( NodeObserver observer ) { observers.remove ( observer ); } /** * Enables the service monitoring for the requested Service. * * @param service */ public void setServiceMonitoring(ServiceAgent service){ for ( NodeObserver ob: observers ) ob.logEvent(Event.SERVICE_ADD_TO_MONITORING, this.getNodeId(), service.getId(), service.getServiceClassName()); } /** * Logs an event to all observers. * * @param event * @param remarks */ public void observerNotice ( Event event, String remarks ) { for ( NodeObserver ob: observers ) ob.logEvent(event, remarks); } /** * Logs an event to all observers. * * @param event * @param sourceNode * @param remarks */ public void observerNotice ( Event event, Object sourceNode, String remarks ) { for ( NodeObserver ob: observers ) ob.logEvent(event, sourceNode, remarks); } /** * Logs an event to all observers. * * @param event * @param sourceNode * @param sourceAgentId * @param remarks */ public void observerNotive ( Event event, Object sourceNode, long sourceAgentId, String remarks ) { for ( NodeObserver ob: observers ) ob.logEvent(event, sourceNode, sourceAgentId, remarks); } /** * Logs an event to all observers. * * @param event * @param sourceNode * @param sourceAgent * @param remarks */ public void observerNotice ( Event event, Object sourceNode, MessageReceiver sourceAgent, String remarks ) { Long sourceAgentId = null; if(sourceAgent != null) sourceAgentId = sourceAgent.getResponsibleForAgentId(); for ( NodeObserver ob: observers ) ob.logEvent(event, sourceNode, sourceAgentId, remarks); } /** * Logs an event to all observers. * * @param event * @param sourceNode * @param sourceAgent * @param destinationNode * @param destinationAgent * @param remarks */ public void observerNotice ( Event event, Object sourceNode, Agent sourceAgent, Object destinationNode, Agent destinationAgent, String remarks ) { Long sourceAgentId = null; if(sourceAgent != null) sourceAgentId = sourceAgent.getId(); Long destinationAgentId = null; if(destinationAgent != null) destinationAgentId = destinationAgent.getId(); for ( NodeObserver ob: observers ) ob.logEvent(event, sourceNode, sourceAgentId, destinationNode, destinationAgentId, remarks); } /** * Logs an event to all observers. * * @param event * @param sourceNode * @param sourceAgentId * @param destinationNode * @param destinationAgentId * @param remarks */ public void observerNotice ( Event event, Object sourceNode, Long sourceAgentId, Object destinationNode, Long destinationAgentId, String remarks ) { for ( NodeObserver ob: observers ) ob.logEvent(event, sourceNode, sourceAgentId, destinationNode, destinationAgentId, remarks); } /** * Gets the status of this node. * * @return status of this node */ public NodeStatus getStatus () { return status; }; /** * Gets some kind of node identifier. * * @return id of this node */ public abstract Serializable getNodeId (); /** * Gets the class loader, this node is bound to. * In a <i>real</i> Las2Peer environment, this should refer to a * {@link i5.las2peer.classLoaders.L2pClassLoader} * * Otherwise, the class loader of this Node class is used. * * @return a class loader */ public ClassLoader getBaseClassLoader () { return baseClassLoader; } /** * Sets the status of this node. * * @param newstatus */ protected void setStatus ( NodeStatus newstatus ) { if ( newstatus == NodeStatus.RUNNING && this instanceof PastryNodeImpl ){ observerNotice(Event.NODE_STATUS_CHANGE, this.getNodeId(), ""+newstatus); for ( NodeObserver observer : observers ) { if(observer instanceof NodeStreamLogger){ try { DateFormat fmt = new SimpleDateFormat( "yyyy-MM-dd_HH-mm-ss" ); NodeHandle nh = (NodeHandle) getNodeId(); String filename = sLogFilePrefix + "_pastry_" + fmt.format(new Date()) + "_" + nh.getNodeId().toStringFull(); filename += ".log"; System.out.println ( "set logfile to " + filename); ((NodeStreamLogger)observer).setOutputFile( filename); } catch ( Exception e ) { System.out.println ( "error setting logfile: " + e ); } } } } else if(newstatus == NodeStatus.CLOSING){ observerNotice(Event.NODE_STATUS_CHANGE, this.getNodeId(), ""+newstatus); } else{ observerNotice(Event.NODE_STATUS_CHANGE, ""+newstatus ); } status = newstatus; } /** * Sets a prefix for a log file, if the node has not been started yet. * * @param prefix */ public void setLogfilePrefix ( String prefix ) { if ( getStatus() != NodeStatus.UNCONFIGURED && getStatus() != NodeStatus.CONFIGURED ) throw new IllegalStateException ( "You can set a logfile prefix only before startup!"); sLogFilePrefix = prefix ; } /** * Gets the filename of the current information file for this node. * The file should be an XML file representation of a {@link NodeInformation}. * * @return filename */ public String getInformationFilename () { return sInformationFileName; } /** * Sets the nodes information filename. * * @param filename */ public void setInformationFilename ( String filename ) { if ( new File( filename ).exists() ) sInformationFileName = filename; } /** * Gets information about this node including all registered service classes. * * @return node information * @throws CryptoException */ public NodeInformation getNodeInformation () throws CryptoException { NodeInformation result = new NodeInformation( getRegisteredServices() ); try { if ( sInformationFileName != null && new File(sInformationFileName).exists()) result = NodeInformation.createFromXmlFile ( sInformationFileName, getRegisteredServices()); } catch ( Exception e ) { e.printStackTrace(); } result.setNodeHandle(getNodeId()); result.setNodeKey ( nodeKeyPair.getPublic()); result.setSignature( CryptoTools.signContent(result.getSignatureContent(), nodeKeyPair.getPrivate())); return result; } /** * Gets information about a distant node. * * @param nodeId * * @return information about the node * @throws NodeNotFoundException */ public abstract NodeInformation getNodeInformation ( Object nodeId ) throws NodeNotFoundException; /** * Gets an array with identifiers of other (locally known) nodes in this network. * * @return array with handles of other (known) p2p network nodes */ public abstract Object[] getOtherKnownNodes (); /** * Starts this node. */ public abstract void launch() throws NodeException; /** * Stops the node. */ public void shutDown () { for ( Long id: htRegisteredReceivers.keySet() ) htRegisteredReceivers.get(id).notifyUnregister(); observerNotice(Event.NODE_SHUTDOWN, this.getNodeId(), null); for(NodeObserver observer : observers){ if(observer instanceof MonitoringObserver){ try { System.out.println("Wait a little to give the observer time to send its last message..."); Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } break; } } htRegisteredReceivers = new Hashtable<Long, MessageReceiver> (); } /** * Registers a (local) Agent for usage through this node. * The Agent has to be unlocked before registration. * * @param receiver * * @throws AgentAlreadyRegisteredException the given agent is already registered to this node * @throws L2pSecurityException the agent is not unlocked * @throws AgentException any problem with the agent itself (probably on calling {@link i5.las2peer.security.Agent#notifyRegistrationTo} * @throws PastryStorageException */ public void registerReceiver(MessageReceiver receiver) throws AgentAlreadyRegisteredException, L2pSecurityException, AgentException { if (getStatus() != NodeStatus.RUNNING) throw new IllegalStateException ("You can register agents only to running nodes!"); if (htRegisteredReceivers.get(receiver.getResponsibleForAgentId()) != null) throw new AgentAlreadyRegisteredException ("This agent is already running here!"); if ( (receiver instanceof Agent) ) { // we have an agent Agent agent = (Agent ) receiver; if ( agent.isLocked() ) throw new L2pSecurityException ("An agent has to be unlocked for registering at a node"); if ( ! knowsAgentLocally ( agent.getId() )) try { storeAgent ( agent ); } catch (AgentAlreadyRegisteredException e) { System.out.println ( "Just for notice - not an error: tried to store an already known agent before registering"); // nothing to do } try { // ensure (unlocked) context getAgentContext( (Agent) receiver ); } catch ( Exception e ) { } if ( agent instanceof UserAgent ){ observerNotice(Event.AGENT_REGISTERED, this.getNodeId(), agent, "UserAgent"); } else if ( agent instanceof ServiceAgent ){ observerNotice(Event.AGENT_REGISTERED, this.getNodeId(), agent, "ServiceAgent"); } else if ( agent instanceof GroupAgent ){ observerNotice(Event.AGENT_REGISTERED, this.getNodeId(), agent, "GroupAgent"); } else if ( agent instanceof MonitoringAgent ){ observerNotice(Event.AGENT_REGISTERED, this.getNodeId(), agent, "MonitoringAgent"); } } else { // ok, we have a mediator observerNotice(Event.AGENT_REGISTERED, this.getNodeId(), receiver, "Mediator"); } htRegisteredReceivers.put(receiver.getResponsibleForAgentId(), receiver); try { receiver.notifyRegistrationTo(this); } catch ( AgentException e ) { observerNotice(Event.AGENT_LOAD_FAILED, this, receiver, e.toString() ); htRegisteredReceivers.remove(receiver.getResponsibleForAgentId()); throw e; } catch (Exception e) { observerNotice(Event.AGENT_LOAD_FAILED, this, receiver, e.toString() ); htRegisteredReceivers.remove( receiver.getResponsibleForAgentId()); throw new AgentException ( "problems notifying agent of registration", e ); } } /** * Unregisters an agent from this node. * * @param agent * @throws AgentNotKnownException the agent is not registered to this node */ public void unregisterAgent ( Agent agent ) throws AgentNotKnownException { unregisterAgent ( agent.getId()); } /** * Is an instance of the given agent running at this node? * * @param agentId */ public void unregisterAgent(long agentId) throws AgentNotKnownException { if ( htRegisteredReceivers.get(agentId) == null) throw new AgentNotKnownException ( agentId ); observerNotice(Event.AGENT_REMOVED, this.getNodeId(), getAgent(agentId), null); htRegisteredReceivers.get(agentId).notifyUnregister(); htRegisteredReceivers.remove( agentId ); } /** * Is an instance of the given agent running at this node? * * @param agent * @return true, if the given agent is running at this node */ public boolean hasLocalAgent ( Agent agent ) { return hasLocalAgent ( agent.getId() ); } /** * Is an instance of the given agent running at this node? * * @param agentId * @return true, if the given agent is registered here */ public boolean hasLocalAgent(long agentId) { return htRegisteredReceivers.get(agentId ) != null; } /** * Sends a message, recipient and sender are stated in the message. * The node tries to find a node hosting the recipient * and sends the message there. * * @param message the message to send * @param listener a listener for getting the result separately */ public void sendMessage ( Message message, MessageResultListener listener ) { sendMessage ( message, listener, SendMode.ANYCAST); } /** * Sends a message, recipient and sender are stated in the message. * Depending on the mode, either all nodes running the given agent * will be notified of this message, or only a random one. * * NOTE: Pastry nodes will always use broadcast at the moment! * * @param message the message to send * @param listener a listener for getting the result separately * @param mode is it a broadcast or an any-cast message? */ public abstract void sendMessage ( Message message, MessageResultListener listener, SendMode mode ); /** * Sends a message to the agent residing at the given node. * * @param message * @param atNodeId * @param listener a listener for getting the result separately * * @throws AgentNotKnownException * @throws NodeNotFoundException * @throws L2pSecurityException */ public abstract void sendMessage ( Message message, Object atNodeId, MessageResultListener listener ) throws AgentNotKnownException, NodeNotFoundException, L2pSecurityException; /** * Sends the given response message to the given node. * * @param message * @param atNodeId * * @throws AgentNotKnownException * @throws NodeNotFoundException * @throws L2pSecurityException */ public void sendResponse(Message message, Object atNodeId) throws AgentNotKnownException, NodeNotFoundException, L2pSecurityException { sendMessage ( message, atNodeId, null ); } /** * For <i>external</i> access to this node. Will be called by the (P2P) network library, when * a new message has been received via the network and could not be handled otherwise. * * Make sure, that the {@link #baseClassLoader} method is used for answer messages. * * @param message * * @throws AgentNotKnownException the designated recipient is not known at this node * @throws MessageException * @throws L2pSecurityException */ public void receiveMessage(Message message) throws AgentNotKnownException, MessageException, L2pSecurityException { if ( message.isResponse()) if ( handoverAnswer(message)) return; //Since this field is not always available if (message.getSendingNodeId() != null){ observerNotice(Event.MESSAGE_RECEIVED, message.getSendingNodeId(), message.getSenderId(), this.getNodeId(), message.getRecipientId(), message.getId() + ""); } else{ observerNotice(Event.MESSAGE_RECEIVED, null, message.getSenderId(), this.getNodeId(), message.getRecipientId(), message.getId() + ""); } MessageReceiver receiver = htRegisteredReceivers.get( message.getRecipientId() ); if ( receiver == null ) throw new AgentNotKnownException(message.getRecipientId()); receiver.receiveMessage(message, getAgentContext ( message.getSenderId())); } /** * Gets an artifact from the p2p storage. * * @param id * * @return the envelope containing the requested artifact * * @throws ArtifactNotFoundException * @throws StorageException */ public abstract Envelope fetchArtifact ( long id ) throws ArtifactNotFoundException, StorageException; /** * Stores an artifact to the p2p storage. * * @param envelope * @throws StorageException * @throws L2pSecurityException * */ public abstract void storeArtifact ( Envelope envelope ) throws StorageException, L2pSecurityException; /** * Removes an artifact from the p2p storage. * <i>NOTE: This is not possible with a FreePastry backend!</i> * * @param id * @param signature * * @throws ArtifactNotFoundException * @throws StorageException */ public abstract void removeArtifact ( long id, byte[] signature) throws ArtifactNotFoundException, StorageException; /** * Searches the nodes for registered Versions of the given Agent. * Returns an array of objects identifying the nodes the given agent is registered to. * * @param agentId id of the agent to look for * @param hintOfExpectedCount a hint for the expected number of results (e.g. to wait for) * @return array with the IDs of nodes, where the given agent is registered * * @throws AgentNotKnownException */ public abstract Object[] findRegisteredAgent ( long agentId, int hintOfExpectedCount ) throws AgentNotKnownException; /** * Search the nodes for registered versions of the given agent. * Returns an array of objects identifying the nodes the given agent is registered to. * * @param agent * @return array with the IDs of nodes, where the given agent is registered * @throws AgentNotKnownException */ public Object[] findRegisteredAgent ( Agent agent ) throws AgentNotKnownException { return findRegisteredAgent(agent.getId()); } /** * Searches the nodes for registered versions of the given agentId. * Returns an array of objects identifying the nodes the given agent is registered to. * * @param agentId id of the agent to look for * @return array with the IDs of nodes, where the given agent is registered * @throws AgentNotKnownException */ public Object[] findRegisteredAgent ( long agentId ) throws AgentNotKnownException { return findRegisteredAgent ( agentId, 1); } /** * searches the nodes for registered versions of the given agent. * Returns an array of objects identifying the nodes the given agent is registered to. * * @param agent * @param hintOfExpectedCount a hint for the expected number of results (e.g. to wait for) * @return array with the IDs of nodes, where the given agent is registered * @throws AgentNotKnownException */ public Object[] findRegisteredAgent ( Agent agent, int hintOfExpectedCount ) throws AgentNotKnownException { return findRegisteredAgent(agent.getId(), hintOfExpectedCount); } /** * Gets an agent description from the net. * * make sure, always to return fresh versions of the requested agent, so that no thread can unlock the private key * for another one! * * @param id * * @return the requested agent * * @throws AgentNotKownException */ public abstract Agent getAgent ( long id ) throws AgentNotKnownException; /** * Does this node know an agent with the given id? * * from {@link i5.las2peer.security.AgentStorage} * * @param id * @return true, if this node knows the given agent */ @Override public boolean hasAgent ( long id ) { // Since an request for this agent is probable after this check, it makes sense // to try to load it into this node and decide afterwards try { getAgent ( id); return true; } catch ( AgentNotKnownException e ){ return false; } } /** * Checks, if an agent of the given id is known locally. * * @param agentId * @return true, if this agent is (already) known here at this node */ public abstract boolean knowsAgentLocally ( long agentId ); /** * Gets a local registered agent by its id. * * @param id * * @return the agent registered to this node * @throws AgentNotKnownException */ public Agent getLocalAgent(long id) throws AgentNotKnownException { MessageReceiver result = htRegisteredReceivers.get( id ); if ( result == null ) throw new AgentNotKnownException ( "The given agent agent is not registered to this node"); if ( result instanceof Agent ) return (Agent) result; else throw new AgentNotKnownException ( "The requested Agent is only known as a Mediator here!"); } /** * Gets an array with all {@link i5.las2peer.security.UserAgent}s registered at this node. * * @return all local registered UserAgents */ public UserAgent[] getRegisteredAgents() { Vector<UserAgent> result = new Vector<UserAgent> (); for ( MessageReceiver rec : htRegisteredReceivers.values() ) { if( rec instanceof UserAgent) result.add ( (UserAgent) rec ); } return result.toArray ( new UserAgent[0]); } /** * Gets an array with all {@link i5.las2peer.security.ServiceAgent}s registered at this node. * * @return all local registered ServiceAgents */ public ServiceAgent[] getRegisteredServices() { Vector<ServiceAgent> result = new Vector<ServiceAgent> (); for ( MessageReceiver rec : htRegisteredReceivers.values() ) { if( rec instanceof ServiceAgent) result.add ( (ServiceAgent) rec ); } return result.toArray ( new ServiceAgent[0]); } /** * Gets a local registered mediator for the given agent id. * If no mediator exists, registers a new one to this node. * * @param agent * * @return the mediator for the given agent * * @throws AgentNotKnownException * @throws L2pSecurityException * @throws AgentException * @throws AgentAlreadyRegisteredException */ public Mediator getOrRegisterLocalMediator ( Agent agent ) throws AgentNotKnownException, L2pSecurityException, AgentAlreadyRegisteredException, AgentException { if ( agent.isLocked ()) throw new L2pSecurityException("you need to unlock the agent for mediation!"); MessageReceiver result = htRegisteredReceivers.get( agent.getId() ); if ( result != null && ! (result instanceof Mediator ) ) throw new AgentNotKnownException ( "The requested Agent is registered directly at this node!"); if ( result == null ) { getAgentContext ( agent ); result = new Mediator ( agent ); registerReceiver(result); } return (Mediator) result; } /** * Stores a new Agent to the network. * * @param agent * * @throws AgentAlreadyRegisteredException * @throws L2pSecurityException * @throws PastryStorageException */ public abstract void storeAgent ( Agent agent ) throws AgentAlreadyRegisteredException, L2pSecurityException, AgentException; /** * Updates an existing agent of the network. * * @param agent * * @throws L2pSecurityException * @throws PastryStorageException * @throws AgentException */ public abstract void updateAgent ( Agent agent ) throws AgentException, L2pSecurityException, PastryStorageException; private Agent anonymousAgent = null; /** * get an agent to use, if no <i>real</i> agent is available * @return a generic anonymous agent */ public Agent getAnonymous () { if ( anonymousAgent == null ) { try { anonymousAgent = getAgent ( MockAgentFactory.getAnonymous().getId() ); } catch (Exception e) { try { anonymousAgent = MockAgentFactory.getAnonymous(); ((UserAgent)anonymousAgent).unlockPrivateKey("anonymous"); storeAgent(anonymousAgent); } catch (Exception e1) { throw new RuntimeException ( "No anonymous agent could be initialized!?!", e1 ); } } } Agent result; try { result = anonymousAgent.cloneLocked(); ((UserAgent) result).unlockPrivateKey("anonymous"); } catch (Exception e) { throw new RuntimeException ( "Strange - should not happen..."); } return result; } /** * Loads the central user list from the backend. */ private void loadUserList () { Agent owner = getAnonymous(); boolean bLoadedOrCreated = false; try { try { activeUserList = fetchArtifact( Envelope.getClassEnvelopeId(UserAgentList.class, MAINLIST_ID)); activeUserList.open ( owner ); bLoadedOrCreated = true; } catch (Exception e) { if ( activeUserList == null ) { activeUserList = Envelope.createClassIdEnvelope(new UserAgentList(), MAINLIST_ID, owner ); activeUserList.open ( owner ); activeUserList.setOverWriteBlindly(false); activeUserList.lockContent(); bLoadedOrCreated = true; } } if ( bLoadedOrCreated && hsUserUpdates.size() > 0 ) { for ( UserAgent agent : hsUserUpdates) activeUserList.getContent(UserAgentList.class).updateUser(agent); doStoreUserList (); } } catch (Exception e) { observerNotice(Event.NODE_ERROR, "Error updating the user registration list: " + e.toString()); e.printStackTrace (); } } /** * Stores the current list. If the storage fails e.g. due to a failed up-to-date-check of the current * user list, the storage is attempted a second time. */ private void storeUserList() { synchronized ( hsUserUpdates ) { try { doStoreUserList(); loadUserList(); } catch (Exception e) { e.printStackTrace (); // one retry because of actuality problems: loadUserList(); try { doStoreUserList(); loadUserList(); } catch (Exception e1) { observerNotice(Event.NODE_ERROR, "Error storing new User List: " + e.toString()); } } } } /** * The actual backend storage procedure. * * @throws EncodingFailedException * @throws StorageException * @throws L2pSecurityException * @throws DecodingFailedException */ private void doStoreUserList() throws EncodingFailedException, StorageException, L2pSecurityException, DecodingFailedException { Agent anon = getAnonymous(); activeUserList.open ( anon ); activeUserList.addSignature(anon); activeUserList.close(); storeArtifact(activeUserList); activeUserList.open(anon); // ok, all changes are stored hsUserUpdates.clear(); } /** * Forces the node to publish all changes on the userlist. */ public void forceUserListUpdate() { if ( hsUserUpdates.size() > 0 ) storeUserList(); } /** * Update the registry of login and mail addresses of known / stored user agents on * an {@link #updateAgent(Agent)} or {@link #storeAgent(Agent)} action. * * @param agent * @throws DuplicateEmailException * @throws DuplicateLoginNameException */ protected void updateUserAgentList ( UserAgent agent ) throws DuplicateEmailException, DuplicateLoginNameException { synchronized ( hsUserUpdates ) { if ( activeUserList == null ) loadUserList(); try { activeUserList.getContent(UserAgentList.class).updateUser( agent ); } catch (EnvelopeException e) { observerNotice(Event.NODE_ERROR, "Envelope error while updating user list: " + e ); } synchronized ( hsUserUpdates ) { hsUserUpdates.add( agent ); if ( hsUserUpdates.size() > 10 ) { storeUserList(); } } } } /** * Gets an id for the user for the given login name. * * @param login * @return agent id * @throws AgentNotKnownException */ public long getAgentIdForLogin ( String login ) throws AgentNotKnownException { if ( activeUserList == null) { loadUserList(); } if ( activeUserList == null ) throw new AgentNotKnownException ("No agents known!"); try { return activeUserList.getContent( UserAgentList.class).getLoginId(login); } catch (AgentNotKnownException e) { // retry once loadUserList(); try { return activeUserList.getContent( UserAgentList.class).getLoginId(login); } catch (EnvelopeException e1) { throw e; } } catch (EnvelopeException e) { throw new AgentNotKnownException ( "Envelope Problems with user list!", e); } } /** * Gets an id for the user for the given email address. * * @param email * @return agent id * @throws AgentNotKnownException */ public long getAgentIdForEmail ( String email ) throws AgentNotKnownException { if ( activeUserList == null) loadUserList(); if ( activeUserList == null ) throw new AgentNotKnownException ("No agents known!"); try { return activeUserList.getContent( UserAgentList.class).getLoginId(email); } catch (AgentNotKnownException e) { throw e; } catch (EnvelopeException e) { throw new AgentNotKnownException ( "Evelope Problems with user list!", e); } } /** * Gets the agent representing the given service class. * * prefer using a locally registered agent * * @param serviceClass * @return the ServiceAgent responsible for the given service class * @throws AgentNotKnownException */ public ServiceAgent getServiceAgent ( String serviceClass ) throws AgentNotKnownException { long agentId = ServiceAgent.serviceClass2Id(serviceClass); Agent result; try { result = getLocalAgent ( agentId ); } catch (AgentNotKnownException e) { result = getAgent ( agentId ); } if ( result == null || ! (result instanceof ServiceAgent) ) { throw new AgentNotKnownException ( "The corresponding agent is not a ServiceAgent!?"); } return (ServiceAgent) result; } /** * Invokes a service method of a local running service agent. * * @param executingAgentId * @param serviceClass * @param method * @param parameters * * @return result of the method invocation * * @throws AgentNotKnownException cannot find the executing agent * @throws L2pSecurityException * @throws InterruptedException * @throws L2pServiceException * */ public Serializable invokeLocally ( long executingAgentId, String serviceClass, String method, Serializable[] parameters ) throws L2pSecurityException, AgentNotKnownException, InterruptedException, L2pServiceException { if ( getStatus() != NodeStatus.RUNNING ) throw new IllegalStateException ( "You can invoke methods only on a running node!"); long serviceAgentId = ServiceAgent.serviceClass2Id(serviceClass); if ( ! hasLocalAgent ( serviceAgentId )) throw new NoSuchServiceException ( "Service not known locally!"); ServiceAgent serviceAgent; try { serviceAgent = getServiceAgent ( serviceClass ); } catch (AgentNotKnownException e1) { throw new NoSuchServiceException ( serviceClass, e1); } RMITask task = new RMITask (serviceClass, method, parameters); Context context = getAgentContext ( executingAgentId ); L2pThread thread = new L2pThread (serviceAgent, task, context); thread.start(); thread.join(); if ( thread.hasException() ) { Exception e = thread.getException(); if ( e instanceof ServiceInvocationException ) throw ( ServiceInvocationException ) e; else throw new ServiceInvocationException ( "Internal exception in service", thread.getException()); } try { return thread.getResult(); } catch (NotFinishedException e) { // should not occur, since we joined before throw new L2pServiceException ( "Interrupted service execution?!", e); } } /** * Tries to get an instance of the given class as a registered service of this node. * * @param classname * @return the instance of the given service class running at this node * @throws NoSuchServiceException */ public Service getLocalServiceInstance ( String classname ) throws NoSuchServiceException { try { ServiceAgent agent = (ServiceAgent) getLocalAgent( ServiceAgent.serviceClass2Id(classname)); return agent.getServiceInstance(); } catch (Exception e) { throw new NoSuchServiceException (classname); } } /** * Tries to get an instance of the given class as a registered service of this node. * @param cls * @return the (typed) instance of the given service class running at this node * @throws NoSuchServiceException */ @SuppressWarnings("unchecked") public <ServiceType extends Service> ServiceType getLocalServiceInstance ( Class<ServiceType> cls ) throws NoSuchServiceException { try { return (ServiceType) getLocalServiceInstance( cls.getName() ); } catch ( ClassCastException e ) { throw new NoSuchServiceException(cls.getName()); } } /** * Invokes a service method of the network. * * @param executing * @param serviceClass * @param serviceMethod * @param parameters * * @return result of the method invocation * * @throws L2pSecurityException * @throws ServiceInvocationException several reasons -- see subclasses * @throws InterruptedException * @throws TimeoutException * @throws UnlockNeededException */ public Serializable invokeGlobally ( Agent executing, String serviceClass, String serviceMethod, Serializable[] parameters ) throws L2pSecurityException, ServiceInvocationException, InterruptedException, TimeoutException, UnlockNeededException { if ( getStatus() != NodeStatus.RUNNING ) throw new IllegalStateException ( "you can invoce methods only on a running node!"); if ( executing.isLocked() ) throw new L2pSecurityException ( "The executing agent has to be unlocked to call a RMI"); try { Agent target = getServiceAgent(serviceClass); Message rmiMessage = new Message ( executing, target, new RMITask ( serviceClass, serviceMethod, parameters)); if ( this instanceof LocalNode ) rmiMessage.setSendingNodeId( (Long) getNodeId() ); else rmiMessage.setSendingNodeId( (NodeHandle) getNodeId () ); Message resultMessage = sendMessageAndWaitForAnswer(rmiMessage); resultMessage.open( executing, this ); Object resultContent = resultMessage.getContent(); if ( resultContent instanceof RMIUnlockContent ) { // service method needed to unlock some envelope(s) throw new UnlockNeededException ( "mediator needed at the target node", resultMessage.getSendingNodeId(), ((RMIUnlockContent) resultContent).getNodeKey() ); } else if ( resultContent instanceof RMIExceptionContent ) { Exception thrown = ((RMIExceptionContent) resultContent).getException(); if ( thrown instanceof ServiceInvocationException ) throw (ServiceInvocationException ) thrown; else if (( thrown instanceof InvocationTargetException )&& (thrown.getCause() instanceof L2pSecurityException) ) { // internal L2pSecurityException (like internal method access or unauthorizes object access) throw new L2pSecurityException ( "internal securityException!", thrown.getCause()); } else throw new ServiceInvocationException ( "remote exception at target node", thrown); } else if ( resultContent instanceof RMIResultContent ) return ((RMIResultContent) resultContent).getContent(); else throw new ServiceInvocationException ( "Unknown RMI response type: " +resultContent.getClass().getCanonicalName()); } catch (AgentNotKnownException e) { throw new NoSuchServiceException ( serviceClass, e ); } catch (EncodingFailedException e) { throw new ServiceInvocationException("message problems!", e); } catch (SerializationException e) { throw new ServiceInvocationException("message problems!", e); } } /** * Registers a MessageResultListener for collecting answers. * * @param messageId * @param listener */ public void registerAnswerListener ( long messageId, MessageResultListener listener ) { if ( listener == null) return; htAnswerListeners.put( messageId, listener); } /** * Hands over an answer message to the corresponding listener. * * @param answer * * @return true, if a listener for this answer was notified */ public boolean handoverAnswer ( Message answer ) { if ( !answer.isResponse()) return false; observerNotice(Event.MESSAGE_RECEIVED_ANSWER, answer.getSendingNodeId(), answer.getSenderId(), this.getNodeId(), answer.getRecipientId(), ""+answer.getResponseToId()); MessageResultListener listener = htAnswerListeners.get ( answer.getResponseToId() ); if ( listener == null ) { System.out.println ("Did not find corresponding observer!"); return false; } listener.collectAnswer(answer); return true; } /** * Sends a message and wait for one answer message. * * @param m * * @return a (possible) response message * * @throws InterruptedException * @throws TimeoutException */ public Message sendMessageAndWaitForAnswer ( Message m ) throws InterruptedException, TimeoutException { long timeout = m.getTimeoutTs() - new Date().getTime(); MessageResultListener listener = new MessageResultListener( timeout ); sendMessage ( m, listener ); listener.waitForOneAnswer(); if ( listener.isSuccess() ) return listener.getResults()[0]; else throw new TimeoutException (); } /** * Sends a message to the given id and wait for one answer message. * * @param m * @param atNodeId * * @return a response message * * @throws AgentNotKnownException * @throws NodeNotFoundException * @throws L2pSecurityException * @throws InterruptedException */ public Message sendMessageAndWaitForAnswer ( Message m, Object atNodeId ) throws AgentNotKnownException, NodeNotFoundException, L2pSecurityException, InterruptedException { long timeout = m.getTimeoutTs() - new Date().getTime(); MessageResultListener listener = new MessageResultListener( timeout ); sendMessage ( m, atNodeId, listener ); listener.waitForOneAnswer(); return listener.getResults()[0]; } /** * Gets the local execution context of an agent. * If there is currently none, a new one will be created and stored for later use. * * @param agentId * * @return the context for the given agent * * @throws L2pSecurityException * @throws AgentNotKnownException */ protected Context getAgentContext ( long agentId ) throws L2pSecurityException, AgentNotKnownException { Context result = htLocalExecutionContexts.get( agentId ); if ( result == null ) { Agent agent = getAgent ( agentId ); result = new Context (this, agent ); htLocalExecutionContexts.put( agentId, result ); } return result; } /** * Gets a (possibly fresh) context for the given agent. * * @param agent * * @return a context */ protected Context getAgentContext ( Agent agent ) { Context result = htLocalExecutionContexts.get( agent.getId() ); if ( result == null || (result.getMainAgent().isLocked() && !agent.isLocked() )) { try { result = new Context ( this, agent ); } catch ( L2pSecurityException e ) { } htLocalExecutionContexts.put( agent.getId(), result); } return result; } /** * Checks, if the given service class is running at this node. * * @param serviceClass * @return true, if this node as an instance of the given service running */ public boolean hasService(String serviceClass) { return hasAgent(ServiceAgent.serviceClass2Id(serviceClass)); } }
package kodaLoss; import static kodaLoss.Bank_HelpersAndTools.isPlayersHandABlackJack; import static kodaLoss.Bank_HelpersAndTools.isPlayersHandOver21; import static kodaLoss.BlackJackConstantsAndTools.PLAYER_IS_BUST; import java.util.ArrayList; import java.util.List; import kodaLoss.UserChoiceAdapter.UserChoice; public class CasinoRound extends AbstractRound { // list to save Split-players for deletion at the end of round! private List<Player> SplitPlayerToDelete = new ArrayList<>(); // Constructor public CasinoRound() { super(); System.out.println("CasinoRound"); controller.activateAdvancedButton(); } @Override public void playerPlays(Player player) { System.out.println("Player plays - Casino rules - started..."); // check for casino rules before playing! // just one casino rule per round, the other will be deactivated // after playing one of them! if (!player.isSplitPlayer()){ activateSplit(player); activateInsurance(player); activateDouble(player); } else { controller.disableAdvancedButton(); controller.allButtonsOff(); controller.setlabelWinnerText(BlackJackConstantsAndTools.SPLIT_TEXT_TO_SPLITPLAYER); BlackJackConstantsAndTools.sleepForXSeconds(); controller.gameIson(); } // activate players buttons controller.gameIson(); uca.resetUserChoice(); // prepare UCA for input while (uca.getUserChoice() != UserChoice.STAY) { if (isPlayersHandOver21(player)) { System.out.println(PLAYER_IS_BUST); controller.setlabelWinnerText(PLAYER_IS_BUST); bank.updateGuiAfterChangeInDataModel(); break; } // sleep to reduce processor load! try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } if (uca.getUserChoice() == UserChoice.HIT) { bank.dealOneCardToPlayer(player); bank.updateGuiAfterChangeInDataModel(); System.out.println("PLAYER HIT"); player.printHandToConsole(); uca.resetUserChoice(); } else if (uca.getUserChoice() == UserChoice.SPLIT) { makeSplitPlayer(player); controller.setlabelWinnerText(BlackJackConstantsAndTools.SPLIT_TEXT_TO_PLAYER); controller.disableAdvancedButton(); uca.resetUserChoice(); } else if (uca.getUserChoice() == UserChoice.DOUBLE) { playDouble(player); break; // break out of loop, round is over for player! } else if (uca.getUserChoice() == UserChoice.INSURANCE){ playInsurance(player); bank.updateGuiAfterChangeInDataModel(); controller.disableAdvancedButton(); uca.resetUserChoice(); } } // print out all data of Player! System.out.println(player.toString()); // finally reset last choice in UCA uca.resetUserChoice(); } // activate double button if players hand allow playing Double private void activateDouble(Player player) { if (checkIfDoubleCanBePlayed(player)){ controller.activateDoubleButton(); } } /** * Check if the dealer got an ACE on the first DEAL, And activates the button * so the player can choice to use Insurance */ public void activateInsurance(Player p) { if (!checkIfInsuranceCanBePlayed(p)) { controller.activateInsuranceButton(); } else { if (p.getPlayersCash() < (int) Math.ceil(p.getPlayersBet() / 2.0d)) { controller.setlabelWinnerText( BlackJackConstantsAndTools.NOT_ENOUGH_CASH_TO_TAKE_INSURANCE); } } } // activate splitbutton if player may play Split public void activateSplit(Player p) { if (true){//checkIfSplitCanBePlayed(p)) { controller.activateSplitButton(); } } // returns true if a player may play Double private boolean checkIfDoubleCanBePlayed(Player player) { return player.getPlayersCash() >= player.getPlayersBet() && player.getPlayersHand().size() <= 2; } //returns true if player may play Split (2 cards of same value, even different // Ranks!) public boolean checkIfSplitCanBePlayed(Player p) { if (p.getPlayersHand().size() != 2) { return false; } else if (p.getPlayersBet() > p.getPlayersCash()) { return false; } else { final Card cardOne = p.getPlayersHand().get(0); final Card cardTwo = p.getPlayersHand().get(1); System.out.println(cardOne.getValue() == cardTwo.getValue()); return (cardOne.getValue() == cardTwo.getValue()); } } // returns true if player may buy an insurance public boolean checkIfInsuranceCanBePlayed(Player p){ return Bank_HelpersAndTools.checkForAceCardOnYourHand(bank.dealer) && p.getPlayersCash() * 2 >= p.getPlayersBet(); } // player plays Double public void playDouble(Player p) { doublePlayersBet(p); bank.dealOneCardToPlayer(p); bank.updateGuiAfterChangeInDataModel(); System.out.println("PLAYER DOUBLE"); } private void doublePlayersBet(Player p) { final int playersBet = p.getPlayersBet(); if (p.getPlayersCash() >= playersBet) { p.addToPlayersCash(playersBet); p.setPlayersBet((int) Math.floor(2.0 * playersBet)); } else { controller.setlabelWinnerText( BlackJackConstantsAndTools.NOT_ENOUGH_CASH_TO_DOUBLE); throw new IllegalArgumentException("doubled bet exceeds Players cash!"); } } // adds an insurance to player and adjusts money private void playInsurance(Player p){ p.setHasInsurance(true); int insurance = (p.getPlayersBet() / 2); p.setPlayersCash((p.getPlayersCash() - insurance) - 1); } // makes a SPLIT_Player to player public void makeSplitPlayer(Player player) { Player splitPlayer = new Player("SPLIT_"+ player.getName() , 0 ); splitPlayer.setSplitPlayer(true); // take a new bet for splitplayer! final int bet = player.getPlayersBet(); splitPlayer.setPlayersBet(bet); player.setPlayersBet(0); player.setPlayersBet(bet); splitPlayer.addCardToHand(player.getPlayersHand().remove(1)); SplitPlayerToDelete.add(splitPlayer); controller.updatePlayer(splitPlayer); bank.updateGuiAfterChangeInDataModel(); bank.dealOneCardToPlayer(player); BlackJackConstantsAndTools.sleepForXSeconds(); bank.dealOneCardToPlayer(splitPlayer); controller.updatePlayer(splitPlayer); for (int i = 0 ; i < bank.registeredPlayers.size() ; i++){ if (bank.registeredPlayers.get(i) == player){ bank.registeredPlayers.add(i+1, splitPlayer); System.out.println(); break; } } bank.updateGuiAfterChangeInDataModel(); } // add Splitplayers money to players at the end of round private void mergeSplitPlayers() { bank.activePlayerOnGui = bank.registeredPlayers.get(0); for (int i = 0 ; i < bank.registeredPlayers.size() ; i++){ Player p = bank.registeredPlayers.get(i); if (p.isSplitPlayer()){ Player addToPlayer = bank.registeredPlayers.get(i-1); addToPlayer.addToPlayersCash(p.getPlayersCash()); } } } // delete splitplayers at the end of round! private void deleteSplitPlayers() { for (Player p : SplitPlayerToDelete){ if (bank.registeredPlayers.contains(p)){ System.out.println("removed : " + p.getName()); bank.registeredPlayers.remove(p); } } } @Override public void cleanUpAfterRound(){ mergeSplitPlayers(); clearHandsOffTheTable(); deleteSplitPlayers(); } @Override public void handlePlayersBetsAndPayWinners() { /* * WITH CASINO RULES! TIE => return betting amount WIN => return 2 * bet WIN * + BJ => return 2.5 bet Loose => players bet is not returned INSURANCE 3:2 * if dealer has a BlackJAck, return bet if dealer wins */ int playersBet; int playersBalance = 0; for (Player player : bank.registeredPlayers) { playersBet = player.getPlayersBet(); if (playersBet == 0){ System.out.println("NOT BET FOR : " + player.getName()); } if (player.getRoundResult() == RoundResult.TIE) { playersBalance = playersBet; } else if (player.getRoundResult() == RoundResult.WIN) { playersBalance = (int) Math.floor(playersBet * 2.0d); // Win with Black Jack adds another 50% of bet! if (isPlayersHandABlackJack(player)) { playersBalance += (int) Math.floor(playersBet / 2.0d); System.out.println("BLACKJACK"); } } else if (player.getRoundResult() == RoundResult.LOOSE) { // insured against loss => return bet (2 * 1/2 bet) // Dealer has a BlackJAck => return 3:2 of bet! if (player.isHasInsurance()) { if (isPlayersHandABlackJack(bank.dealer)) { playersBalance += (int) Math.floor(1.5 * player.getPlayersBet()); } else { playersBalance = player.getPlayersBet(); } } else { playersBalance = 0; } } // last rounds Players bet as default in gui for next round // player.setPlayersBet(0); controller.setlabelWinnerText(String.format("%s $: + %d" , player.getName() , playersBalance )); player.addToPlayersCash(playersBalance); player.setRoundResult(null); player.setHasInsurance(false); bank.updateGuiAfterChangeInDataModel(); BlackJackConstantsAndTools.sleepForXSeconds(); } } }
package org.fxmisc.richtext; import static org.fxmisc.richtext.PopupAlignment.*; import static org.reactfx.EventStreams.*; import static org.reactfx.util.Tuples.*; import java.time.Duration; import java.util.Optional; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.IntConsumer; import java.util.function.IntFunction; import java.util.function.IntSupplier; import java.util.function.IntUnaryOperator; import java.util.function.UnaryOperator; import java.util.stream.Stream; import javafx.beans.binding.Binding; import javafx.beans.binding.Bindings; import javafx.beans.binding.BooleanBinding; import javafx.beans.binding.ObjectBinding; import javafx.beans.property.BooleanProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.Property; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.value.ObservableBooleanValue; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableSet; import javafx.css.PseudoClass; import javafx.css.StyleableObjectProperty; import javafx.event.Event; import javafx.geometry.BoundingBox; import javafx.geometry.Bounds; import javafx.geometry.Insets; import javafx.geometry.Point2D; import javafx.scene.Node; import javafx.scene.control.IndexRange; import javafx.scene.layout.Background; import javafx.scene.layout.BackgroundFill; import javafx.scene.layout.CornerRadii; import javafx.scene.layout.Region; import javafx.scene.paint.Color; import javafx.scene.paint.Paint; import javafx.scene.text.Text; import javafx.scene.text.TextFlow; import javafx.stage.PopupWindow; import org.fxmisc.flowless.Cell; import org.fxmisc.flowless.VirtualFlow; import org.fxmisc.flowless.VirtualFlowHit; import org.fxmisc.flowless.Virtualized; import org.fxmisc.flowless.VirtualizedScrollPane; import org.fxmisc.richtext.CssProperties.EditableProperty; import org.fxmisc.undo.UndoManager; import org.fxmisc.undo.UndoManagerFactory; import org.reactfx.EventStream; import org.reactfx.EventStreams; import org.reactfx.StateMachine; import org.reactfx.Subscription; import org.reactfx.collection.LiveList; import org.reactfx.util.Tuple2; import org.reactfx.value.Val; import org.reactfx.value.Var; /** * Text editing control. Accepts user input (keyboard, mouse) and * provides API to assign style to text ranges. It is suitable for * syntax highlighting and rich-text editors. * * <p>Subclassing is allowed to define the type of style, e.g. inline * style or style classes.</p> * * <p>Note: Scroll bars no longer appear when the content spans outside * of the viewport. To add scroll bars, the area needs to be embedded in * a {@link VirtualizedScrollPane}. {@link AreaFactory} is provided to make * this more convenient.</p> * * <h3>Overriding keyboard shortcuts</h3> * * {@code StyledTextArea} comes with {@link #onKeyTypedProperty()} and * {@link #onKeyPressedProperty()} handlers installed to handle keyboard input. * Ordinary character input is handled by the {@code onKeyTyped} handler and * control key combinations (including Enter and Tab) are handled by the * {@code onKeyPressed} handler. To add or override some keyboard shortcuts, * but keep the rest in place, you would combine the default event handler with * a new one that adds or overrides some of the default key combinations. This * is how to bind {@code Ctrl+S} to the {@code save()} operation: * <pre> * {@code * import static javafx.scene.input.KeyCode.*; * import static javafx.scene.input.KeyCombination.*; * import static org.fxmisc.wellbehaved.event.EventPattern.*; * * import org.fxmisc.wellbehaved.event.EventHandlerHelper; * * EventHandler<? super KeyEvent> ctrlS = EventHandlerHelper * .on(keyPressed(S, CONTROL_DOWN)).act(event -> save()) * .create(); * * EventHandlerHelper.install(area.onKeyPressedProperty(), ctrlS); * } * </pre> * * @param <S> type of style that can be applied to text. */ public class StyledTextArea<PS, S> extends Region implements TextEditingArea<PS, S>, EditActions<PS, S>, ClipboardActions<PS, S>, NavigationActions<PS, S>, UndoActions, TwoDimensional, Virtualized { /** * Index range [0, 0). */ public static final IndexRange EMPTY_RANGE = new IndexRange(0, 0); private static final PseudoClass HAS_CARET = PseudoClass.getPseudoClass("has-caret"); private static final PseudoClass FIRST_PAR = PseudoClass.getPseudoClass("first-paragraph"); private static final PseudoClass LAST_PAR = PseudoClass.getPseudoClass("last-paragraph"); /** * Background fill for highlighted text. */ private final StyleableObjectProperty<Paint> highlightFill = new CssProperties.HighlightFillProperty(this, Color.DODGERBLUE); /** * Text color for highlighted text. */ private final StyleableObjectProperty<Paint> highlightTextFill = new CssProperties.HighlightTextFillProperty(this, Color.WHITE); // editable property /** * Indicates whether this text area can be edited by the user. * Note that this property doesn't affect editing through the API. */ private final BooleanProperty editable = new EditableProperty<>(this); public final boolean isEditable() { return editable.get(); } public final void setEditable(boolean value) { editable.set(value); } public final BooleanProperty editableProperty() { return editable; } // wrapText property /** * When a run of text exceeds the width of the text region, * then this property indicates whether the text should wrap * onto another line. */ private final BooleanProperty wrapText = new SimpleBooleanProperty(this, "wrapText"); public final boolean isWrapText() { return wrapText.get(); } public final void setWrapText(boolean value) { wrapText.set(value); } public final BooleanProperty wrapTextProperty() { return wrapText; } // undo manager @Override public UndoManager getUndoManager() { return model.getUndoManager(); } @Override public void setUndoManager(UndoManagerFactory undoManagerFactory) { model.setUndoManager(undoManagerFactory); } /** * Popup window that will be positioned by this text area relative to the * caret or selection. Use {@link #popupAlignmentProperty()} to specify * how the popup should be positioned relative to the caret or selection. * Use {@link #popupAnchorOffsetProperty()} or * {@link #popupAnchorAdjustmentProperty()} to further adjust the position. */ private final ObjectProperty<PopupWindow> popupWindow = new SimpleObjectProperty<>(); public void setPopupWindow(PopupWindow popup) { popupWindow.set(popup); } public PopupWindow getPopupWindow() { return popupWindow.get(); } public ObjectProperty<PopupWindow> popupWindowProperty() { return popupWindow; } /** @deprecated Use {@link #setPopupWindow(PopupWindow)}. */ @Deprecated public void setPopupAtCaret(PopupWindow popup) { popupWindow.set(popup); } /** @deprecated Use {@link #getPopupWindow()}. */ @Deprecated public PopupWindow getPopupAtCaret() { return popupWindow.get(); } /** @deprecated Use {@link #popupWindowProperty()}. */ @Deprecated public ObjectProperty<PopupWindow> popupAtCaretProperty() { return popupWindow; } /** * Specifies further offset (in pixels) of the popup window from the * position specified by {@link #popupAlignmentProperty()}. * * <p>If {@link #popupAnchorAdjustmentProperty()} is also specified, then * it overrides the offset set by this property. */ private final ObjectProperty<Point2D> popupAnchorOffset = new SimpleObjectProperty<>(); public void setPopupAnchorOffset(Point2D offset) { popupAnchorOffset.set(offset); } public Point2D getPopupAnchorOffset() { return popupAnchorOffset.get(); } public ObjectProperty<Point2D> popupAnchorOffsetProperty() { return popupAnchorOffset; } /** * Specifies how to adjust the popup window's anchor point. The given * operator is invoked with the screen position calculated according to * {@link #popupAlignmentProperty()} and should return a new screen * position. This position will be used as the popup window's anchor point. * * <p>Setting this property overrides {@link #popupAnchorOffsetProperty()}. */ private final ObjectProperty<UnaryOperator<Point2D>> popupAnchorAdjustment = new SimpleObjectProperty<>(); public void setPopupAnchorAdjustment(UnaryOperator<Point2D> f) { popupAnchorAdjustment.set(f); } public UnaryOperator<Point2D> getPopupAnchorAdjustment() { return popupAnchorAdjustment.get(); } public ObjectProperty<UnaryOperator<Point2D>> popupAnchorAdjustmentProperty() { return popupAnchorAdjustment; } /** * Defines where the popup window given in {@link #popupWindowProperty()} * is anchored, i.e. where its anchor point is positioned. This position * can further be adjusted by {@link #popupAnchorOffsetProperty()} or * {@link #popupAnchorAdjustmentProperty()}. */ private final ObjectProperty<PopupAlignment> popupAlignment = new SimpleObjectProperty<>(CARET_TOP); public void setPopupAlignment(PopupAlignment pos) { popupAlignment.set(pos); } public PopupAlignment getPopupAlignment() { return popupAlignment.get(); } public ObjectProperty<PopupAlignment> popupAlignmentProperty() { return popupAlignment; } /** * Defines how long the mouse has to stay still over the text before a * {@link MouseOverTextEvent} of type {@code MOUSE_OVER_TEXT_BEGIN} is * fired on this text area. When set to {@code null}, no * {@code MouseOverTextEvent}s are fired on this text area. * * <p>Default value is {@code null}. */ private final ObjectProperty<Duration> mouseOverTextDelay = new SimpleObjectProperty<>(null); public void setMouseOverTextDelay(Duration delay) { mouseOverTextDelay.set(delay); } public Duration getMouseOverTextDelay() { return mouseOverTextDelay.get(); } public ObjectProperty<Duration> mouseOverTextDelayProperty() { return mouseOverTextDelay; } /** * Defines how to handle an event in which the user has selected some text, dragged it to a * new location within the area, and released the mouse at some character {@code index} * within the area. * * <p>By default, this will relocate the selected text to the character index where the mouse * was released. To override it, use {@link #setOnSelectionDrop(IntConsumer)}. */ private Property<IntConsumer> onSelectionDrop = new SimpleObjectProperty<>(this::moveSelectedText); public final void setOnSelectionDrop(IntConsumer consumer) { onSelectionDrop.setValue(consumer); } public final IntConsumer getOnSelectionDrop() { return onSelectionDrop.getValue(); } private final ObjectProperty<IntFunction<? extends Node>> paragraphGraphicFactory = new SimpleObjectProperty<>(null); public void setParagraphGraphicFactory(IntFunction<? extends Node> factory) { paragraphGraphicFactory.set(factory); } public IntFunction<? extends Node> getParagraphGraphicFactory() { return paragraphGraphicFactory.get(); } public ObjectProperty<IntFunction<? extends Node>> paragraphGraphicFactoryProperty() { return paragraphGraphicFactory; } /** * Indicates whether the initial style should also be used for plain text * inserted into this text area. When {@code false}, the style immediately * preceding the insertion position is used. Default value is {@code false}. */ public BooleanProperty useInitialStyleForInsertionProperty() { return model.useInitialStyleForInsertionProperty(); } public void setUseInitialStyleForInsertion(boolean value) { model.setUseInitialStyleForInsertion(value); } public boolean getUseInitialStyleForInsertion() { return model.getUseInitialStyleForInsertion(); } private Optional<Tuple2<Codec<PS>, Codec<S>>> styleCodecs = Optional.empty(); /** * Sets codecs to encode/decode style information to/from binary format. * Providing codecs enables clipboard actions to retain the style information. */ public void setStyleCodecs(Codec<PS> paragraphStyleCodec, Codec<S> textStyleCodec) { styleCodecs = Optional.of(t(paragraphStyleCodec, textStyleCodec)); } @Override public Optional<Tuple2<Codec<PS>, Codec<S>>> getStyleCodecs() { return styleCodecs; } /** * The <em>estimated</em> scrollX value. This can be set in order to scroll the content. * Value is only accurate when area does not wrap lines and uses the same font size * throughout the entire area. */ @Override public Var<Double> estimatedScrollXProperty() { return virtualFlow.estimatedScrollXProperty(); } public double getEstimatedScrollX() { return virtualFlow.estimatedScrollXProperty().getValue(); } public void setEstimatedScrollX(double value) { virtualFlow.estimatedScrollXProperty().setValue(value); } /** * The <em>estimated</em> scrollY value. This can be set in order to scroll the content. * Value is only accurate when area does not wrap lines and uses the same font size * throughout the entire area. */ @Override public Var<Double> estimatedScrollYProperty() { return virtualFlow.estimatedScrollYProperty(); } public double getEstimatedScrollY() { return virtualFlow.estimatedScrollYProperty().getValue(); } public void setEstimatedScrollY(double value) { virtualFlow.estimatedScrollYProperty().setValue(value); } // text @Override public final String getText() { return model.getText(); } @Override public final ObservableValue<String> textProperty() { return model.textProperty(); } // rich text @Override public final StyledDocument<PS, S> getDocument() { return model.getDocument(); } // length @Override public final int getLength() { return model.getLength(); } @Override public final ObservableValue<Integer> lengthProperty() { return model.lengthProperty(); } // caret position @Override public final int getCaretPosition() { return model.getCaretPosition(); } @Override public final ObservableValue<Integer> caretPositionProperty() { return model.caretPositionProperty(); } // selection anchor @Override public final int getAnchor() { return model.getAnchor(); } @Override public final ObservableValue<Integer> anchorProperty() { return model.anchorProperty(); } // selection @Override public final IndexRange getSelection() { return model.getSelection(); } @Override public final ObservableValue<IndexRange> selectionProperty() { return model.selectionProperty(); } // selected text @Override public final String getSelectedText() { return model.getSelectedText(); } @Override public final ObservableValue<String> selectedTextProperty() { return model.selectedTextProperty(); } // current paragraph index @Override public final int getCurrentParagraph() { return model.getCurrentParagraph(); } @Override public final ObservableValue<Integer> currentParagraphProperty() { return model.currentParagraphProperty(); } // caret column @Override public final int getCaretColumn() { return model.getCaretColumn(); } @Override public final ObservableValue<Integer> caretColumnProperty() { return model.caretColumnProperty(); } // paragraphs @Override public LiveList<Paragraph<PS, S>> getParagraphs() { return model.getParagraphs(); } // beingUpdated public ObservableBooleanValue beingUpdatedProperty() { return model.beingUpdatedProperty(); } public boolean isBeingUpdated() { return model.isBeingUpdated(); } // total width estimate /** * The <em>estimated</em> width of the entire document. Accurate when area does not wrap lines and * uses the same font size throughout the entire area. Value is only supposed to be <em>set</em> by * the skin, not the user. */ @Override public Val<Double> totalWidthEstimateProperty() { return virtualFlow.totalWidthEstimateProperty(); } public double getTotalWidthEstimate() { return virtualFlow.totalWidthEstimateProperty().getValue(); } // total height estimate /** * The <em>estimated</em> height of the entire document. Accurate when area does not wrap lines and * uses the same font size throughout the entire area. Value is only supposed to be <em>set</em> by * the skin, not the user. */ @Override public Val<Double> totalHeightEstimateProperty() { return virtualFlow.totalHeightEstimateProperty(); } public double getTotalHeightEstimate() { return virtualFlow.totalHeightEstimateProperty().getValue(); } // text changes @Override public final EventStream<PlainTextChange> plainTextChanges() { return model.plainTextChanges(); } // rich text changes @Override public final EventStream<RichTextChange<PS, S>> richChanges() { return model.richChanges(); } private final StyledTextAreaBehavior behavior; private Subscription subscriptions = () -> {}; private final Binding<Boolean> caretVisible; private final Val<UnaryOperator<Point2D>> _popupAnchorAdjustment; private final VirtualFlow<Paragraph<PS, S>, Cell<Paragraph<PS, S>, ParagraphBox<PS, S>>> virtualFlow; // used for two-level navigation, where on the higher level are // paragraphs and on the lower level are lines within a paragraph private final TwoLevelNavigator navigator; private boolean followCaretRequested = false; /** * model */ private final StyledTextAreaModel<PS, S> model; /** * @return this area's {@link StyledTextAreaModel} */ final StyledTextAreaModel<PS, S> getModel() { return model; } /** * The underlying document that can be displayed by multiple {@code StyledTextArea}s. */ public final EditableStyledDocument<PS, S> getContent() { return model.getContent(); } /** * Style used by default when no other style is provided. */ public final S getInitialTextStyle() { return model.getInitialTextStyle(); } /** * Style used by default when no other style is provided. */ public final PS getInitialParagraphStyle() { return model.getInitialParagraphStyle(); } /** * Style applicator used by the default skin. */ private final BiConsumer<? super TextExt, S> applyStyle; public final BiConsumer<? super TextExt, S> getApplyStyle() { return applyStyle; } /** * Style applicator used by the default skin. */ private final BiConsumer<TextFlow, PS> applyParagraphStyle; public final BiConsumer<TextFlow, PS> getApplyParagraphStyle() { return applyParagraphStyle; } /** * Indicates whether style should be preserved on undo/redo, * copy/paste and text move. * TODO: Currently, only undo/redo respect this flag. */ public final boolean isPreserveStyle() { return model.isPreserveStyle(); } /** * Creates a text area with empty text content. * * @param initialTextStyle style to use in places where no other style is * specified (yet). * @param applyStyle function that, given a {@link Text} node and * a style, applies the style to the text node. This function is * used by the default skin to apply style to text nodes. * @param initialParagraphStyle style to use in places where no other style is * specified (yet). * @param applyParagraphStyle function that, given a {@link TextFlow} node and * a style, applies the style to the paragraph node. This function is * used by the default skin to apply style to paragraph nodes. */ public StyledTextArea(PS initialParagraphStyle, BiConsumer<TextFlow, PS> applyParagraphStyle, S initialTextStyle, BiConsumer<? super TextExt, S> applyStyle ) { this(initialParagraphStyle, applyParagraphStyle, initialTextStyle, applyStyle, true); } public StyledTextArea(PS initialParagraphStyle, BiConsumer<TextFlow, PS> applyParagraphStyle, S initialTextStyle, BiConsumer<? super TextExt, S> applyStyle, boolean preserveStyle ) { this(initialParagraphStyle, applyParagraphStyle, initialTextStyle, applyStyle, new EditableStyledDocumentImpl<>(initialParagraphStyle, initialTextStyle), preserveStyle); } /** * The same as {@link #StyledTextArea(Object, BiConsumer, Object, BiConsumer)} except that * this constructor can be used to create another {@code StyledTextArea} object that * shares the same {@link EditableStyledDocument}. */ public StyledTextArea(PS initialParagraphStyle, BiConsumer<TextFlow, PS> applyParagraphStyle, S initialTextStyle, BiConsumer<? super TextExt, S> applyStyle, EditableStyledDocument<PS, S> document ) { this(initialParagraphStyle, applyParagraphStyle, initialTextStyle, applyStyle, document, true); } public StyledTextArea(PS initialParagraphStyle, BiConsumer<TextFlow, PS> applyParagraphStyle, S initialTextStyle, BiConsumer<? super TextExt, S> applyStyle, EditableStyledDocument<PS, S> document, boolean preserveStyle ) { this.model = new StyledTextAreaModel<>(initialParagraphStyle, initialTextStyle, document, preserveStyle); this.applyStyle = applyStyle; this.applyParagraphStyle = applyParagraphStyle; // allow tab traversal into area setFocusTraversable(true); this.setBackground(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY))); getStyleClass().add("styled-text-area"); getStylesheets().add(StyledTextArea.class.getResource("styled-text-area.css").toExternalForm()); // keeps track of currently used non-empty cells @SuppressWarnings("unchecked") ObservableSet<ParagraphBox<PS, S>> nonEmptyCells = FXCollections.observableSet(); // Initialize content virtualFlow = VirtualFlow.createVertical( getParagraphs(), par -> { Cell<Paragraph<PS, S>, ParagraphBox<PS, S>> cell = createCell( par, applyStyle, applyParagraphStyle); nonEmptyCells.add(cell.getNode()); return cell.beforeReset(() -> nonEmptyCells.remove(cell.getNode())) .afterUpdateItem(p -> nonEmptyCells.add(cell.getNode())); }); getChildren().add(virtualFlow); // initialize navigator IntSupplier cellCount = () -> getParagraphs().size(); IntUnaryOperator cellLength = i -> virtualFlow.getCell(i).getNode().getLineCount(); navigator = new TwoLevelNavigator(cellCount, cellLength); // follow the caret every time the caret position or paragraphs change EventStream<?> caretPosDirty = invalidationsOf(caretPositionProperty()); EventStream<?> paragraphsDirty = invalidationsOf(getParagraphs()); EventStream<?> selectionDirty = invalidationsOf(selectionProperty()); // need to reposition popup even when caret hasn't moved, but selection has changed (been deselected) EventStream<?> caretDirty = merge(caretPosDirty, paragraphsDirty, selectionDirty); subscribeTo(caretDirty, x -> requestFollowCaret()); // whether or not to animate the caret BooleanBinding blinkCaret = focusedProperty() .and(editableProperty()) .and(disabledProperty().not()); manageBinding(blinkCaret); // The caret is visible in periodic intervals, // but only when blinkCaret is true. caretVisible = EventStreams.valuesOf(blinkCaret) .flatMap(blink -> blink ? booleanPulse(Duration.ofMillis(500), caretDirty) : EventStreams.valuesOf(Val.constant(false))) .toBinding(false); manageBinding(caretVisible); // Adjust popup anchor by either a user-provided function, // or user-provided offset, or don't adjust at all. Val<UnaryOperator<Point2D>> userOffset = Val.map( popupAnchorOffsetProperty(), offset -> anchor -> anchor.add(offset)); _popupAnchorAdjustment = Val.orElse( popupAnchorAdjustmentProperty(), userOffset) .orElseConst(UnaryOperator.identity()); // dispatch MouseOverTextEvents when mouseOverTextDelay is not null EventStreams.valuesOf(mouseOverTextDelayProperty()) .flatMap(delay -> delay != null ? mouseOverTextEvents(nonEmptyCells, delay) : EventStreams.never()) .subscribe(evt -> Event.fireEvent(this, evt)); behavior = new StyledTextAreaBehavior(this); } /** * Returns caret bounds relative to the viewport, i.e. the visual bounds * of the embedded VirtualFlow. */ Optional<Bounds> getCaretBounds() { return virtualFlow.getCellIfVisible(getCurrentParagraph()) .map(c -> { Bounds cellBounds = c.getNode().getCaretBounds(); return virtualFlow.cellToViewport(c, cellBounds); }); } /** * Returns x coordinate of the caret in the current paragraph. */ ParagraphBox.CaretOffsetX getCaretOffsetX() { int idx = getCurrentParagraph(); return getCell(idx).getCaretOffsetX(); } double getViewportHeight() { return virtualFlow.getHeight(); } CharacterHit hit(ParagraphBox.CaretOffsetX x, TwoDimensional.Position targetLine) { int parIdx = targetLine.getMajor(); ParagraphBox<PS, S> cell = virtualFlow.getCell(parIdx).getNode(); CharacterHit parHit = cell.hitTextLine(x, targetLine.getMinor()); return parHit.offset(getParagraphOffset(parIdx)); } CharacterHit hit(ParagraphBox.CaretOffsetX x, double y) { VirtualFlowHit<Cell<Paragraph<PS, S>, ParagraphBox<PS, S>>> hit = virtualFlow.hit(0.0, y); if(hit.isBeforeCells()) { return CharacterHit.insertionAt(0); } else if(hit.isAfterCells()) { return CharacterHit.insertionAt(getLength()); } else { int parIdx = hit.getCellIndex(); int parOffset = getParagraphOffset(parIdx); ParagraphBox<PS, S> cell = hit.getCell().getNode(); Point2D cellOffset = hit.getCellOffset(); CharacterHit parHit = cell.hitText(x, cellOffset.getY()); return parHit.offset(parOffset); } } /** * Helpful for determining which letter is at point x, y: * <pre> * {@code * StyledTextArea area = // creation code * area.addEventHandler(MouseEvent.MOUSE_PRESSED, (MouseEvent e) -> { * CharacterHit hit = area.hit(e.getX(), e.getY()); * int characterPosition = hit.getInsertionIndex(); * * // move the caret to that character's position * area.moveTo(characterPosition, SelectionPolicy.CLEAR); * }} * </pre> * @param x * @param y */ public CharacterHit hit(double x, double y) { VirtualFlowHit<Cell<Paragraph<PS, S>, ParagraphBox<PS, S>>> hit = virtualFlow.hit(x, y); if(hit.isBeforeCells()) { return CharacterHit.insertionAt(0); } else if(hit.isAfterCells()) { return CharacterHit.insertionAt(getLength()); } else { int parIdx = hit.getCellIndex(); int parOffset = getParagraphOffset(parIdx); ParagraphBox<PS, S> cell = hit.getCell().getNode(); Point2D cellOffset = hit.getCellOffset(); CharacterHit parHit = cell.hit(cellOffset); return parHit.offset(parOffset); } } /** * Returns the current line as a two-level index. * The major number is the paragraph index, the minor * number is the line number within the paragraph. * * <p>This method has a side-effect of bringing the current * paragraph to the viewport if it is not already visible. */ TwoDimensional.Position currentLine() { int parIdx = getCurrentParagraph(); Cell<Paragraph<PS, S>, ParagraphBox<PS, S>> cell = virtualFlow.getCell(parIdx); int lineIdx = cell.getNode().getCurrentLineIndex(); return _position(parIdx, lineIdx); } TwoDimensional.Position _position(int par, int line) { return navigator.position(par, line); } @Override public final String getText(int start, int end) { return model.getText(start, end); } @Override public String getText(int paragraph) { return model.getText(paragraph); } public Paragraph<PS, S> getParagraph(int index) { return model.getParagraph(index); } @Override public StyledDocument<PS, S> subDocument(int start, int end) { return model.subDocument(start, end); } @Override public StyledDocument<PS, S> subDocument(int paragraphIndex) { return model.subDocument(paragraphIndex); } /** * Returns the selection range in the given paragraph. */ public IndexRange getParagraphSelection(int paragraph) { return model.getParagraphSelection(paragraph); } /** * Returns the style of the character with the given index. * If {@code index} points to a line terminator character, * the last style used in the paragraph terminated by that * line terminator is returned. */ public S getStyleOfChar(int index) { return model.getStyleOfChar(index); } /** * Returns the style at the given position. That is the style of the * character immediately preceding {@code position}, except when * {@code position} points to a paragraph boundary, in which case it * is the style at the beginning of the latter paragraph. * * <p>In other words, most of the time {@code getStyleAtPosition(p)} * is equivalent to {@code getStyleOfChar(p-1)}, except when {@code p} * points to a paragraph boundary, in which case it is equivalent to * {@code getStyleOfChar(p)}. */ public S getStyleAtPosition(int position) { return model.getStyleAtPosition(position); } /** * Returns the range of homogeneous style that includes the given position. * If {@code position} points to a boundary between two styled ranges, then * the range preceding {@code position} is returned. If {@code position} * points to a boundary between two paragraphs, then the first styled range * of the latter paragraph is returned. */ public IndexRange getStyleRangeAtPosition(int position) { return model.getStyleRangeAtPosition(position); } /** * Returns the styles in the given character range. */ public StyleSpans<S> getStyleSpans(int from, int to) { return model.getStyleSpans(from, to); } /** * Returns the styles in the given character range. */ public StyleSpans<S> getStyleSpans(IndexRange range) { return getStyleSpans(range.getStart(), range.getEnd()); } /** * Returns the style of the character with the given index in the given * paragraph. If {@code index} is beyond the end of the paragraph, the * style at the end of line is returned. If {@code index} is negative, it * is the same as if it was 0. */ public S getStyleOfChar(int paragraph, int index) { return model.getStyleOfChar(paragraph, index); } /** * Returns the style at the given position in the given paragraph. * This is equivalent to {@code getStyleOfChar(paragraph, position-1)}. */ public S getStyleAtPosition(int paragraph, int position) { return model.getStyleAtPosition(paragraph, position); } /** * Returns the range of homogeneous style that includes the given position * in the given paragraph. If {@code position} points to a boundary between * two styled ranges, then the range preceding {@code position} is returned. */ public IndexRange getStyleRangeAtPosition(int paragraph, int position) { return model.getStyleRangeAtPosition(paragraph, position); } /** * Returns styles of the whole paragraph. */ public StyleSpans<S> getStyleSpans(int paragraph) { return model.getStyleSpans(paragraph); } /** * Returns the styles in the given character range of the given paragraph. */ public StyleSpans<S> getStyleSpans(int paragraph, int from, int to) { return model.getStyleSpans(paragraph, from, to); } /** * Returns the styles in the given character range of the given paragraph. */ public StyleSpans<S> getStyleSpans(int paragraph, IndexRange range) { return getStyleSpans(paragraph, range.getStart(), range.getEnd()); } @Override public Position position(int row, int col) { return model.position(row, col); } @Override public Position offsetToPosition(int charOffset, Bias bias) { return model.offsetToPosition(charOffset, bias); } void scrollBy(Point2D deltas) { virtualFlow.scrollXBy(deltas.getX()); virtualFlow.scrollYBy(deltas.getY()); } void show(double y) { virtualFlow.show(y); } void showCaretAtBottom() { int parIdx = getCurrentParagraph(); Cell<Paragraph<PS, S>, ParagraphBox<PS, S>> cell = virtualFlow.getCell(parIdx); Bounds caretBounds = cell.getNode().getCaretBounds(); double y = caretBounds.getMaxY(); virtualFlow.showAtOffset(parIdx, getViewportHeight() - y); } void showCaretAtTop() { int parIdx = getCurrentParagraph(); Cell<Paragraph<PS, S>, ParagraphBox<PS, S>> cell = virtualFlow.getCell(parIdx); Bounds caretBounds = cell.getNode().getCaretBounds(); double y = caretBounds.getMinY(); virtualFlow.showAtOffset(parIdx, -y); } void requestFollowCaret() { followCaretRequested = true; requestLayout(); } private void followCaret() { int parIdx = getCurrentParagraph(); Cell<Paragraph<PS, S>, ParagraphBox<PS, S>> cell = virtualFlow.getCell(parIdx); Bounds caretBounds = cell.getNode().getCaretBounds(); double graphicWidth = cell.getNode().getGraphicPrefWidth(); Bounds region = extendLeft(caretBounds, graphicWidth); virtualFlow.show(parIdx, region); } /** * Sets style for the given character range. */ public void setStyle(int from, int to, S style) { model.setStyle(from, to, style); } /** * Sets style for the whole paragraph. */ public void setStyle(int paragraph, S style) { model.setStyle(paragraph, style); } /** * Sets style for the given range relative in the given paragraph. */ public void setStyle(int paragraph, int from, int to, S style) { model.setStyle(paragraph, from, to, style); } /** * Set multiple style ranges at once. This is equivalent to * <pre> * for(StyleSpan{@code <S>} span: styleSpans) { * setStyle(from, from + span.getLength(), span.getStyle()); * from += span.getLength(); * } * </pre> * but the actual implementation is more efficient. */ public void setStyleSpans(int from, StyleSpans<? extends S> styleSpans) { model.setStyleSpans(from, styleSpans); } /** * Set multiple style ranges of a paragraph at once. This is equivalent to * <pre> * for(StyleSpan{@code <S>} span: styleSpans) { * setStyle(paragraph, from, from + span.getLength(), span.getStyle()); * from += span.getLength(); * } * </pre> * but the actual implementation is more efficient. */ public void setStyleSpans(int paragraph, int from, StyleSpans<? extends S> styleSpans) { model.setStyleSpans(paragraph, from, styleSpans); } /** * Sets style for the whole paragraph. */ public void setParagraphStyle(int paragraph, PS paragraphStyle) { model.setParagraphStyle(paragraph, paragraphStyle); } /** * Resets the style of the given range to the initial style. */ public void clearStyle(int from, int to) { model.clearStyle(from, to); } /** * Resets the style of the given paragraph to the initial style. */ public void clearStyle(int paragraph) { model.clearStyle(paragraph); } /** * Resets the style of the given range in the given paragraph * to the initial style. */ public void clearStyle(int paragraph, int from, int to) { model.clearStyle(paragraph, from, to); } /** * Resets the style of the given paragraph to the initial style. */ public void clearParagraphStyle(int paragraph) { model.clearParagraphStyle(paragraph); } @Override public void replaceText(int start, int end, String text) { model.replaceText(start, end, text); } @Override public void replace(int start, int end, StyledDocument<PS, S> replacement) { model.replace(start, end, replacement); } @Override public void selectRange(int anchor, int caretPosition) { model.selectRange(anchor, caretPosition); } @Override public void positionCaret(int pos) { model.positionCaret(pos); } public void dispose() { subscriptions.unsubscribe(); model.dispose(); behavior.dispose(); virtualFlow.dispose(); } @Override protected void layoutChildren() { virtualFlow.resize(getWidth(), getHeight()); if(followCaretRequested) { followCaretRequested = false; followCaret(); } // position popup PopupWindow popup = getPopupWindow(); PopupAlignment alignment = getPopupAlignment(); UnaryOperator<Point2D> adjustment = _popupAnchorAdjustment.getValue(); if(popup != null) { positionPopup(popup, alignment, adjustment); } } private Cell<Paragraph<PS, S>, ParagraphBox<PS, S>> createCell( Paragraph<PS, S> paragraph, BiConsumer<? super TextExt, S> applyStyle, BiConsumer<TextFlow, PS> applyParagraphStyle) { ParagraphBox<PS, S> box = new ParagraphBox<>(paragraph, applyParagraphStyle, applyStyle); box.highlightFillProperty().bind(highlightFill); box.highlightTextFillProperty().bind(highlightTextFill); box.wrapTextProperty().bind(wrapTextProperty()); box.graphicFactoryProperty().bind(paragraphGraphicFactoryProperty()); box.graphicOffset.bind(virtualFlow.breadthOffsetProperty()); Val<Boolean> hasCaret = Val.combine( box.indexProperty(), currentParagraphProperty(), (bi, cp) -> bi.intValue() == cp.intValue()); Subscription hasCaretPseudoClass = hasCaret.values().subscribe(value -> box.pseudoClassStateChanged(HAS_CARET, value)); Subscription firstParPseudoClass = box.indexProperty().values().subscribe(idx -> box.pseudoClassStateChanged(FIRST_PAR, idx == 0)); Subscription lastParPseudoClass = EventStreams.combine( box.indexProperty().values(), getParagraphs().sizeProperty().values() ).subscribe(in -> in.exec((i, n) -> box.pseudoClassStateChanged(LAST_PAR, i == n-1))); // caret is visible only in the paragraph with the caret Val<Boolean> cellCaretVisible = hasCaret.flatMap(x -> x ? caretVisible : Val.constant(false)); box.caretVisibleProperty().bind(cellCaretVisible); // bind cell's caret position to area's caret column, // when the cell is the one with the caret box.caretPositionProperty().bind(hasCaret.flatMap(has -> has ? caretColumnProperty() : Val.constant(0))); // keep paragraph selection updated ObjectBinding<IndexRange> cellSelection = Bindings.createObjectBinding(() -> { int idx = box.getIndex(); return idx != -1 ? getParagraphSelection(idx) : StyledTextArea.EMPTY_RANGE; }, selectionProperty(), box.indexProperty()); box.selectionProperty().bind(cellSelection); return new Cell<Paragraph<PS, S>, ParagraphBox<PS, S>>() { @Override public ParagraphBox<PS, S> getNode() { return box; } @Override public void updateIndex(int index) { box.setIndex(index); } @Override public void dispose() { box.highlightFillProperty().unbind(); box.highlightTextFillProperty().unbind(); box.wrapTextProperty().unbind(); box.graphicFactoryProperty().unbind(); box.graphicOffset.unbind(); hasCaretPseudoClass.unsubscribe(); firstParPseudoClass.unsubscribe(); lastParPseudoClass.unsubscribe(); box.caretVisibleProperty().unbind(); box.caretPositionProperty().unbind(); box.selectionProperty().unbind(); cellSelection.dispose(); } }; } private ParagraphBox<PS, S> getCell(int index) { return virtualFlow.getCell(index).getNode(); } private EventStream<MouseOverTextEvent> mouseOverTextEvents(ObservableSet<ParagraphBox<PS, S>> cells, Duration delay) { return merge(cells, c -> c.stationaryIndices(delay).map(e -> e.unify( l -> l.map((pos, charIdx) -> MouseOverTextEvent.beginAt(c.localToScreen(pos), getParagraphOffset(c.getIndex()) + charIdx)), r -> MouseOverTextEvent.end()))); } private int getParagraphOffset(int parIdx) { return position(parIdx, 0).toOffset(); } private void positionPopup( PopupWindow popup, PopupAlignment alignment, UnaryOperator<Point2D> adjustment) { Optional<Bounds> bounds = null; switch(alignment.getAnchorObject()) { case CARET: bounds = getCaretBoundsOnScreen(); break; case SELECTION: bounds = getSelectionBoundsOnScreen(); break; } bounds.ifPresent(b -> { double x = 0, y = 0; switch(alignment.getHorizontalAlignment()) { case LEFT: x = b.getMinX(); break; case H_CENTER: x = (b.getMinX() + b.getMaxX()) / 2; break; case RIGHT: x = b.getMaxX(); break; } switch(alignment.getVerticalAlignment()) { case TOP: y = b.getMinY(); case V_CENTER: y = (b.getMinY() + b.getMaxY()) / 2; break; case BOTTOM: y = b.getMaxY(); break; } Point2D anchor = adjustment.apply(new Point2D(x, y)); popup.setAnchorX(anchor.getX()); popup.setAnchorY(anchor.getY()); }); } private Optional<Bounds> getCaretBoundsOnScreen() { return virtualFlow.getCellIfVisible(getCurrentParagraph()) .map(c -> c.getNode().getCaretBoundsOnScreen()); } private Optional<Bounds> getSelectionBoundsOnScreen() { IndexRange selection = getSelection(); if(selection.getLength() == 0) { return getCaretBoundsOnScreen(); } Bounds[] bounds = virtualFlow.visibleCells().stream() .map(c -> c.getNode().getSelectionBoundsOnScreen()) .filter(Optional::isPresent) .map(Optional::get) .toArray(Bounds[]::new); if(bounds.length == 0) { return Optional.empty(); } double minX = Stream.of(bounds).mapToDouble(Bounds::getMinX).min().getAsDouble(); double maxX = Stream.of(bounds).mapToDouble(Bounds::getMaxX).max().getAsDouble(); double minY = Stream.of(bounds).mapToDouble(Bounds::getMinY).min().getAsDouble(); double maxY = Stream.of(bounds).mapToDouble(Bounds::getMaxY).max().getAsDouble(); return Optional.of(new BoundingBox(minX, minY, maxX-minX, maxY-minY)); } private <T> void subscribeTo(EventStream<T> src, Consumer<T> cOnsumer) { manageSubscription(src.subscribe(cOnsumer)); } private void manageSubscription(Subscription subscription) { subscriptions = subscriptions.and(subscription); } private void manageBinding(Binding<?> binding) { subscriptions = subscriptions.and(binding::dispose); } private static Bounds extendLeft(Bounds b, double w) { if(w == 0) { return b; } else { return new BoundingBox( b.getMinX() - w, b.getMinY(), b.getWidth() + w, b.getHeight()); } } private static EventStream<Boolean> booleanPulse(Duration duration, EventStream<?> restartImpulse) { EventStream<?> ticks = EventStreams.restartableTicks(duration, restartImpulse); return StateMachine.init(false) .on(restartImpulse.withDefaultEvent(null)).transition((state, impulse) -> true) .on(ticks).transition((state, tick) -> !state) .toStateStream(); } }
package leetcode; public class Problem1014 { public int shipWithinDays(int[] weights, int D) { int left = 0; int right = 0; for (int w : weights) { left = Math.max(left, w); // max right += w; // sum } while (left < right) { int mid = (left + right) / 2; if (isPossible(weights, D, mid)) { right = mid; } else { left = mid + 1; } } return left; } private static boolean isPossible(int[] weights, int d, int max) { int sum = 0; int split = 1; for (int weight : weights) { if (sum + weight > max) { sum = 0; split++; if (split > d) { return false; } } sum += weight; } return true; } }
package leetcode; import java.util.Arrays; public class Problem1129 { public int[] shortestAlternatingPaths(int n, int[][] red_edges, int[][] blue_edges) { // TODO return null; } public static void main(String[] args) { Problem1129 prob = new Problem1129(); System.out.println(Arrays.toString(prob.shortestAlternatingPaths(3, new int[][]{{0, 1}, {1, 2}}, new int[][]{}))); // [0,1,-1] System.out.println(Arrays.toString(prob.shortestAlternatingPaths(3, new int[][]{{0, 1}}, new int[][]{{2, 1}}))); // [0,1,-1] System.out.println(Arrays.toString(prob.shortestAlternatingPaths(3, new int[][]{{1, 0}}, new int[][]{{2, 1}}))); // [0,-1,-1] System.out.println(Arrays.toString(prob.shortestAlternatingPaths(3, new int[][]{{0, 1}}, new int[][]{{1, 2}}))); // [0,1,2] System.out.println(Arrays.toString(prob.shortestAlternatingPaths(3, new int[][]{{0, 1}, {0, 2}}, new int[][]{{1, 0}}))); // [0,1,1] System.out.println(Arrays.toString(prob.shortestAlternatingPaths(4, new int[][]{{0, 1}, {1, 2}, {3, 2}}, new int[][]{{1, 3}}))); // [0,1,3,2] } }
package com.bkromhout.ruqus; import android.content.Context; import android.content.res.TypedArray; import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.NonNull; import android.support.v4.graphics.drawable.DrawableCompat; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.widget.*; import com.afollestad.materialdialogs.DialogAction; import com.afollestad.materialdialogs.MaterialDialog; import io.realm.Sort; import java.util.ArrayList; import java.util.Date; import java.util.regex.Pattern; /** * RealmQueryView * @author bkromhout */ public class RealmQueryView extends FrameLayout { private static final String ARG_STR_SEP = ";"; private static final Pattern ARG_STR_SEP_PATTERN = Pattern.compile("\\Q" + ARG_STR_SEP + "\\E"); private enum Mode { MAIN, C_BUILD, S_BUILD } /* Views for main mode. */ private RelativeLayout mainCont; private RQVCard queryableChooser; private ScrollView scrollView; private LinearLayout partsCont; private RQVCard sortChooser; /* Views for either builder mode. */ private ScrollView builderScrollView; private TextView builderHeader; private LinearLayout builderParts; private Button cancelButton; private Button saveButton; /* Views for condition builder mode. */ private Spinner fieldChooser; private Spinner conditionalChooser; /* Views for sort builder mode. */ private Button addSortField; /** * Current theme type. */ private RuqusTheme theme; /** * Current user query. */ private RealmUserQuery ruq; /** * Current mode. */ private Mode mode; /** * Simple name of the current {@link Queryable} class. */ private String currClassName; /** * List of current visible flat field names; changes when {@link #currClassName} changes. */ private ArrayList<String> currVisibleFlatFieldNames; /* Variables for the condition builder. */ /** * Index of the query part currently being worked on. */ private int currPartIdx; /** * Real name of the field currently selected in the condition builder. */ private String currFieldName; /** * {@link FieldType} of the field currently selected in the condition builder; changes when {@link #currFieldName} * changes. */ private FieldType currFieldType; /** * Real name of the transformer/conditional currently selected in the condition builder. */ private String currTransName; /** * Holds IDs of views added to the {@link #builderParts} view group which we check to get arguments. */ private ArrayList<Integer> argViewIds; /* Variables for the sort builder. */ /** * Holds IDs of sort field spinners. */ private ArrayList<Integer> sortSpinnerIds; /** * Holds IDs of buttons which remove sort fields. */ private ArrayList<Integer> removeSortBtnIds; /** * Holds IDs of radio groups which set sort directions. */ private ArrayList<Integer> sortDirRgIds; /* Constructors. */ public RealmQueryView(Context context) { this(context, null, null, null); } public RealmQueryView(Context context, RealmUserQuery ruq) { this(context, null, ruq, null); } public RealmQueryView(Context context, RuqusTheme theme) { this(context, null, null, theme); } public RealmQueryView(Context context, RealmUserQuery ruq, RuqusTheme theme) { this(context, null, ruq, theme); } public RealmQueryView(Context context, AttributeSet attrs) { this(context, attrs, null, null); } public RealmQueryView(Context context, AttributeSet attrs, RealmUserQuery ruq, RuqusTheme theme) { super(context, attrs); this.ruq = ruq; this.theme = theme; init(context, attrs); } /* Public methods. */ /** * Sets the theme of the view and any child views. * @param theme Theme to switch to. */ public void setTheme(RuqusTheme theme) { this.theme = theme; // Set theme on queryable and sort choosers. queryableChooser.setTheme(theme); sortChooser.setTheme(theme); // Set theme on all condition cards. for (int i = 0; i < partsCont.getChildCount(); i++) ((RQVCard2) partsCont.getChildAt(i)).setTheme(theme); // TODO Set for builder modes. } /** * Check whether the {@link RealmUserQuery} that this {@link RealmQueryView} currently has is fully-formed. * @return True if query is fully-formed, otherwise false. */ public boolean isQueryValid() { return ruq.isQueryValid(); } /** * Get the {@link RealmUserQuery} which this {@link RealmQueryView} currently has. Note that {@link RealmUserQuery} * implements {@link Parcelable}, which allows it to be passed around quickly and easily. * <p/> * This method does not guarantee that the returned query will be fully-formed and valid. Call {@link * RealmUserQuery#isQueryValid()} to check for validity before calling {@link RealmUserQuery#execute()}. * @return Realm user query object. */ public RealmUserQuery getRealmUserQuery() { return this.ruq; } /** * Set up this {@link RealmQueryView} using the given {@link RealmUserQuery}. * @param ruq Realm user query to use to set up this {@link RealmQueryView}. Must be fully-formed or this method * will do nothing. */ public void setRealmUserQuery(RealmUserQuery ruq) { if (!ruq.isQueryValid()) return; this.ruq = ruq; setupUsingRUQ(); } /* Non-public methods. */ /** * Initialize our view. * @param context Context to use. * @param attrs Attributes. */ private void init(Context context, AttributeSet attrs) { inflate(context, R.layout.realm_query_view, this); // Find main mode views. mainCont = (RelativeLayout) findViewById(R.id.main); queryableChooser = (RQVCard) findViewById(R.id.queryable_type); scrollView = (ScrollView) findViewById(R.id.main_scroll_view); partsCont = (LinearLayout) findViewById(R.id.query_parts); sortChooser = (RQVCard) findViewById(R.id.sort_type); // Find common builder mode views. builderScrollView = (ScrollView) findViewById(R.id.builder_scroll_view); builderHeader = (TextView) findViewById(R.id.builder_header); builderParts = (LinearLayout) findViewById(R.id.builder_parts); cancelButton = (Button) findViewById(R.id.cancel); saveButton = (Button) findViewById(R.id.save); // Find condition builder views. fieldChooser = (Spinner) findViewById(R.id.field_chooser); conditionalChooser = (Spinner) findViewById(R.id.conditional_chooser); // Find sort builder views. addSortField = (Button) findViewById(R.id.add_sort_field); // Read attributes. initAttrs(context, attrs); // Initialize UI. mode = Mode.MAIN; initUi(); // Create a new RealmUserQuery if we weren't given one. if (ruq == null) ruq = new RealmUserQuery(); } /** * Initializes the view using the given attributes. * @param context Context to use. * @param attrs Attributes. */ private void initAttrs(Context context, AttributeSet attrs) { TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RealmQueryView); if (theme == null) { // Get theme, default to light. theme = typedArray.getInt(R.styleable.RealmQueryView_ruqus_theme, RuqusTheme.LIGHT.ordinal()) == 0 ? RuqusTheme.LIGHT : RuqusTheme.DARK; } typedArray.recycle(); } /** * Initialize the UI. */ private void initUi() { setTheme(theme); // Set up main mode views. // Set click handlers for queryable and sort choosers. queryableChooser.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { onQueryableChooserClicked(); } }); sortChooser.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { onSortChooserClicked(); } }); // Set up common builder views. cancelButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { switchMode(Mode.MAIN); } }); saveButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { onSaveClicked(); } }); // Set up condition builder views. /*fieldChooser.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { onFieldChooserItemSelected((String) parent.getItemAtPosition(position), false); } @Override public void onNothingSelected(AdapterView<?> parent) { onFieldChooserItemSelected(Ruqus.CHOOSE_FIELD, false); } });*/ fieldChooser.setOnTouchListener(fieldChooserListener); fieldChooser.setOnItemSelectedListener(fieldChooserListener); /*conditionalChooser.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { onConditionalChooserItemSelected((String) parent.getItemAtPosition(position), false); } @Override public void onNothingSelected(AdapterView<?> parent) { currTransName = null; updateArgViews(); } });*/ conditionalChooser.setOnTouchListener(conditionalChooserListener); conditionalChooser.setOnItemSelectedListener(conditionalChooserListener); // Set up sort builder views. addSortField.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { addSortFieldView(-1, null); } }); // Finish setup. if (ruq == null) { // If we don't have a realm user query already, setup is very minimal, we just disable the scrollview and // sort choosers. setConditionsAndSortEnabled(false); } else { // If we have a RUQ already, we need to draw our view accordingly. Unless it's invalid, in which case we // want to get rid of it. if (ruq.isQueryValid()) setupUsingRUQ(); else ruq = null; } } @Override protected Parcelable onSaveInstanceState() { // Allow parent classes to save state. Parcelable superState = super.onSaveInstanceState(); SavedState ss = new SavedState(superState); // Save our state. ss.theme = this.theme; ss.ruq = this.ruq; ss.mode = this.mode; if (this.mode == Mode.C_BUILD) { // Only save condition builder variables if we're in that mode. ss.currPartIdx = this.currPartIdx; ss.currFieldName = this.currFieldName; ss.currTransName = this.currTransName; ss.currArgsString = stashableArgsString(); } else if (this.mode == Mode.S_BUILD) { // Only save sort builder variables if we're in that mode. ss.currSortFields = stashableSortFields(); ss.currSortDirs = stashableSortDirections(); } return ss; } @Override protected void onRestoreInstanceState(Parcelable state) { //Allow parent classes to restore state. if (!(state instanceof SavedState)) { super.onRestoreInstanceState(state); return; } SavedState ss = (SavedState) state; super.onRestoreInstanceState(ss.getSuperState()); // Restore our state. this.theme = ss.theme; this.ruq = ss.ruq; this.mode = ss.mode; setupUsingRUQ(); if (this.mode == Mode.C_BUILD) { // Only try to restore condition builder if we were in that mode. this.currPartIdx = ss.currPartIdx; this.currFieldName = ss.currFieldName; this.currTransName = ss.currTransName; restoreConditionBuilderMode(ss.currArgsString); } else if (this.mode == Mode.S_BUILD) { // Only try to restore sort builder if we were in that mode. restoreSortBuilderMode(ss.currSortFields, ss.currSortDirs); } } /** * Switches the view between main and various builder modes. * @param mode Mode to switch to. */ private void switchMode(Mode mode) { // Make sure we clean up if coming from a builder mode, or hide the main container if going to one. if (this.mode == Mode.C_BUILD && mode == Mode.MAIN) tearDownConditionBuilderMode(); else if (this.mode == Mode.S_BUILD && mode == Mode.MAIN) tearDownSortBuilderMode(); else if (this.mode == Mode.MAIN && mode != this.mode) mainCont.setVisibility(GONE); // Switch mode and UI. switch (mode) { case MAIN: mainCont.setVisibility(VISIBLE); break; case C_BUILD: { initConditionBuilderMode(currPartIdx >= partsCont.getChildCount() - 1 ? null : ruq.getConditions().get(currPartIdx)); builderScrollView.setVisibility(VISIBLE); break; } case S_BUILD: initSortBuilderMode(ruq.getSortFields(), ruq.getSortDirs()); builderScrollView.setVisibility(VISIBLE); break; } this.mode = mode; } /** * Set up the view using the current value of {@link #ruq}. */ private void setupUsingRUQ() { if (ruq == null || ruq.getQueryClass() == null) return; // Set queryable class. String realName = ruq.getQueryClass().getSimpleName(); setQueryable(realName, Ruqus.getClassData().visibleNameOf(realName)); // Set sort fields (if present). if (ruq.getSortFields().size() > 0) { sortChooser.setMode(RQVCard.Mode.CARD); sortChooser.setCardText("Sorted by " + ruq.getSortString()); } else sortChooser.setMode(RQVCard.Mode.OUTLINE); // Add part cards. partsCont.removeAllViews(); // Make sure parts container is empty first! for (Condition condition : ruq.getConditions()) appendPartView(condition); // Append an add part view. appendAddPartView(); } /** * Sets the "enabled" state of the query parts container and the sort chooser. * @param enabled If true, enable views. Otherwise disable them. */ private void setConditionsAndSortEnabled(boolean enabled) { scrollView.setEnabled(enabled); sortChooser.setEnabled(enabled); } /** * Creates an {@link RQVCard2} and sets it to card mode, filling it in using the given {@code condition}. The * condition doesn't need to be valid, this method is used when restoring the view's state after a configuration * change. * @param condition Condition to use to fill the card's text. */ private void appendPartView(Condition condition) { if (condition == null) throw new IllegalArgumentException("Must provide a Condition."); // Get visible condition string. String visCondString = condition.toString(); // Create a new card. RQVCard2 cond = new RQVCard2(getContext(), theme); cond.setMode(RQVCard2.Mode.CARD); // Set index tag to the current child count of the conditions container, since that will be this item's index // once it is added to the end of it. Also set content tag to the same as the current content. cond.setTag(R.id.ruqus_index, partsCont.getChildCount()); cond.setTag(R.id.ruqus_curr_val, visCondString); // Set the card's text to the visible condition string. cond.setCardText(visCondString); // Set the card's click listener based on the type of condition. if (condition.getType() == Condition.Type.NORMAL) { // Normal condition listener. cond.setCardClickListener(new OnClickListener() { @Override public void onClick(View v) { onConditionClicked((Integer) v.getTag(R.id.ruqus_index)); } }); } else { // Operator listener. cond.setCardClickListener(new OnClickListener() { @Override public void onClick(View v) { onOperatorClicked((Integer) v.getTag(R.id.ruqus_index), (String) v.getTag(R.id.ruqus_curr_val)); } }); } // Set the card's long click listener. cond.setCardLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View v) { onPartLongClicked((Integer) v.getTag(R.id.ruqus_index)); return true; } }); // Set a unique view ID. cond.setId(Util.getUniqueViewId()); // Add to the parts container. partsCont.addView(cond); } /** * Creates an {@link RQVCard2} and sets it to outlines mode with the texts "Add Operator" and "Add Condition", then * adds it to the end of {@link #partsCont}. */ private void appendAddPartView() { // Only add the view if we have the same number of views and conditions currently (indicates each view is // tied to a condition. if (ruq != null && partsCont.getChildCount() == ruq.conditionCount()) { RQVCard2 add = new RQVCard2(getContext(), theme); add.setMode(RQVCard2.Mode.OUTLINES); add.setOutlineText(R.string.ruqus_add_operator_nl, R.string.ruqus_add_condition_nl); // Set tag to the current child count of the conditions container, since that will be this item's index // once it is added to the end of it. add.setTag(R.id.ruqus_index, partsCont.getChildCount()); // Set the outline text views' OnClickListeners. add.setOutline1ClickListener(new OnClickListener() { @Override public void onClick(View v) { onOperatorClicked((Integer) v.getTag(R.id.ruqus_index), null); } }); add.setOutline2ClickListener(new OnClickListener() { @Override public void onClick(View v) { onConditionClicked((Integer) v.getTag(R.id.ruqus_index)); } }); // Set a unique view ID. add.setId(Util.getUniqueViewId()); // Add to the parts container. partsCont.addView(add); } } /** * Clears the view back to its initial state and sets {@link #ruq} to a new instance of {@link RealmUserQuery}. */ private void reset() { // Switch to main mode (will tear down builder modes if necessary). switchMode(Mode.MAIN); // New RUQ. ruq = new RealmUserQuery(); currClassName = null; currVisibleFlatFieldNames = null; currPartIdx = -1; // Reset choosers back to outline mode. queryableChooser.setMode(RQVCard.Mode.OUTLINE); sortChooser.setMode(RQVCard.Mode.OUTLINE); // Clear all children from condition container. partsCont.removeAllViews(); // Disable conditions container and sort chooser. setConditionsAndSortEnabled(false); } /** * Show a dialog with the visible names of all classes annotated with {@link Queryable}. */ private void onQueryableChooserClicked() { new MaterialDialog.Builder(getContext()) .title(R.string.ruqus_choose_queryable_title) .items(Ruqus.getClassData().getVisibleNames(true)) .itemsCallback(new MaterialDialog.ListCallback() { @Override public void onSelection(MaterialDialog dialog, View itemView, int which, CharSequence text) { String realName = Ruqus.classNameFromVisibleName(text.toString()); reset(); setQueryable(realName, text.toString()); ruq.setQueryClass(realName); } }) .show(); } /** * Called when the queryable class has been set. Only affects the view, not {@link #ruq}. * @param visibleName Visible name of the queryable class. */ private void setQueryable(String realName, String visibleName) { // Set instance vars. currClassName = realName; currVisibleFlatFieldNames = Ruqus.visibleFlatFieldsForClass(currClassName); currVisibleFlatFieldNames.add(0, Ruqus.CHOOSE_FIELD); // Set condition builder field chooser's adapter. fieldChooser.setAdapter(makeFieldAdapter()); // Set queryable chooser's card text and mode. queryableChooser.setCardText(visibleName); queryableChooser.setMode(RQVCard.Mode.CARD); // Append an add view to the conditions container, then enable the conditions container and sort chooser. appendAddPartView(); setConditionsAndSortEnabled(true); } private ArrayAdapter<String> makeFieldAdapter() { return new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_dropdown_item, currVisibleFlatFieldNames); } /** * Called when an {@link RQVCard2}'s outline text view which reads "Add Operator", or a card which has been filled * in with a real operator, is clicked. Shows a dialog of visible names of all no-args transformers (AKA, * "Operators"). * @param index Index of the card in the conditions container. * @param currVal The text which is currently on the card, or null if the card is in outline mode. */ private void onOperatorClicked(final int index, final String currVal) { new MaterialDialog.Builder(getContext()) .title(index == partsCont.getChildCount() - 1 ? R.string.ruqus_add_operator : R.string.ruqus_change_operator) .items(Ruqus.getTransformerData().getVisibleNoArgNames()) .itemsCallback(new MaterialDialog.ListCallback() { @Override public void onSelection(MaterialDialog dialog, View itemView, int which, CharSequence text) { if (currVal == null || !currVal.equals(text.toString())) setOperator(index, text.toString()); } }) .show(); } /** * Called when a card has been set as an operator card. * @param index Index of the card in the conditions container. * @param visibleName String to put on the card. */ private void setOperator(int index, String visibleName) { String realName = Ruqus.transformerNameFromVisibleName(visibleName, true); RQVCard2 card = (RQVCard2) partsCont.getChildAt(index); card.setTag(R.id.ruqus_curr_val, visibleName); if (card.getMode() == RQVCard2.Mode.OUTLINES) { // This was an outline-mode card before this, and ruq doesn't have a condition for it. // Set the card's card listener and long click listener. card.setCardClickListener(new OnClickListener() { @Override public void onClick(View v) { onOperatorClicked((Integer) v.getTag(R.id.ruqus_index), (String) v.getTag(R.id.ruqus_curr_val)); } }); card.setCardLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View v) { onPartLongClicked((Integer) v.getTag(R.id.ruqus_index)); return true; } }); // Set the card's text. card.setCardText(visibleName); // Set the card's mode to CARD. card.setMode(RQVCard2.Mode.CARD); // Create a new condition; we just need to set the transformer's real name and the realm class's name // since it's an no-args condition. Condition condition = new Condition(); condition.setTransformer(realName); condition.setRealmClass(currClassName); // Add the condition to the query. ruq.getConditions().add(condition); // Finally, append another add view to the conditions container. appendAddPartView(); } else { // This was a card-mode card already, ruq already had a condition for it. // Update card text. card.setCardText(visibleName); // Update condition. Condition condition = ruq.getConditions().get(index); condition.setTransformer(realName); condition.setRealmClass(currClassName); } } /** * Called when an {@link RQVCard2}'s outline text view which reads "Add Condition", or when a card which has been * filled in with a real condition, is clicked. Switches to condition builder mode. * @param index Index of the card in the conditions container. */ private void onConditionClicked(final int index) { this.currPartIdx = index; switchMode(Mode.C_BUILD); } /** * Called when the sort mode chooser is clicked. Switches to sort builder mode. */ private void onSortChooserClicked() { switchMode(Mode.S_BUILD); } /** * Show a dialog asking if we want to delete the long-clicked card. * @param index Index of the card in the conditions container. */ private void onPartLongClicked(final int index) { new MaterialDialog.Builder(getContext()) .title(R.string.ruqus_remove_operator) .negativeText(R.string.ruqus_no) .positiveText(R.string.ruqus_yes) .onPositive(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { // Remove from RUQ. ruq.getConditions().remove(index); // Remove from conditions container. partsCont.removeViewAt(index); } }) .show(); } /** * Called when the builder's save button is clicked (in either builder mode). */ private void onSaveClicked() { switch (mode) { case C_BUILD: { // Validate field. if (currFieldName == null || currFieldType == null) { Toast.makeText(getContext(), R.string.ruqus_error_must_set_field, Toast.LENGTH_LONG).show(); return; } // Validate conditional. if (currTransName == null) { Toast.makeText(getContext(), R.string.ruqus_error_must_set_conditional, Toast.LENGTH_LONG).show(); return; } // Validate and get args. Object[] args = getArgsIfValid(); if (args == null) return; // Get card. RQVCard2 card = (RQVCard2) partsCont.getChildAt(currPartIdx); // Create or get condition. Condition condition = currPartIdx == partsCont.getChildCount() - 1 ? new Condition() : ruq.getConditions().get(currPartIdx); // Fill in/update the condition. if (condition.getRealmClass() == null) condition.setRealmClass(currClassName); condition.setField(currFieldName); condition.setTransformer(currTransName); condition.setArgs(args); // Get the visible condition string. String visCondString = condition.toString(); // Set the card's text (and its tag). card.setTag(R.id.ruqus_curr_val, visCondString); card.setCardText(visCondString); // If the card is still in OUTLINES mode, we know this is a new Condition, and that we need to do a bit // more setup for the card prior to adding the Condition to the query and switching back to MAIN mode. if (card.getMode() == RQVCard2.Mode.OUTLINES) { // New condition, we need to set the card up a bit more too. // Set the card's listener and long click listener. card.setCardClickListener(new OnClickListener() { @Override public void onClick(View v) { onConditionClicked((Integer) v.getTag(R.id.ruqus_index)); } }); card.setCardLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View v) { onPartLongClicked((Integer) v.getTag(R.id.ruqus_index)); return true; } }); // Set the card's mode to CARD. card.setMode(RQVCard2.Mode.CARD); // Add the condition to the query. ruq.getConditions().add(condition); // Finally, append another add view to the conditions container. appendAddPartView(); } break; } case S_BUILD: { ArrayList<String> sortFields = new ArrayList<>(); ArrayList<Sort> sortDirs = new ArrayList<>(); // Get sort fields. for (Integer sortSpinnerId : sortSpinnerIds) sortFields.add(Ruqus.fieldFromVisibleField(currClassName, (String) ((Spinner) builderParts.findViewById(sortSpinnerId)).getSelectedItem())); // Ensure none of the sort fields are the default "Choose Field" string. if (sortFields.contains(Ruqus.CHOOSE_FIELD)) { Toast.makeText(getContext(), R.string.ruqus_error_some_sort_fields_not_chosen, Toast.LENGTH_LONG) .show(); return; } // Get sort dirs. for (Integer sortDirRgId : sortDirRgIds) sortDirs.add(((RadioGroup) builderParts.findViewById(sortDirRgId)) .getCheckedRadioButtonId() == R.id.asc ? Sort.ASCENDING : Sort.DESCENDING); // Set ruq sort fields. ruq.setSorts(sortFields, sortDirs); // Set sort chooser mode and/or card text. if (sortFields.size() > 0) { sortChooser.setMode(RQVCard.Mode.CARD); sortChooser.setCardText("Sorted by " + ruq.getSortString()); } else sortChooser.setMode(RQVCard.Mode.OUTLINE); break; } } // Switch back to main container. switchMode(Mode.MAIN); } /* Methods for Condition builder mode. */ /** * Called to set up the builder views for condition builder mode. * @param condition Condition to use to pre-fill views. */ private void initConditionBuilderMode(Condition condition) { // Make sure currPartIdx is set. if (currPartIdx == -1) throw new IllegalArgumentException("Must set currPartIdx for C_BUILD mode."); // Set up views. builderHeader.setText(R.string.ruqus_edit_condition_title); fieldChooser.setVisibility(VISIBLE); // Set up vars. argViewIds = new ArrayList<>(); // Set up from condition. if (condition != null) { // Select correct value in field chooser. //currFieldName = condition.getField(); fieldChooser.setSelection(currVisibleFlatFieldNames.indexOf( Ruqus.visibleFieldFromField(currClassName, condition.getField()))); // Set up views based on it. onFieldChooserItemSelected(Ruqus.visibleFieldFromField(currClassName, condition.getField()), false); // Select correct transformer. //currTransName = condition.getTransformer(); conditionalChooser.setSelection(1 + Ruqus.getTransformerData().getVisibleNames( currFieldType.getClazz()).indexOf(Ruqus.getTransformerData().visibleNameOf( condition.getTransformer()))); // Set up views based on it. onConditionalChooserItemSelected(Ruqus.getTransformerData().visibleNameOf(condition.getTransformer()), false); // Fill in argument views. fillArgViews(condition.getArgs()); } } /** * Called to restore the view hierarchy state if we were in condition builder mode prior to a configuration change. * @param argsString String containing values to put in arg views. */ private void restoreConditionBuilderMode(String argsString) { // Make sure currPartIdx is set. if (currClassName == null) throw new IllegalArgumentException("Cannot restore without currClassName"); if (currPartIdx == -1) throw new IllegalArgumentException("Must set currPartIdx for C_BUILD mode."); // Set up views. builderHeader.setText(R.string.ruqus_edit_condition_title); fieldChooser.setVisibility(VISIBLE); // Set up vars. argViewIds = new ArrayList<>(); // Try to restore chosen field. if (currFieldName != null) { fieldChooser.setSelection(currVisibleFlatFieldNames.indexOf( Ruqus.visibleFieldFromField(currClassName, currFieldName))); // Set up views based on it. onFieldChooserItemSelected(Ruqus.visibleFieldFromField(currClassName, currFieldName), true); } // Try to restore chosen transformer. if (currTransName != null) { conditionalChooser.setSelection(1 + Ruqus.getTransformerData().getVisibleNames( currFieldType.getClazz()).indexOf(Ruqus.getTransformerData().visibleNameOf(currTransName))); // Set up views based on it. onConditionalChooserItemSelected(Ruqus.getTransformerData().visibleNameOf(currTransName), true); } // Try to restore inputs. restoreArgViews(argsString); // Hide main view and show builder view. mainCont.setVisibility(GONE); builderScrollView.setVisibility(VISIBLE); } /** * Called to clean up the builder views when finishing condition builder mode. */ private void tearDownConditionBuilderMode() { // Clean up views. builderParts.removeAllViews(); fieldChooser.setSelection(0); fieldChooser.setVisibility(GONE); conditionalChooser.setVisibility(GONE); builderScrollView.setVisibility(GONE); // Clean up vars. currPartIdx = -1; currFieldName = null; currFieldType = null; currTransName = null; argViewIds = null; } private SpinnerInteractionListener fieldChooserListener = new SpinnerInteractionListener() { boolean isTouching = false; @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (isTouching) { onFieldChooserItemSelected((String) parent.getItemAtPosition(position), false); isTouching = false; } } @Override public void onNothingSelected(AdapterView<?> parent) { if (isTouching) { onFieldChooserItemSelected(Ruqus.CHOOSE_FIELD, false); isTouching = false; } } @Override public boolean onTouch(View v, MotionEvent event) { isTouching = true; return false; } }; private SpinnerInteractionListener conditionalChooserListener = new SpinnerInteractionListener() { boolean isTouching = false; @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (isTouching) { onConditionalChooserItemSelected((String) parent.getItemAtPosition(position), false); isTouching = false; } } @Override public void onNothingSelected(AdapterView<?> parent) { if (isTouching) { currTransName = null; updateArgViews(); isTouching = false; } } @Override public boolean onTouch(View v, MotionEvent event) { isTouching = true; return false; } }; /** * Called when an item is selected in the condition builder field chooser. * @param selStr Selected item string. */ private void onFieldChooserItemSelected(String selStr, boolean manual) { if (Ruqus.CHOOSE_FIELD.equals(selStr)) { currFieldName = null; currFieldType = null; updateArgViews(); conditionalChooser.setVisibility(GONE); return; } // It's a real field. String realFieldName = Ruqus.fieldFromVisibleField(currClassName, selStr); if (manual || currFieldName == null || !currFieldName.equals(realFieldName)) { // We only care if if was changed. currFieldName = realFieldName; // Get field type from field. currFieldType = Ruqus.typeEnumForField(currClassName, currFieldName); // Get the list of visible names for all transformers which accept the given field type. ArrayList<String> conditionals = Ruqus.getTransformerData().getVisibleNames(currFieldType.getClazz()); conditionals.add(0, Ruqus.CHOOSE_CONDITIONAL); // Create an array adapter from it. ArrayAdapter<String> conditionalAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_dropdown_item, conditionals); // Bind the adapter to the spinner. conditionalChooser.setAdapter(conditionalAdapter); // Make sure conditional chooser is visible. conditionalChooser.setVisibility(VISIBLE); } } /** * Called when an item is selected in the condition builder conditional chooser. * @param selStr Selected item string. */ private void onConditionalChooserItemSelected(String selStr, boolean manual) { if (Ruqus.CHOOSE_CONDITIONAL.equals(selStr)) { currTransName = null; updateArgViews(); return; } // It's a real transformer. String realTransName = Ruqus.transformerNameFromVisibleName(selStr, false); if (manual || currTransName == null || !currTransName.equals(realTransName)) { // We only care if it was changed. currTransName = realTransName; updateArgViews(); } } /** * Update the views in {@link #builderParts} so that they allow the user to input the correct type of data based on * the current {@link #currFieldName}, {@link #currFieldType}, and {@link #currTransName}. */ private void updateArgViews() { builderParts.removeAllViews(); if (currFieldName == null || currFieldType == null || currTransName == null) { currTransName = null; return; } // Add views based on the field type and the number of arguments that the transformer accepts. int numArgs = Ruqus.numberOfArgsFor(currTransName); for (int i = 0; i < numArgs; i++) { final int id = Util.getUniqueViewId(); switch (currFieldType) { case BOOLEAN: RadioGroup rgFalseTrue = (RadioGroup) View.inflate(getContext(), R.layout.rg_false_true, null); rgFalseTrue.setId(id); builderParts.addView(rgFalseTrue); break; case DATE: DateInputView dateInputView = new DateInputView(getContext(), theme); // Set up date button to open date picker dialog. dateInputView.setId(id); builderParts.addView(dateInputView); break; case DOUBLE: case FLOAT: EditText etDecimal = (EditText) View.inflate(getContext(), R.layout.et_decimal, null); etDecimal.setId(id); builderParts.addView(etDecimal); break; case INTEGER: case LONG: case SHORT: EditText etWholeNumber = (EditText) View.inflate(getContext(), R.layout.et_whole_number, null); etWholeNumber.setId(id); builderParts.addView(etWholeNumber); break; case STRING: EditText etString = (EditText) View.inflate(getContext(), R.layout.et_string, null); etString.setId(id); builderParts.addView(etString); break; } argViewIds.add(id); } } /** * Fill in argument views in condition builder using the values passed in {@code args}. * @param args Values retrieved using {@link Condition#getArgs()}. */ private void fillArgViews(Object[] args) { if (args == null) return; for (int i = 0; i < args.length && i < argViewIds.size(); i++) { View view = builderParts.findViewById(argViewIds.get(i)); switch (currFieldType) { case BOOLEAN: ((RadioGroup) view).check((Boolean) args[i] ? R.id.rb_true : R.id.rb_false); break; case DATE: ((DateInputView) view).setDate((Date) args[i]); break; case DOUBLE: case FLOAT: case INTEGER: case LONG: case SHORT: ((TextView) view).setText(String.valueOf(args[i])); break; case STRING: ((TextView) view).setText((String) args[i]); break; } } } /** * Restore the condition builder arg views's contents. * @param argsString String containing values to put in arg views. * @see #stashableArgsString() */ private void restoreArgViews(String argsString) { if (argsString == null || argsString.isEmpty()) return; String[] args = ARG_STR_SEP_PATTERN.split(argsString); for (int i = 0; i < args.length && i < argViewIds.size(); i++) { View view = builderParts.findViewById(argViewIds.get(i)); switch (currFieldType) { case BOOLEAN: ((RadioGroup) view).check("true".equals(args[i]) ? R.id.rb_true : R.id.rb_false); break; case DATE: ((DateInputView) view).setText(args[i]); break; case DOUBLE: case FLOAT: case INTEGER: case LONG: case SHORT: case STRING: ((TextView) view).setText(args[i]); break; } } } /** * Attempts to validates the values that the user has provided to the condition builder, and returns them if they * pass. * @return Array of input values as Objects, or null if any input values are invalid. */ private Object[] getArgsIfValid() { Object[] args = new Object[argViewIds.size()]; for (int i = 0; i < argViewIds.size(); i++) { View argView = builderParts.findViewById(argViewIds.get(i)); switch (currFieldType) { case BOOLEAN: // There's no way that neither of the radio buttons are checked :) RadioGroup rgFalseTrue = (RadioGroup) argView; args[i] = rgFalseTrue.getCheckedRadioButtonId() != R.id.rb_false; continue; case DATE: DateInputView dateInputView = (DateInputView) argView; if (!dateInputView.hasDate()) { dateInputView.setError(getContext().getString(R.string.ruqus_error_empty_date)); return null; } args[i] = dateInputView.getDate(); continue; case DOUBLE: EditText etDouble = (EditText) argView; if (etDouble.length() == 0) { etDouble.setError(getContext().getString(R.string.ruqus_error_empty_input)); return null; } args[i] = FieldType.parseNumberIfPossible(currFieldType, etDouble.getText().toString()); if (args[i] == null) { etDouble.setError(getContext().getString(R.string.ruqus_error_out_of_range_double)); return null; } continue; case FLOAT: EditText etFloat = (EditText) argView; if (etFloat.length() == 0) { etFloat.setError(getContext().getString(R.string.ruqus_error_empty_input)); return null; } args[i] = FieldType.parseNumberIfPossible(currFieldType, etFloat.getText().toString()); if (args[i] == null) { etFloat.setError(getContext().getString(R.string.ruqus_error_out_of_range_float)); return null; } continue; case INTEGER: EditText etInteger = (EditText) argView; if (etInteger.length() == 0) { etInteger.setError(getContext().getString(R.string.ruqus_error_empty_input)); return null; } args[i] = FieldType.parseNumberIfPossible(currFieldType, etInteger.getText().toString()); if (args[i] == null) { etInteger.setError(getContext().getString(R.string.ruqus_error_out_of_range_integer)); return null; } continue; case LONG: EditText etLong = (EditText) argView; if (etLong.length() == 0) { etLong.setError(getContext().getString(R.string.ruqus_error_empty_input)); return null; } args[i] = FieldType.parseNumberIfPossible(currFieldType, etLong.getText().toString()); if (args[i] == null) { etLong.setError(getContext().getString(R.string.ruqus_error_out_of_range_long)); return null; } continue; case SHORT: EditText etShort = (EditText) argView; if (etShort.length() == 0) { etShort.setError(getContext().getString(R.string.ruqus_error_empty_input)); return null; } args[i] = FieldType.parseNumberIfPossible(currFieldType, etShort.getText().toString()); if (args[i] == null) { etShort.setError(getContext().getString(R.string.ruqus_error_out_of_range_short)); return null; } continue; case STRING: EditText etString = (EditText) argView; args[i] = etString.getText().toString(); if (((String) args[i]).isEmpty()) { etString.setError(getContext().getString(R.string.ruqus_error_empty_input)); return null; } } } return args; } /** * Get the condition builder arg views' contents as a string so that we can restore them later. * @return String which we have stashed our arg views' contents in. * @see #restoreArgViews(String) */ private String stashableArgsString() { StringBuilder builder = new StringBuilder(); for (int i = 0; i < argViewIds.size(); i++) { View argView = builderParts.findViewById(argViewIds.get(i)); switch (currFieldType) { case BOOLEAN: builder.append(((RadioGroup) argView).getCheckedRadioButtonId() == R.id.rb_false ? "false" : "true"); continue; case DATE: builder.append(((DateInputView) argView).getText()); continue; case DOUBLE: case FLOAT: case INTEGER: case LONG: case SHORT: case STRING: builder.append(((EditText) argView).getText().toString()); } builder.append(ARG_STR_SEP); } if (builder.length() > 0) builder.delete(builder.lastIndexOf(ARG_STR_SEP), builder.length()); return builder.toString(); } /* Methods for sort builder mode. */ /** * Called to set up the builder views for sort builder mode. * @param sortFields Current sort fields. * @param sortDirs Current sort directions. */ private void initSortBuilderMode(ArrayList<String> sortFields, ArrayList<Sort> sortDirs) { // Set up views. builderHeader.setText(R.string.ruqus_choose_sort_fields_title); addSortField.setEnabled(true); addSortField.setVisibility(VISIBLE); // Set up vars. sortSpinnerIds = new ArrayList<>(); removeSortBtnIds = new ArrayList<>(); sortDirRgIds = new ArrayList<>(); // If present, add current sort fields. for (int i = 0; i < sortFields.size(); i++) addSortFieldView(currVisibleFlatFieldNames.indexOf(Ruqus.visibleFieldFromField(currClassName, sortFields.get(i))), sortDirs.get(i)); } /** * Called to restore the view hierarchy state if we were in sort builder mode prior to a configuration change. * <p/> * TODO doesn't correctly restore sort dirs, but does get the fields right... * @param sortFields Sort fields to restore. * @param sortDirs Sort directions to restore. */ private void restoreSortBuilderMode(ArrayList<String> sortFields, ArrayList<Sort> sortDirs) { initSortBuilderMode(sortFields, sortDirs); // Hide main view and show builder view. mainCont.setVisibility(GONE); builderScrollView.setVisibility(VISIBLE); } /** * Called to clean up the builder views when finishing sort builder mode. */ private void tearDownSortBuilderMode() { // Clean up views. addSortField.setVisibility(GONE); builderParts.removeAllViews(); builderScrollView.setVisibility(GONE); // Clean up vars. sortSpinnerIds = null; removeSortBtnIds = null; sortDirRgIds = null; } /** * Called to add a sort field view to {@link #builderParts} (and optionally pre-fill it). * @param selectedFieldPos Position in spinner to pre-select, or -1. * @param sortDir Sort direction to pre-select, or null. */ private void addSortFieldView(int selectedFieldPos, Sort sortDir) { final int idx = sortSpinnerIds.size(); RelativeLayout sortPart = (RelativeLayout) View.inflate(getContext(), R.layout.sort_part, null); // Set label text. ((TextView) sortPart.findViewById(R.id.sort_field_label)).setText( getContext().getString(R.string.ruqus_sort_field_label, idx)); // Set up spinner. Spinner fieldSpinner = (Spinner) sortPart.findViewById(R.id.sort_field); fieldSpinner.setAdapter(makeFieldAdapter()); fieldSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // Make sure the user didn't select nothing. String selStr = (String) parent.getItemAtPosition(position); if (Ruqus.CHOOSE_FIELD.equals(selStr)) builderParts.findViewById(sortDirRgIds.get(idx)).setVisibility(GONE); else setSortDirOptions(idx, selStr); } @Override public void onNothingSelected(AdapterView<?> parent) { builderParts.findViewById(sortDirRgIds.get(idx)).setVisibility(GONE); } }); // Set up remove button. ImageButton removeButton = (ImageButton) sortPart.findViewById(R.id.remove_field); DrawableCompat.setTint(removeButton.getDrawable(), theme == RuqusTheme.LIGHT ? Ruqus.DARK_TEXT_COLOR : Ruqus.LIGHT_TEXT_COLOR); removeButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { removeSortField(idx); } }); // Set up radio group. RadioGroup sortDirRg = (RadioGroup) sortPart.findViewById(R.id.rg_sort_dir); // Generate unique view IDs for the spinner, button, and radio group and set them. int fieldSpinnerId = Util.getUniqueViewId(); int removeButtonId = Util.getUniqueViewId(); int sortDirRgId = Util.getUniqueViewId(); fieldSpinner.setId(fieldSpinnerId); removeButton.setId(removeButtonId); sortDirRg.setId(sortDirRgId); // Add IDs to lists. sortSpinnerIds.add(fieldSpinnerId); removeSortBtnIds.add(removeButtonId); sortDirRgIds.add(sortDirRgId); // If that was our third sort field, we disable the button that adds them. if (sortSpinnerIds.size() == 3) addSortField.setEnabled(false); // Add this to the builder container (Add one, since we want it added after the header view). builderParts.addView(sortPart); // Fill this sort field layout's views in if necessary. if (selectedFieldPos != -1) { // Select the correct item in the spinner. fieldSpinner.setSelection(selectedFieldPos); // Manually update the radio buttons' text if need be. String selStr = (String) fieldSpinner.getItemAtPosition(selectedFieldPos); if (Ruqus.CHOOSE_FIELD.equals(selStr)) sortDirRg.setVisibility(GONE); else setSortDirOptions(idx, selStr); // Select the correct radio button. sortDirRg.check(sortDir == Sort.ASCENDING ? R.id.asc : R.id.desc); } } /** * Called when a remove sort field button is clicked. */ private void removeSortField(int index) { // Remove IDs from lists. sortSpinnerIds.remove(index); removeSortBtnIds.remove(index); sortDirRgIds.remove(index); // Remove from builder container (Add one to the index, since the header view is there). builderParts.removeViewAt(index); // Enable add button. addSortField.setEnabled(true); } /** * Called when the selection on a sort field spinner is changed. */ private void setSortDirOptions(int index, String visibleFieldName) { String[] pretty = Ruqus.typeEnumForField(currClassName, Ruqus.fieldFromVisibleField( currClassName, visibleFieldName)).getPrettySortStrings(); RadioGroup rg = (RadioGroup) builderParts.findViewById(sortDirRgIds.get(index)); ((RadioButton) rg.findViewById(R.id.asc)).setText(pretty[0]); ((RadioButton) rg.findViewById(R.id.desc)).setText(pretty[1]); rg.setVisibility(VISIBLE); } /** * Get a list of sort fields which are currently chosen so we can restore them later. * @return List of currently selected sort fields. */ private ArrayList<String> stashableSortFields() { ArrayList<String> sortFields = new ArrayList<>(); for (Integer sortSpinnerId : sortSpinnerIds) sortFields.add(Ruqus.fieldFromVisibleField(currClassName, (String) ((Spinner) builderParts.findViewById(sortSpinnerId)).getSelectedItem())); return sortFields; } /** * Get a list of sort directions which are currently chosen so we can restore them later. * @return List of currently selected sort directions. */ private ArrayList<Sort> stashableSortDirections() { ArrayList<Sort> sortDirs = new ArrayList<>(); for (Integer sortDirRgId : sortDirRgIds) sortDirs.add(((RadioGroup) builderParts.findViewById(sortDirRgId)) .getCheckedRadioButtonId() == R.id.asc ? Sort.ASCENDING : Sort.DESCENDING); return sortDirs; } /* State persistence. */ /** * Helps us easily save and restore our view's state. */ static class SavedState extends BaseSavedState { // General variables. Will always be written/read. RuqusTheme theme; RealmUserQuery ruq; Mode mode; // Condition builder variables. Will only be written/read if we're in condition builder mode. int currPartIdx; String currFieldName; String currTransName; String currArgsString; // Sort builder variables. Will only be written/read if we're in sort builder mode. ArrayList<String> currSortFields; ArrayList<Sort> currSortDirs; public SavedState(Parcelable superState) { super(superState); } private SavedState(Parcel in) { super(in); // Read general variables' values back. int tmpTheme = in.readInt(); this.theme = tmpTheme == -1 ? null : RuqusTheme.values()[tmpTheme]; this.ruq = in.readParcelable(RealmUserQuery.class.getClassLoader()); int tmpMode = in.readInt(); this.mode = tmpMode == -1 ? null : Mode.values()[tmpMode]; if (this.mode == Mode.C_BUILD) { // If we were in condition builder mode, read those variables' values back. this.currPartIdx = in.readInt(); this.currFieldName = in.readString(); this.currTransName = in.readString(); this.currArgsString = in.readString(); } else if (this.mode == Mode.S_BUILD) { // If we were in sort builder mode, read those variables' values back. this.currSortFields = in.createStringArrayList(); this.currSortDirs = new ArrayList<>(); ArrayList<Integer> temp = new ArrayList<>(); in.readList(temp, null); for (Integer sortOrdinal : temp) this.currSortDirs.add(Sort.values()[sortOrdinal]); } } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); // Write general variables' values. out.writeInt(this.theme == null ? -1 : this.theme.ordinal()); out.writeParcelable(this.ruq, flags); out.writeInt(this.mode == null ? -1 : this.mode.ordinal()); if (this.mode == Mode.C_BUILD) { // If we're in condition builder mode, write those variables' values. out.writeInt(this.currPartIdx); out.writeString(this.currFieldName); out.writeString(this.currTransName); out.writeString(this.currArgsString); } else if (this.mode == Mode.S_BUILD) { // If we're in sort builder mode, write those variables' values. out.writeStringList(this.currSortFields); ArrayList<Integer> temp = new ArrayList<>(); for (Sort sortDir : this.currSortDirs) temp.add(sortDir.ordinal()); out.writeList(temp); } } public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { @Override public SavedState createFromParcel(Parcel in) {return new SavedState(in);} @Override public SavedState[] newArray(int size) {return new SavedState[size];} }; } }
package mb.spectrum; import static mb.spectrum.UiUtils.createConfigurableBooleanProperty; import static mb.spectrum.UiUtils.createConfigurableIntegerProperty; import static mb.spectrum.UiUtils.createUtilityPane; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import javafx.animation.AnimationTimer; import javafx.animation.PauseTransition; import javafx.animation.SequentialTransition; import javafx.animation.Transition; import javafx.application.Application; import javafx.application.Platform; import javafx.beans.binding.Bindings; import javafx.beans.property.BooleanProperty; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.SceneAntialiasing; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.effect.Glow; import javafx.scene.input.KeyEvent; import javafx.scene.layout.Background; import javafx.scene.layout.BackgroundFill; import javafx.scene.layout.BorderPane; import javafx.scene.layout.CornerRadii; import javafx.scene.layout.Pane; import javafx.scene.layout.StackPane; import javafx.scene.paint.Color; import javafx.stage.Stage; import javafx.util.Duration; import mb.spectrum.embedded.EmbeddedStrategy; import mb.spectrum.prop.ConfigurableBooleanProperty; import mb.spectrum.prop.ConfigurableChoiceProperty; import mb.spectrum.prop.ConfigurableColorProperty; import mb.spectrum.prop.ConfigurableIntegerProperty; import mb.spectrum.prop.ConfigurableProperty; import mb.spectrum.prop.IncrementalActionProperty; import mb.spectrum.view.View; public class Spectrum extends Application { private static final int SAMPLING_RATE = Integer.valueOf( ConfigService.getInstance().getOrCreateProperty("mb.sampling-rate", String.valueOf(48000))); private static final int BUFFER_SIZE = Integer.valueOf( ConfigService.getInstance().getOrCreateProperty("mb.buffer-size", String.valueOf(1024))); private static final int INIT_SCENE_WIDTH = 800; private static final int INIT_SCENE_HEIGHT = 480; private static final String VIEW_LABEL_COLOR = "#00aeff"; private static final double VIEW_LABEL_FADE_IN_MS = 1000; private static final double VIEW_LABEL_LINGER_MS = 1000; private static final double VIEW_LABEL_FADE_OUT_MS = 1000; private PlatformStrategy strategy; private Scene scene; private StackPane stackPane; private List<View> views; private View currentView; private int currentViewIdx; private Timer viewRotateTimer; private boolean viewTransitioning; /* Property management */ private PropertyPane propertyPane; private Transition currentPropertyTransition; private Map<Integer, Integer> lastPropertyMap; /* Global Properties */ List<ConfigurableProperty<? extends Object>> globalPropertyList; private ConfigurableIntegerProperty propGlobalGain; private ConfigurableBooleanProperty propViewAutoRotate; private ConfigurableIntegerProperty propViewAutoRotateInterval; private ConfigurableBooleanProperty propEnableSmoothTransitions; public Spectrum() { views = new ViewLazyList(BUFFER_SIZE); currentViewIdx = 0; currentView = views.get(currentViewIdx); strategy = StrategyLoader.getInstance().getStrategy(); /* if(DesktopStrategy.class.equals(strategy.getClass())) { views.add(new StereoAnalogMetersView()); } */ } @Override public void start(Stage stage) throws Exception { strategy.initialize(stage); createGlobalProperties(); initLastPropertyMap(); startAudio(); setupStage(stage); startFrameListener(); } @Override public void stop() throws Exception { stopAudio(); strategy.close(); } public boolean isPropertiesVisible() { return propertyPane.isVisible(); } private boolean isPropertySelected() { return propertyPane.selectedProperty().get(); } private void initLastPropertyMap() { lastPropertyMap = new HashMap<>(views.size()); // -1 is used for the global property list for (int i = -1; i < views.size(); i++) { lastPropertyMap.put(i, 0); } } private void createGlobalProperties() { final String keyPrefix = "global."; propGlobalGain = createConfigurableIntegerProperty( keyPrefix + "gain", "Global Gain", 10, 400, 100, 10, "%"); propViewAutoRotate = createConfigurableBooleanProperty( keyPrefix + "viewAutoRotate", "Auto Rotate Views", false); propViewAutoRotate.getProp().addListener((obs, oldVal, newVal) -> { if(newVal != oldVal) { if(newVal) { scheduleViewRotateTimer(); } else { cancelViewRotateTimer(); } } }); propViewAutoRotateInterval = createConfigurableIntegerProperty( keyPrefix + "viewAutoRotateInterval", "View Rotate Interval", 5, 6000, 60, 5, "sec"); propEnableSmoothTransitions = createConfigurableBooleanProperty( keyPrefix + "enableSmoothTransitions", "Enable Smooth Transitions", true); globalPropertyList = new ArrayList<>(Arrays.asList( propGlobalGain, propViewAutoRotate, propViewAutoRotateInterval, propEnableSmoothTransitions)); // Poweroff if(strategy instanceof EmbeddedStrategy) { IncrementalActionProperty propPoweroff = new IncrementalActionProperty("Power Off", 8); propPoweroff.setOnAction((e) -> { togglePropertiesOff(); UiUtils.createAndShowShutdownPrompt(strategy.getStage(), true); }); globalPropertyList.add(propPoweroff); } } private void startAudio() { String path = getParameters().getNamed().get("file"); if(path != null) { strategy.startAudio(path, BUFFER_SIZE); } else { strategy.startAudio(true, BUFFER_SIZE, SAMPLING_RATE, 16); } strategy.setListener(new AudioListener() { public void samples(float[] left, float[] right) { // Global gain float gain = propGlobalGain.getProp().get() / 100f; for (int i = 0; i < left.length; i++) { left[i] = left[i] * gain; } for (int i = 0; i < right.length; i++) { right[i] = right[i] * gain; } currentView.dataAvailable(left, right); } }); } private void stopAudio() { strategy.stopAudio(); } private void setupStage(Stage stage) { /* Create scene and root stack pane */ stackPane = new StackPane(currentView.getRoot()); // This is needed for correct smooth transitions stackPane.setBackground(new Background(new BackgroundFill(Color.TRANSPARENT, CornerRadii.EMPTY, Insets.EMPTY))); stackPane.setAlignment(Pos.CENTER); stage.setScene(scene = new Scene(stackPane, INIT_SCENE_WIDTH, INIT_SCENE_HEIGHT, false, strategy instanceof EmbeddedStrategy ? SceneAntialiasing.DISABLED : SceneAntialiasing.BALANCED)); scene.setFill(Color.BLACK); currentView.onShow(); stackPane.prefWidthProperty().bind(scene.widthProperty()); stage.setMaximized(!Boolean.valueOf( getParameters().getNamed().get("windowed"))); stage.show(); /* Event handlers */ stage.addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() { public void handle(KeyEvent event) { onKey(event); } }); /* View rotate timer */ if(propViewAutoRotate.getProp().get()) { scheduleViewRotateTimer(); } /* Property pane */ propertyPane = createPropertyPane(); propertyPane.setProperties(currentView.getProperties()); stackPane.getChildren().add(propertyPane); } private void startFrameListener() { new AnimationTimer() { public void handle(long now) { currentView.nextFrame(); } }.start(); } private void onKey(KeyEvent event) { switch (event.getCode()) { case RIGHT: if(isPropertiesVisible()) { // Update the value if a property is currently selected, else move to the next property if(isPropertySelected()) { changeCurrentPropertyValue(true, event.isShiftDown()); } else { nextProperty(); } } else { nextView(); } break; case LEFT: if(isPropertiesVisible()) { // Update the value if a property is currently selected, else move to the previous property if(isPropertySelected()) { changeCurrentPropertyValue(false, event.isShiftDown()); } else { prevProperty(); } } else { prevView(); } break; case SPACE: if(event.isControlDown()) { if(isPropertiesVisible()) { togglePropertiesOff(); } else { toggleGlobalPropertiesOn(); } } else { if(isPropertiesVisible()) { selectOrDeselectCurrentProperty(); } else { toggleCurrentViewPropertiesOn(); } } // Prevents checkbox selection if the currently visible property is a boolean event.consume(); break; case ENTER: if(isPropertiesVisible()) { firePropertyButtonIfInFocus(); } break; case UP: if(isPropertiesVisible()) { changeCurrentPropertyValue(true, event.isShiftDown()); } break; case DOWN: if(isPropertiesVisible()) { changeCurrentPropertyValue(false, event.isShiftDown()); } break; case C: if(event.isControlDown()) { Platform.exit(); } break; case F: if(event.isControlDown()) { Stage stage = (Stage) scene.getWindow(); stage.setFullScreen(true); } break; case ESCAPE: if(isPropertiesVisible()) { hideProperties(); } break; default: break; } } /** * Triggers the current property pane fade out after two seconds */ private void schedulePropertyFadeOut() { if(isPropertiesVisible() && isSmoothTransitionsEnabled()) { currentPropertyTransition = new SequentialTransition( new PauseTransition(Duration.seconds(2)), UiUtils.createFadeOutTransition(propertyPane, 1000, 0.5, null)); currentPropertyTransition.play(); } } /** * Cancels the current property's transition */ private void cancelPropertyFadeOutIfPlaying() { if(isPropertiesVisible() && isSmoothTransitionsEnabled()) { if(currentPropertyTransition != null) { currentPropertyTransition.stop(); } propertyPane.setOpacity(1); } } /** * Toggles on the global properties pane */ private void toggleGlobalPropertiesOn() { if(!isPropertiesVisible()) { propertyPane.setProperties(globalPropertyList); propertyPane.setCurrPropIdx(0); showProperties(); } } /** * Resets the property index and shows first property of current view */ private void toggleCurrentViewPropertiesOn() { if(!isPropertiesVisible() && !currentView.getProperties().isEmpty()) { propertyPane.setProperties(currentView.getProperties()); propertyPane.setCurrPropIdx(lastPropertyMap.get(currentViewIdx)); showProperties(); } } /** * If properties are currently shown, hides the current property */ private void togglePropertiesOff() { if(isPropertiesVisible()) { hideProperties(); } } /** * Switch to the next view from the list. */ private void nextView() { if(!viewTransitioning) { int idx = currentViewIdx + 1; if(idx > views.size() - 1) { idx = views.size() - 1; } switchView(idx); } } /** * Switch to the previous view from the list. */ private void prevView() { if(!viewTransitioning) { int idx = currentViewIdx - 1; if(idx < 0) { idx = 0; } switchView(idx); } } private void switchView(int idx) { if(idx != currentViewIdx) { currentViewIdx = idx; // Reset properties togglePropertiesOff(); if(isSmoothTransitionsEnabled()) { viewTransitioning = true; UiUtils.createFadeOutTransition(currentView.getRoot(), 500, new EventHandler<ActionEvent>() { public void handle(ActionEvent event) { // Trigger "hide" of current view currentView.onHide(); // Set new current view and add to scene currentView = views.get(currentViewIdx); stackPane.getChildren().set(0, currentView.getRoot()); UiUtils.createFadeInTransition(currentView.getRoot(), 500, new EventHandler<ActionEvent>() { public void handle(ActionEvent event) { // Trigger "show" of new view currentView.onShow(); // Show view label with animation /* Pane parent = currentView.getRoot(); BorderPane title = createViewTitlePane(currentView.getName()); parent.getChildren().add(title); Transition trans = UiUtils.createFadeInOutTransition( title, VIEW_LABEL_FADE_IN_MS, VIEW_LABEL_LINGER_MS, VIEW_LABEL_FADE_OUT_MS, new EventHandler<ActionEvent>() { public void handle(ActionEvent event) { parent.getChildren().remove(title); } }); trans.play(); */ viewTransitioning = false; } }).play(); } }).play(); } else { // Trigger "hide" of current view currentView.onHide(); // Set new current view and add to scene currentView = views.get(currentViewIdx); currentView.getRoot().setOpacity(1); stackPane.getChildren().set(0, currentView.getRoot()); // Trigger "show" of new view currentView.onShow(); } } } private void nextProperty() { cancelPropertyFadeOutIfPlaying(); // Special handling of color properties if(propertyPane.getControl() instanceof ColorControl) { ColorControl control = (ColorControl) propertyPane.getControl(); if(!control.isLastSelected()) { control.selectNextGauge(); // Resume fadeout schedulePropertyFadeOut(); return; } } // Increment the current property propertyPane.nextProperty(); updateLastPropertyMap(); // Resume fadeout schedulePropertyFadeOut(); } private void prevProperty() { cancelPropertyFadeOutIfPlaying(); // Special handling of color properties if(propertyPane.getControl() instanceof ColorControl) { ColorControl control = (ColorControl) propertyPane.getControl(); if(!control.isFirstSelected()) { control.selectPrevGauge(); // Resume fadeout schedulePropertyFadeOut(); return; } } // Decrement the current property propertyPane.prevProperty(); updateLastPropertyMap(); // Resume fadeout schedulePropertyFadeOut(); } private void selectOrDeselectCurrentProperty() { cancelPropertyFadeOutIfPlaying(); BooleanProperty selectedProperty = propertyPane.selectedProperty(); selectedProperty.set(!selectedProperty.get()); // Resume fadeout schedulePropertyFadeOut(); } private void showProperties() { if(!propertyPane.getProperties().isEmpty()) { propertyPane.setVisible(true); if(isSmoothTransitionsEnabled()) { UiUtils.createFadeInTransition(propertyPane, 1000, new EventHandler<ActionEvent>() { public void handle(ActionEvent event) { schedulePropertyFadeOut(); } }).play(); } } } private void hideProperties() { // Remove all bindings of current property and deselect propertyPane.getCurrProperty().getProp().unbind(); propertyPane.selectedProperty().set(false); if(isSmoothTransitionsEnabled()) { UiUtils.createFadeOutTransition(propertyPane, 1000, new EventHandler<ActionEvent>() { public void handle(ActionEvent event) { propertyPane.setVisible(false); } }).play(); } else { propertyPane.setVisible(false); } } private void updateLastPropertyMap() { lastPropertyMap.put(currentViewIdx, propertyPane.getCurrPropIdx()); } private BorderPane createViewTitlePane(String viewName) { Label label = new Label(viewName); Pane parent = currentView.getRoot(); label.styleProperty().bind(Bindings.concat( "-fx-font-size: ", parent.widthProperty().divide(20), ";", "-fx-font-family: 'Alex Brush';", "-fx-text-fill: ", VIEW_LABEL_COLOR, ";")); label.setEffect(new Glow(1)); BorderPane pane = createUtilityPane(currentView.getRoot(), 1.5, 4, 0.6); pane.setCenter(label); BorderPane.setAlignment(label, Pos.CENTER); return pane; } private boolean isSmoothTransitionsEnabled() { return propEnableSmoothTransitions.get(); } private PropertyPane createPropertyPane() { PropertyPane pane = new PropertyPane(); pane.widthRatioProperty().set(1.1); pane.heightRatioProperty().set(1.2); pane.setVisible(false); // TODO Verify this is not necessary anymore // This can be used to identify the control pane.setUserData("Property Control"); return pane; } private void changeCurrentPropertyValue(boolean increment, boolean reverseIfChoiceProp) { cancelPropertyFadeOutIfPlaying(); ConfigurableProperty<? extends Object> prop = propertyPane.getCurrProperty(); // Special handling of choice properties if(prop instanceof ConfigurableChoiceProperty && reverseIfChoiceProp) { increment = !increment; } // Special handling of color properties if(prop instanceof ConfigurableColorProperty) { ColorControl control = (ColorControl) propertyPane.getControl(); if(increment) { control.incrementCurrent(); } else { control.decrementCurrent(); } return; } if (increment) { prop.increment(); } else { prop.decrement(); } schedulePropertyFadeOut(); } private void scheduleViewRotateTimer() { int interval = propViewAutoRotateInterval.getProp().get() * 1000; viewRotateTimer = new Timer(true); viewRotateTimer.schedule(new TimerTask() { public void run() { // Don't switch views if a property is currently visible if(!isPropertiesVisible()) { final int idx; if(currentViewIdx + 1 > views.size() - 1) { idx = 0; } else { idx = currentViewIdx + 1; } Platform.runLater(new Runnable() { public void run() { switchView(idx); } }); } } }, interval, interval); } private void cancelViewRotateTimer() { if(viewRotateTimer != null) { viewRotateTimer.cancel(); viewRotateTimer = null; } } private void firePropertyButtonIfInFocus() { Node focusOwner = currentView.getRoot().getScene().getFocusOwner(); if(focusOwner instanceof Button && isPropertiesVisible()) { cancelPropertyFadeOutIfPlaying(); ((Button) focusOwner).fire(); schedulePropertyFadeOut(); } } public static void main(String[] args) { // SvgImageLoaderFactory.install(new AttributeDimensionProvider()); launch(args); } }
package org.jsoup.nodes; import org.jsoup.SerializationException; import org.jsoup.helper.Validate; import org.jsoup.internal.StringUtil; import org.jsoup.select.NodeFilter; import org.jsoup.select.NodeTraversor; import org.jsoup.select.NodeVisitor; import javax.annotation.Nullable; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; /** The base, abstract Node model. Elements, Documents, Comments etc are all Node instances. @author Jonathan Hedley, jonathan@hedley.net */ public abstract class Node implements Cloneable { static final List<Node> EmptyNodes = Collections.emptyList(); static final String EmptyString = ""; @Nullable Node parentNode; // Nodes don't always have parents int siblingIndex; /** * Default constructor. Doesn't setup base uri, children, or attributes; use with caution. */ protected Node() { } /** Get the node name of this node. Use for debugging purposes and not logic switching (for that, use instanceof). @return node name */ public abstract String nodeName(); /** * Check if this Node has an actual Attributes object. */ protected abstract boolean hasAttributes(); /** Checks if this node has a parent. Nodes won't have parents if (e.g.) they are newly created and not added as a child to an existing node, or if they are a {@link #shallowClone()}. In such cases, {@link #parent()} will return {@code null}. @return if this node has a parent. */ public boolean hasParent() { return parentNode != null; } /** * Get an attribute's value by its key. <b>Case insensitive</b> * <p> * To get an absolute URL from an attribute that may be a relative URL, prefix the key with <code><b>abs</b></code>, * which is a shortcut to the {@link #absUrl} method. * </p> * E.g.: * <blockquote><code>String url = a.attr("abs:href");</code></blockquote> * * @param attributeKey The attribute key. * @return The attribute, or empty string if not present (to avoid nulls). * @see #attributes() * @see #hasAttr(String) * @see #absUrl(String) */ public String attr(String attributeKey) { Validate.notNull(attributeKey); if (!hasAttributes()) return EmptyString; String val = attributes().getIgnoreCase(attributeKey); if (val.length() > 0) return val; else if (attributeKey.startsWith("abs:")) return absUrl(attributeKey.substring("abs:".length())); else return ""; } /** * Get all of the element's attributes. * @return attributes (which implements iterable, in same order as presented in original HTML). */ public abstract Attributes attributes(); /** Get the number of attributes that this Node has. @return the number of attributes @since 1.14.2 */ public int attributesSize() { // added so that we can test how many attributes exist without implicitly creating the Attributes object return hasAttributes() ? attributes().size() : 0; } /** * Set an attribute (key=value). If the attribute already exists, it is replaced. The attribute key comparison is * <b>case insensitive</b>. The key will be set with case sensitivity as set in the parser settings. * @param attributeKey The attribute key. * @param attributeValue The attribute value. * @return this (for chaining) */ public Node attr(String attributeKey, String attributeValue) { attributeKey = NodeUtils.parser(this).settings().normalizeAttribute(attributeKey); attributes().putIgnoreCase(attributeKey, attributeValue); return this; } /** * Test if this Node has an attribute. <b>Case insensitive</b>. * @param attributeKey The attribute key to check. * @return true if the attribute exists, false if not. */ public boolean hasAttr(String attributeKey) { Validate.notNull(attributeKey); if (!hasAttributes()) return false; if (attributeKey.startsWith("abs:")) { String key = attributeKey.substring("abs:".length()); if (attributes().hasKeyIgnoreCase(key) && !absUrl(key).isEmpty()) return true; } return attributes().hasKeyIgnoreCase(attributeKey); } /** * Remove an attribute from this node. * @param attributeKey The attribute to remove. * @return this (for chaining) */ public Node removeAttr(String attributeKey) { Validate.notNull(attributeKey); if (hasAttributes()) attributes().removeIgnoreCase(attributeKey); return this; } /** * Clear (remove) all of the attributes in this node. * @return this, for chaining */ public Node clearAttributes() { if (hasAttributes()) { Iterator<Attribute> it = attributes().iterator(); while (it.hasNext()) { it.next(); it.remove(); } } return this; } /** Get the base URI that applies to this node. Will return an empty string if not defined. Used to make relative links absolute. @return base URI @see #absUrl */ public abstract String baseUri(); /** * Set the baseUri for just this node (not its descendants), if this Node tracks base URIs. * @param baseUri new URI */ protected abstract void doSetBaseUri(String baseUri); /** Update the base URI of this node and all of its descendants. @param baseUri base URI to set */ public void setBaseUri(final String baseUri) { Validate.notNull(baseUri); doSetBaseUri(baseUri); } public String absUrl(String attributeKey) { Validate.notEmpty(attributeKey); if (!(hasAttributes() && attributes().hasKeyIgnoreCase(attributeKey))) // not using hasAttr, so that we don't recurse down hasAttr->absUrl return ""; return StringUtil.resolve(baseUri(), attributes().getIgnoreCase(attributeKey)); } protected abstract List<Node> ensureChildNodes(); /** Get a child node by its 0-based index. @param index index of child node @return the child node at this index. Throws a {@code IndexOutOfBoundsException} if the index is out of bounds. */ public Node childNode(int index) { return ensureChildNodes().get(index); } /** Get this node's children. Presented as an unmodifiable list: new children can not be added, but the child nodes themselves can be manipulated. @return list of children. If no children, returns an empty list. */ public List<Node> childNodes() { if (childNodeSize() == 0) return EmptyNodes; List<Node> children = ensureChildNodes(); List<Node> rewrap = new ArrayList<>(children.size()); // wrapped so that looping and moving will not throw a CME as the source changes rewrap.addAll(children); return Collections.unmodifiableList(rewrap); } /** * Returns a deep copy of this node's children. Changes made to these nodes will not be reflected in the original * nodes * @return a deep copy of this node's children */ public List<Node> childNodesCopy() { final List<Node> nodes = ensureChildNodes(); final ArrayList<Node> children = new ArrayList<>(nodes.size()); for (Node node : nodes) { children.add(node.clone()); } return children; } /** * Get the number of child nodes that this node holds. * @return the number of child nodes that this node holds. */ public abstract int childNodeSize(); protected Node[] childNodesAsArray() { return ensureChildNodes().toArray(new Node[0]); } /** * Delete all this node's children. * @return this node, for chaining */ public abstract Node empty(); /** Gets this node's parent node. @return parent node; or null if no parent. @see #hasParent() */ public @Nullable Node parent() { return parentNode; } /** Gets this node's parent node. Not overridable by extending classes, so useful if you really just need the Node type. @return parent node; or null if no parent. */ public @Nullable final Node parentNode() { return parentNode; } /** * Get this node's root node; that is, its topmost ancestor. If this node is the top ancestor, returns {@code this}. * @return topmost ancestor. */ public Node root() { Node node = this; while (node.parentNode != null) node = node.parentNode; return node; } /** * Gets the Document associated with this Node. * @return the Document associated with this Node, or null if there is no such Document. */ public @Nullable Document ownerDocument() { Node root = root(); return (root instanceof Document) ? (Document) root : null; } /** * Remove (delete) this node from the DOM tree. If this node has children, they are also removed. */ public void remove() { Validate.notNull(parentNode); parentNode.removeChild(this); } /** * Insert the specified HTML into the DOM before this node (as a preceding sibling). * @param html HTML to add before this node * @return this node, for chaining * @see #after(String) */ public Node before(String html) { addSiblingHtml(siblingIndex, html); return this; } /** * Insert the specified node into the DOM before this node (as a preceding sibling). * @param node to add before this node * @return this node, for chaining * @see #after(Node) */ public Node before(Node node) { Validate.notNull(node); Validate.notNull(parentNode); parentNode.addChildren(siblingIndex, node); return this; } /** * Insert the specified HTML into the DOM after this node (as a following sibling). * @param html HTML to add after this node * @return this node, for chaining * @see #before(String) */ public Node after(String html) { addSiblingHtml(siblingIndex + 1, html); return this; } /** * Insert the specified node into the DOM after this node (as a following sibling). * @param node to add after this node * @return this node, for chaining * @see #before(Node) */ public Node after(Node node) { Validate.notNull(node); Validate.notNull(parentNode); parentNode.addChildren(siblingIndex + 1, node); return this; } private void addSiblingHtml(int index, String html) { Validate.notNull(html); Validate.notNull(parentNode); Element context = parent() instanceof Element ? (Element) parent() : null; List<Node> nodes = NodeUtils.parser(this).parseFragmentInput(html, context, baseUri()); parentNode.addChildren(index, nodes.toArray(new Node[0])); } /** Wrap the supplied HTML around this node. @param html HTML to wrap around this node, e.g. {@code <div class="head"></div>}. Can be arbitrarily deep. If the input HTML does not parse to a result starting with an Element, this will be a no-op. @return this node, for chaining. */ public Node wrap(String html) { Validate.notEmpty(html); // Parse context - parent (because wrapping), this, or null Element context = parentNode != null && parentNode instanceof Element ? (Element) parentNode : this instanceof Element ? (Element) this : null; List<Node> wrapChildren = NodeUtils.parser(this).parseFragmentInput(html, context, baseUri()); Node wrapNode = wrapChildren.get(0); if (!(wrapNode instanceof Element)) // nothing to wrap with; noop return this; Element wrap = (Element) wrapNode; Element deepest = getDeepChild(wrap); if (parentNode != null) parentNode.replaceChild(this, wrap); deepest.addChildren(this); // side effect of tricking wrapChildren to lose first // remainder (unbalanced wrap, like <div></div><p></p> -- The <p> is remainder if (wrapChildren.size() > 0) { //noinspection ForLoopReplaceableByForEach (beacause it allocates an Iterator which is wasteful here) for (int i = 0; i < wrapChildren.size(); i++) { Node remainder = wrapChildren.get(i); // if no parent, this could be the wrap node, so skip if (wrap == remainder) continue; if (remainder.parentNode != null) remainder.parentNode.removeChild(remainder); wrap.after(remainder); } } return this; } /** * Removes this node from the DOM, and moves its children up into the node's parent. This has the effect of dropping * the node but keeping its children. * <p> * For example, with the input html: * </p> * <p>{@code <div>One <span>Two <b>Three</b></span></div>}</p> * Calling {@code element.unwrap()} on the {@code span} element will result in the html: * <p>{@code <div>One Two <b>Three</b></div>}</p> * and the {@code "Two "} {@link TextNode} being returned. * * @return the first child of this node, after the node has been unwrapped. @{code Null} if the node had no children. * @see #remove() * @see #wrap(String) */ public @Nullable Node unwrap() { Validate.notNull(parentNode); final List<Node> childNodes = ensureChildNodes(); Node firstChild = childNodes.size() > 0 ? childNodes.get(0) : null; parentNode.addChildren(siblingIndex, this.childNodesAsArray()); this.remove(); return firstChild; } private Element getDeepChild(Element el) { List<Element> children = el.children(); if (children.size() > 0) return getDeepChild(children.get(0)); else return el; } void nodelistChanged() { // Element overrides this to clear its shadow children elements } /** * Replace this node in the DOM with the supplied node. * @param in the node that will will replace the existing node. */ public void replaceWith(Node in) { Validate.notNull(in); Validate.notNull(parentNode); parentNode.replaceChild(this, in); } protected void setParentNode(Node parentNode) { Validate.notNull(parentNode); if (this.parentNode != null) this.parentNode.removeChild(this); this.parentNode = parentNode; } protected void replaceChild(Node out, Node in) { Validate.isTrue(out.parentNode == this); Validate.notNull(in); if (in.parentNode != null) in.parentNode.removeChild(in); final int index = out.siblingIndex; ensureChildNodes().set(index, in); in.parentNode = this; in.setSiblingIndex(index); out.parentNode = null; } protected void removeChild(Node out) { Validate.isTrue(out.parentNode == this); final int index = out.siblingIndex; ensureChildNodes().remove(index); reindexChildren(index); out.parentNode = null; } protected void addChildren(Node... children) { //most used. short circuit addChildren(int), which hits reindex children and array copy final List<Node> nodes = ensureChildNodes(); for (Node child: children) { reparentChild(child); nodes.add(child); child.setSiblingIndex(nodes.size()-1); } } protected void addChildren(int index, Node... children) { Validate.notNull(children); if (children.length == 0) { return; } final List<Node> nodes = ensureChildNodes(); // fast path - if used as a wrap (index=0, children = child[0].parent.children - do inplace final Node firstParent = children[0].parent(); if (firstParent != null && firstParent.childNodeSize() == children.length) { boolean sameList = true; final List<Node> firstParentNodes = firstParent.ensureChildNodes(); // identity check contents to see if same int i = children.length; while (i if (children[i] != firstParentNodes.get(i)) { sameList = false; break; } } if (sameList) { // moving, so OK to empty firstParent and short-circuit boolean wasEmpty = childNodeSize() == 0; firstParent.empty(); nodes.addAll(index, Arrays.asList(children)); i = children.length; while (i children[i].parentNode = this; } if (!(wasEmpty && children[0].siblingIndex == 0)) // skip reindexing if we just moved reindexChildren(index); return; } } Validate.noNullElements(children); for (Node child : children) { reparentChild(child); } nodes.addAll(index, Arrays.asList(children)); reindexChildren(index); } protected void reparentChild(Node child) { child.setParentNode(this); } private void reindexChildren(int start) { if (childNodeSize() == 0) return; final List<Node> childNodes = ensureChildNodes(); for (int i = start; i < childNodes.size(); i++) { childNodes.get(i).setSiblingIndex(i); } } /** Retrieves this node's sibling nodes. Similar to {@link #childNodes() node.parent.childNodes()}, but does not include this node (a node is not a sibling of itself). @return node siblings. If the node has no parent, returns an empty list. */ public List<Node> siblingNodes() { if (parentNode == null) return Collections.emptyList(); List<Node> nodes = parentNode.ensureChildNodes(); List<Node> siblings = new ArrayList<>(nodes.size() - 1); for (Node node: nodes) if (node != this) siblings.add(node); return siblings; } /** Get this node's next sibling. @return next sibling, or @{code null} if this is the last sibling */ public @Nullable Node nextSibling() { if (parentNode == null) return null; // root final List<Node> siblings = parentNode.ensureChildNodes(); final int index = siblingIndex+1; if (siblings.size() > index) return siblings.get(index); else return null; } /** Get this node's previous sibling. @return the previous sibling, or @{code null} if this is the first sibling */ public @Nullable Node previousSibling() { if (parentNode == null) return null; // root if (siblingIndex > 0) return parentNode.ensureChildNodes().get(siblingIndex-1); else return null; } /** * Get the list index of this node in its node sibling list. E.g. if this is the first node * sibling, returns 0. * @return position in node sibling list * @see org.jsoup.nodes.Element#elementSiblingIndex() */ public int siblingIndex() { return siblingIndex; } protected void setSiblingIndex(int siblingIndex) { this.siblingIndex = siblingIndex; } /** * Perform a depth-first traversal through this node and its descendants. * @param nodeVisitor the visitor callbacks to perform on each node * @return this node, for chaining */ public Node traverse(NodeVisitor nodeVisitor) { Validate.notNull(nodeVisitor); NodeTraversor.traverse(nodeVisitor, this); return this; } /** * Perform a depth-first filtering through this node and its descendants. * @param nodeFilter the filter callbacks to perform on each node * @return this node, for chaining */ public Node filter(NodeFilter nodeFilter) { Validate.notNull(nodeFilter); NodeTraversor.filter(nodeFilter, this); return this; } /** Get the outer HTML of this node. For example, on a {@code p} element, may return {@code <p>Para</p>}. @return outer HTML @see Element#html() @see Element#text() */ public String outerHtml() { StringBuilder accum = StringUtil.borrowBuilder(); outerHtml(accum); return StringUtil.releaseBuilder(accum); } protected void outerHtml(Appendable accum) { NodeTraversor.traverse(new OuterHtmlVisitor(accum, NodeUtils.outputSettings(this)), this); } /** Get the outer HTML of this node. @param accum accumulator to place HTML into @throws IOException if appending to the given accumulator fails. */ abstract void outerHtmlHead(final Appendable accum, int depth, final Document.OutputSettings out) throws IOException; abstract void outerHtmlTail(final Appendable accum, int depth, final Document.OutputSettings out) throws IOException; /** * Write this node and its children to the given {@link Appendable}. * * @param appendable the {@link Appendable} to write to. * @return the supplied {@link Appendable}, for chaining. */ public <T extends Appendable> T html(T appendable) { outerHtml(appendable); return appendable; } /** * Gets this node's outer HTML. * @return outer HTML. * @see #outerHtml() */ public String toString() { return outerHtml(); } protected void indent(Appendable accum, int depth, Document.OutputSettings out) throws IOException { accum.append('\n').append(StringUtil.padding(depth * out.indentAmount())); } /** * Check if this node is the same instance of another (object identity test). * <p>For an node value equality check, see {@link #hasSameValue(Object)}</p> * @param o other object to compare to * @return true if the content of this node is the same as the other * @see Node#hasSameValue(Object) */ @Override public boolean equals(@Nullable Object o) { // implemented just so that javadoc is clear this is an identity test return this == o; } /** Provides a hashCode for this Node, based on it's object identity. Changes to the Node's content will not impact the result. @return an object identity based hashcode for this Node */ @Override public int hashCode() { // implemented so that javadoc and scanners are clear this is an identity test return super.hashCode(); } /** * Check if this node is has the same content as another node. A node is considered the same if its name, attributes and content match the * other node; particularly its position in the tree does not influence its similarity. * @param o other object to compare to * @return true if the content of this node is the same as the other */ public boolean hasSameValue(@Nullable Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; return this.outerHtml().equals(((Node) o).outerHtml()); } /** * Create a stand-alone, deep copy of this node, and all of its children. The cloned node will have no siblings or * parent node. As a stand-alone object, any changes made to the clone or any of its children will not impact the * original node. * <p> * The cloned node may be adopted into another Document or node structure using {@link Element#appendChild(Node)}. * @return a stand-alone cloned node, including clones of any children * @see #shallowClone() */ @SuppressWarnings("MethodDoesntCallSuperMethod") // because it does call super.clone in doClone - analysis just isn't following @Override public Node clone() { Node thisClone = doClone(null); // splits for orphan // Queue up nodes that need their children cloned (BFS). final LinkedList<Node> nodesToProcess = new LinkedList<>(); nodesToProcess.add(thisClone); while (!nodesToProcess.isEmpty()) { Node currParent = nodesToProcess.remove(); final int size = currParent.childNodeSize(); for (int i = 0; i < size; i++) { final List<Node> childNodes = currParent.ensureChildNodes(); Node childClone = childNodes.get(i).doClone(currParent); childNodes.set(i, childClone); nodesToProcess.add(childClone); } } return thisClone; } /** * Create a stand-alone, shallow copy of this node. None of its children (if any) will be cloned, and it will have * no parent or sibling nodes. * @return a single independent copy of this node * @see #clone() */ public Node shallowClone() { return doClone(null); } /* * Return a clone of the node using the given parent (which can be null). * Not a deep copy of children. */ protected Node doClone(@Nullable Node parent) { Node clone; try { clone = (Node) super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } clone.parentNode = parent; // can be null, to create an orphan split clone.siblingIndex = parent == null ? 0 : siblingIndex; return clone; } private static class OuterHtmlVisitor implements NodeVisitor { private final Appendable accum; private final Document.OutputSettings out; OuterHtmlVisitor(Appendable accum, Document.OutputSettings out) { this.accum = accum; this.out = out; out.prepareEncoder(); } public void head(Node node, int depth) { try { node.outerHtmlHead(accum, depth, out); } catch (IOException exception) { throw new SerializationException(exception); } } public void tail(Node node, int depth) { if (!node.nodeName().equals("#text")) { // saves a void hit. try { node.outerHtmlTail(accum, depth, out); } catch (IOException exception) { throw new SerializationException(exception); } } } } }
package org.lantern; import java.io.File; import java.io.IOException; import java.lang.Thread.UncaughtExceptionHandler; import java.util.HashMap; import java.util.Properties; import org.apache.log4j.PropertyConfigurator; import org.eclipse.swt.widgets.Display; import org.littleshoot.proxy.DefaultHttpProxyServer; import org.littleshoot.proxy.HttpFilter; import org.littleshoot.proxy.KeyStoreManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Launches a new Lantern HTTP proxy. */ public class Launcher { private static Logger LOG; /** * Starts the proxy from the command line. * * @param args Any command line arguments. */ public static void main(final String... args) { configureLogger(); LOG = LoggerFactory.getLogger(Launcher.class); Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() { @Override public void uncaughtException(final Thread t, final Throwable e) { LOG.error("Uncaught exception", e); } }); Display.setAppName("Lantern"); final Display display = LanternHub.display(); //final Shell shell = new Shell(display); final SystemTray tray = LanternHub.systemTray(); if (!LanternUtils.isConfigured() || LanternUtils.newInstall()) { // Make sure the installer screens themselves don't run through a // defunct Lantern proxy that likely has just been uninstalled. Configurator.unproxy(); final LanternBrowser browser = new LanternBrowser(false); browser.install(); if (!display.isDisposed ()) { LOG.info("Browser completed...launching Lantern"); launchLantern(); } } else { launchLantern(); } // This is necessary to keep the tray/menu item up in the case // where we're not launching a browser. while (!display.isDisposed ()) { if (!display.readAndDispatch ()) display.sleep (); } } public static void launchLantern() { final KeyStoreManager proxyKeyStore = LanternHub.getKeyStoreManager(); final int sslRandomPort = LanternUtils.randomPort(); LOG.info("Running SSL HTTP proxy on port: "+sslRandomPort); final org.littleshoot.proxy.HttpProxyServer sslProxy = new DefaultHttpProxyServer(sslRandomPort, new HashMap<String, HttpFilter>(), null, proxyKeyStore, null); //final org.littleshoot.proxy.HttpProxyServer sslProxy = // new DefaultHttpProxyServer(sslRandomPort); sslProxy.start(false, false); // We just use a fixed port for the plain-text proxy on localhost, as // there's no reason to randomize it since it's not public. // If testing two instances on the same machine, just change it on // one of them. // The reason this exists is complicated. It's for the case when the // offerer gets an incoming connection from the answerer, and then // only on the answerer side. The answerer "client" socket relays // its data to the local proxy. final org.littleshoot.proxy.HttpProxyServer plainTextProxy = new DefaultHttpProxyServer( LanternConstants.PLAINTEXT_LOCALHOST_PROXY_PORT); plainTextProxy.start(true, false); LOG.info("About to start Lantern server on port: "+ LanternConstants.LANTERN_LOCALHOST_HTTP_PORT); final XmppHandler xmpp = new XmppHandler(sslRandomPort, LanternConstants.PLAINTEXT_LOCALHOST_PROXY_PORT, LanternHub.systemTray()); final HttpProxyServer server = new LanternHttpProxyServer( LanternConstants.LANTERN_LOCALHOST_HTTP_PORT, LanternConstants.LANTERN_LOCALHOST_HTTPS_PORT, //null, sslRandomPort, proxyKeyStore, xmpp); server.start(); } private static void configureLogger() { final String propsPath = "src/main/resources/log4j.properties"; final File props = new File(propsPath); if (props.isFile()) { System.out.println("Running from main line"); PropertyConfigurator.configure(propsPath); } else { System.out.println("Not on main line..."); final File logDir = LanternUtils.logDir(); final File logFile = new File(logDir, "java.log"); setLoggerProps(logFile); } } private static void setLoggerProps(final File logFile) { final Properties props = new Properties(); try { final String logPath = logFile.getCanonicalPath(); props.put("log4j.appender.RollingTextFile.File", logPath); props.put("log4j.rootLogger", "warn, RollingTextFile"); props.put("log4j.appender.RollingTextFile", "org.apache.log4j.RollingFileAppender"); props.put("log4j.appender.RollingTextFile.MaxFileSize", "1MB"); props.put("log4j.appender.RollingTextFile.MaxBackupIndex", "1"); props.put("log4j.appender.RollingTextFile.layout", "org.apache.log4j.PatternLayout"); props.put( "log4j.appender.RollingTextFile.layout.ConversionPattern", "%-6r %d{ISO8601} %-5p [%t] %c{2}.%M (%F:%L) - %m%n"); // This throws and swallows a FileNotFoundException, but it // doesn't matter. Just weird. PropertyConfigurator.configure(props); System.out.println("Set logger file to: " + logPath); } catch (final IOException e) { System.out.println("Exception setting log4j props with file: " + logFile); e.printStackTrace(); } } }
package com.taobao.zeus.socket.master; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.apache.hadoop.hive.ql.parse.HiveParser.nullCondition_return; import org.jboss.netty.channel.Channel; import org.quartz.SchedulerException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.taobao.zeus.broadcast.alarm.MailAlarm; import com.taobao.zeus.broadcast.alarm.SMSAlarm; import com.taobao.zeus.client.ZeusException; import com.taobao.zeus.model.DebugHistory; import com.taobao.zeus.model.FileDescriptor; import com.taobao.zeus.model.HostGroupCache; import com.taobao.zeus.model.JobDescriptor; import com.taobao.zeus.model.JobHistory; import com.taobao.zeus.model.JobStatus; import com.taobao.zeus.model.JobStatus.TriggerType; import com.taobao.zeus.model.Profile; import com.taobao.zeus.mvc.Controller; import com.taobao.zeus.mvc.Dispatcher; import com.taobao.zeus.schedule.mvc.AddJobListener; import com.taobao.zeus.schedule.mvc.DebugInfoLog; import com.taobao.zeus.schedule.mvc.DebugListener; import com.taobao.zeus.schedule.mvc.JobController; import com.taobao.zeus.schedule.mvc.JobFailListener; import com.taobao.zeus.schedule.mvc.JobSuccessListener; import com.taobao.zeus.schedule.mvc.ScheduleInfoLog; import com.taobao.zeus.schedule.mvc.StopScheduleJobListener; import com.taobao.zeus.schedule.mvc.ZeusJobException; import com.taobao.zeus.schedule.mvc.event.DebugFailEvent; import com.taobao.zeus.schedule.mvc.event.DebugSuccessEvent; import com.taobao.zeus.schedule.mvc.event.Events; import com.taobao.zeus.schedule.mvc.event.JobFailedEvent; import com.taobao.zeus.schedule.mvc.event.JobLostEvent; import com.taobao.zeus.schedule.mvc.event.JobMaintenanceEvent; import com.taobao.zeus.schedule.mvc.event.JobSuccessEvent; import com.taobao.zeus.socket.SocketLog; import com.taobao.zeus.socket.master.MasterWorkerHolder.HeartBeatInfo; import com.taobao.zeus.socket.master.reqresp.MasterExecuteJob; import com.taobao.zeus.socket.protocol.Protocol.ExecuteKind; import com.taobao.zeus.socket.protocol.Protocol.Response; import com.taobao.zeus.socket.protocol.Protocol.Status; import com.taobao.zeus.store.GroupBean; import com.taobao.zeus.store.JobBean; import com.taobao.zeus.store.mysql.persistence.JobPersistence; import com.taobao.zeus.store.mysql.persistence.JobPersistenceOld; import com.taobao.zeus.util.CronExpParser; import com.taobao.zeus.util.DateUtil; import com.taobao.zeus.util.Environment; import com.taobao.zeus.util.Tuple; import com.taobao.zeus.util.ZeusDateTool; public class Master { private MasterContext context; private static Logger log = LoggerFactory.getLogger(Master.class); public Master(final MasterContext context) { this.context = context; GroupBean root = context.getGroupManager().getGlobeGroupBean(); if (Environment.isPrePub()) { // stop listener context.getDispatcher().addDispatcherListener( new StopScheduleJobListener()); } context.getDispatcher().addDispatcherListener( new AddJobListener(context, this)); context.getDispatcher().addDispatcherListener( new JobFailListener(context)); context.getDispatcher().addDispatcherListener( new DebugListener(context)); context.getDispatcher().addDispatcherListener( new JobSuccessListener(context)); Map<String, JobBean> allJobBeans = root.getAllSubJobBeans(); for (String id : allJobBeans.keySet()) { context.getDispatcher().addController( new JobController(context, this, id)); } context.getDispatcher().forwardEvent(Events.Initialize); context.setMaster(this); //host context.refreshHostGroupCache(); log.info("refresh HostGroup Cache"); context.getSchedulePool().scheduleAtFixedRate(new Runnable() { @Override public void run() { context.refreshHostGroupCache(); log.info("refresh HostGroup Cache"); } }, 1, 1, TimeUnit.HOURS); private void checkTimeOver() { for (MasterWorkerHolder w : context.getWorkers().values()) { checkScheduleTimeOver(w); //TODO // checkManualTimeOver(w); // checkDebugTimeOver(w); } } private void checkDebugTimeOver(MasterWorkerHolder w) { for (Map.Entry<String, Boolean> entry : w.getDebugRunnings().entrySet()) { if (entry.getValue() != null && entry.getValue()) { continue; } String historyId = entry.getKey(); DebugHistory his = context.getDebugHistoryManager() .findDebugHistory(historyId); long maxTime; FileDescriptor fd; try { fd = context.getFileManager().getFile(his.getFileId()); Profile pf = context.getProfileManager().findByUid( fd.getOwner()); String maxTimeString = pf.getHadoopConf().get( "zeus.job.maxtime"); if (maxTimeString == null || maxTimeString.trim().isEmpty()) { continue; } maxTime = Long.parseLong(maxTimeString); if (maxTime < 0) { continue; } } catch (Exception e) { continue; } long runTime = (System.currentTimeMillis() - his.getStartTime() .getTime()) / 1000 / 60; if (runTime > maxTime) { if (timeOverAlarm(null, fd, runTime, maxTime, 2, null)) { w.getDebugRunnings().replace(historyId, false, true); } } } } private void checkManualTimeOver(MasterWorkerHolder w) { for (Map.Entry<String, Boolean> entry : w.getManualRunnings() .entrySet()) { if (entry.getValue() != null && entry.getValue()) { continue; } String historyId = entry.getKey(); JobHistory his = context.getJobHistoryManager().findJobHistory( historyId); JobDescriptor jd = context.getGroupManager() .getJobDescriptor(his.getJobId()).getX(); long maxTime; try { String maxTimeString = jd.getProperties().get( "zeus.job.maxtime"); if (maxTimeString == null || maxTimeString.trim().isEmpty()) { continue; } maxTime = Long.parseLong(maxTimeString); if (maxTime < 0) { continue; } } catch (Exception e) { continue; } long runTime = (System.currentTimeMillis() - his.getStartTime() .getTime()) / 1000 / 60; if (runTime > maxTime) { if (timeOverAlarm(his, null, runTime, maxTime, 1, jd)) { w.getManualRunnings().replace(historyId, false, true); } } } } private void checkScheduleTimeOver(MasterWorkerHolder w) { for (Map.Entry<String, Boolean> entry : w.getRunnings().entrySet()) { if (entry.getValue() != null && entry.getValue()) { continue; } String jobId = entry.getKey(); JobDescriptor jd = context.getGroupManager() .getJobDescriptor(jobId).getX(); String maxTimeString = jd.getProperties().get("zeus.job.maxtime"); long maxTime; try { if (maxTimeString == null || maxTimeString.trim().isEmpty()) { continue; } maxTime = Long.parseLong(maxTimeString); if (maxTime < 0) { continue; } } catch (Exception e) { continue; } JobHistory his = context.getJobHistoryManager().findJobHistory( context.getGroupManager().getJobStatus(jobId) .getHistoryId()); if (his != null && his.getStartTime() != null) { long runTime = (System.currentTimeMillis() - his.getStartTime() .getTime()) / 1000 / 60; if (runTime > maxTime) { log.info("send the timeOverAlarm of job: " + jobId); if (timeOverAlarm(his, null, runTime, maxTime, 0, jd)) { w.getRunnings().replace(jobId, false, true); } } } } } private boolean timeOverAlarm(final JobHistory his, FileDescriptor fd, long runTime, long maxTime, int type, JobDescriptor jd) { final MailAlarm mailAlarm = (MailAlarm) context.getApplicationContext() .getBean("mailAlarm"); SMSAlarm smsAlarm = (SMSAlarm) context.getApplicationContext().getBean( "smsAlarm"); final StringBuffer title = new StringBuffer("["); switch (type) { case 0: title.append("").append("] jobID=").append(his.getJobId()); break; case 1: title.append("").append("] jobID=").append(his.getJobId()); break; case 2: title.append("").append("] ").append(fd.getName()); } final StringBuffer content = new StringBuffer(title); if(jd != null){ title.append(" (").append(jd.getName()).append(")"); content.append("\nJOB").append(jd.getName()); Map<String, String> properties=jd.getProperties(); if(properties != null){ String plevel=properties.get("run.priority.level"); if("1".equals(plevel)){ content.append("\nJob: ").append("low"); }else if("2".equals(plevel)){ content.append("\nJob: ").append("medium"); }else if("3".equals(plevel)){ content.append("\nJob: ").append("high"); } } content.append("\nJOBOwner").append(jd.getOwner()); } content.append("\n").append(runTime).append("") .append("\n").append(maxTime).append(""); if(his != null){ content.append("\n\n").append(his.getLog().getContent().replaceAll("\\n", "<br/>")); } try { if (type == 2) { } else { new Thread() { @Override public void run() { try { Thread.sleep(6000); mailAlarm .alarm(his.getId(), title.toString(), content.toString() .replace("\n", "<br/>")); } catch (Exception e) { log.error("send run timeover mail alarm failed", e); } } }.start(); if (type == 0) { String priorityLevel = "3"; if(jd != null){ priorityLevel = jd.getProperties().get("run.priority.level"); } if(priorityLevel == null || !priorityLevel.trim().equals("1")){ Calendar now = Calendar.getInstance(); int hour = now.get(Calendar.HOUR_OF_DAY); int day = now.get(Calendar.DAY_OF_WEEK); if (day == Calendar.SATURDAY || day == Calendar.SUNDAY || hour < 9 || hour > 18) { smsAlarm.alarm(his.getId(), title.toString(),content.toString(), null); //mailAlarm.alarm(his.getId(), title.toString(),content.toString(), null); } } } } return true; } catch (Exception e) { log.error("send run timeover alarm failed", e); return false; } } public void workerDisconnectProcess(Channel channel) { MasterWorkerHolder holder = context.getWorkers().get(channel); if (holder != null) { context.getWorkers().remove(channel); final List<JobHistory> hiss = new ArrayList<JobHistory>(); Map<String, Tuple<JobDescriptor, JobStatus>> map = context .getGroupManager().getJobDescriptor( holder.getRunnings().keySet()); for (String key : map.keySet()) { JobStatus js = map.get(key).getY(); if (js.getHistoryId() != null) { hiss.add(context.getJobHistoryManager().findJobHistory( js.getHistoryId())); } js.setStatus(com.taobao.zeus.model.JobStatus.Status.FAILED); context.getGroupManager().updateJobStatus(js); } new Thread() { @Override public void run() { try { Thread.sleep(30000); } catch (InterruptedException e) { } for (JobHistory his : hiss) { String jobId = his.getJobId(); JobHistory history = new JobHistory(); history.setJobId(jobId); history.setToJobId(his.getToJobId()); history.setTriggerType(his.getTriggerType()); history.setIllustrate("worker"); history.setOperator(his.getOperator()); history.setHostGroupId(his.getHostGroupId()); context.getJobHistoryManager().addJobHistory(history); Master.this.run(history); } }; }.start(); } } public void debug(DebugHistory debug) { JobElement element = new JobElement(debug.getId(), debug.gethostGroupId()); debug.setStatus(com.taobao.zeus.model.JobStatus.Status.RUNNING); debug.setStartTime(new Date()); context.getDebugHistoryManager().updateDebugHistory(debug); debug.getLog().appendZeus( new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " "); context.getDebugHistoryManager().updateDebugHistoryLog(debug.getId(), debug.getLog().getContent()); context.getDebugQueue().offer(element); System.out.println("offer debug queue :" +context.getDebugQueue().size()+ " element :"+element.getJobID()); } public JobHistory run(JobHistory history) { String jobId = history.getJobId(); int priorityLevel = 3; try{ JobDescriptor jd = context.getGroupManager().getJobDescriptor(jobId).getX(); String priorityLevelStr = jd.getProperties().get("run.priority.level"); if(priorityLevelStr!=null){ priorityLevel = Integer.parseInt(priorityLevelStr); } }catch(Exception ex){ priorityLevel = 3; } JobElement element = new JobElement(jobId, history.getHostGroupId(), priorityLevel); history.setStatus(com.taobao.zeus.model.JobStatus.Status.RUNNING); if (history.getTriggerType() == TriggerType.MANUAL_RECOVER) { for (JobElement e : new ArrayList<JobElement>(context.getQueue())) { if (e.getJobID().equals(jobId)) { history.getLog().appendZeus(""); history.setStartTime(new Date()); history.setEndTime(new Date()); history.setStatus(com.taobao.zeus.model.JobStatus.Status.FAILED); break; } } for (Channel key : context.getWorkers().keySet()) { MasterWorkerHolder worker = context.getWorkers().get(key); if (worker.getRunnings().containsKey(jobId)) { history.getLog().appendZeus(""); history.setStartTime(new Date()); history.setEndTime(new Date()); history.setStatus(com.taobao.zeus.model.JobStatus.Status.FAILED); break; } } } if (history.getStatus() == com.taobao.zeus.model.JobStatus.Status.RUNNING) { history.getLog().appendZeus( new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") .format(new Date()) + " "); context.getJobHistoryManager().updateJobHistoryLog(history.getId(), history.getLog().getContent()); if (history.getTriggerType() == TriggerType.MANUAL) { element.setJobID(history.getId()); context.getManualQueue().offer(element); } else { JobStatus js = context.getGroupManager().getJobStatus( history.getJobId()); js.setStatus(com.taobao.zeus.model.JobStatus.Status.RUNNING); js.setHistoryId(history.getId()); context.getGroupManager().updateJobStatus(js); context.getQueue().offer(element); } } context.getJobHistoryManager().updateJobHistory(history); context.getJobHistoryManager().updateJobHistoryLog(history.getId(), history.getLog().getContent()); return history; } //actionaction public void runScheduleJobToAction(List<JobPersistenceOld> jobDetails, Date now, SimpleDateFormat df2, Map<Long, JobPersistence> actionDetails, String currentDateStr){ for(JobPersistenceOld jobDetail : jobDetails){ //ScheduleType: 0 ; 1; 2 if(jobDetail.getScheduleType() != null && jobDetail.getScheduleType()==0){ try{ String jobCronExpression = jobDetail.getCronExpression(); String cronDate= df2.format(now); List<String> lTime = new ArrayList<String>(); if(jobCronExpression != null && jobCronExpression.trim().length() > 0){ boolean isCronExp = false; try{ isCronExp = CronExpParser.Parser(jobCronExpression, cronDate, lTime); }catch(Exception ex){ isCronExp = false; } if (!isCronExp) { log.error("Cron," + cronDate + ";cron" + jobCronExpression); } for (int i = 0; i < lTime.size(); i++) { String actionDateStr = ZeusDateTool.StringToDateStr(lTime.get(i), "yyyy-MM-dd HH:mm:ss", "yyyyMMddHHmmss"); String actionCronExpr = ZeusDateTool.StringToDateStr(lTime.get(i), "yyyy-MM-dd HH:mm:ss", "s m H d M") + " ?"; JobPersistence actionPer = new JobPersistence(); actionPer.setId(Long.parseLong(actionDateStr)*10000+jobDetail.getId());//update action id actionPer.setToJobId(jobDetail.getId()); actionPer.setAuto(jobDetail.getAuto()); actionPer.setConfigs(jobDetail.getConfigs()); actionPer.setCronExpression(actionCronExpr);//update action cron expression actionPer.setCycle(jobDetail.getCycle()); String jobDependencies = jobDetail.getDependencies(); actionPer.setDependencies(jobDependencies); actionPer.setJobDependencies(jobDependencies); actionPer.setDescr(jobDetail.getDescr()); actionPer.setGmtCreate(jobDetail.getGmtCreate()); actionPer.setGmtModified(new Date()); actionPer.setGroupId(jobDetail.getGroupId()); actionPer.setHistoryId(jobDetail.getHistoryId()); actionPer.setHost(jobDetail.getHost()); actionPer.setHostGroupId(jobDetail.getHostGroupId()); actionPer.setLastEndTime(jobDetail.getLastEndTime()); actionPer.setLastResult(jobDetail.getLastResult()); actionPer.setName(jobDetail.getName()); actionPer.setOffset(jobDetail.getOffset()); actionPer.setOwner(jobDetail.getOwner()); actionPer.setPostProcessers(jobDetail.getPostProcessers()); actionPer.setPreProcessers(jobDetail.getPreProcessers()); actionPer.setReadyDependency(jobDetail.getReadyDependency()); actionPer.setResources(jobDetail.getResources()); actionPer.setRunType(jobDetail.getRunType()); actionPer.setScheduleType(jobDetail.getScheduleType()); actionPer.setScript(jobDetail.getScript()); actionPer.setStartTime(jobDetail.getStartTime()); actionPer.setStartTimestamp(jobDetail.getStartTimestamp()); actionPer.setStatisStartTime(jobDetail.getStatisStartTime()); actionPer.setStatisEndTime(jobDetail.getStatisEndTime()); actionPer.setStatus(jobDetail.getStatus()); actionPer.setTimezone(jobDetail.getTimezone()); try { //System.out.println("JobId: " + jobDetail.getId()+"; ActionId: " +actionPer.getId()); log.info("JobId: " + jobDetail.getId()+"; ActionId: " +actionPer.getId()); //if(actionPer.getId()>Long.parseLong(currentDateStr)){ context.getGroupManager().saveJob(actionPer); // System.out.println("success"); log.info("success"); actionDetails.put(actionPer.getId(),actionPer); } catch (ZeusException e) { // System.out.println("failed"); log.error("JobId:" + jobDetail.getId() + " Action" +actionPer.getId() + "", e); } } } }catch(Exception ex){ log.error("Action",ex); } } if(jobDetail.getScheduleType() != null && jobDetail.getScheduleType()==2){ try{ if(jobDetail.getDependencies()==null || jobDetail.getDependencies().trim().length()==0){ Date date = null; try { date = DateUtil.timestamp2Date(jobDetail.getStartTimestamp(), DateUtil.getDefaultTZStr()); //System.out.println(date); } catch (ParseException e) { date = new Date(); log.error("parse job start timestamp to date failed,", e); } SimpleDateFormat dfTime=new SimpleDateFormat("HHmmss"); SimpleDateFormat dfDate=new SimpleDateFormat("yyyyMMdd"); SimpleDateFormat dfMinute=new SimpleDateFormat("mmss"); String currentDate = dfDate.format(new Date()); String startTime = dfTime.format(date); String startMinute = dfMinute.format(date); if(jobDetail.getCycle().equals("day")){ Date newStartDate = ZeusDateTool.StringToDate(currentDate+startTime, "yyyyMMddHHmmss"); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(newStartDate.getTime()); calendar.add(Calendar.DATE, -1); calendar.getTime(); Date statisStartTime = calendar.getTime(); calendar.add(Calendar.MINUTE, 60*23+59); Date statisEndTime = calendar.getTime(); JobPersistence actionPer = new JobPersistence(); actionPer.setId(Long.parseLong(currentDate+startTime)*10000+jobDetail.getId());//update action id actionPer.setToJobId(jobDetail.getId()); actionPer.setAuto(jobDetail.getAuto()); actionPer.setConfigs(jobDetail.getConfigs()); actionPer.setCronExpression(jobDetail.getCronExpression()); actionPer.setCycle(jobDetail.getCycle()); String jobDependencies = jobDetail.getDependencies(); actionPer.setDependencies(jobDependencies); actionPer.setJobDependencies(jobDependencies); actionPer.setDescr(jobDetail.getDescr()); actionPer.setGmtCreate(jobDetail.getGmtCreate()); actionPer.setGmtModified(new Date()); actionPer.setGroupId(jobDetail.getGroupId()); actionPer.setHistoryId(jobDetail.getHistoryId()); actionPer.setHost(jobDetail.getHost()); actionPer.setLastEndTime(jobDetail.getLastEndTime()); actionPer.setLastResult(jobDetail.getLastResult()); actionPer.setName(jobDetail.getName()); actionPer.setOffset(jobDetail.getOffset()); actionPer.setOwner(jobDetail.getOwner()); actionPer.setPostProcessers(jobDetail.getPostProcessers()); actionPer.setPreProcessers(jobDetail.getPreProcessers()); actionPer.setReadyDependency(jobDetail.getReadyDependency()); actionPer.setResources(jobDetail.getResources()); actionPer.setRunType(jobDetail.getRunType()); actionPer.setScheduleType(jobDetail.getScheduleType()); actionPer.setScript(jobDetail.getScript()); actionPer.setStartTime(newStartDate); actionPer.setStartTimestamp(newStartDate.getTime()); actionPer.setStatisStartTime(statisStartTime); actionPer.setStatisEndTime(statisEndTime); actionPer.setStatus(jobDetail.getStatus()); actionPer.setHostGroupId(jobDetail.getHostGroupId()); actionPer.setTimezone(jobDetail.getTimezone()); try { //System.out.println("JobId: " + jobDetail.getId()+"; ActionId: " +actionPer.getId()); //if(actionPer.getId()>Long.parseLong(currentDateStr)){ context.getGroupManager().saveJob(actionPer); System.out.println("success"); actionDetails.put(actionPer.getId(),actionPer); } catch (ZeusException e) { System.out.println("failed"); log.error("JobId:" + jobDetail.getId() + " Action" +actionPer.getId() + "", e); } } if(jobDetail.getCycle().equals("hour")){ for (int i = 0; i < 24; i++) { String startHour = String.valueOf(i); if(startHour.trim().length()<2){ startHour = "0"+startHour; } Date newStartDate = ZeusDateTool.StringToDate(currentDate+startHour+startMinute, "yyyyMMddHHmmss"); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(newStartDate.getTime()); calendar.add(Calendar.HOUR, -1); calendar.getTime(); Date statisStartTime = calendar.getTime(); calendar.add(Calendar.MINUTE, 59); Date statisEndTime = calendar.getTime(); JobPersistence actionPer = new JobPersistence(); actionPer.setId(Long.parseLong(currentDate+startHour+startMinute)*10000+jobDetail.getId());//update action id actionPer.setToJobId(jobDetail.getId()); actionPer.setAuto(jobDetail.getAuto()); actionPer.setConfigs(jobDetail.getConfigs()); actionPer.setCronExpression(jobDetail.getCronExpression()); actionPer.setCycle(jobDetail.getCycle()); String jobDependencies = jobDetail.getDependencies(); actionPer.setDependencies(jobDependencies); actionPer.setJobDependencies(jobDependencies); actionPer.setDescr(jobDetail.getDescr()); actionPer.setGmtCreate(jobDetail.getGmtCreate()); actionPer.setGmtModified(new Date()); actionPer.setGroupId(jobDetail.getGroupId()); actionPer.setHistoryId(jobDetail.getHistoryId()); actionPer.setHost(jobDetail.getHost()); actionPer.setLastEndTime(jobDetail.getLastEndTime()); actionPer.setLastResult(jobDetail.getLastResult()); actionPer.setName(jobDetail.getName()); actionPer.setOffset(jobDetail.getOffset()); actionPer.setOwner(jobDetail.getOwner()); actionPer.setPostProcessers(jobDetail.getPostProcessers()); actionPer.setPreProcessers(jobDetail.getPreProcessers()); actionPer.setReadyDependency(jobDetail.getReadyDependency()); actionPer.setResources(jobDetail.getResources()); actionPer.setRunType(jobDetail.getRunType()); actionPer.setScheduleType(jobDetail.getScheduleType()); actionPer.setScript(jobDetail.getScript()); actionPer.setStartTime(newStartDate); actionPer.setStartTimestamp(newStartDate.getTime()); actionPer.setStatisStartTime(statisStartTime); actionPer.setStatisEndTime(statisEndTime); actionPer.setStatus(jobDetail.getStatus()); actionPer.setTimezone(jobDetail.getTimezone()); actionPer.setHostGroupId(jobDetail.getHostGroupId()); try { System.out.println("JobId: " + jobDetail.getId()+"; ActionId: " +actionPer.getId()); //if(actionPer.getId()>Long.parseLong(currentDateStr)){ context.getGroupManager().saveJob(actionPer); System.out.println("success"); actionDetails.put(actionPer.getId(),actionPer); } catch (ZeusException e) { System.out.println("failed"); log.error("JobId:" + jobDetail.getId() + " Action" +actionPer.getId() + "", e); } } } } }catch(Exception ex){ log.error("Action",ex); } } } } //action public void runDependencesJobToAction(List<JobPersistenceOld> jobDetails, Map<Long, JobPersistence> actionDetails,String currentDateStr, int loopCount){ int noCompleteCount = 0; loopCount ++; // System.out.println("loopCount"+loopCount); for(JobPersistenceOld jobDetail : jobDetails){ //ScheduleType: 0 ; 1; 2 if((jobDetail.getScheduleType() != null && jobDetail.getScheduleType()==1) || (jobDetail.getScheduleType() != null && jobDetail.getScheduleType()==2)){ try{ String jobDependencies = jobDetail.getDependencies(); String actionDependencies = ""; if(jobDependencies != null && jobDependencies.trim().length()>0){ Map<String,List<JobPersistence>> dependActionList = new HashMap<String,List<JobPersistence>>(); String[] dependStrs = jobDependencies.split(","); for(String deps : dependStrs){ List<JobPersistence> dependActions = new ArrayList<JobPersistence>(); Iterator<JobPersistence> actionIt = actionDetails.values().iterator(); while(actionIt.hasNext()){ JobPersistence action = actionIt.next(); if(action.getToJobId().toString().equals(deps)){ dependActions.add(action); } } dependActionList.put(deps, dependActions); if(loopCount > 40){ if(!jobDetail.getConfigs().contains("sameday")){ if(dependActionList.get(deps).size()==0){ List<JobPersistence> lastJobActions = context.getGroupManager().getLastJobAction(deps); if(lastJobActions != null && lastJobActions.size()>0){ actionDetails.put(lastJobActions.get(0).getId(),lastJobActions.get(0)); dependActions.add(lastJobActions.get(0)); dependActionList.put(deps, dependActions); }else{ break; } } } } } boolean isComplete = true; String actionMostDeps = ""; for(String deps : dependStrs){ if(dependActionList.get(deps).size()==0){ isComplete = false; noCompleteCount ++; break; } if(actionMostDeps.trim().length()==0){ actionMostDeps = deps; } if(dependActionList.get(deps).size()>dependActionList.get(actionMostDeps).size()){ actionMostDeps = deps; }else if(dependActionList.get(deps).size()==dependActionList.get(actionMostDeps).size()){ if(dependActionList.get(deps).get(0).getId()<dependActionList.get(actionMostDeps).get(0).getId()){ actionMostDeps = deps; } } } if(!isComplete){ continue; }else{ List<JobPersistence> actions = dependActionList.get(actionMostDeps); if(actions != null && actions.size()>0){ for(JobPersistence actionModel : actions){ actionDependencies = String.valueOf(actionModel.getId()); for(String deps : dependStrs){ if(!deps.equals(actionMostDeps)){ List<JobPersistence> actionOthers = dependActionList.get(deps); Long actionOtherId = actionOthers.get(0).getId(); for(JobPersistence actionOtherModel : actionOthers){ if(Math.abs((actionOtherModel.getId()-actionModel.getId()))<Math.abs((actionOtherId-actionModel.getId()))){ actionOtherId = actionOtherModel.getId(); } } if(actionDependencies.trim().length()>0){ actionDependencies += ","; } actionDependencies += String.valueOf((actionOtherId/10000)*10000 + Long.parseLong(deps)); } } //action JobPersistence actionPer = new JobPersistence(); actionPer.setId((actionModel.getId()/10000)*10000+jobDetail.getId());//update action id actionPer.setToJobId(jobDetail.getId()); actionPer.setAuto(jobDetail.getAuto()); actionPer.setConfigs(jobDetail.getConfigs()); actionPer.setCronExpression(jobDetail.getCronExpression());//update action cron expression actionPer.setCycle(jobDetail.getCycle()); actionPer.setDependencies(actionDependencies); actionPer.setJobDependencies(jobDependencies); actionPer.setDescr(jobDetail.getDescr()); actionPer.setGmtCreate(jobDetail.getGmtCreate()); actionPer.setGmtModified(new Date()); actionPer.setGroupId(jobDetail.getGroupId()); actionPer.setHistoryId(jobDetail.getHistoryId()); actionPer.setHost(jobDetail.getHost()); actionPer.setHostGroupId(jobDetail.getHostGroupId()); actionPer.setLastEndTime(jobDetail.getLastEndTime()); actionPer.setLastResult(jobDetail.getLastResult()); actionPer.setName(jobDetail.getName()); actionPer.setOffset(jobDetail.getOffset()); actionPer.setOwner(jobDetail.getOwner()); actionPer.setPostProcessers(jobDetail.getPostProcessers()); actionPer.setPreProcessers(jobDetail.getPreProcessers()); actionPer.setReadyDependency(jobDetail.getReadyDependency()); actionPer.setResources(jobDetail.getResources()); actionPer.setRunType(jobDetail.getRunType()); actionPer.setScheduleType(jobDetail.getScheduleType()); actionPer.setScript(jobDetail.getScript()); actionPer.setStartTime(jobDetail.getStartTime()); actionPer.setStartTimestamp(jobDetail.getStartTimestamp()); actionPer.setStatisStartTime(jobDetail.getStatisStartTime()); actionPer.setStatisEndTime(jobDetail.getStatisEndTime()); actionPer.setStatus(jobDetail.getStatus()); actionPer.setTimezone(jobDetail.getTimezone()); try { if(!actionDetails.containsKey(actionPer.getId())){ System.out.println("JobId: " + jobDetail.getId()+"; ActionId: " +actionPer.getId()); //if(actionPer.getId()>Long.parseLong(currentDateStr)){ context.getGroupManager().saveJob(actionPer); System.out.println("success"); actionDetails.put(actionPer.getId(),actionPer); } } catch (ZeusException e) { log.error("JobId:" + jobDetail.getId() + " Action" +actionPer.getId() + "", e); } } } } } }catch(Exception ex){ log.error("Action", ex); } } } if(noCompleteCount > 0 && loopCount < 60){ runDependencesJobToAction(jobDetails, actionDetails, currentDateStr, loopCount); } } }
package com.taobao.zeus.socket.master; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.apache.hadoop.hive.ql.parse.HiveParser.nullCondition_return; import org.jboss.netty.channel.Channel; import org.quartz.SchedulerException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.taobao.zeus.broadcast.alarm.MailAlarm; import com.taobao.zeus.broadcast.alarm.SMSAlarm; import com.taobao.zeus.client.ZeusException; import com.taobao.zeus.model.DebugHistory; import com.taobao.zeus.model.FileDescriptor; import com.taobao.zeus.model.HostGroupCache; import com.taobao.zeus.model.JobDescriptor; import com.taobao.zeus.model.JobHistory; import com.taobao.zeus.model.JobStatus; import com.taobao.zeus.model.JobStatus.TriggerType; import com.taobao.zeus.model.Profile; import com.taobao.zeus.mvc.Controller; import com.taobao.zeus.mvc.Dispatcher; import com.taobao.zeus.schedule.mvc.AddJobListener; import com.taobao.zeus.schedule.mvc.DebugInfoLog; import com.taobao.zeus.schedule.mvc.DebugListener; import com.taobao.zeus.schedule.mvc.JobController; import com.taobao.zeus.schedule.mvc.JobFailListener; import com.taobao.zeus.schedule.mvc.JobSuccessListener; import com.taobao.zeus.schedule.mvc.ScheduleInfoLog; import com.taobao.zeus.schedule.mvc.StopScheduleJobListener; import com.taobao.zeus.schedule.mvc.ZeusJobException; import com.taobao.zeus.schedule.mvc.event.DebugFailEvent; import com.taobao.zeus.schedule.mvc.event.DebugSuccessEvent; import com.taobao.zeus.schedule.mvc.event.Events; import com.taobao.zeus.schedule.mvc.event.JobFailedEvent; import com.taobao.zeus.schedule.mvc.event.JobLostEvent; import com.taobao.zeus.schedule.mvc.event.JobMaintenanceEvent; import com.taobao.zeus.schedule.mvc.event.JobSuccessEvent; import com.taobao.zeus.socket.SocketLog; import com.taobao.zeus.socket.master.MasterWorkerHolder.HeartBeatInfo; import com.taobao.zeus.socket.master.reqresp.MasterExecuteJob; import com.taobao.zeus.socket.protocol.Protocol.ExecuteKind; import com.taobao.zeus.socket.protocol.Protocol.Response; import com.taobao.zeus.socket.protocol.Protocol.Status; import com.taobao.zeus.store.GroupBean; import com.taobao.zeus.store.JobBean; import com.taobao.zeus.store.mysql.persistence.JobPersistence; import com.taobao.zeus.store.mysql.persistence.JobPersistenceOld; import com.taobao.zeus.util.CronExpParser; import com.taobao.zeus.util.Environment; import com.taobao.zeus.util.Tuple; import com.taobao.zeus.util.ZeusDateTool; public class Master { private MasterContext context; private static Logger log = LoggerFactory.getLogger(Master.class); public Master(final MasterContext context) { this.context = context; GroupBean root = context.getGroupManager().getGlobeGroupBean(); if (Environment.isPrePub()) { // stop listener context.getDispatcher().addDispatcherListener( new StopScheduleJobListener()); } context.getDispatcher().addDispatcherListener( new AddJobListener(context, this)); context.getDispatcher().addDispatcherListener( new JobFailListener(context)); context.getDispatcher().addDispatcherListener( new DebugListener(context)); context.getDispatcher().addDispatcherListener( new JobSuccessListener(context)); Map<String, JobBean> allJobBeans = root.getAllSubJobBeans(); for (String id : allJobBeans.keySet()) { context.getDispatcher().addController( new JobController(context, this, id)); } context.getDispatcher().forwardEvent(Events.Initialize); context.setMaster(this); //host context.refreshHostGroupCache(); log.info("refresh HostGroup Cache"); context.getSchedulePool().scheduleAtFixedRate(new Runnable() { @Override public void run() { context.refreshHostGroupCache(); log.info("refresh HostGroup Cache"); } }, 1, 1, TimeUnit.HOURS); private void checkTimeOver() { for (MasterWorkerHolder w : context.getWorkers().values()) { checkScheduleTimeOver(w); //TODO // checkManualTimeOver(w); // checkDebugTimeOver(w); } } private void checkDebugTimeOver(MasterWorkerHolder w) { for (Map.Entry<String, Boolean> entry : w.getDebugRunnings().entrySet()) { if (entry.getValue() != null && entry.getValue()) { continue; } String historyId = entry.getKey(); DebugHistory his = context.getDebugHistoryManager() .findDebugHistory(historyId); long maxTime; FileDescriptor fd; try { fd = context.getFileManager().getFile(his.getFileId()); Profile pf = context.getProfileManager().findByUid( fd.getOwner()); String maxTimeString = pf.getHadoopConf().get( "zeus.job.maxtime"); if (maxTimeString == null || maxTimeString.trim().isEmpty()) { continue; } maxTime = Long.parseLong(maxTimeString); if (maxTime < 0) { continue; } } catch (Exception e) { continue; } long runTime = (System.currentTimeMillis() - his.getStartTime() .getTime()) / 1000 / 60; if (runTime > maxTime) { if (timeOverAlarm(null, fd, runTime, maxTime, 2, null)) { w.getDebugRunnings().replace(historyId, false, true); } } } } private void checkManualTimeOver(MasterWorkerHolder w) { for (Map.Entry<String, Boolean> entry : w.getManualRunnings() .entrySet()) { if (entry.getValue() != null && entry.getValue()) { continue; } String historyId = entry.getKey(); JobHistory his = context.getJobHistoryManager().findJobHistory( historyId); JobDescriptor jd = context.getGroupManager() .getJobDescriptor(his.getJobId()).getX(); long maxTime; try { String maxTimeString = jd.getProperties().get( "zeus.job.maxtime"); if (maxTimeString == null || maxTimeString.trim().isEmpty()) { continue; } maxTime = Long.parseLong(maxTimeString); if (maxTime < 0) { continue; } } catch (Exception e) { continue; } long runTime = (System.currentTimeMillis() - his.getStartTime() .getTime()) / 1000 / 60; if (runTime > maxTime) { if (timeOverAlarm(his, null, runTime, maxTime, 1, jd)) { w.getManualRunnings().replace(historyId, false, true); } } } } private void checkScheduleTimeOver(MasterWorkerHolder w) { for (Map.Entry<String, Boolean> entry : w.getRunnings().entrySet()) { if (entry.getValue() != null && entry.getValue()) { continue; } String jobId = entry.getKey(); JobDescriptor jd = context.getGroupManager() .getJobDescriptor(jobId).getX(); String maxTimeString = jd.getProperties().get("zeus.job.maxtime"); long maxTime; try { if (maxTimeString == null || maxTimeString.trim().isEmpty()) { continue; } maxTime = Long.parseLong(maxTimeString); if (maxTime < 0) { continue; } } catch (Exception e) { continue; } JobHistory his = context.getJobHistoryManager().findJobHistory( context.getGroupManager().getJobStatus(jobId) .getHistoryId()); if (his != null && his.getStartTime() != null) { long runTime = (System.currentTimeMillis() - his.getStartTime() .getTime()) / 1000 / 60; if (runTime > maxTime) { log.info("send the timeOverAlarm of job: " + jobId); if (timeOverAlarm(his, null, runTime, maxTime, 0, jd)) { w.getRunnings().replace(jobId, false, true); } } } } } private boolean timeOverAlarm(final JobHistory his, FileDescriptor fd, long runTime, long maxTime, int type, JobDescriptor jd) { final MailAlarm mailAlarm = (MailAlarm) context.getApplicationContext() .getBean("mailAlarm"); SMSAlarm smsAlarm = (SMSAlarm) context.getApplicationContext().getBean( "smsAlarm"); final StringBuffer title = new StringBuffer("["); switch (type) { case 0: title.append("").append("] jobID=").append(his.getJobId()); break; case 1: title.append("").append("] jobID=").append(his.getJobId()); break; case 2: title.append("").append("] ").append(fd.getName()); } final StringBuffer content = new StringBuffer(title); if(jd != null){ title.append(" (").append(jd.getName()).append(")"); content.append("\nJOB").append(jd.getName()); Map<String, String> properties=jd.getProperties(); if(properties != null){ String plevel=properties.get("run.priority.level"); if("1".equals(plevel)){ content.append("\nJob: ").append("low"); }else if("2".equals(plevel)){ content.append("\nJob: ").append("medium"); }else if("3".equals(plevel)){ content.append("\nJob: ").append("high"); } } content.append("\nJOBOwner").append(jd.getOwner()); } content.append("\n").append(runTime).append("") .append("\n").append(maxTime).append(""); if(his != null){ content.append("\n\n").append(his.getLog().getContent().replaceAll("\\n", "<br/>")); } try { if (type == 2) { } else { new Thread() { @Override public void run() { try { Thread.sleep(6000); mailAlarm .alarm(his.getId(), title.toString(), content.toString() .replace("\n", "<br/>")); } catch (Exception e) { log.error("send run timeover mail alarm failed", e); } } }.start(); if (type == 0) { String priorityLevel = "3"; if(jd != null){ priorityLevel = jd.getProperties().get("run.priority.level"); } if(priorityLevel == null || !priorityLevel.trim().equals("1")){ Calendar now = Calendar.getInstance(); int hour = now.get(Calendar.HOUR_OF_DAY); int day = now.get(Calendar.DAY_OF_WEEK); if (day == Calendar.SATURDAY || day == Calendar.SUNDAY || hour < 9 || hour > 18) { smsAlarm.alarm(his.getId(), title.toString(),content.toString(), null); //mailAlarm.alarm(his.getId(), title.toString(),content.toString(), null); } } } } return true; } catch (Exception e) { log.error("send run timeover alarm failed", e); return false; } } public void workerDisconnectProcess(Channel channel) { MasterWorkerHolder holder = context.getWorkers().get(channel); if (holder != null) { // SocketLog.info("worker disconnect, ip:" + channel.getRemoteAddress().toString()); context.getWorkers().remove(channel); final List<JobHistory> hiss = new ArrayList<JobHistory>(); Map<String, Tuple<JobDescriptor, JobStatus>> map = context .getGroupManager().getJobDescriptor( holder.getRunnings().keySet()); for (String key : map.keySet()) { JobStatus js = map.get(key).getY(); if (js.getHistoryId() != null) { JobHistory his = context.getJobHistoryManager().findJobHistory( js.getHistoryId()); if(his != null){ hiss.add(his); } } /*js.setStatus(com.taobao.zeus.model.JobStatus.Status.FAILED); context.getGroupManager().updateJobStatus(js);*/ } new Thread() { @Override public void run() { try { Thread.sleep(30000); } catch (InterruptedException e) { } for (JobHistory his : hiss) { String jobId = his.getJobId(); his.setEndTime(new Date()); his.setStatus(com.taobao.zeus.model.JobStatus.Status.FAILED); his.setIllustrate("worker"); context.getJobHistoryManager().updateJobHistory(his); JobHistory history = new JobHistory(); history.setJobId(jobId); history.setToJobId(his.getToJobId()); history.setTriggerType(his.getTriggerType()); history.setIllustrate("worker"); history.setOperator(his.getOperator()); history.setHostGroupId(his.getHostGroupId()); context.getJobHistoryManager().addJobHistory(history); Master.this.run(history); } }; }.start(); } } public void debug(DebugHistory debug) { JobElement element = new JobElement(debug.getId(), debug.gethostGroupId()); debug.setStatus(com.taobao.zeus.model.JobStatus.Status.RUNNING); debug.setStartTime(new Date()); context.getDebugHistoryManager().updateDebugHistory(debug); debug.getLog().appendZeus( new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " "); context.getDebugHistoryManager().updateDebugHistoryLog(debug.getId(), debug.getLog().getContent()); context.getDebugQueue().offer(element); System.out.println("offer debug queue :" +context.getDebugQueue().size()+ " element :"+element.getJobID()); } public JobHistory run(JobHistory history) { String jobId = history.getJobId(); int priorityLevel = 3; try{ JobDescriptor jd = context.getGroupManager().getJobDescriptor(jobId).getX(); String priorityLevelStr = jd.getProperties().get("run.priority.level"); if(priorityLevelStr!=null){ priorityLevel = Integer.parseInt(priorityLevelStr); } }catch(Exception ex){ priorityLevel = 3; } JobElement element = new JobElement(jobId, history.getHostGroupId(), priorityLevel); history.setStatus(com.taobao.zeus.model.JobStatus.Status.RUNNING); if (history.getTriggerType() == TriggerType.MANUAL_RECOVER) { for (JobElement e : new ArrayList<JobElement>(context.getQueue())) { if (e.getJobID().equals(jobId)) { history.getLog().appendZeus(""); history.setStartTime(new Date()); history.setEndTime(new Date()); history.setStatus(com.taobao.zeus.model.JobStatus.Status.FAILED); break; } } for (Channel key : context.getWorkers().keySet()) { MasterWorkerHolder worker = context.getWorkers().get(key); if (worker.getRunnings().containsKey(jobId)) { history.getLog().appendZeus(""); history.setStartTime(new Date()); history.setEndTime(new Date()); history.setStatus(com.taobao.zeus.model.JobStatus.Status.FAILED); break; } } } if (history.getStatus() == com.taobao.zeus.model.JobStatus.Status.RUNNING) { history.getLog().appendZeus( new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") .format(new Date()) + " "); context.getJobHistoryManager().updateJobHistoryLog(history.getId(), history.getLog().getContent()); if (history.getTriggerType() == TriggerType.MANUAL) { element.setJobID(history.getId()); context.getManualQueue().offer(element); } else { JobStatus js = context.getGroupManager().getJobStatus( history.getJobId()); js.setStatus(com.taobao.zeus.model.JobStatus.Status.RUNNING); js.setHistoryId(history.getId()); context.getGroupManager().updateJobStatus(js); context.getQueue().offer(element); } } context.getJobHistoryManager().updateJobHistory(history); context.getJobHistoryManager().updateJobHistoryLog(history.getId(), history.getLog().getContent()); return history; } //actionaction public void runScheduleJobToAction(List<JobPersistenceOld> jobDetails, Date now, SimpleDateFormat df2, Map<Long, JobPersistence> actionDetails, String currentDateStr){ for(JobPersistenceOld jobDetail : jobDetails){ //ScheduleType: 0 ; 1; 2 if(jobDetail.getScheduleType() != null && jobDetail.getScheduleType()==0){ try{ String jobCronExpression = jobDetail.getCronExpression(); String cronDate= df2.format(now); List<String> lTime = new ArrayList<String>(); if(jobCronExpression != null && jobCronExpression.trim().length() > 0){ boolean isCronExp = false; try{ isCronExp = CronExpParser.Parser(jobCronExpression, cronDate, lTime); }catch(Exception ex){ isCronExp = false; } if (!isCronExp) { log.error("Cron," + cronDate + ";cron" + jobCronExpression); } for (int i = 0; i < lTime.size(); i++) { String actionDateStr = ZeusDateTool.StringToDateStr(lTime.get(i), "yyyy-MM-dd HH:mm:ss", "yyyyMMddHHmm"); String actionCronExpr = ZeusDateTool.StringToDateStr(lTime.get(i), "yyyy-MM-dd HH:mm:ss", "0 m H d M") + " ?"; JobPersistence actionPer = new JobPersistence(); actionPer.setId(Long.parseLong(actionDateStr)*1000000+jobDetail.getId());//update action id actionPer.setToJobId(jobDetail.getId()); actionPer.setAuto(jobDetail.getAuto()); actionPer.setConfigs(jobDetail.getConfigs()); actionPer.setCronExpression(actionCronExpr);//update action cron expression actionPer.setCycle(jobDetail.getCycle()); String jobDependencies = jobDetail.getDependencies(); actionPer.setDependencies(jobDependencies); actionPer.setJobDependencies(jobDependencies); actionPer.setDescr(jobDetail.getDescr()); actionPer.setGmtCreate(jobDetail.getGmtCreate()); actionPer.setGmtModified(new Date()); actionPer.setGroupId(jobDetail.getGroupId()); actionPer.setHistoryId(jobDetail.getHistoryId()); actionPer.setHost(jobDetail.getHost()); actionPer.setHostGroupId(jobDetail.getHostGroupId()); actionPer.setLastEndTime(jobDetail.getLastEndTime()); actionPer.setLastResult(jobDetail.getLastResult()); actionPer.setName(jobDetail.getName()); actionPer.setOffset(jobDetail.getOffset()); actionPer.setOwner(jobDetail.getOwner()); actionPer.setPostProcessers(jobDetail.getPostProcessers()); actionPer.setPreProcessers(jobDetail.getPreProcessers()); actionPer.setReadyDependency(jobDetail.getReadyDependency()); actionPer.setResources(jobDetail.getResources()); actionPer.setRunType(jobDetail.getRunType()); actionPer.setScheduleType(jobDetail.getScheduleType()); /* actionPer.setScript(jobDetail.getScript());*/ actionPer.setStartTime(jobDetail.getStartTime()); actionPer.setStartTimestamp(jobDetail.getStartTimestamp()); actionPer.setStatisStartTime(jobDetail.getStatisStartTime()); actionPer.setStatisEndTime(jobDetail.getStatisEndTime()); actionPer.setStatus(jobDetail.getStatus()); actionPer.setTimezone(jobDetail.getTimezone()); try { //System.out.println("JobId: " + jobDetail.getId()+"; ActionId: " +actionPer.getId()); log.info("JobId: " + jobDetail.getId()+"; ActionId: " +actionPer.getId()); //if(actionPer.getId()>Long.parseLong(currentDateStr)){ context.getGroupManager().saveJob(actionPer); // System.out.println("success"); log.info("success"); actionDetails.put(actionPer.getId(),actionPer); } catch (ZeusException e) { // System.out.println("failed"); log.error("JobId:" + jobDetail.getId() + " Action" +actionPer.getId() + "", e); } } } }catch(Exception ex){ log.error("Action",ex); } } /** * if(jobDetail.getScheduleType() != null && jobDetail.getScheduleType()==2){ try{ if(jobDetail.getDependencies()==null || jobDetail.getDependencies().trim().length()==0){ Date date = null; try { date = DateUtil.timestamp2Date(jobDetail.getStartTimestamp(), DateUtil.getDefaultTZStr()); //System.out.println(date); } catch (ParseException e) { date = new Date(); log.error("parse job start timestamp to date failed,", e); } SimpleDateFormat dfTime=new SimpleDateFormat("HHmmss"); SimpleDateFormat dfDate=new SimpleDateFormat("yyyyMMdd"); SimpleDateFormat dfMinute=new SimpleDateFormat("mmss"); String currentDate = dfDate.format(new Date()); String startTime = dfTime.format(date); String startMinute = dfMinute.format(date); //- if(jobDetail.getCycle().equals("day")){ Date newStartDate = ZeusDateTool.StringToDate(currentDate+startTime, "yyyyMMddHHmmss"); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(newStartDate.getTime()); calendar.add(Calendar.DATE, -1); calendar.getTime(); Date statisStartTime = calendar.getTime(); calendar.add(Calendar.MINUTE, 60*23+59); Date statisEndTime = calendar.getTime(); JobPersistence actionPer = new JobPersistence(); actionPer.setId(Long.parseLong(currentDate+startTime)*10000+jobDetail.getId());//update action id actionPer.setToJobId(jobDetail.getId()); actionPer.setAuto(jobDetail.getAuto()); actionPer.setConfigs(jobDetail.getConfigs()); actionPer.setCronExpression(jobDetail.getCronExpression()); actionPer.setCycle(jobDetail.getCycle()); String jobDependencies = jobDetail.getDependencies(); actionPer.setDependencies(jobDependencies); actionPer.setJobDependencies(jobDependencies); actionPer.setDescr(jobDetail.getDescr()); actionPer.setGmtCreate(jobDetail.getGmtCreate()); actionPer.setGmtModified(new Date()); actionPer.setGroupId(jobDetail.getGroupId()); actionPer.setHistoryId(jobDetail.getHistoryId()); actionPer.setHost(jobDetail.getHost()); actionPer.setLastEndTime(jobDetail.getLastEndTime()); actionPer.setLastResult(jobDetail.getLastResult()); actionPer.setName(jobDetail.getName()); actionPer.setOffset(jobDetail.getOffset()); actionPer.setOwner(jobDetail.getOwner()); actionPer.setPostProcessers(jobDetail.getPostProcessers()); actionPer.setPreProcessers(jobDetail.getPreProcessers()); actionPer.setReadyDependency(jobDetail.getReadyDependency()); actionPer.setResources(jobDetail.getResources()); actionPer.setRunType(jobDetail.getRunType()); actionPer.setScheduleType(jobDetail.getScheduleType()); actionPer.setScript(jobDetail.getScript()); actionPer.setStartTime(newStartDate); actionPer.setStartTimestamp(newStartDate.getTime()); actionPer.setStatisStartTime(statisStartTime); actionPer.setStatisEndTime(statisEndTime); actionPer.setStatus(jobDetail.getStatus()); actionPer.setHostGroupId(jobDetail.getHostGroupId()); actionPer.setTimezone(jobDetail.getTimezone()); try { //System.out.println("JobId: " + jobDetail.getId()+"; ActionId: " +actionPer.getId()); //if(actionPer.getId()>Long.parseLong(currentDateStr)){ context.getGroupManager().saveJob(actionPer); System.out.println("success"); actionDetails.put(actionPer.getId(),actionPer); //} } catch (ZeusException e) { System.out.println("failed"); log.error("JobId:" + jobDetail.getId() + " Action" +actionPer.getId() + "", e); } } if(jobDetail.getCycle().equals("hour")){ for (int i = 0; i < 24; i++) { String startHour = String.valueOf(i); if(startHour.trim().length()<2){ startHour = "0"+startHour; } Date newStartDate = ZeusDateTool.StringToDate(currentDate+startHour+startMinute, "yyyyMMddHHmmss"); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(newStartDate.getTime()); calendar.add(Calendar.HOUR, -1); calendar.getTime(); Date statisStartTime = calendar.getTime(); calendar.add(Calendar.MINUTE, 59); Date statisEndTime = calendar.getTime(); JobPersistence actionPer = new JobPersistence(); actionPer.setId(Long.parseLong(currentDate+startHour+startMinute)*10000+jobDetail.getId());//update action id actionPer.setToJobId(jobDetail.getId()); actionPer.setAuto(jobDetail.getAuto()); actionPer.setConfigs(jobDetail.getConfigs()); actionPer.setCronExpression(jobDetail.getCronExpression()); actionPer.setCycle(jobDetail.getCycle()); String jobDependencies = jobDetail.getDependencies(); actionPer.setDependencies(jobDependencies); actionPer.setJobDependencies(jobDependencies); actionPer.setDescr(jobDetail.getDescr()); actionPer.setGmtCreate(jobDetail.getGmtCreate()); actionPer.setGmtModified(new Date()); actionPer.setGroupId(jobDetail.getGroupId()); actionPer.setHistoryId(jobDetail.getHistoryId()); actionPer.setHost(jobDetail.getHost()); actionPer.setLastEndTime(jobDetail.getLastEndTime()); actionPer.setLastResult(jobDetail.getLastResult()); actionPer.setName(jobDetail.getName()); actionPer.setOffset(jobDetail.getOffset()); actionPer.setOwner(jobDetail.getOwner()); actionPer.setPostProcessers(jobDetail.getPostProcessers()); actionPer.setPreProcessers(jobDetail.getPreProcessers()); actionPer.setReadyDependency(jobDetail.getReadyDependency()); actionPer.setResources(jobDetail.getResources()); actionPer.setRunType(jobDetail.getRunType()); actionPer.setScheduleType(jobDetail.getScheduleType()); actionPer.setScript(jobDetail.getScript()); actionPer.setStartTime(newStartDate); actionPer.setStartTimestamp(newStartDate.getTime()); actionPer.setStatisStartTime(statisStartTime); actionPer.setStatisEndTime(statisEndTime); actionPer.setStatus(jobDetail.getStatus()); actionPer.setTimezone(jobDetail.getTimezone()); actionPer.setHostGroupId(jobDetail.getHostGroupId()); try { System.out.println("JobId: " + jobDetail.getId()+"; ActionId: " +actionPer.getId()); //if(actionPer.getId()>Long.parseLong(currentDateStr)){ context.getGroupManager().saveJob(actionPer); System.out.println("success"); actionDetails.put(actionPer.getId(),actionPer); //} } catch (ZeusException e) { System.out.println("failed"); log.error("JobId:" + jobDetail.getId() + " Action" +actionPer.getId() + "", e); } } } } }catch(Exception ex){ log.error("Action",ex); } }*/ } } //action public void runDependencesJobToAction(List<JobPersistenceOld> jobDetails, Map<Long, JobPersistence> actionDetails,String currentDateStr, int loopCount){ int noCompleteCount = 0; loopCount ++; // System.out.println("loopCount"+loopCount); for(JobPersistenceOld jobDetail : jobDetails){ //ScheduleType: 0 ; 1; 2 if((jobDetail.getScheduleType() != null && jobDetail.getScheduleType()==1) || (jobDetail.getScheduleType() != null && jobDetail.getScheduleType()==2)){ try{ String jobDependencies = jobDetail.getDependencies(); String actionDependencies = ""; if(jobDependencies != null && jobDependencies.trim().length()>0){ Map<String,List<JobPersistence>> dependActionList = new HashMap<String,List<JobPersistence>>(); String[] dependStrs = jobDependencies.split(","); for(String deps : dependStrs){ List<JobPersistence> dependActions = new ArrayList<JobPersistence>(); Iterator<JobPersistence> actionIt = actionDetails.values().iterator(); while(actionIt.hasNext()){ JobPersistence action = actionIt.next(); if(action.getToJobId().toString().equals(deps)){ dependActions.add(action); } } dependActionList.put(deps, dependActions); if(loopCount > 40){ if(!jobDetail.getConfigs().contains("sameday")){ if(dependActionList.get(deps).size()==0){ List<JobPersistence> lastJobActions = context.getGroupManager().getLastJobAction(deps); if(lastJobActions != null && lastJobActions.size()>0){ actionDetails.put(lastJobActions.get(0).getId(),lastJobActions.get(0)); dependActions.add(lastJobActions.get(0)); dependActionList.put(deps, dependActions); }else{ break; } } } } } boolean isComplete = true; String actionMostDeps = ""; for(String deps : dependStrs){ if(dependActionList.get(deps).size()==0){ isComplete = false; noCompleteCount ++; break; } if(actionMostDeps.trim().length()==0){ actionMostDeps = deps; } if(dependActionList.get(deps).size()>dependActionList.get(actionMostDeps).size()){ actionMostDeps = deps; }else if(dependActionList.get(deps).size()==dependActionList.get(actionMostDeps).size()){ if(dependActionList.get(deps).get(0).getId()<dependActionList.get(actionMostDeps).get(0).getId()){ actionMostDeps = deps; } } } if(!isComplete){ continue; }else{ List<JobPersistence> actions = dependActionList.get(actionMostDeps); if(actions != null && actions.size()>0){ for(JobPersistence actionModel : actions){ actionDependencies = String.valueOf(actionModel.getId()); for(String deps : dependStrs){ if(!deps.equals(actionMostDeps)){ List<JobPersistence> actionOthers = dependActionList.get(deps); Long actionOtherId = actionOthers.get(0).getId(); for(JobPersistence actionOtherModel : actionOthers){ if(Math.abs((actionOtherModel.getId()-actionModel.getId()))<Math.abs((actionOtherId-actionModel.getId()))){ actionOtherId = actionOtherModel.getId(); } } if(actionDependencies.trim().length()>0){ actionDependencies += ","; } actionDependencies += String.valueOf((actionOtherId/1000000)*1000000 + Long.parseLong(deps)); } } //action JobPersistence actionPer = new JobPersistence(); actionPer.setId((actionModel.getId()/1000000)*1000000+jobDetail.getId());//update action id actionPer.setToJobId(jobDetail.getId()); actionPer.setAuto(jobDetail.getAuto()); actionPer.setConfigs(jobDetail.getConfigs()); actionPer.setCronExpression(jobDetail.getCronExpression());//update action cron expression actionPer.setCycle(jobDetail.getCycle()); actionPer.setDependencies(actionDependencies); actionPer.setJobDependencies(jobDependencies); actionPer.setDescr(jobDetail.getDescr()); actionPer.setGmtCreate(jobDetail.getGmtCreate()); actionPer.setGmtModified(new Date()); actionPer.setGroupId(jobDetail.getGroupId()); actionPer.setHistoryId(jobDetail.getHistoryId()); actionPer.setHost(jobDetail.getHost()); actionPer.setHostGroupId(jobDetail.getHostGroupId()); actionPer.setLastEndTime(jobDetail.getLastEndTime()); actionPer.setLastResult(jobDetail.getLastResult()); actionPer.setName(jobDetail.getName()); actionPer.setOffset(jobDetail.getOffset()); actionPer.setOwner(jobDetail.getOwner()); actionPer.setPostProcessers(jobDetail.getPostProcessers()); actionPer.setPreProcessers(jobDetail.getPreProcessers()); actionPer.setReadyDependency(jobDetail.getReadyDependency()); actionPer.setResources(jobDetail.getResources()); actionPer.setRunType(jobDetail.getRunType()); actionPer.setScheduleType(jobDetail.getScheduleType()); /* actionPer.setScript(jobDetail.getScript());*/ actionPer.setStartTime(jobDetail.getStartTime()); actionPer.setStartTimestamp(jobDetail.getStartTimestamp()); actionPer.setStatisStartTime(jobDetail.getStatisStartTime()); actionPer.setStatisEndTime(jobDetail.getStatisEndTime()); actionPer.setStatus(jobDetail.getStatus()); actionPer.setTimezone(jobDetail.getTimezone()); try { if(!actionDetails.containsKey(actionPer.getId())){ System.out.println("JobId: " + jobDetail.getId()+"; ActionId: " +actionPer.getId()); //if(actionPer.getId()>Long.parseLong(currentDateStr)){ context.getGroupManager().saveJob(actionPer); System.out.println("success"); actionDetails.put(actionPer.getId(),actionPer); } } catch (ZeusException e) { log.error("JobId:" + jobDetail.getId() + " Action" +actionPer.getId() + "", e); } } } } } }catch(Exception ex){ log.error("Action", ex); } } } if(noCompleteCount > 0 && loopCount < 60){ runDependencesJobToAction(jobDetails, actionDetails, currentDateStr, loopCount); } } }
package org.scm4j.vcs; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.eclipse.jgit.api.*; import org.eclipse.jgit.api.CreateBranchCommand.SetupUpstreamMode; import org.eclipse.jgit.api.ListBranchCommand.ListMode; import org.eclipse.jgit.api.ResetCommand.ResetType; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.api.errors.RefAlreadyExistsException; import org.eclipse.jgit.diff.DiffEntry; import org.eclipse.jgit.diff.DiffEntry.ChangeType; import org.eclipse.jgit.diff.DiffEntry.Side; import org.eclipse.jgit.diff.DiffFormatter; import org.eclipse.jgit.lib.*; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevSort; import org.eclipse.jgit.revwalk.RevTag; import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.storage.file.FileRepositoryBuilder; import org.eclipse.jgit.transport.CredentialsProvider; import org.eclipse.jgit.transport.RefSpec; import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider; import org.eclipse.jgit.treewalk.CanonicalTreeParser; import org.scm4j.vcs.api.*; import org.scm4j.vcs.api.exceptions.EVCSBranchExists; import org.scm4j.vcs.api.exceptions.EVCSException; import org.scm4j.vcs.api.exceptions.EVCSFileNotFound; import org.scm4j.vcs.api.exceptions.EVCSTagExists; import org.scm4j.vcs.api.workingcopy.IVCSLockedWorkingCopy; import org.scm4j.vcs.api.workingcopy.IVCSRepositoryWorkspace; import org.scm4j.vcs.api.workingcopy.IVCSWorkspace; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.net.*; import java.net.Proxy.Type; import java.nio.charset.StandardCharsets; import java.util.*; public class GitVCS implements IVCS { public static final String GIT_VCS_TYPE_STRING = "git"; private static final String MASTER_BRANCH_NAME = "master"; private static final String REFS_REMOTES_ORIGIN = Constants.R_REMOTES + Constants.DEFAULT_REMOTE_NAME + "/"; private CredentialsProvider credentials; private final IVCSRepositoryWorkspace repo; public CredentialsProvider getCredentials() { return credentials; } public GitVCS(IVCSRepositoryWorkspace repo) { this.repo = repo; } public void setCredentials(CredentialsProvider credentials) { this.credentials = credentials; } private String getRealBranchName(String branchName) { return branchName == null ? MASTER_BRANCH_NAME : branchName; } public Git getLocalGit(IVCSLockedWorkingCopy wc) throws Exception { Repository gitRepo = new FileRepositoryBuilder() .setGitDir(new File(wc.getFolder(), ".git")) .build(); Boolean repoInited = gitRepo .getObjectDatabase() .exists(); if (!repoInited) { Git .cloneRepository() .setDirectory(wc.getFolder()) .setURI(repo.getRepoUrl()) .setCredentialsProvider(credentials) .setNoCheckout(true) //.setBranch(Constants.R_HEADS + Constants.MASTER) .call() .close(); } return new Git(gitRepo); } public VCSChangeType gitChangeTypeToVCSChangeType(ChangeType changeType) { switch (changeType) { case ADD: return VCSChangeType.ADD; case DELETE: return VCSChangeType.DELETE; case MODIFY: return VCSChangeType.MODIFY; default: return VCSChangeType.UNKNOWN; } } @Override public void createBranch(String srcBranchName, String newBranchName, String commitMessage) { // note: no commit message could be attached in Git try (IVCSLockedWorkingCopy wc = repo.getVCSLockedWorkingCopy(); Git git = getLocalGit(wc); Repository gitRepo = git.getRepository()) { checkout(git, gitRepo, srcBranchName); git .branchCreate() .setUpstreamMode(SetupUpstreamMode.TRACK) .setName(newBranchName) .call(); RefSpec refSpec = new RefSpec().setSourceDestination(newBranchName, newBranchName); push(git, refSpec); } catch (RefAlreadyExistsException e) { throw new EVCSBranchExists (e); } catch (GitAPIException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void deleteBranch(String branchName, String commitMessage) { try (IVCSLockedWorkingCopy wc = repo.getVCSLockedWorkingCopy(); Git git = getLocalGit(wc); Repository gitRepo = git.getRepository()) { checkout(git, gitRepo, MASTER_BRANCH_NAME); git .branchDelete() .setBranchNames(branchName) .setForce(true) // avoid "not merged" exception .call(); RefSpec refSpec = new RefSpec( ":refs/heads/" + branchName); push(git, refSpec); } catch (GitAPIException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } private void push(Git git, RefSpec refSpec) throws GitAPIException { PushCommand cmd = git .push() .setPushAll(); if (refSpec != null) { cmd.setRefSpecs(refSpec); } cmd .setRemote("origin") .setCredentialsProvider(credentials) .call(); } @Override public VCSMergeResult merge(String srcBranchName, String dstBranchName, String commitMessage) { try (IVCSLockedWorkingCopy wc = repo.getVCSLockedWorkingCopy(); Git git = getLocalGit(wc); Repository gitRepo = git.getRepository()) { checkout(git, gitRepo, dstBranchName); MergeResult mr = git .merge() .include(gitRepo.findRef("origin/" + getRealBranchName(srcBranchName))) .setMessage(commitMessage) .call(); Boolean success = !mr.getMergeStatus().equals(MergeResult.MergeStatus.CONFLICTING) && !mr.getMergeStatus().equals(MergeResult.MergeStatus.FAILED) && !mr.getMergeStatus().equals(MergeResult.MergeStatus.ABORTED) && !mr.getMergeStatus().equals(MergeResult.MergeStatus.NOT_SUPPORTED); List<String> conflictingFiles = new ArrayList<>(); if (!success) { conflictingFiles.addAll(mr.getConflicts().keySet()); try { git .reset() .setMode(ResetType.HARD) .call(); } catch(Exception e) { wc.setCorrupted(true); } } else { push(git, null); } return new VCSMergeResult(success, conflictingFiles); } catch (GitAPIException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void setCredentials(String user, String password) { setCredentials(new UsernamePasswordCredentialsProvider(user, password)); } @Override public void setProxy(final String host, final int port, final String proxyUser, final String proxyPassword) { ProxySelector.setDefault(new ProxySelector() { final ProxySelector delegate = ProxySelector.getDefault(); @Override public List<Proxy> select(URI uri) { if (uri.toString().toLowerCase().contains(repo.getRepoUrl().toLowerCase())) { return Collections.singletonList(new Proxy(Type.HTTP, InetSocketAddress .createUnresolved(host, port))); } else { return delegate == null ? Collections.singletonList(Proxy.NO_PROXY) : delegate.select(uri); } } @Override public void connectFailed(URI uri, SocketAddress sa, IOException ioe) { if (delegate != null) { delegate.connectFailed(uri, sa, ioe); } } }); Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { System.out.println(super.getRequestingSite().getHostName()); System.out.println(repo.getRepoUrl()); if (super.getRequestingSite().getHostName().contains(repo.getRepoUrl()) && super.getRequestingPort() == port) { return new PasswordAuthentication(proxyUser, proxyPassword.toCharArray()); } return super.getPasswordAuthentication(); } }); } @Override public String getRepoUrl() { return repo.getRepoUrl(); } private File getFileFromRepo(String branchName, String fileRelativePath) { try (IVCSLockedWorkingCopy wc = repo.getVCSLockedWorkingCopy(); Git git = getLocalGit(wc); Repository gitRepo = git.getRepository()) { checkout(git, gitRepo, branchName); return new File(wc.getFolder(), fileRelativePath); } catch (GitAPIException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public String getFileContent(String branchName, String fileRelativePath, String encoding) { File file = getFileFromRepo(branchName, fileRelativePath); if (!file.exists()) { throw new EVCSFileNotFound(String.format("File %s is not found", fileRelativePath)); } try { return IOUtils.toString(file.toURI(), encoding); } catch (Exception e) { throw new RuntimeException(e); } } @Override public VCSCommit setFileContent(String branchName, String filePath, String content, String commitMessage) { try (IVCSLockedWorkingCopy wc = repo.getVCSLockedWorkingCopy(); Git git = getLocalGit(wc); Repository gitRepo = git.getRepository()) { checkout(git, gitRepo, branchName); File file = new File(wc.getFolder(), filePath); if (!file.exists()) { FileUtils.forceMkdir(file.getParentFile()); file.createNewFile(); git .add() .addFilepattern(filePath) .call(); } try (FileWriter fw = new FileWriter(file, false)) { fw.write(content); } RevCommit newCommit = git .commit() .setOnly(filePath) .setMessage(commitMessage) .call(); String bn = getRealBranchName(branchName); RefSpec refSpec = new RefSpec(bn + ":" + bn); push(git, refSpec); return getVCSCommit(newCommit); } catch (GitAPIException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } void checkout(Git git, Repository gitRepo, String branchName) throws Exception { String bn = getRealBranchName(branchName); git .pull() .setCredentialsProvider(credentials) .call(); git .checkout() .setStartPoint("origin/" + bn) .setCreateBranch(gitRepo.exactRef("refs/heads/" + bn) == null) .setUpstreamMode(SetupUpstreamMode.TRACK) .setName(bn) .call(); } @Override public String getFileContent(String branchName, String filePath) { return getFileContent(branchName, filePath, StandardCharsets.UTF_8.name()); } @Override public List<VCSDiffEntry> getBranchesDiff(String srcBranchName, String dstBranchName) { try (IVCSLockedWorkingCopy wc = repo.getVCSLockedWorkingCopy(); Git git = getLocalGit(wc); Repository gitRepo = git.getRepository(); RevWalk walk = new RevWalk(gitRepo)) { String srcBN = getRealBranchName(srcBranchName); String dstBN = getRealBranchName(dstBranchName); RevCommit destHeadCommit = walk.parseCommit(git.getRepository().resolve("remotes/origin/" + dstBN)); ObjectReader reader = gitRepo.newObjectReader(); checkout(git, gitRepo, dstBranchName); git .merge() .include(gitRepo.findRef("origin/" + srcBN)) .setCommit(false) .call(); CanonicalTreeParser srcTreeIter = new CanonicalTreeParser(); srcTreeIter.reset(reader, destHeadCommit.getTree()); List<DiffEntry> diffs = git .diff() .setOldTree(srcTreeIter) .call(); List<VCSDiffEntry> res = new ArrayList<>(); for (DiffEntry diffEntry : diffs) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (DiffFormatter formatter = new DiffFormatter(baos)) { formatter.setRepository(git.getRepository()); formatter.format(diffEntry); } VCSDiffEntry vcsEntry = new VCSDiffEntry( diffEntry.getPath(diffEntry.getChangeType() == ChangeType.ADD ? Side.NEW : Side.OLD), gitChangeTypeToVCSChangeType(diffEntry.getChangeType()), baos.toString("UTF-8")); res.add(vcsEntry); } return res; } catch (GitAPIException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public Set<String> getBranches() { try (IVCSLockedWorkingCopy wc = repo.getVCSLockedWorkingCopy(); Git git = getLocalGit(wc); Repository gitRepo = git.getRepository()) { checkout(git, gitRepo, MASTER_BRANCH_NAME); List<Ref> refs = git .branchList() .setListMode(ListMode.REMOTE) .call(); Set<String> res = new HashSet<>(); for (Ref ref : refs) { res.add(ref.getName().replace(REFS_REMOTES_ORIGIN, "")); } return res; } catch (GitAPIException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public List<VCSCommit> log(String branchName, int limit) { try (IVCSLockedWorkingCopy wc = repo.getVCSLockedWorkingCopy(); Git git = getLocalGit(wc); Repository gitRepo = git.getRepository()) { LogCommand log = git .log() .add(gitRepo.resolve("refs/remotes/origin/" + getRealBranchName(branchName))); if (limit > 0) { log.setMaxCount(limit); } Iterable<RevCommit> logs = log.call(); List<VCSCommit> res = new ArrayList<>(); for (RevCommit commit : logs) { res.add(getVCSCommit(commit)); } return res; } catch (GitAPIException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public String getVCSTypeString() { return GIT_VCS_TYPE_STRING; } @Override public VCSCommit removeFile(String branchName, String filePath, String commitMessage) { try (IVCSLockedWorkingCopy wc = repo.getVCSLockedWorkingCopy(); Git git = getLocalGit(wc); Repository gitRepo = git.getRepository()) { checkout(git, gitRepo, branchName); git .rm() .addFilepattern(filePath) .setCached(false) .call(); RevCommit res = git .commit() .setMessage(commitMessage) .setAll(true) .call(); push(git, null); return getVCSCommit(res); } catch (GitAPIException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } private VCSCommit getVCSCommit(RevCommit revCommit) { return new VCSCommit(revCommit.getName(), revCommit.getFullMessage(), revCommit.getAuthorIdent().getName()); } public List<VCSCommit> getCommitsRange(String branchName, String afterCommitId, String untilCommitId) { try (IVCSLockedWorkingCopy wc = repo.getVCSLockedWorkingCopy(); Git git = getLocalGit(wc); Repository gitRepo = git.getRepository()) { checkout(git, gitRepo, branchName); String bn = getRealBranchName(branchName); ObjectId sinceCommit = afterCommitId == null ? getInitialCommit(gitRepo, bn).getId() : ObjectId.fromString(afterCommitId); ObjectId untilCommit = untilCommitId == null ? gitRepo.exactRef("refs/heads/" + bn).getObjectId() : ObjectId.fromString(untilCommitId); Iterable<RevCommit> commits; commits = git .log() .addRange(sinceCommit, untilCommit) .call(); List<VCSCommit> res = new ArrayList<>(); for (RevCommit commit : commits) { VCSCommit vcsCommit = getVCSCommit(commit); res.add(vcsCommit); } Collections.reverse(res); return res; } catch (GitAPIException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } private RevCommit getInitialCommit(Repository gitRepo, String branchName) throws Exception { try (RevWalk rw = new RevWalk(gitRepo)) { Ref ref = gitRepo.exactRef("refs/heads/" + branchName); ObjectId headCommitId = ref.getObjectId(); RevCommit root = rw.parseCommit(headCommitId); rw.markStart(root); rw.sort(RevSort.REVERSE); return rw.next(); } } @Override public IVCSWorkspace getWorkspace() { return repo.getWorkspace(); } @Override public List<VCSCommit> getCommitsRange(String branchName, String startFromCommitId, WalkDirection direction, int limit) { try (IVCSLockedWorkingCopy wc = repo.getVCSLockedWorkingCopy(); Git git = getLocalGit(wc); Repository gitRepo = git.getRepository()) { checkout(git, gitRepo, branchName); String bn = getRealBranchName(branchName); List<VCSCommit> res = new ArrayList<>(); try (RevWalk rw = new RevWalk(gitRepo)) { RevCommit startCommit; RevCommit endCommit; if (direction == WalkDirection.ASC) { Ref ref = gitRepo.exactRef("refs/heads/" + bn); ObjectId headCommitId = ref.getObjectId(); startCommit = rw.parseCommit( headCommitId ); ObjectId sinceCommit = startFromCommitId == null ? getInitialCommit(gitRepo, bn).getId() : ObjectId.fromString(startFromCommitId); endCommit = rw.parseCommit(sinceCommit); } else { ObjectId sinceCommit = startFromCommitId == null ? gitRepo.exactRef("refs/heads/" + bn).getObjectId() : ObjectId.fromString(startFromCommitId); startCommit = rw.parseCommit( sinceCommit ); endCommit = getInitialCommit(gitRepo, bn); } rw.markStart(startCommit); RevCommit commit = rw.next(); while (commit != null) { VCSCommit vcsCommit = getVCSCommit(commit); res.add(vcsCommit); if (commit.getName().equals(endCommit.getName())) { break; } commit = rw.next(); } } if (direction == WalkDirection.ASC) { Collections.reverse(res); } if (limit != 0) { res = res.subList(0, limit); } return res; } catch (GitAPIException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } private RevCommit getHeadRevCommit (String branchName) { try (IVCSLockedWorkingCopy wc = repo.getVCSLockedWorkingCopy(); Git git = getLocalGit(wc); Repository gitRepo = git.getRepository(); RevWalk rw = new RevWalk(gitRepo)) { String bn = getRealBranchName(branchName); Ref ref = gitRepo.exactRef("refs/remotes/origin/" + bn); ObjectId commitId = ref.getObjectId(); return rw.parseCommit( commitId ); } catch (GitAPIException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public VCSCommit getHeadCommit(String branchName) { RevCommit branchHeadCommit = getHeadRevCommit(getRealBranchName(branchName)); return getVCSCommit(branchHeadCommit); } @Override public String toString() { return "GitVCS [url=" + repo.getRepoUrl() + "]"; } @Override public Boolean fileExists(String branchName, String filePath) { return getFileFromRepo(branchName, filePath).exists(); } @Override public VCSTag createTag(String branchName, String tagName, String tagMessage) throws EVCSTagExists { try (IVCSLockedWorkingCopy wc = repo.getVCSLockedWorkingCopy(); Git git = getLocalGit(wc); Repository gitRepo = git.getRepository(); RevWalk rw = new RevWalk(gitRepo)) { checkout(git, gitRepo, branchName); Ref ref = git .tag() .setAnnotated(true) .setMessage(tagMessage) .setName(tagName) .setObjectId(null) //rw.gparseCommit(ObjectId.fromString(commitIdToTag))) .call(); push(git, new RefSpec(ref.getName())); RevTag revTag = rw.parseTag(ref.getObjectId()); RevCommit revCommit = rw.parseCommit(ref.getObjectId()); VCSCommit relatedCommit = getVCSCommit(revCommit); return new VCSTag(revTag.getTagName(), revTag.getFullMessage(), revTag.getTaggerIdent().getName(), relatedCommit); } catch(RefAlreadyExistsException e) { throw new EVCSTagExists(e); } catch (GitAPIException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public List<VCSTag> getTags() { try (IVCSLockedWorkingCopy wc = repo.getVCSLockedWorkingCopy(); Git git = getLocalGit(wc); Repository gitRepo = git.getRepository(); RevWalk rw = new RevWalk(gitRepo)) { List<Ref> tagRefs = getTagRefs(); List<VCSTag> res = new ArrayList<>(); RevTag revTag; RevCommit revCommit; for (Ref ref : tagRefs) { ObjectId relatedCommitObjectId = ref.getPeeledObjectId() == null ? ref.getObjectId() : ref.getPeeledObjectId(); revTag = rw.parseTag(ref.getObjectId()); revCommit = rw.parseCommit(relatedCommitObjectId); VCSCommit relatedCommit = getVCSCommit(revCommit); VCSTag tag = new VCSTag(revTag.getTagName(), revTag.getFullMessage(), revTag.getTaggerIdent().getName(), relatedCommit); res.add(tag); } return res; } catch (Exception e) { throw new RuntimeException(e); } } List<Ref> getTagRefs() throws Exception { try (IVCSLockedWorkingCopy wc = repo.getVCSLockedWorkingCopy(); Git git = getLocalGit(wc); Repository gitRepo = git.getRepository()) { checkout(git, gitRepo, MASTER_BRANCH_NAME); List<Ref> refs = git .tagList() .call(); return refs; } } @Override public VCSTag getLastTag() { List<Ref> tagRefs; try { tagRefs = getTagRefs(); if (tagRefs.isEmpty()) { return null; } } catch (Exception e) { throw new RuntimeException(e); } try (IVCSLockedWorkingCopy wc = repo.getVCSLockedWorkingCopy(); Git git = getLocalGit(wc); Repository gitRepo = git.getRepository(); RevWalk rw = new RevWalk(gitRepo)) { Collections.sort(tagRefs, new Comparator<Ref>() { public int compare(Ref o1, Ref o2) { try (Repository gitRepo = git.getRepository(); RevWalk rw = new RevWalk(gitRepo)) { // for exception rethrow test only Date d1 = rw.parseTag(o1.getObjectId()).getTaggerIdent().getWhen(); Date d2 = rw.parseTag(o2.getObjectId()).getTaggerIdent().getWhen(); return d1.compareTo(d2); } catch (Exception e) { throw new RuntimeException(e); } } }); Ref ref = tagRefs.get(tagRefs.size() - 1); RevCommit revCommit = rw.parseCommit(ref.getObjectId()); VCSCommit relatedCommit = getVCSCommit(revCommit); if (git.getRepository().peel(ref).getPeeledObjectId() == null) { return new VCSTag(ref.getName().replace("refs/tags/", ""), null, null, relatedCommit); } RevTag revTag = rw.parseTag(ref.getObjectId()); return new VCSTag(revTag.getTagName(), revTag.getFullMessage(), revTag.getTaggerIdent().getName(), relatedCommit); } catch (GitAPIException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void removeTag(String tagName) { try (IVCSLockedWorkingCopy wc = repo.getVCSLockedWorkingCopy(); Git git = getLocalGit(wc); Repository gitRepo = git.getRepository(); RevWalk rw = new RevWalk(gitRepo)) { checkout(git, gitRepo, MASTER_BRANCH_NAME); git .tagDelete() .setTags(tagName) .call(); push(git, new RefSpec(":refs/tags/" + tagName)); } catch (GitAPIException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } }
package edu.umich.intnw.scout; import java.net.SocketException; import edu.umich.mobility.networktest.NativeNetworkTest; import android.util.Log; public class NetworkTest { private static String TAG = NetworkTest.class.getName(); final private static int timeoutSecs = 5; public String localAddr; public String remoteAddr; public int bw_down_Bps; public int bw_up_Bps; public int rtt_ms; public NetworkTest(String local) { init(local, "141.212.110.115"); } public NetworkTest(String local, String remote) { init(local, remote); } public void init(String local, String remote) { localAddr = local; remoteAddr = remote; } public class NetworkTestException extends Exception { public NetworkTestException(String msg) { super(msg); } }; public void runTests() throws NetworkTestException { Log.d(TAG, "Starting tests on " + localAddr); NativeNetworkTest nativeTest = new NativeNetworkTest(localAddr, remoteAddr); try { Log.d(TAG, "Starting download test"); bw_down_Bps = nativeTest.runDownloadTest(timeoutSecs); Log.d(TAG, "Starting upload test"); bw_up_Bps = nativeTest.runUploadTest(timeoutSecs); Log.d(TAG, "Starting RTT test"); rtt_ms = nativeTest.runRTTTest(); Log.d(TAG, "Results: bw_down " + bw_down_Bps + " bw_up " + bw_up_Bps + " rtt " + rtt_ms); } catch (SocketException e) { throw new NetworkTestException(e.getMessage()); } } };
package org.scm4j.vcs; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.net.Authenticator; import java.net.InetSocketAddress; import java.net.PasswordAuthentication; import java.net.Proxy; import java.net.Proxy.Type; import java.net.ProxySelector; import java.net.SocketAddress; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.eclipse.jgit.api.CheckoutCommand; import org.eclipse.jgit.api.CreateBranchCommand.SetupUpstreamMode; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.ListBranchCommand.ListMode; import org.eclipse.jgit.api.LogCommand; import org.eclipse.jgit.api.MergeResult; import org.eclipse.jgit.api.PushCommand; import org.eclipse.jgit.api.ResetCommand.ResetType; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.api.errors.RefAlreadyExistsException; import org.eclipse.jgit.diff.DiffEntry; import org.eclipse.jgit.diff.DiffEntry.ChangeType; import org.eclipse.jgit.diff.DiffEntry.Side; import org.eclipse.jgit.diff.DiffFormatter; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.ObjectReader; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevObject; import org.eclipse.jgit.revwalk.RevSort; import org.eclipse.jgit.revwalk.RevTag; import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.storage.file.FileRepositoryBuilder; import org.eclipse.jgit.transport.CredentialsProvider; import org.eclipse.jgit.transport.RefSpec; import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider; import org.eclipse.jgit.treewalk.CanonicalTreeParser; import org.scm4j.vcs.api.IVCS; import org.scm4j.vcs.api.VCSChangeType; import org.scm4j.vcs.api.VCSCommit; import org.scm4j.vcs.api.VCSDiffEntry; import org.scm4j.vcs.api.VCSMergeResult; import org.scm4j.vcs.api.VCSTag; import org.scm4j.vcs.api.WalkDirection; import org.scm4j.vcs.api.exceptions.EVCSBranchExists; import org.scm4j.vcs.api.exceptions.EVCSException; import org.scm4j.vcs.api.exceptions.EVCSFileNotFound; import org.scm4j.vcs.api.exceptions.EVCSTagExists; import org.scm4j.vcs.api.workingcopy.IVCSLockedWorkingCopy; import org.scm4j.vcs.api.workingcopy.IVCSRepositoryWorkspace; import org.scm4j.vcs.api.workingcopy.IVCSWorkspace; public class GitVCS implements IVCS { public static final String GIT_VCS_TYPE_STRING = "git"; private static final String MASTER_BRANCH_NAME = "master"; private static final String REFS_REMOTES_ORIGIN = Constants.R_REMOTES + Constants.DEFAULT_REMOTE_NAME + "/"; private CredentialsProvider credentials; private final IVCSRepositoryWorkspace repo; public CredentialsProvider getCredentials() { return credentials; } public GitVCS(IVCSRepositoryWorkspace repo) { this.repo = repo; } public void setCredentials(CredentialsProvider credentials) { this.credentials = credentials; } private String getRealBranchName(String branchName) { return branchName == null ? MASTER_BRANCH_NAME : branchName; } protected Git getLocalGit(String folder) throws Exception { Repository gitRepo = new FileRepositoryBuilder() .setGitDir(new File(folder, ".git")) .build(); Boolean repoInited = gitRepo .getObjectDatabase() .exists(); if (!repoInited) { Git .cloneRepository() .setDirectory(new File(folder)) .setURI(repo.getRepoUrl()) .setCredentialsProvider(credentials) .setNoCheckout(true) .setCloneAllBranches(true) //.setBranch(Constants.R_HEADS + Constants.MASTER) .call() .close(); } return new Git(gitRepo); } protected Git getLocalGit(IVCSLockedWorkingCopy wc) throws Exception { return getLocalGit(wc.getFolder().getPath()); } public VCSChangeType gitChangeTypeToVCSChangeType(ChangeType changeType) { switch (changeType) { case ADD: return VCSChangeType.ADD; case DELETE: return VCSChangeType.DELETE; case MODIFY: return VCSChangeType.MODIFY; default: return VCSChangeType.UNKNOWN; } } @Override public void createBranch(String srcBranchName, String newBranchName, String commitMessage) { // note: no commit message could be attached in Git try (IVCSLockedWorkingCopy wc = repo.getVCSLockedWorkingCopy(); Git git = getLocalGit(wc); Repository gitRepo = git.getRepository()) { checkout(git, gitRepo, srcBranchName, null); git .branchCreate() .setUpstreamMode(SetupUpstreamMode.TRACK) .setName(newBranchName) .call(); RefSpec refSpec = new RefSpec().setSourceDestination(newBranchName, newBranchName); push(git, refSpec); } catch (RefAlreadyExistsException e) { throw new EVCSBranchExists (e); } catch (GitAPIException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void deleteBranch(String branchName, String commitMessage) { try (IVCSLockedWorkingCopy wc = repo.getVCSLockedWorkingCopy(); Git git = getLocalGit(wc); Repository gitRepo = git.getRepository()) { checkout(git, gitRepo, MASTER_BRANCH_NAME, null); git .branchDelete() .setBranchNames(branchName) .setForce(true) // avoid "not merged" exception .call(); RefSpec refSpec = new RefSpec( ":refs/heads/" + branchName); push(git, refSpec); } catch (GitAPIException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } private void push(Git git, RefSpec refSpec) throws GitAPIException { PushCommand cmd = git .push(); if (refSpec != null) { cmd.setRefSpecs(refSpec); } else { cmd.setPushAll(); } cmd .setRemote("origin") .setCredentialsProvider(credentials) .call(); } @Override public VCSMergeResult merge(String srcBranchName, String dstBranchName, String commitMessage) { try (IVCSLockedWorkingCopy wc = repo.getVCSLockedWorkingCopy(); Git git = getLocalGit(wc); Repository gitRepo = git.getRepository()) { checkout(git, gitRepo, dstBranchName, null); MergeResult mr = git .merge() .include(gitRepo.findRef("origin/" + getRealBranchName(srcBranchName))) .setMessage(commitMessage) .call(); Boolean success = !mr.getMergeStatus().equals(MergeResult.MergeStatus.CONFLICTING) && !mr.getMergeStatus().equals(MergeResult.MergeStatus.FAILED) && !mr.getMergeStatus().equals(MergeResult.MergeStatus.ABORTED) && !mr.getMergeStatus().equals(MergeResult.MergeStatus.NOT_SUPPORTED); List<String> conflictingFiles = new ArrayList<>(); if (!success) { conflictingFiles.addAll(mr.getConflicts().keySet()); try { git .reset() .setMode(ResetType.HARD) .call(); } catch(Exception e) { wc.setCorrupted(true); } } else { push(git, null); } return new VCSMergeResult(success, conflictingFiles); } catch (GitAPIException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void setCredentials(String user, String password) { setCredentials(new UsernamePasswordCredentialsProvider(user, password)); } @Override public void setProxy(final String host, final int port, final String proxyUser, final String proxyPassword) { ProxySelector.setDefault(new ProxySelector() { final ProxySelector delegate = ProxySelector.getDefault(); @Override public List<Proxy> select(URI uri) { if (uri.toString().toLowerCase().contains(repo.getRepoUrl().toLowerCase())) { return Collections.singletonList(new Proxy(Type.HTTP, InetSocketAddress .createUnresolved(host, port))); } else { return delegate == null ? Collections.singletonList(Proxy.NO_PROXY) : delegate.select(uri); } } @Override public void connectFailed(URI uri, SocketAddress sa, IOException ioe) { if (delegate != null) { delegate.connectFailed(uri, sa, ioe); } } }); Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { System.out.println(super.getRequestingSite().getHostName()); System.out.println(repo.getRepoUrl()); if (super.getRequestingSite().getHostName().contains(repo.getRepoUrl()) && super.getRequestingPort() == port) { return new PasswordAuthentication(proxyUser, proxyPassword.toCharArray()); } return super.getPasswordAuthentication(); } }); } @Override public String getRepoUrl() { return repo.getRepoUrl(); } @Override public String getFileContent(String branchName, String fileRelativePath, String revision) { try (IVCSLockedWorkingCopy wc = repo.getVCSLockedWorkingCopy(); Git git = getLocalGit(wc); Repository gitRepo = git.getRepository()) { checkout(git, gitRepo, branchName, revision); File file = new File(wc.getFolder(), fileRelativePath); if (!file.exists()) { throw new EVCSFileNotFound(String.format("File %s is not found", fileRelativePath)); } String res = IOUtils.toString(file.toURI(), StandardCharsets.UTF_8); if (revision != null) { // leaving Detached HEAD state String bn = getRealBranchName(branchName); git .checkout() .setStartPoint("origin/" + bn) .setCreateBranch(gitRepo.exactRef("refs/heads/" + bn) == null) .setUpstreamMode(SetupUpstreamMode.TRACK) .setName(bn) .call(); } return res; } catch(EVCSFileNotFound e) { throw e; } catch (GitAPIException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public VCSCommit setFileContent(String branchName, String filePath, String content, String commitMessage) { try (IVCSLockedWorkingCopy wc = repo.getVCSLockedWorkingCopy(); Git git = getLocalGit(wc); Repository gitRepo = git.getRepository()) { checkout(git, gitRepo, branchName, null); File file = new File(wc.getFolder(), filePath); if (!file.exists()) { FileUtils.forceMkdir(file.getParentFile()); file.createNewFile(); git .add() .addFilepattern(filePath) .call(); } try (FileWriter fw = new FileWriter(file, false)) { fw.write(content); } RevCommit newCommit = git .commit() .setOnly(filePath) .setMessage(commitMessage) .call(); String bn = getRealBranchName(branchName); RefSpec refSpec = new RefSpec(bn + ":" + bn); push(git, refSpec); return getVCSCommit(newCommit); } catch (GitAPIException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } void checkout(Git git, Repository gitRepo, String branchName, String revision) throws Exception { String bn = getRealBranchName(branchName); CheckoutCommand cmd = git.checkout(); if (revision == null) { git .pull() .call(); cmd .setStartPoint("origin/" + bn) .setCreateBranch(gitRepo.exactRef("refs/heads/" + bn) == null) .setUpstreamMode(SetupUpstreamMode.TRACK) .setName(bn) .call(); } else { try (RevWalk walk = new RevWalk(gitRepo)) { RevCommit commit = walk.parseCommit(RevCommit.fromString(revision)); // note: entering "detached HEAD" state here cmd .setName(commit.getName()) .call(); } } } @Override public List<VCSDiffEntry> getBranchesDiff(String srcBranchName, String dstBranchName) { try (IVCSLockedWorkingCopy wc = repo.getVCSLockedWorkingCopy(); Git git = getLocalGit(wc); Repository gitRepo = git.getRepository(); RevWalk walk = new RevWalk(gitRepo)) { String srcBN = getRealBranchName(srcBranchName); String dstBN = getRealBranchName(dstBranchName); RevCommit destHeadCommit = walk.parseCommit(git.getRepository().resolve("remotes/origin/" + dstBN)); ObjectReader reader = gitRepo.newObjectReader(); checkout(git, gitRepo, dstBranchName, null); git .merge() .include(gitRepo.findRef("origin/" + srcBN)) .setCommit(false) .call(); CanonicalTreeParser srcTreeIter = new CanonicalTreeParser(); srcTreeIter.reset(reader, destHeadCommit.getTree()); List<DiffEntry> diffs = git .diff() .setOldTree(srcTreeIter) .call(); List<VCSDiffEntry> res = new ArrayList<>(); for (DiffEntry diffEntry : diffs) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (DiffFormatter formatter = new DiffFormatter(baos)) { formatter.setRepository(git.getRepository()); formatter.format(diffEntry); } VCSDiffEntry vcsEntry = new VCSDiffEntry( diffEntry.getPath(diffEntry.getChangeType() == ChangeType.ADD ? Side.NEW : Side.OLD), gitChangeTypeToVCSChangeType(diffEntry.getChangeType()), baos.toString("UTF-8")); res.add(vcsEntry); } return res; } catch (GitAPIException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public Set<String> getBranches(String path) { try (IVCSLockedWorkingCopy wc = repo.getVCSLockedWorkingCopy(); Git git = getLocalGit(wc); Repository gitRepo = git.getRepository()) { git .pull() .call(); List<Ref> refs = git .branchList() .setListMode(ListMode.REMOTE) .call(); Set<String> res = new HashSet<>(); String bn; for (Ref ref : refs) { bn = ref.getName().replace(REFS_REMOTES_ORIGIN, ""); if (path == null) { res.add(bn); } else { if (bn.startsWith(path)) { res.add(bn); } } } return res; } catch (GitAPIException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public List<VCSCommit> log(String branchName, int limit) { try (IVCSLockedWorkingCopy wc = repo.getVCSLockedWorkingCopy(); Git git = getLocalGit(wc); Repository gitRepo = git.getRepository()) { LogCommand log = git .log() .add(gitRepo.resolve("refs/remotes/origin/" + getRealBranchName(branchName))); if (limit > 0) { log.setMaxCount(limit); } Iterable<RevCommit> logs = log.call(); List<VCSCommit> res = new ArrayList<>(); for (RevCommit commit : logs) { res.add(getVCSCommit(commit)); } return res; } catch (GitAPIException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public String getVCSTypeString() { return GIT_VCS_TYPE_STRING; } @Override public VCSCommit removeFile(String branchName, String filePath, String commitMessage) { try (IVCSLockedWorkingCopy wc = repo.getVCSLockedWorkingCopy(); Git git = getLocalGit(wc); Repository gitRepo = git.getRepository()) { checkout(git, gitRepo, branchName, null); git .rm() .addFilepattern(filePath) .setCached(false) .call(); RevCommit res = git .commit() .setMessage(commitMessage) .setAll(true) .call(); push(git, null); return getVCSCommit(res); } catch (GitAPIException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } protected VCSCommit getVCSCommit(RevCommit revCommit) { return new VCSCommit(revCommit.getName(), revCommit.getFullMessage(), revCommit.getAuthorIdent().getName()); } public List<VCSCommit> getCommitsRange(String branchName, String afterCommitId, String untilCommitId) { try (IVCSLockedWorkingCopy wc = repo.getVCSLockedWorkingCopy(); Git git = getLocalGit(wc); Repository gitRepo = git.getRepository()) { checkout(git, gitRepo, branchName, null); String bn = getRealBranchName(branchName); ObjectId sinceCommit = afterCommitId == null ? getInitialCommit(gitRepo, bn).getId() : ObjectId.fromString(afterCommitId); ObjectId untilCommit = untilCommitId == null ? gitRepo.exactRef("refs/heads/" + bn).getObjectId() : ObjectId.fromString(untilCommitId); Iterable<RevCommit> commits; commits = git .log() .addRange(sinceCommit, untilCommit) .call(); List<VCSCommit> res = new ArrayList<>(); for (RevCommit commit : commits) { VCSCommit vcsCommit = getVCSCommit(commit); res.add(vcsCommit); } Collections.reverse(res); return res; } catch (GitAPIException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } private RevCommit getInitialCommit(Repository gitRepo, String branchName) throws Exception { try (RevWalk rw = new RevWalk(gitRepo)) { Ref ref = gitRepo.exactRef("refs/heads/" + branchName); ObjectId headCommitId = ref.getObjectId(); RevCommit root = rw.parseCommit(headCommitId); rw.markStart(root); rw.sort(RevSort.REVERSE); return rw.next(); } } @Override public IVCSWorkspace getWorkspace() { return repo.getWorkspace(); } @Override public List<VCSCommit> getCommitsRange(String branchName, String startFromCommitId, WalkDirection direction, int limit) { try (IVCSLockedWorkingCopy wc = repo.getVCSLockedWorkingCopy(); Git git = getLocalGit(wc); Repository gitRepo = git.getRepository(); RevWalk rw = new RevWalk(gitRepo)) { checkout(git, gitRepo, branchName, null); String bn = getRealBranchName(branchName); List<VCSCommit> res = new ArrayList<>(); RevCommit startCommit; RevCommit endCommit; if (direction == WalkDirection.ASC) { Ref ref = gitRepo.exactRef("refs/heads/" + bn); ObjectId headCommitId = ref.getObjectId(); startCommit = rw.parseCommit( headCommitId ); ObjectId sinceCommit = startFromCommitId == null ? getInitialCommit(gitRepo, bn).getId() : ObjectId.fromString(startFromCommitId); endCommit = rw.parseCommit(sinceCommit); } else { ObjectId sinceCommit = startFromCommitId == null ? gitRepo.exactRef("refs/heads/" + bn).getObjectId() : ObjectId.fromString(startFromCommitId); startCommit = rw.parseCommit( sinceCommit ); endCommit = getInitialCommit(gitRepo, bn); } rw.markStart(startCommit); RevCommit commit = rw.next(); while (commit != null) { VCSCommit vcsCommit = getVCSCommit(commit); res.add(vcsCommit); if (commit.getName().equals(endCommit.getName())) { break; } commit = rw.next(); } if (direction == WalkDirection.ASC) { Collections.reverse(res); } if (limit != 0) { res = res.subList(0, limit); } return res; } catch (GitAPIException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } private RevCommit getHeadRevCommit (String branchName) { try (IVCSLockedWorkingCopy wc = repo.getVCSLockedWorkingCopy(); Git git = getLocalGit(wc); Repository gitRepo = git.getRepository(); RevWalk rw = new RevWalk(gitRepo)) { String bn = getRealBranchName(branchName); Ref ref = gitRepo.exactRef("refs/remotes/origin/" + bn); ObjectId commitId = ref.getObjectId(); return rw.parseCommit( commitId ); } catch (GitAPIException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public VCSCommit getHeadCommit(String branchName) { RevCommit branchHeadCommit = getHeadRevCommit(getRealBranchName(branchName)); return getVCSCommit(branchHeadCommit); } @Override public String toString() { return "GitVCS [url=" + repo.getRepoUrl() + "]"; } @Override public Boolean fileExists(String branchName, String filePath) { try (IVCSLockedWorkingCopy wc = repo.getVCSLockedWorkingCopy(); Git git = getLocalGit(wc); Repository gitRepo = git.getRepository()) { checkout(git, gitRepo, branchName, null); return new File(wc.getFolder(), filePath).exists(); } catch (GitAPIException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public VCSTag createTag(String branchName, String tagName, String tagMessage, String revisionToTag) throws EVCSTagExists { try (IVCSLockedWorkingCopy wc = repo.getVCSLockedWorkingCopy(); Git git = getLocalGit(wc); Repository gitRepo = git.getRepository(); RevWalk rw = new RevWalk(gitRepo)) { checkout(git, gitRepo, branchName, null); RevCommit commitToTag = revisionToTag == null ? null : rw.parseCommit(ObjectId.fromString(revisionToTag)); Ref ref = git .tag() .setAnnotated(true) .setMessage(tagMessage) .setName(tagName) .setObjectId(commitToTag) .call(); push(git, new RefSpec(ref.getName())); RevTag revTag = rw.parseTag(ref.getObjectId()); RevCommit revCommit = rw.parseCommit(ref.getObjectId()); VCSCommit relatedCommit = getVCSCommit(revCommit); return new VCSTag(revTag.getTagName(), revTag.getFullMessage(), revTag.getTaggerIdent().getName(), relatedCommit); } catch(RefAlreadyExistsException e) { throw new EVCSTagExists(e); } catch (GitAPIException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public List<VCSTag> getTags() { try (IVCSLockedWorkingCopy wc = repo.getVCSLockedWorkingCopy(); Git git = getLocalGit(wc); Repository gitRepo = git.getRepository(); RevWalk rw = new RevWalk(gitRepo)) { git.pull().call(); List<Ref> tagRefs = getTagRefs(); List<VCSTag> res = new ArrayList<>(); RevCommit revCommit; for (Ref ref : tagRefs) { ObjectId relatedCommitObjectId = ref.getPeeledObjectId() == null ? ref.getObjectId() : ref.getPeeledObjectId(); revCommit = rw.parseCommit(relatedCommitObjectId); VCSCommit relatedCommit = getVCSCommit(revCommit); RevObject revObject = rw.parseAny(ref.getObjectId()); VCSTag tag; if (revObject instanceof RevTag) { RevTag revTag = (RevTag) revObject; tag = new VCSTag(revTag.getTagName(), revTag.getFullMessage(), revTag.getTaggerIdent().getName(), relatedCommit); } else { tag = new VCSTag(ref.getName().replace("refs/tags/", ""), null, null, relatedCommit); } res.add(tag); } return res; } catch (Exception e) { throw new RuntimeException(e); } } List<Ref> getTagRefs() throws Exception { try (IVCSLockedWorkingCopy wc = repo.getVCSLockedWorkingCopy(); Git git = getLocalGit(wc); Repository gitRepo = git.getRepository()) { git.pull().call(); List<Ref> refs = git .tagList() .call(); return refs; } } @Override public void removeTag(String tagName) { try (IVCSLockedWorkingCopy wc = repo.getVCSLockedWorkingCopy(); Git git = getLocalGit(wc); Repository gitRepo = git.getRepository(); RevWalk rw = new RevWalk(gitRepo)) { checkout(git, gitRepo, MASTER_BRANCH_NAME, null); git .tagDelete() .setTags(tagName) .call(); push(git, new RefSpec(":refs/tags/" + tagName)); } catch (GitAPIException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void checkout(String branchName, String targetPath, String revision) { try (Git git = getLocalGit(targetPath); Repository gitRepo = git.getRepository()) { checkout(git, gitRepo, branchName, revision); } catch (GitAPIException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public List<VCSTag> getTagsOnRevision(String revision) { try (IVCSLockedWorkingCopy wc = repo.getVCSLockedWorkingCopy(); Git git = getLocalGit(wc); Repository gitRepo = git.getRepository(); RevWalk rw = new RevWalk(gitRepo)) { List<VCSTag> res = new ArrayList<>(); git.pull().call(); List<Ref> tagRefs = getTagRefs(); RevCommit revCommit; for (Ref ref : tagRefs) { ObjectId relatedCommitObjectId = ref.getPeeledObjectId() == null ? ref.getObjectId() : ref.getPeeledObjectId(); revCommit = rw.parseCommit(relatedCommitObjectId); if (revCommit.getName().equals(revision)) { VCSCommit relatedCommit = getVCSCommit(revCommit); RevObject revObject = rw.parseAny(ref.getObjectId()); if (revObject instanceof RevTag) { RevTag revTag = (RevTag) revObject; res.add(new VCSTag(revTag.getTagName(), revTag.getFullMessage(), revTag.getTaggerIdent().getName(), relatedCommit)); } else { res.add(new VCSTag(ref.getName().replace("refs/tags/", ""), null, null, relatedCommit)); } } } return res; } catch (GitAPIException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } }
package sc.fiji; import cleargl.*; import ij.ImagePlus; import net.imagej.ops.geom.geom3d.mesh.DefaultMesh; import net.imglib2.RealLocalizable; import sc.fiji.display.process.MeshConverter; import java.awt.AWTException; import java.awt.Rectangle; import java.awt.Robot; import java.awt.image.BufferedImage; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.concurrent.CopyOnWriteArrayList; import org.scijava.ui.behaviour.ClickBehaviour; import com.jogamp.opengl.GLAutoDrawable; import scenery.*; import scenery.controls.behaviours.ArcballCameraControl; import scenery.controls.behaviours.FPSCameraControl; import scenery.rendermodules.opengl.DeferredLightingRenderer; public class ThreeDViewer extends SceneryDefaultApplication { static ThreeDViewer viewer; static Thread animationThread; static Mesh aMesh = null; static Boolean defaultArcBall = true; public ThreeDViewer() { super("ThreeDViewer", 800, 600); } public ThreeDViewer(String applicationName, int windowWidth, int windowHeight) { super(applicationName, windowWidth, windowHeight); } public void init(GLAutoDrawable pDrawable) { setDeferredRenderer( new DeferredLightingRenderer( pDrawable.getGL().getGL4(), getGlWindow().getWidth(), getGlWindow().getHeight() ) ); getHub().add(SceneryElement.RENDERER, getDeferredRenderer()); PointLight[] lights = new PointLight[2]; for( int i = 0; i < lights.length; i++ ) { lights[i] = new PointLight(); lights[i].setPosition( new GLVector(2.0f * i, 2.0f * i, 2.0f * i) ); lights[i].setEmissionColor( new GLVector(1.0f, 0.0f, 1.0f) ); lights[i].setIntensity( 0.2f*(i+1) ); getScene().addChild( lights[i] ); } Camera cam = new DetachedHeadCamera(); cam.setPosition( new GLVector(0.0f, 0.0f, -5.0f) ); cam.setView( new GLMatrix().setCamera(cam.getPosition(), cam.getPosition().plus(cam.getForward()), cam.getUp()) ); cam.setProjection( new GLMatrix().setPerspectiveProjectionMatrix( (float) (70.0f / 180.0f * java.lang.Math.PI), 1024f / 1024f, 0.1f, 1000.0f) ); cam.setActive( true ); getScene().addChild(cam); getDeferredRenderer().initializeScene(getScene()); viewer = this; } public void inputSetup() { //setInputHandler((ClearGLInputHandler) viewer.getHub().get(SceneryElement.INPUT)); ClickBehaviour objectSelector = new ClickBehaviour() { public void click( int x, int y ) { System.out.println( "Clicked at x=" + x + " y=" + y ); } }; viewer.getInputHandler().useDefaultBindings(""); viewer.getInputHandler().addBehaviour("object_selection_mode", objectSelector); enableArcBallControl(); } public static void addBox() { addBox( new GLVector(0.0f, 0.0f, 0.0f) ); } public static void addBox( GLVector position ) { addBox( position, new GLVector(0.0f, 0.0f, 0.0f) ); } public static void addBox( GLVector position, GLVector size ) { addBox( position, size, new GLVector( 0.9f, 0.9f, 0.9f ) ); } public static void addBox( GLVector position, GLVector size, GLVector color ) { System.err.println( "Adding box" ); Material boxmaterial = new Material(); boxmaterial.setAmbient( new GLVector(1.0f, 0.0f, 0.0f) ); boxmaterial.setDiffuse( color ); boxmaterial.setSpecular( new GLVector(1.0f, 1.0f, 1.0f) ); boxmaterial.setDoubleSided(true); //boxmaterial.getTextures().put("diffuse", SceneViewer3D.class.getResource("textures/helix.png").getFile() ); final Box box = new Box( size ); box.setMaterial( boxmaterial ); box.setPosition( position ); //System.err.println( "Num elements in scene: " + viewer.getSceneNodes().size() ); viewer.getScene().addChild(box); if( defaultArcBall ) enableArcBallControl(); //System.err.println( "Num elements in scene: " + viewer.getSceneNodes().size() ); } public static void addSphere() { addSphere( new GLVector(0.0f, 0.0f, 0.0f), 1 ); } public static void addSphere( GLVector position, float radius ) { addSphere( position, radius, new GLVector( 0.9f, 0.9f, 0.9f ) ); } public static void addSphere( GLVector position, float radius, GLVector color ) { Material material = new Material(); material.setAmbient( new GLVector(1.0f, 0.0f, 0.0f) ); material.setDiffuse( color ); material.setSpecular( new GLVector(1.0f, 1.0f, 1.0f) ); //boxmaterial.getTextures().put("diffuse", SceneViewer3D.class.getResource("textures/helix.png").getFile() ); final Sphere sphere = new Sphere( radius, 20 ); sphere.setMaterial( material ); sphere.setPosition( position ); viewer.getScene().addChild(sphere); if( defaultArcBall ) enableArcBallControl(); } public static void addPointLight() { Material material = new Material(); material.setAmbient( new GLVector(1.0f, 0.0f, 0.0f) ); material.setDiffuse( new GLVector(0.0f, 1.0f, 0.0f) ); material.setSpecular( new GLVector(1.0f, 1.0f, 1.0f) ); //boxmaterial.getTextures().put("diffuse", SceneViewer3D.class.getResource("textures/helix.png").getFile() ); final PointLight light = new PointLight(); light.setMaterial( material ); light.setPosition( new GLVector(0.0f, 0.0f, 0.0f) ); viewer.getScene().addChild(light); } public static void writeSCMesh( String filename, Mesh scMesh ) { File f = new File( filename ); BufferedOutputStream out; try { out = new BufferedOutputStream( new FileOutputStream( f ) ); out.write( "solid STL generated by FIJI\n".getBytes() ); float[] verts = scMesh.getVertices(); float[] norms = scMesh.getNormals(); for( int k = 0; k < verts.length/9; k++ ) { int offset = k * 9; out.write( ("facet normal " + norms[offset] + " " + norms[offset+1] + " " + norms[offset+2] + "\n").getBytes() ); out.write( "outer loop\n".getBytes() ); for( int v = 0; v < 3; v++ ) { int voff = v*3; out.write( ( "vertex\t" + verts[offset+voff] + " " + verts[offset+voff+1] + " " + verts[offset+voff+2] + "\n" ).getBytes() ); } out.write( "endloop\n".getBytes() ); out.write( "endfacet\n".getBytes() ); } out.write( "endsolid vcg\n".getBytes() ); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void addSTL( String filename ) { Mesh scMesh = new Mesh(); scMesh.readFromSTL( filename ); net.imagej.ops.geom.geom3d.mesh.Mesh opsMesh = MeshConverter.getOpsMesh( scMesh ); //((DefaultMesh) opsMesh).centerMesh(); addMesh( opsMesh ); } public static void addObj( String filename ) { Mesh scMesh = new Mesh(); scMesh.readFromOBJ( filename, false );// Could check if there is a MTL to use to toggle flag net.imagej.ops.geom.geom3d.mesh.Mesh opsMesh = MeshConverter.getOpsMesh( scMesh ); //((DefaultMesh) opsMesh).centerMesh(); addMesh( opsMesh ); } public static void addMesh( net.imagej.ops.geom.geom3d.mesh.Mesh mesh ) { Mesh scMesh = MeshConverter.getSceneryMesh( mesh ); Material material = new Material(); material.setAmbient( new GLVector(1.0f, 0.0f, 0.0f) ); material.setDiffuse( new GLVector(0.0f, 1.0f, 0.0f) ); material.setSpecular( new GLVector(1.0f, 1.0f, 1.0f) ); material.setDoubleSided(true); scMesh.setMaterial( material ); scMesh.setPosition( new GLVector(1.0f, 1.0f, 1.0f) ); aMesh = scMesh; viewer.getScene().addChild( scMesh ); if( defaultArcBall ) enableArcBallControl(); // System.err.println( "Number of nodes in scene: " + ThreeDViewer.getSceneNodes().size() ); } public static void removeMesh( Mesh scMesh ) { viewer.getScene().removeChild( scMesh ); } public static Mesh getSelectedMesh() { return aMesh; } public static Thread getAnimationThread() { return ThreeDViewer.animationThread; } public static void setAnimationThread( Thread newAnimator ) { ThreeDViewer.animationThread = newAnimator; } public static void takeScreenshot() { float[] bounds = viewer.getGlWindow().getBounds(); // if we're in a jpanel, this isn't the way to get bounds try { Robot robot = new Robot(); BufferedImage screenshot = robot.createScreenCapture( new Rectangle( (int)bounds[0], (int)bounds[1], (int)bounds[2], (int)bounds[3] ) ); ImagePlus imp = new ImagePlus( "ThreeDViewer_Screenshot", screenshot ); imp.show(); } catch (AWTException e) { e.printStackTrace(); } } public static void enableArcBallControl() { GLVector target; if( getSelectedMesh() == null ) { target = new GLVector( 0, 0, 0 ); } else { net.imagej.ops.geom.geom3d.mesh.Mesh opsMesh = MeshConverter.getOpsMesh( getSelectedMesh() ); RealLocalizable center = ((DefaultMesh) opsMesh).getCenter(); target = new GLVector( center.getFloatPosition(0), center.getFloatPosition(1), center.getFloatPosition(2) ); } ArcballCameraControl targetArcball = new ArcballCameraControl("mouse_control", viewer.getScene().findObserver(), viewer.getGlWindow().getWidth(), viewer.getGlWindow().getHeight(), target); targetArcball.setMaximumDistance(Float.MAX_VALUE); viewer.getInputHandler().addBehaviour("mouse_control", targetArcball); viewer.getInputHandler().addBehaviour("scroll_arcball", targetArcball); viewer.getInputHandler().addKeyBinding("scroll_arcball", "scroll"); } public static void enableFPSControl() { FPSCameraControl fpsControl = new FPSCameraControl("mouse_control", viewer.getScene().findObserver(), viewer.getGlWindow().getWidth(), viewer.getGlWindow().getHeight()); viewer.getInputHandler().addBehaviour("mouse_control", fpsControl); viewer.getInputHandler().removeBehaviour("scroll_arcball"); } public static ThreeDViewer getViewer() { return viewer; } public static Node[] getSceneNodes() { CopyOnWriteArrayList<Node> children = viewer.getScene().getChildren(); return viewer.getScene().getChildren().toArray( new Node[children.size()] ); } public static void main(String... args) { ThreeDViewer viewer = new ThreeDViewer( "ThreeDViewer", 800, 600 ); viewer.main(); } }
package io.spine.server.procman; import com.google.common.annotations.VisibleForTesting; import com.google.protobuf.Message; import io.spine.core.CommandContext; import io.spine.core.CommandEnvelope; import io.spine.core.Event; import io.spine.core.EventEnvelope; import io.spine.core.MessageEnvelope; import io.spine.core.RejectionEnvelope; import io.spine.server.command.CommandHandlerMethod; import io.spine.server.command.CommandHandlingEntity; import io.spine.server.commandbus.CommandBus; import io.spine.server.event.EventReactorMethod; import io.spine.server.model.HandlerMethod; import io.spine.server.model.Model; import io.spine.server.rejection.RejectionReactorMethod; import io.spine.validate.ValidatingBuilder; import java.util.List; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; public abstract class ProcessManager<I, S extends Message, B extends ValidatingBuilder<S, ? extends Message.Builder>> extends CommandHandlingEntity<I, S, B> { /** The Command Bus to post routed commands. */ private volatile CommandBus commandBus; protected ProcessManager(I id) { super(id); } @Override protected ProcessManagerClass<?> getModelClass() { return Model.getInstance() .asProcessManagerClass(getClass()); } @Override protected ProcessManagerClass<?> thisClass() { return (ProcessManagerClass<?>) super.thisClass(); } /** The method to inject {@code CommandBus} instance from the repository. */ void setCommandBus(CommandBus commandBus) { this.commandBus = checkNotNull(commandBus); } /** Returns the {@code CommandBus} to which post commands produced by this process manager. */ protected CommandBus getCommandBus() { return commandBus; } @Override @VisibleForTesting protected B getBuilder() { return super.getBuilder(); } /** * Dispatches the command to the handler method and transforms the output * into a list of events. * * @param cmd the envelope with the command to dispatch * @return the list of events generated as the result of handling the command. */ @Override protected List<Event> dispatchCommand(CommandEnvelope cmd) { final CommandHandlerMethod method = thisClass().getHandler(cmd.getMessageClass()); final List<? extends Message> messages = method.invoke(this, cmd.getMessage(), cmd.getCommandContext()); final List<Event> result = toEvents(messages, cmd); return result; } /** * Transforms the passed list of event messages into the list of events. * * @param eventMessages event messages for which generate events * @param origin the envelope with the origin of events * @return list of events */ private List<Event> toEvents(List<? extends Message> eventMessages, MessageEnvelope origin) { return HandlerMethod.toEvents(getProducerId(), getVersion(), eventMessages, origin); } /** * Dispatches an event to the event reactor method of the process manager. * * @param event the envelope with the event * @return a list of produced events or an empty list if the process manager does not * produce new events because of the passed event */ List<Event> dispatchEvent(EventEnvelope event) { final EventReactorMethod method = thisClass().getReactor(event.getMessageClass()); final List<? extends Message> eventMessages = method.invoke(this, event.getMessage(), event.getEventContext()); final List<Event> events = toEvents(eventMessages, event); return events; } /** * Dispatches a rejection to the reacting method of the process manager. * * @param rejection the envelope with the rejection * @return a list of produced events or an empty list if the process manager does not * produce new events because of the passed event */ List<Event> dispatchRejection(RejectionEnvelope rejection) { final RejectionReactorMethod method = thisClass().getReactor(rejection.getMessageClass()); final List<? extends Message> eventMessages = method.invoke(this, rejection.getMessage(), rejection.getRejectionContext()); final List<Event> events = toEvents(eventMessages, rejection); return events; } protected CommandRouter newRouterFor(Message commandMessage, CommandContext commandContext) { checkNotNull(commandMessage); checkNotNull(commandContext); final CommandBus commandBus = ensureCommandBus(); final CommandRouter router = new CommandRouter(commandBus, commandMessage, commandContext); return router; } /** * Creates a new {@code IteratingCommandRouter}. * * <p>An {@code IteratingCommandRouter} allows to create several commands * in response to a command received by the {@code ProcessManager} and post these commands * one by one. * * <p>A typical usage looks like this: * <pre> * {@literal @}Assign * CommandRouted on(MyCommand message, CommandContext context) { * // Create new command messages here. * router = newIteratingRouterFor(message, context); * return router.add(messageOne) * .add(messageTwo) * .add(messageThree) * .routeFirst(); * } * * {@literal @}Subscribe * void on(EventOne message, EventContext context) { * if (router.hasNext()) { * router.routeNext(); * } * } * </pre> * * @param commandMessage the source command message * @param commandContext the context of the source command * @return new {@code IteratingCommandRouter} * @see IteratingCommandRouter#routeFirst() * @see IteratingCommandRouter#routeNext() */ protected IteratingCommandRouter newIteratingRouterFor(Message commandMessage, CommandContext commandContext) { checkNotNull(commandMessage); checkNotNull(commandContext); final CommandBus commandBus = ensureCommandBus(); final IteratingCommandRouter router = new IteratingCommandRouter(commandBus, commandMessage, commandContext); return router; } private CommandBus ensureCommandBus() { final CommandBus commandBus = getCommandBus(); checkState(commandBus != null, "CommandBus must be initialized"); return commandBus; } @Override protected String getMissingTxMessage() { return "ProcessManager modification is not available this way. " + "Please modify the state from a command handling or event reacting method."; } }
package com.breakersoft.plow.test; import static org.junit.Assert.*; import javax.annotation.Resource; import org.junit.Before; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; import com.breakersoft.plow.Cluster; import com.breakersoft.plow.Job; import com.breakersoft.plow.Project; import com.breakersoft.plow.Quota; import com.breakersoft.plow.rnd.thrift.Hardware; import com.breakersoft.plow.rnd.thrift.Ping; import com.breakersoft.plow.service.NodeService; import com.breakersoft.plow.service.ProjectService; import com.breakersoft.plow.thrift.Blueprint; import com.breakersoft.plow.thrift.JobBp; import com.breakersoft.plow.thrift.LayerBp; import com.google.common.collect.Lists; import com.google.common.collect.Sets; @Transactional @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={ "file:src/main/webapp/WEB-INF/spring/root-context.xml" }) public abstract class AbstractTest extends AbstractTransactionalJUnit4SpringContextTests { @Resource ProjectService projectService; @Resource NodeService nodeService; protected Project TEST_PROJECT; protected Cluster TEST_CLUSTER; protected Quota TEST_QUOTA; @Before public void initTestProject() { TEST_PROJECT = projectService.createProject("unittest", "Unit Test Project"); TEST_CLUSTER = nodeService.createCluster("unittest", "unittest"); TEST_QUOTA = nodeService.createQuota(TEST_PROJECT, TEST_CLUSTER, 10, 15); nodeService.setDefaultCluster(TEST_CLUSTER); } public Blueprint getTestBlueprint() { JobBp jbp = new JobBp(); jbp.setName("test"); jbp.setUid(100); jbp.setUsername("stella"); jbp.setPaused(false); jbp.setProject("unittest"); LayerBp layer = new LayerBp(); layer.setChunk(1); layer.setCommand(Lists.newArrayList("sleep", "5" )); layer.setMaxCores(8); layer.setMinCores(1); layer.setMinRamMb(1024); layer.setName("test_ls"); layer.setRange("1-10"); layer.setTags(Sets.newHashSet("unittest")); Blueprint bp = new Blueprint(); bp.job = jbp; bp.addToLayers(layer); return bp; } public Ping getTestNodePing() { Hardware hw = new Hardware(); hw.cpuModel = "Intel i7"; hw.platform = "OSX 10.8.1 x86_64"; hw.freeRamMb = 4096; hw.freeSwapMb = 1024; hw.physicalCpus = 2; hw.totalRamMb = 4096; hw.totalSwapMb = 1024; Ping ping = new Ping(); ping.bootTime = System.currentTimeMillis() - 1000; ping.hostname = "localhost"; ping.ipAddr = "127.0.0.1"; ping.isReboot = true; ping.tasks = Lists.newArrayList(); ping.hw = hw; return ping; } @SuppressWarnings("deprecation") public void assertFrameCount(Job job, int count) { assertEquals(count, simpleJdbcTemplate.queryForInt( "SELECT COUNT(1) FROM plow.task, plow.layer " + "WHERE task.pk_layer = layer.pk_layer AND layer.pk_job=?", job.getJobId())); } @SuppressWarnings("deprecation") public void assertLayerCount(Job job, int count) { assertEquals(count, simpleJdbcTemplate.queryForInt( "SELECT COUNT(1) FROM plow.layer " + "WHERE layer.pk_job=?", job.getJobId())); } }
package org.slf4j.event; import java.util.Queue; import org.slf4j.Logger; import org.slf4j.Marker; import org.slf4j.helpers.SubstituteLogger; public class EventRecodingLogger implements Logger { String name; SubstituteLogger logger; Queue<SubstituteLoggingEvent> eventQueue; public EventRecodingLogger(SubstituteLogger logger, Queue<SubstituteLoggingEvent> eventQueue) { this.logger = logger; this.name = logger.getName(); this.eventQueue = eventQueue; } public String getName() { return name; } private void recordEvent(Level level, String msg, Object[] args, Throwable throwable) { recordEvent(level, null, msg, args, throwable); } private void recordEvent(Level level, Marker marker, String msg, Object[] args, Throwable throwable) { // System.out.println("recording logger:"+name+", msg:"+msg); SubstituteLoggingEvent loggingEvent = new SubstituteLoggingEvent(); loggingEvent.setTimeStamp(System.currentTimeMillis()); loggingEvent.setLevel(level); loggingEvent.setLogger(logger); loggingEvent.setLoggerName(name); loggingEvent.setMarker(marker); loggingEvent.setMessage(msg); loggingEvent.setArgumentArray(args); loggingEvent.setThrowable(throwable); loggingEvent.setThreadName(Thread.currentThread().getName()); eventQueue.add(loggingEvent); } public boolean isTraceEnabled() { return true; } public void trace(String msg) { recordEvent(Level.TRACE, msg, null, null); } public void trace(String format, Object arg) { recordEvent(Level.TRACE, format, new Object[] { arg }, null); } public void trace(String format, Object arg1, Object arg2) { recordEvent(Level.TRACE, format, new Object[] { arg1, arg2 }, null); } public void trace(String format, Object... arguments) { recordEvent(Level.TRACE, format, arguments, null); } public void trace(String msg, Throwable t) { recordEvent(Level.TRACE, msg, null, t); } public boolean isTraceEnabled(Marker marker) { return true; } public void trace(Marker marker, String msg) { recordEvent(Level.TRACE, marker, msg, null, null); } public void trace(Marker marker, String format, Object arg) { recordEvent(Level.TRACE, marker, format, new Object[] { arg }, null); } public void trace(Marker marker, String format, Object arg1, Object arg2) { recordEvent(Level.TRACE, marker, format, new Object[] { arg1, arg2 }, null); } public void trace(Marker marker, String format, Object... argArray) { recordEvent(Level.TRACE, marker, format, argArray, null); } public void trace(Marker marker, String msg, Throwable t) { recordEvent(Level.TRACE, marker, msg, null, t); } public boolean isDebugEnabled() { return true; } public void debug(String msg) { recordEvent(Level.DEBUG, msg, null, null); } public void debug(String format, Object arg) { recordEvent(Level.DEBUG, format, new Object[] { arg }, null); } public void debug(String format, Object arg1, Object arg2) { recordEvent(Level.DEBUG, format, new Object[] { arg1, arg2 }, null); } public void debug(String format, Object... arguments) { recordEvent(Level.DEBUG, format, arguments, null); } public void debug(String msg, Throwable t) { recordEvent(Level.DEBUG, msg, null, t); } public boolean isDebugEnabled(Marker marker) { return true; } public void debug(Marker marker, String msg) { recordEvent(Level.DEBUG, marker, msg, null, null); } public void debug(Marker marker, String format, Object arg) { recordEvent(Level.DEBUG, marker, format, new Object[] { arg }, null); } public void debug(Marker marker, String format, Object arg1, Object arg2) { recordEvent(Level.DEBUG, marker, format, new Object[] { arg1, arg2 }, null); } public void debug(Marker marker, String format, Object... arguments) { recordEvent(Level.DEBUG, marker, format, arguments, null); } public void debug(Marker marker, String msg, Throwable t) { recordEvent(Level.DEBUG, marker, msg, null, t); } public boolean isInfoEnabled() { return true; } public void info(String msg) { recordEvent(Level.INFO, msg, null, null); } public void info(String format, Object arg) { recordEvent(Level.INFO, format, new Object[] { arg }, null); } public void info(String format, Object arg1, Object arg2) { recordEvent(Level.INFO, format, new Object[] { arg1, arg2 }, null); } public void info(String format, Object... arguments) { recordEvent(Level.INFO, format, arguments, null); } public void info(String msg, Throwable t) { recordEvent(Level.INFO, msg, null, t); } public boolean isInfoEnabled(Marker marker) { return true; } public void info(Marker marker, String msg) { recordEvent(Level.INFO, marker, msg, null, null); } public void info(Marker marker, String format, Object arg) { recordEvent(Level.INFO, marker, format, new Object[] { arg }, null); } public void info(Marker marker, String format, Object arg1, Object arg2) { recordEvent(Level.INFO, marker, format, new Object[] { arg1, arg2 }, null); } public void info(Marker marker, String format, Object... arguments) { recordEvent(Level.INFO, marker, format, arguments, null); } public void info(Marker marker, String msg, Throwable t) { recordEvent(Level.INFO, marker, msg, null, t); } public boolean isWarnEnabled() { return true; } public void warn(String msg) { recordEvent(Level.WARN, msg, null, null); } public void warn(String format, Object arg) { recordEvent(Level.WARN, format, new Object[] { arg }, null); } public void warn(String format, Object arg1, Object arg2) { recordEvent(Level.WARN, format, new Object[] { arg1, arg2 }, null); } public void warn(String format, Object... arguments) { recordEvent(Level.WARN, format, arguments, null); } public void warn(String msg, Throwable t) { recordEvent(Level.WARN, msg, null, t); } public boolean isWarnEnabled(Marker marker) { return true; } public void warn(Marker marker, String msg) { recordEvent(Level.WARN, marker, msg, null, null); } public void warn(Marker marker, String format, Object arg) { recordEvent(Level.WARN, format, new Object[] { arg }, null); } public void warn(Marker marker, String format, Object arg1, Object arg2) { recordEvent(Level.WARN, marker, format, new Object[] { arg1, arg2 }, null); } public void warn(Marker marker, String format, Object... arguments) { recordEvent(Level.WARN, marker, format, arguments, null); } public void warn(Marker marker, String msg, Throwable t) { recordEvent(Level.WARN, marker, msg, null, t); } public boolean isErrorEnabled() { return true; } public void error(String msg) { recordEvent(Level.ERROR, msg, null, null); } public void error(String format, Object arg) { recordEvent(Level.ERROR, format, new Object[] { arg }, null); } public void error(String format, Object arg1, Object arg2) { recordEvent(Level.ERROR, format, new Object[] { arg1, arg2 }, null); } public void error(String format, Object... arguments) { recordEvent(Level.ERROR, format, arguments, null); } public void error(String msg, Throwable t) { recordEvent(Level.ERROR, msg, null, t); } public boolean isErrorEnabled(Marker marker) { return true; } public void error(Marker marker, String msg) { recordEvent(Level.ERROR, marker, msg, null, null); } public void error(Marker marker, String format, Object arg) { recordEvent(Level.ERROR, marker, format, new Object[] { arg }, null); } public void error(Marker marker, String format, Object arg1, Object arg2) { recordEvent(Level.ERROR, marker, format, new Object[] { arg1, arg2 }, null); } public void error(Marker marker, String format, Object... arguments) { recordEvent(Level.ERROR, marker, format, arguments, null); } public void error(Marker marker, String msg, Throwable t) { recordEvent(Level.ERROR, marker, msg, null, t); } }
package test.SVPA; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.Collection; import java.util.LinkedList; import java.util.List; import com.google.common.collect.ImmutableList; import org.apache.commons.lang3.tuple.ImmutablePair; import org.junit.Test; import automata.AutomataException; import automata.svpa.Call; import automata.svpa.Internal; import automata.svpa.Return; import automata.svpa.SVPA; import automata.svpa.SVPAMove; import automata.svpa.TaggedSymbol; import automata.svpa.TaggedSymbol.SymbolTag; import theory.BooleanAlgebra; import theory.characters.BinaryCharPred; import theory.characters.CharPred; import theory.characters.ICharPred; import theory.characters.StdCharPred; import theory.intervals.EqualitySolver; import theory.intervals.UnaryCharIntervalSolver; public class SVPAUnitTest { @Test public void testCreateDot() { autA.createDotFile("vpaA", ""); } @Test public void testPropertiesAccessors() { assertTrue(autA.isDeterministic(ba)); assertTrue(autA.stateCount == 2); assertTrue(autA.transitionCount == 6); } @Test public void testEmptyFull() { SVPA<ICharPred, Character> empty = SVPA.getEmptySVPA(ba); SVPA<ICharPred, Character> full = SVPA.getFullSVPA(ba); assertTrue(empty.isEmpty); assertFalse(full.isEmpty); } @Test public void testAccept() { assertTrue(autA.accepts(ab, ba)); assertTrue(autA.accepts(anotb, ba)); assertFalse(autA.accepts(notab, ba)); assertFalse(autA.accepts(notanotb, ba)); assertTrue(autB.accepts(ab, ba)); assertFalse(autB.accepts(anotb, ba)); assertTrue(autB.accepts(notab, ba)); assertFalse(autB.accepts(notanotb, ba)); } @Test public void testIntersectionWith() { // Compute intersection SVPA<ICharPred, Character> inters = autA.intersectionWith(autB, ba); assertTrue(inters.accepts(ab, ba)); assertFalse(inters.accepts(anotb, ba)); assertFalse(inters.accepts(notab, ba)); assertFalse(inters.accepts(notanotb, ba)); } @Test public void testUnion() { // Compute union SVPA<ICharPred, Character> inters = autA.unionWith(autB, ba); assertTrue(inters.accepts(ab, ba)); assertTrue(inters.accepts(anotb, ba)); assertTrue(inters.accepts(notab, ba)); assertFalse(inters.accepts(notanotb, ba)); } @Test public void testMkTotal() { SVPA<ICharPred, Character> totA = autA.mkTotal(ba); assertTrue(totA.accepts(ab, ba)); assertTrue(totA.accepts(anotb, ba)); assertFalse(totA.accepts(notab, ba)); assertFalse(totA.accepts(notanotb, ba)); assertTrue(totA.stateCount == autA.stateCount + 1); assertTrue(totA.transitionCount == 21); } // @Test // public void testComplement() { // try { // Context c = new Context(); // Z3Provider<IntExpr> z3p = new Z3Provider<IntExpr>(c, c.IntSort()); // BooleanAlgebra<Predicate<IntExpr>, IntExpr> ba = z3p; // SVPA<Predicate<IntExpr>, IntExpr> autA = getSVPAa(c, ba); // SVPA<Predicate<IntExpr>, IntExpr> complementA = autA // .complement(ba); // SVPA<Predicate<IntExpr>, IntExpr> autB = getSVPAb(c, ba); // SVPA<Predicate<IntExpr>, IntExpr> complementB= autB // .complement(ba); // TaggedSymbol<IntExpr> c1 = new TaggedSymbol<IntExpr>(c.MkInt(1), // SymbolTag.Call); // TaggedSymbol<IntExpr> i1 = new TaggedSymbol<IntExpr>(c.MkInt(1), // SymbolTag.Internal); // TaggedSymbol<IntExpr> c5 = new TaggedSymbol<IntExpr>(c.MkInt(5), // SymbolTag.Call); // TaggedSymbol<IntExpr> r5 = new TaggedSymbol<IntExpr>(c.MkInt(5), // SymbolTag.Return); // TaggedSymbol<IntExpr> r6 = new TaggedSymbol<IntExpr>(c.MkInt(6), // SymbolTag.Return); // @SuppressWarnings("unchecked") // List<TaggedSymbol<IntExpr>> la = Arrays.asList(i1); // @SuppressWarnings("unchecked") // List<TaggedSymbol<IntExpr>> lb = Arrays.asList(c5,r6); // @SuppressWarnings("unchecked") // List<TaggedSymbol<IntExpr>> lab = Arrays.asList(c5,r5); // @SuppressWarnings("unchecked") // List<TaggedSymbol<IntExpr>> lnot = Arrays.asList(c1,r5); // assertTrue(autA.accepts(la, ba)); // assertFalse(autA.accepts(lb, ba)); // assertTrue(autA.accepts(lab, ba)); // assertFalse(autA.accepts(lnot, ba)); // assertFalse(complementA.accepts(la, ba)); // assertTrue(complementA.accepts(lb, ba)); // assertFalse(complementA.accepts(lab, ba)); // assertTrue(complementA.accepts(lnot, ba)); // assertFalse(autB.accepts(la, ba)); // assertTrue(autB.accepts(lb, ba)); // assertTrue(autB.accepts(lab, ba)); // assertFalse(autB.accepts(lnot, ba)); // assertTrue(complementB.accepts(la, ba)); // assertFalse(complementB.accepts(lb, ba)); // assertFalse(complementB.accepts(lab, ba)); // assertTrue(complementB.accepts(lnot, ba)); // } catch (Z3Exception e) { // System.out.print(e); // } catch (AutomataException e) { // System.out.print(e); // @Test // public void testDeterminization() { // try { // Context c = new Context(); // Z3Provider<IntExpr> z3p = new Z3Provider<IntExpr>(c, c.IntSort()); // BooleanAlgebra<Predicate<IntExpr>, IntExpr> ba = z3p; // SVPA<Predicate<IntExpr>, IntExpr> autA = getSVPAa(c, ba); // SVPA<Predicate<IntExpr>, IntExpr> detA= autA // .determinize(ba); // TaggedSymbol<IntExpr> c1 = new TaggedSymbol<IntExpr>(c.MkInt(1), // SymbolTag.Call); // TaggedSymbol<IntExpr> i1 = new TaggedSymbol<IntExpr>(c.MkInt(1), // SymbolTag.Internal); // TaggedSymbol<IntExpr> c5 = new TaggedSymbol<IntExpr>(c.MkInt(5), // SymbolTag.Call); // TaggedSymbol<IntExpr> r5 = new TaggedSymbol<IntExpr>(c.MkInt(5), // SymbolTag.Return); // TaggedSymbol<IntExpr> r6 = new TaggedSymbol<IntExpr>(c.MkInt(6), // SymbolTag.Return); // @SuppressWarnings("unchecked") // List<TaggedSymbol<IntExpr>> la = Arrays.asList(c5,i1,r5); // @SuppressWarnings("unchecked") // List<TaggedSymbol<IntExpr>> lb = Arrays.asList(c5,r6); // @SuppressWarnings("unchecked") // List<TaggedSymbol<IntExpr>> lab = Arrays.asList(c5,r5); // @SuppressWarnings("unchecked") // List<TaggedSymbol<IntExpr>> lnot = Arrays.asList(c1,r5); // assertTrue(autA.accepts(la, ba)); // assertFalse(autA.accepts(lb, ba)); // assertTrue(autA.accepts(lab, ba)); // assertFalse(autA.accepts(lnot, ba)); // assertTrue(detA.accepts(la, ba)); // assertFalse(detA.accepts(lb, ba)); // assertTrue(detA.accepts(lab, ba)); // assertFalse(detA.accepts(lnot, ba)); // } catch (Z3Exception e) { // System.out.print(e); // } catch (AutomataException e) { // System.out.print(e); // @Test // public void testEpsilonRem() { // try { // Context c = new Context(); // Z3Provider<IntExpr> z3p = new Z3Provider<IntExpr>(c, c.IntSort()); // BooleanAlgebra<Predicate<IntExpr>, IntExpr> ba = z3p; // SVPA<Predicate<IntExpr>, IntExpr> autA = getSVPAa(c, ba); // SVPA<Predicate<IntExpr>, IntExpr> epsFree= autA // .removeEpsilonMoves(ba); // TaggedSymbol<IntExpr> c1 = new TaggedSymbol<IntExpr>(c.MkInt(1), // SymbolTag.Call); // TaggedSymbol<IntExpr> i1 = new TaggedSymbol<IntExpr>(c.MkInt(1), // SymbolTag.Internal); // TaggedSymbol<IntExpr> c5 = new TaggedSymbol<IntExpr>(c.MkInt(5), // SymbolTag.Call); // TaggedSymbol<IntExpr> r5 = new TaggedSymbol<IntExpr>(c.MkInt(5), // SymbolTag.Return); // TaggedSymbol<IntExpr> r6 = new TaggedSymbol<IntExpr>(c.MkInt(6), // SymbolTag.Return); // @SuppressWarnings("unchecked") // List<TaggedSymbol<IntExpr>> la = Arrays.asList(i1); // @SuppressWarnings("unchecked") // List<TaggedSymbol<IntExpr>> lb = Arrays.asList(c5,r6); // @SuppressWarnings("unchecked") // List<TaggedSymbol<IntExpr>> lab = Arrays.asList(c5,r5); // @SuppressWarnings("unchecked") // List<TaggedSymbol<IntExpr>> lnot = Arrays.asList(c1,r5); // assertTrue(autA.accepts(la, ba)); // assertFalse(autA.accepts(lb, ba)); // assertTrue(autA.accepts(lab, ba)); // assertFalse(autA.accepts(lnot, ba)); // assertTrue(epsFree.accepts(la, ba)); // assertFalse(epsFree.accepts(lb, ba)); // assertTrue(epsFree.accepts(lab, ba)); // assertFalse(epsFree.accepts(lnot, ba)); // } catch (Z3Exception e) { // System.out.print(e); // } catch (AutomataException e) { // System.out.print(e); // @Test // public void testDiff() { // try { // Context c = new Context(); // Z3Provider<IntExpr> z3p = new Z3Provider<IntExpr>(c, c.IntSort()); // BooleanAlgebra<Predicate<IntExpr>, IntExpr> ba = z3p; // SVPA<Predicate<IntExpr>, IntExpr> autA = getSVPAa(c, ba); // SVPA<Predicate<IntExpr>, IntExpr> autB = getSVPAb(c, ba); // SVPA<Predicate<IntExpr>, IntExpr> diff = autA // .minus(autB, z3p); // TaggedSymbol<IntExpr> c1 = new TaggedSymbol<IntExpr>(c.MkInt(1), // SymbolTag.Call); // TaggedSymbol<IntExpr> i1 = new TaggedSymbol<IntExpr>(c.MkInt(1), // SymbolTag.Internal); // TaggedSymbol<IntExpr> c5 = new TaggedSymbol<IntExpr>(c.MkInt(5), // SymbolTag.Call); // TaggedSymbol<IntExpr> r5 = new TaggedSymbol<IntExpr>(c.MkInt(5), // SymbolTag.Return); // TaggedSymbol<IntExpr> r6 = new TaggedSymbol<IntExpr>(c.MkInt(6), // SymbolTag.Return); // @SuppressWarnings("unchecked") // List<TaggedSymbol<IntExpr>> a = Arrays.asList(i1); // @SuppressWarnings("unchecked") // List<TaggedSymbol<IntExpr>> b = Arrays.asList(c5,r6); // @SuppressWarnings("unchecked") // List<TaggedSymbol<IntExpr>> ab = Arrays.asList(c5,r5); // @SuppressWarnings("unchecked") // List<TaggedSymbol<IntExpr>> notab = Arrays.asList(c1,r5); // assertTrue(autA.accepts(a, ba)); // assertFalse(autA.accepts(b, ba)); // assertTrue(autA.accepts(ab, ba)); // assertFalse(autA.accepts(notab, ba)); // assertTrue(autB.accepts(b, ba)); // assertFalse(autB.accepts(a, ba)); // assertTrue(autB.accepts(ab, ba)); // assertFalse(autB.accepts(notab, ba)); // assertFalse(diff.accepts(ab, ba)); // assertTrue(diff.accepts(a, ba)); // assertFalse(diff.accepts(b, ba)); // assertFalse(diff.accepts(notab, ba)); // } catch (Z3Exception e) { // System.out.print(e); // } catch (AutomataException e) { // System.out.print(e); // @Test // public void testEquivalence() { // try { // Context c = new Context(); // Z3Provider<IntExpr> z3p = new Z3Provider<IntExpr>(c, c.IntSort()); // BooleanAlgebra<Predicate<IntExpr>, IntExpr> ba = z3p; // SVPA<Predicate<IntExpr>, IntExpr> autA = getSVPAa(c, ba); // SVPA<Predicate<IntExpr>, IntExpr> cA = autA // .complement(ba); // SVPA<Predicate<IntExpr>, IntExpr> cUcA = autA // .unionWith(cA, ba); // SVPA<Predicate<IntExpr>, IntExpr> ccA = cA // .complement(ba); // SVPA<Predicate<IntExpr>, IntExpr> autB = getSVPAb(c, ba); // SVPA<Predicate<IntExpr>, IntExpr> cB = autB // .complement(ba); // SVPA<Predicate<IntExpr>, IntExpr> cUcB = autB // .unionWith(cB, ba); // SVPA<Predicate<IntExpr>, IntExpr> ccB = cB // .complement(ba); // assertFalse(autA.isEquivalentTo(autB, ba)); // autA.createDotFile("a", ""); // autA.removeEpsilonMoves(ba).createDotFile("ae", ""); // autA.removeEpsilonMoves(ba).mkTotal(ba).createDotFile("at", ""); // autA.createDotFile("a1", ""); // autA.createDotFile("a1", ""); // autA.minus(ccA, ba).createDotFile("diff1", ""); // ccA.minus(autA, ba).createDotFile("diff2", ""); // cA.createDotFile("ca", ""); // ccA.createDotFile("cca", ""); // assertTrue(autA.isEquivalentTo(ccA, ba)); // assertTrue(autB.isEquivalentTo(ccB, ba)); // assertTrue(autA.isEquivalentTo(autA.intersectionWith(autA, ba), ba)); // assertTrue(SVPA.getEmptySVPA(ba).isEquivalentTo(autA.minus(autA, ba), // assertTrue(cUcA.isEquivalentTo(SVPA.getFullSVPA(ba), ba)); // assertTrue(cUcB.isEquivalentTo(SVPA.getFullSVPA(ba), ba)); // assertTrue(cUcB.isEquivalentTo(cUcA, ba)); // assertFalse(autB.isEquivalentTo(autA, ba)); // } catch (Z3Exception e) { // System.out.print(e); // } catch (AutomataException e) { // System.out.print(e); // @Test // public void testEpsRemove() { // try { // Context c = new Context(); // Z3Provider<IntExpr> z3p = new Z3Provider<IntExpr>(c, c.IntSort()); // BooleanAlgebra<Predicate<IntExpr>, IntExpr> ba = z3p; // //First Automaton // SVPA<Predicate<IntExpr>, IntExpr> autA = getSVPAa(c, ba); // //Second Automaton // SVPA<Predicate<IntExpr>, IntExpr> autAnoEps = // autA.removeEpsilonMoves(ba); // assertFalse(autA.isEpsilonFree); // assertTrue(autAnoEps.isEpsilonFree); // } catch (Z3Exception e) { // System.out.print(e); // } catch (AutomataException e) { // System.out.print(e); // @Test // public void testGetWitness() { // try { // Context c = new Context(); // Z3Provider<IntExpr> z3p = new Z3Provider<IntExpr>(c, c.IntSort()); // BooleanAlgebra<Predicate<IntExpr>, IntExpr> ba = z3p; // SVPA<Predicate<IntExpr>, IntExpr> autA = getSVPAa(c, ba); // autA.getWitness(ba); // } catch (Z3Exception e) { // System.out.print(e); // } catch (AutomataException e) { // System.out.print(e); // @Test // public void testReachRem() { // try { // Context c = new Context(); // Z3Provider<IntExpr> z3p = new Z3Provider<IntExpr>(c, c.IntSort()); // BooleanAlgebra<Predicate<IntExpr>, IntExpr> ba = z3p; // Predicate<IntExpr> geq0 = new Predicate<IntExpr>("x", c.MkGe( // (IntExpr) c.MkConst(c.MkSymbol("x"), c.IntSort()), // c.MkInt(0)), c.IntSort()); // Collection<SVPAMove<Predicate<IntExpr>, IntExpr>> transA = new // LinkedList<SVPAMove<Predicate<IntExpr>, IntExpr>>(); // transA.add(new Call<Predicate<IntExpr>, IntExpr>(0,1,0, // geq0)); // transA.add(new Return<Predicate<IntExpr>, IntExpr>(1,2,0, // geq0)); // //First Automaton // SVPA<Predicate<IntExpr>, IntExpr> autA = SVPA.MkSVPA(transA, // Arrays.asList(0), Arrays.asList(2), ba); // assertFalse(autA.isEmpty); // } catch (Z3Exception e) { // System.out.print(e); // } catch (AutomataException e) { // System.out.print(e); // Predicates UnaryCharIntervalSolver uba = new UnaryCharIntervalSolver(); EqualitySolver ba = new EqualitySolver(); CharPred alpha = StdCharPred.LOWER_ALPHA; CharPred allAlpha = StdCharPred.ALPHA; CharPred a = new CharPred('a'); CharPred num = StdCharPred.NUM; CharPred trueChar = StdCharPred.TRUE; CharPred trueRetChar = new CharPred(CharPred.MIN_CHAR, CharPred.MAX_CHAR, true); CharPred comma = new CharPred(','); Integer onlyX = 1; BinaryCharPred equality = new BinaryCharPred(StdCharPred.TRUE, true); TaggedSymbol<Character> ca = new TaggedSymbol<>('a', SymbolTag.Call); TaggedSymbol<Character> ra = new TaggedSymbol<>('a', SymbolTag.Return); TaggedSymbol<Character> cb = new TaggedSymbol<Character>('b', SymbolTag.Call); TaggedSymbol<Character> rb = new TaggedSymbol<Character>('b', SymbolTag.Return); TaggedSymbol<Character> c1 = new TaggedSymbol<Character>('1', SymbolTag.Call); TaggedSymbol<Character> r1 = new TaggedSymbol<Character>('1', SymbolTag.Return); TaggedSymbol<Character> ia = new TaggedSymbol<Character>('a', SymbolTag.Internal); TaggedSymbol<Character> ib = new TaggedSymbol<Character>('b', SymbolTag.Internal); TaggedSymbol<Character> i1 = new TaggedSymbol<Character>('1', SymbolTag.Internal); List<TaggedSymbol<Character>> matchedAlpha = Arrays.asList(ca, ra); List<TaggedSymbol<Character>> unmatchedAlpha = Arrays.asList(ca, ca, rb, ra); List<TaggedSymbol<Character>> hasNum = Arrays.asList(c1, r1, ca); List<TaggedSymbol<Character>> internalAlpha = Arrays.asList(ia, ib); List<TaggedSymbol<Character>> internalNum = Arrays.asList(ia, ib, i1); List<TaggedSymbol<Character>> ab = Arrays.asList(cb, ia, rb); List<TaggedSymbol<Character>> notab = Arrays.asList(cb, ia); List<TaggedSymbol<Character>> anotb = Arrays.asList(cb, ib, ca, ra, rb); List<TaggedSymbol<Character>> notanotb = Arrays.asList(ca, ib); SVPA<ICharPred, Character> autA = getSVPAa(ba); SVPA<ICharPred, Character> autB = getSVPAb(ba); SVPA<ICharPred, Character> autPeter = getCFGAutomata(ba); // Only accepts well-matched nested words of lower alphabetic chars private SVPA<ICharPred, Character> getSVPAa(BooleanAlgebra<ICharPred, Character> ba) { Collection<SVPAMove<ICharPred, Character>> transitions = new LinkedList<SVPAMove<ICharPred, Character>>(); transitions.add(new Internal<ICharPred, Character>(0, 0, alpha)); transitions.add(new Internal<ICharPred, Character>(1, 1, alpha)); transitions.add(new Call<ICharPred, Character>(0, 1, 0, alpha)); transitions.add(new Return<ICharPred, Character>(1, 0, 0, equality)); transitions.add(new Call<ICharPred, Character>(1, 1, 1, alpha)); transitions.add(new Return<ICharPred, Character>(1, 1, 1, equality)); try { return SVPA.MkSVPA(transitions, Arrays.asList(0), Arrays.asList(0), ba); } catch (AutomataException e) { return null; } } // Contains a somewhere as internal doesn't care about other symbols private SVPA<ICharPred, Character> getSVPAb(BooleanAlgebra<ICharPred, Character> ba) { Collection<SVPAMove<ICharPred, Character>> transitions = new LinkedList<SVPAMove<ICharPred, Character>>(); transitions.add(new Internal<ICharPred, Character>(0, 0, trueChar)); transitions.add(new Internal<ICharPred, Character>(1, 1, trueChar)); transitions.add(new Internal<ICharPred, Character>(0, 1, a)); transitions.add(new Call<ICharPred, Character>(0, 0, 0, trueChar)); transitions.add(new Return<ICharPred, Character>(0, 0, 0, trueRetChar)); transitions.add(new Call<ICharPred, Character>(1, 1, 0, trueChar)); transitions.add(new Return<ICharPred, Character>(1, 1, 0, trueRetChar)); try { return SVPA.MkSVPA(transitions, Arrays.asList(0), Arrays.asList(1), ba); } catch (AutomataException e) { return null; } } // Test from Peter Ohman private SVPA<ICharPred, Character> getCFGAutomata(BooleanAlgebra<ICharPred, Character> ba){ Collection<SVPAMove<ICharPred, Character>> transitions = new LinkedList<SVPAMove<ICharPred, Character>>(); // extra state "0" is prior to the entry of "main" transitions.add(new Internal<ICharPred, Character>(0, 1, new CharPred('1'))); transitions.add(new Call<ICharPred, Character>(1, 2, 1, new CharPred('2'))); transitions.add(new Internal<ICharPred, Character>(2, 3, new CharPred('3'))); transitions.add(new Internal<ICharPred, Character>(2, 4, new CharPred('4'))); transitions.add(new Call<ICharPred, Character>(3, 2, 3, new CharPred('2'))); transitions.add(new Return<ICharPred, Character>(4, 5, 3, new CharPred('5',true))); transitions.add(new Return<ICharPred, Character>(4, 6, 1, new CharPred('6',true))); transitions.add(new Return<ICharPred, Character>(4, 8, 7, new CharPred('8',true))); transitions.add(new Internal<ICharPred, Character>(5, 4, new CharPred('4'))); transitions.add(new Internal<ICharPred, Character>(6, 7, new CharPred('7'))); transitions.add(new Call<ICharPred, Character>(7, 2, 7, new CharPred('2'))); transitions.add(new Internal<ICharPred, Character>(8, 9, new CharPred('9'))); try { SVPA<ICharPred, Character> svpa = SVPA.MkSVPA(transitions, Arrays.asList(0), Arrays.asList(5), ba); //List<TaggedSymbol<Character>> l = svpa.getWitness(ba); //System.out.println(l); return svpa; } catch (AutomataException e) { return null; } } // Utility function for getBigIntersection() test private CharPred allCharsExcept(Character excluded, boolean returnPred){ if(excluded == null){ if(returnPred) return(trueRetChar); else return(StdCharPred.TRUE); } // weird stuff to avoid Java errors for increment/decrementing chars char prev = excluded; prev char next = excluded; next++; return(new CharPred(ImmutableList.of(ImmutablePair.of(CharPred.MIN_CHAR, prev), ImmutablePair.of(next, CharPred.MAX_CHAR)), returnPred)); } // Another test from Peter @Test public void getBigIntersection(){ EqualitySolver ba = new EqualitySolver(); Collection<SVPAMove<ICharPred, Character>> transitions1 = new LinkedList<SVPAMove<ICharPred, Character>>(); transitions1.add(new Internal<ICharPred, Character>(0, 1, new CharPred((char)0x0000))); transitions1.add(new Internal<ICharPred, Character>(3, 2, new CharPred((char)0x0001))); transitions1.add(new Internal<ICharPred, Character>(5, 4, new CharPred((char)0x0003))); transitions1.add(new Internal<ICharPred, Character>(4, 6, new CharPred((char)0x0005))); transitions1.add(new Internal<ICharPred, Character>(6, 7, new CharPred((char)0x0006))); transitions1.add(new Internal<ICharPred, Character>(7, 3, new CharPred((char)0x0002))); transitions1.add(new Internal<ICharPred, Character>(9, 8, new CharPred((char)0x0007))); transitions1.add(new Internal<ICharPred, Character>(11, 10, new CharPred((char)0x0009))); transitions1.add(new Internal<ICharPred, Character>(10, 12, new CharPred((char)0x000B))); transitions1.add(new Internal<ICharPred, Character>(14, 13, new CharPred((char)0x000C))); transitions1.add(new Internal<ICharPred, Character>(15, 14, new CharPred((char)0x000D))); transitions1.add(new Internal<ICharPred, Character>(17, 16, new CharPred((char)0x000F))); transitions1.add(new Internal<ICharPred, Character>(17, 18, new CharPred((char)0x0011))); transitions1.add(new Internal<ICharPred, Character>(18, 19, new CharPred((char)0x0012))); transitions1.add(new Internal<ICharPred, Character>(21, 20, new CharPred((char)0x0013))); transitions1.add(new Internal<ICharPred, Character>(21, 22, new CharPred((char)0x0015))); transitions1.add(new Internal<ICharPred, Character>(22, 17, new CharPred((char)0x0010))); transitions1.add(new Internal<ICharPred, Character>(24, 23, new CharPred((char)0x0016))); transitions1.add(new Internal<ICharPred, Character>(23, 21, new CharPred((char)0x0014))); transitions1.add(new Internal<ICharPred, Character>(25, 9, new CharPred((char)0x0008))); transitions1.add(new Internal<ICharPred, Character>(27, 26, new CharPred((char)0x0019))); transitions1.add(new Internal<ICharPred, Character>(27, 28, new CharPred((char)0x001B))); transitions1.add(new Internal<ICharPred, Character>(30, 29, new CharPred((char)0x001C))); transitions1.add(new Internal<ICharPred, Character>(32, 31, new CharPred((char)0x001E))); transitions1.add(new Internal<ICharPred, Character>(33, 31, new CharPred((char)0x001E))); transitions1.add(new Internal<ICharPred, Character>(34, 32, new CharPred((char)0x001F))); transitions1.add(new Internal<ICharPred, Character>(34, 33, new CharPred((char)0x0020))); transitions1.add(new Internal<ICharPred, Character>(36, 35, new CharPred((char)0x0022))); transitions1.add(new Internal<ICharPred, Character>(38, 37, new CharPred((char)0x0024))); transitions1.add(new Internal<ICharPred, Character>(38, 36, new CharPred((char)0x0023))); transitions1.add(new Internal<ICharPred, Character>(28, 39, new CharPred((char)0x0026))); transitions1.add(new Internal<ICharPred, Character>(41, 40, new CharPred((char)0x0027))); transitions1.add(new Internal<ICharPred, Character>(43, 42, new CharPred((char)0x0029))); transitions1.add(new Internal<ICharPred, Character>(35, 43, new CharPred((char)0x002A))); transitions1.add(new Internal<ICharPred, Character>(35, 44, new CharPred((char)0x002B))); transitions1.add(new Internal<ICharPred, Character>(46, 45, new CharPred((char)0x002C))); transitions1.add(new Internal<ICharPred, Character>(45, 47, new CharPred((char)0x002E))); transitions1.add(new Internal<ICharPred, Character>(47, 48, new CharPred((char)0x002F))); transitions1.add(new Internal<ICharPred, Character>(48, 49, new CharPred((char)0x0030))); transitions1.add(new Internal<ICharPred, Character>(49, 50, new CharPred((char)0x0031))); transitions1.add(new Internal<ICharPred, Character>(50, 51, new CharPred((char)0x0032))); transitions1.add(new Internal<ICharPred, Character>(51, 52, new CharPred((char)0x0033))); transitions1.add(new Internal<ICharPred, Character>(52, 53, new CharPred((char)0x0034))); transitions1.add(new Internal<ICharPred, Character>(53, 54, new CharPred((char)0x0035))); transitions1.add(new Internal<ICharPred, Character>(54, 55, new CharPred((char)0x0036))); transitions1.add(new Internal<ICharPred, Character>(56, 34, new CharPred((char)0x0021))); transitions1.add(new Internal<ICharPred, Character>(56, 57, new CharPred((char)0x0038))); transitions1.add(new Internal<ICharPred, Character>(59, 58, new CharPred((char)0x0039))); transitions1.add(new Internal<ICharPred, Character>(59, 60, new CharPred((char)0x003B))); transitions1.add(new Internal<ICharPred, Character>(57, 61, new CharPred((char)0x003C))); transitions1.add(new Internal<ICharPred, Character>(62, 59, new CharPred((char)0x003A))); transitions1.add(new Internal<ICharPred, Character>(64, 63, new CharPred((char)0x003E))); transitions1.add(new Internal<ICharPred, Character>(64, 65, new CharPred((char)0x0040))); transitions1.add(new Internal<ICharPred, Character>(67, 66, new CharPred((char)0x0041))); transitions1.add(new Internal<ICharPred, Character>(60, 64, new CharPred((char)0x003F))); transitions1.add(new Internal<ICharPred, Character>(69, 68, new CharPred((char)0x0043))); transitions1.add(new Internal<ICharPred, Character>(71, 70, new CharPred((char)0x0045))); transitions1.add(new Internal<ICharPred, Character>(70, 67, new CharPred((char)0x0042))); transitions1.add(new Internal<ICharPred, Character>(65, 69, new CharPred((char)0x0044))); transitions1.add(new Internal<ICharPred, Character>(73, 72, new CharPred((char)0x0047))); transitions1.add(new Internal<ICharPred, Character>(68, 73, new CharPred((char)0x0048))); transitions1.add(new Internal<ICharPred, Character>(75, 74, new CharPred((char)0x0049))); transitions1.add(new Internal<ICharPred, Character>(77, 76, new CharPred((char)0x004B))); transitions1.add(new Internal<ICharPred, Character>(79, 78, new CharPred((char)0x004D))); transitions1.add(new Internal<ICharPred, Character>(12, 79, new CharPred((char)0x004E))); transitions1.add(new Internal<ICharPred, Character>(31, 80, new CharPred((char)0x004F))); transitions1.add(new Internal<ICharPred, Character>(81, 21, new CharPred((char)0x0014))); transitions1.add(new Internal<ICharPred, Character>(82, 81, new CharPred((char)0x0050))); transitions1.add(new Internal<ICharPred, Character>(20, 82, new CharPred((char)0x0051))); transitions1.add(new Internal<ICharPred, Character>(16, 24, new CharPred((char)0x0017))); transitions1.add(new Internal<ICharPred, Character>(83, 15, new CharPred((char)0x000E))); transitions1.add(new Internal<ICharPred, Character>(72, 83, new CharPred((char)0x0052))); transitions1.add(new Internal<ICharPred, Character>(1, 84, new CharPred((char)0x0053))); transitions1.add(new Internal<ICharPred, Character>(84, 82, new CharPred((char)0x0051))); transitions1.add(new Internal<ICharPred, Character>(84, 85, new CharPred((char)0x0054))); transitions1.add(new Internal<ICharPred, Character>(85, 24, new CharPred((char)0x0017))); transitions1.add(new Internal<ICharPred, Character>(8, 86, new CharPred((char)0x0055))); transitions1.add(new Internal<ICharPred, Character>(86, 87, new CharPred((char)0x0056))); transitions1.add(new Internal<ICharPred, Character>(89, 88, new CharPred((char)0x0057))); transitions1.add(new Internal<ICharPred, Character>(90, 89, new CharPred((char)0x0058))); transitions1.add(new Internal<ICharPred, Character>(91, 75, new CharPred((char)0x004A))); transitions1.add(new Internal<ICharPred, Character>(55, 91, new CharPred((char)0x005A))); transitions1.add(new Internal<ICharPred, Character>(74, 92, new CharPred((char)0x005B))); transitions1.add(new Internal<ICharPred, Character>(92, 77, new CharPred((char)0x004C))); transitions1.add(new Internal<ICharPred, Character>(93, 90, new CharPred((char)0x0059))); transitions1.add(new Internal<ICharPred, Character>(76, 93, new CharPred((char)0x005C))); transitions1.add(new Internal<ICharPred, Character>(58, 64, new CharPred((char)0x003F))); transitions1.add(new Internal<ICharPred, Character>(95, 94, new CharPred((char)0x005D))); transitions1.add(new Internal<ICharPred, Character>(95, 96, new CharPred((char)0x005F))); transitions1.add(new Internal<ICharPred, Character>(98, 97, new CharPred((char)0x0060))); transitions1.add(new Internal<ICharPred, Character>(98, 99, new CharPred((char)0x0062))); transitions1.add(new Internal<ICharPred, Character>(97, 100, new CharPred((char)0x0063))); transitions1.add(new Internal<ICharPred, Character>(100, 101, new CharPred((char)0x0064))); transitions1.add(new Internal<ICharPred, Character>(101, 73, new CharPred((char)0x0048))); transitions1.add(new Internal<ICharPred, Character>(99, 100, new CharPred((char)0x0063))); transitions1.add(new Internal<ICharPred, Character>(94, 98, new CharPred((char)0x0061))); transitions1.add(new Internal<ICharPred, Character>(103, 102, new CharPred((char)0x0065))); transitions1.add(new Internal<ICharPred, Character>(63, 69, new CharPred((char)0x0044))); transitions1.add(new Internal<ICharPred, Character>(105, 104, new CharPred((char)0x0067))); transitions1.add(new Internal<ICharPred, Character>(107, 106, new CharPred((char)0x0069))); transitions1.add(new Internal<ICharPred, Character>(104, 108, new CharPred((char)0x006B))); transitions1.add(new Internal<ICharPred, Character>(108, 109, new CharPred((char)0x006C))); transitions1.add(new Internal<ICharPred, Character>(109, 11, new CharPred((char)0x000A))); transitions1.add(new Internal<ICharPred, Character>(111, 110, new CharPred((char)0x006D))); transitions1.add(new Internal<ICharPred, Character>(110, 105, new CharPred((char)0x0068))); transitions1.add(new Internal<ICharPred, Character>(113, 112, new CharPred((char)0x006F))); transitions1.add(new Internal<ICharPred, Character>(114, 113, new CharPred((char)0x0070))); transitions1.add(new Internal<ICharPred, Character>(115, 114, new CharPred((char)0x0071))); transitions1.add(new Internal<ICharPred, Character>(78, 116, new CharPred((char)0x0073))); transitions1.add(new Internal<ICharPred, Character>(117, 1, new CharPred((char)0x0000))); transitions1.add(new Internal<ICharPred, Character>(118, 5, new CharPred((char)0x0004))); transitions1.add(new Internal<ICharPred, Character>(29, 115, new CharPred((char)0x0072))); transitions1.add(new Internal<ICharPred, Character>(13, 119, new CharPred((char)0x0076))); transitions1.add(new Internal<ICharPred, Character>(96, 98, new CharPred((char)0x0061))); transitions1.add(new Internal<ICharPred, Character>(19, 120, new CharPred((char)0x0077))); transitions1.add(new Internal<ICharPred, Character>(122, 121, new CharPred((char)0x0078))); transitions1.add(new Internal<ICharPred, Character>(121, 111, new CharPred((char)0x006E))); transitions1.add(new Internal<ICharPred, Character>(124, 123, new CharPred((char)0x007A))); transitions1.add(new Internal<ICharPred, Character>(123, 125, new CharPred((char)0x007C))); transitions1.add(new Internal<ICharPred, Character>(127, 126, new CharPred((char)0x007D))); transitions1.add(new Internal<ICharPred, Character>(126, 124, new CharPred((char)0x007B))); transitions1.add(new Internal<ICharPred, Character>(129, 128, new CharPred((char)0x007F))); transitions1.add(new Internal<ICharPred, Character>(128, 127, new CharPred((char)0x007E))); transitions1.add(new Internal<ICharPred, Character>(88, 130, new CharPred((char)0x0081))); transitions1.add(new Internal<ICharPred, Character>(130, 129, new CharPred((char)0x0080))); transitions1.add(new Internal<ICharPred, Character>(125, 131, new CharPred((char)0x0082))); transitions1.add(new Internal<ICharPred, Character>(131, 132, new CharPred((char)0x0083))); transitions1.add(new Internal<ICharPred, Character>(87, 117, new CharPred((char)0x0074))); transitions1.add(new Internal<ICharPred, Character>(134, 133, new CharPred((char)0x0084))); transitions1.add(new Internal<ICharPred, Character>(133, 107, new CharPred((char)0x006A))); transitions1.add(new Internal<ICharPred, Character>(136, 135, new CharPred((char)0x0086))); transitions1.add(new Internal<ICharPred, Character>(135, 137, new CharPred((char)0x0088))); transitions1.add(new Internal<ICharPred, Character>(2, 136, new CharPred((char)0x0087))); transitions1.add(new Internal<ICharPred, Character>(139, 138, new CharPred((char)0x0089))); transitions1.add(new Internal<ICharPred, Character>(138, 134, new CharPred((char)0x0085))); transitions1.add(new Internal<ICharPred, Character>(137, 140, new CharPred((char)0x008B))); transitions1.add(new Internal<ICharPred, Character>(140, 139, new CharPred((char)0x008A))); transitions1.add(new Internal<ICharPred, Character>(141, 122, new CharPred((char)0x0079))); transitions1.add(new Internal<ICharPred, Character>(142, 141, new CharPred((char)0x008C))); transitions1.add(new Internal<ICharPred, Character>(143, 142, new CharPred((char)0x008D))); transitions1.add(new Internal<ICharPred, Character>(144, 143, new CharPred((char)0x008E))); transitions1.add(new Internal<ICharPred, Character>(145, 144, new CharPred((char)0x008F))); transitions1.add(new Internal<ICharPred, Character>(146, 145, new CharPred((char)0x0090))); transitions1.add(new Internal<ICharPred, Character>(148, 147, new CharPred((char)0x0092))); transitions1.add(new Internal<ICharPred, Character>(132, 146, new CharPred((char)0x0091))); transitions1.add(new Internal<ICharPred, Character>(61, 103, new CharPred((char)0x0066))); transitions1.add(new Internal<ICharPred, Character>(61, 149, new CharPred((char)0x0094))); transitions1.add(new Internal<ICharPred, Character>(149, 102, new CharPred((char)0x0065))); transitions1.add(new Internal<ICharPred, Character>(150, 40, new CharPred((char)0x0027))); transitions1.add(new Internal<ICharPred, Character>(40, 56, new CharPred((char)0x0037))); transitions1.add(new Internal<ICharPred, Character>(26, 39, new CharPred((char)0x0026))); transitions1.add(new Internal<ICharPred, Character>(39, 150, new CharPred((char)0x0095))); transitions1.add(new Internal<ICharPred, Character>(39, 41, new CharPred((char)0x0028))); transitions1.add(new Internal<ICharPred, Character>(152, 151, new CharPred((char)0x0096))); transitions1.add(new Internal<ICharPred, Character>(153, 152, new CharPred((char)0x0097))); transitions1.add(new Internal<ICharPred, Character>(106, 153, new CharPred((char)0x0098))); transitions1.add(new Internal<ICharPred, Character>(155, 154, new CharPred((char)0x0099))); transitions1.add(new Internal<ICharPred, Character>(156, 155, new CharPred((char)0x009A))); transitions1.add(new Internal<ICharPred, Character>(157, 156, new CharPred((char)0x009B))); transitions1.add(new Internal<ICharPred, Character>(151, 157, new CharPred((char)0x009C))); transitions1.add(new Internal<ICharPred, Character>(158, 46, new CharPred((char)0x002D))); transitions1.add(new Internal<ICharPred, Character>(154, 158, new CharPred((char)0x009D))); transitions1.add(new Internal<ICharPred, Character>(160, 159, new CharPred((char)0x009E))); transitions1.add(new Internal<ICharPred, Character>(66, 161, new CharPred((char)0x00A0))); transitions1.add(new Internal<ICharPred, Character>(162, 71, new CharPred((char)0x0046))); transitions1.add(new Internal<ICharPred, Character>(159, 162, new CharPred((char)0x00A1))); transitions1.add(new Internal<ICharPred, Character>(161, 25, new CharPred((char)0x0018))); transitions1.add(new Internal<ICharPred, Character>(116, 160, new CharPred((char)0x009F))); transitions1.add(new Internal<ICharPred, Character>(102, 80, new CharPred((char)0x004F))); transitions1.add(new Internal<ICharPred, Character>(112, 118, new CharPred((char)0x0075))); transitions1.add(new Internal<ICharPred, Character>(163, 27, new CharPred((char)0x001A))); transitions1.add(new Internal<ICharPred, Character>(164, 163, new CharPred((char)0x00A2))); transitions1.add(new Internal<ICharPred, Character>(164, 38, new CharPred((char)0x0025))); transitions1.add(new Internal<ICharPred, Character>(165, 164, new CharPred((char)0x00A3))); transitions1.add(new Internal<ICharPred, Character>(147, 165, new CharPred((char)0x00A4))); transitions1.add(new Internal<ICharPred, Character>(166, 148, new CharPred((char)0x0093))); transitions1.add(new Internal<ICharPred, Character>(120, 166, new CharPred((char)0x00A5))); transitions1.add(new Internal<ICharPred, Character>(80, 62, new CharPred((char)0x003D))); transitions1.add(new Internal<ICharPred, Character>(80, 95, new CharPred((char)0x005E))); transitions1.add(new Internal<ICharPred, Character>(37, 35, new CharPred((char)0x0022))); transitions1.add(new Internal<ICharPred, Character>(42, 56, new CharPred((char)0x0037))); transitions1.add(new Internal<ICharPred, Character>(44, 42, new CharPred((char)0x0029))); // 2 goes here (it's still slow even without this one)... Collection<SVPAMove<ICharPred, Character>> transitions3 = new LinkedList<SVPAMove<ICharPred, Character>>(); transitions3.add(new Internal<ICharPred, Character>(0, 0, allCharsExcept((char)0x000F, false))); transitions3.add(new Call<ICharPred, Character>(0, 0, 0, allCharsExcept((char)0x000F, false))); transitions3.add(new Return<ICharPred, Character>(0, 0, 0, allCharsExcept((char)0x000F, true))); Collection<SVPAMove<ICharPred, Character>> transitions4 = new LinkedList<SVPAMove<ICharPred, Character>>(); transitions4.add(new Internal<ICharPred, Character>(0, 0, StdCharPred.TRUE)); transitions4.add(new Call<ICharPred, Character>(0, 0, 0, StdCharPred.TRUE)); transitions4.add(new Return<ICharPred, Character>(0, 0, 0, trueRetChar)); transitions4.add(new Internal<ICharPred, Character>(0, 1, new CharPred((char)0x0016))); transitions4.add(new Internal<ICharPred, Character>(1, 1, StdCharPred.TRUE)); transitions4.add(new Call<ICharPred, Character>(1, 1, 0, StdCharPred.TRUE)); transitions4.add(new Return<ICharPred, Character>(1, 1, 0, trueRetChar)); transitions4.add(new Internal<ICharPred, Character>(1, 2, new CharPred((char)0x0014))); transitions4.add(new Internal<ICharPred, Character>(2, 2, StdCharPred.TRUE)); transitions4.add(new Call<ICharPred, Character>(2, 2, 0, StdCharPred.TRUE)); transitions4.add(new Return<ICharPred, Character>(2, 2, 0, trueRetChar)); Collection<SVPAMove<ICharPred, Character>> transitions5 = new LinkedList<SVPAMove<ICharPred, Character>>(); transitions5.add(new Internal<ICharPred, Character>(0, 0, StdCharPred.TRUE)); transitions5.add(new Call<ICharPred, Character>(0, 0, 0, StdCharPred.TRUE)); transitions5.add(new Return<ICharPred, Character>(0, 0, 0, trueRetChar)); transitions5.add(new Internal<ICharPred, Character>(0, 1, new CharPred((char)0x0050))); transitions5.add(new Internal<ICharPred, Character>(1, 1, StdCharPred.TRUE)); transitions5.add(new Call<ICharPred, Character>(1, 1, 0, StdCharPred.TRUE)); transitions5.add(new Return<ICharPred, Character>(1, 1, 0, trueRetChar)); transitions5.add(new Internal<ICharPred, Character>(1, 2, new CharPred((char)0x0014))); transitions5.add(new Internal<ICharPred, Character>(2, 2, StdCharPred.TRUE)); transitions5.add(new Call<ICharPred, Character>(2, 2, 0, StdCharPred.TRUE)); transitions5.add(new Return<ICharPred, Character>(2, 2, 0, trueRetChar)); try { SVPA<ICharPred, Character> svpa1 = SVPA.MkSVPA(transitions1, Arrays.asList(0), Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166), ba); SVPA<ICharPred, Character> svpa3 = SVPA.MkSVPA(transitions3, Arrays.asList(0), Arrays.asList(0), ba); SVPA<ICharPred, Character> svpa4 = SVPA.MkSVPA(transitions4, Arrays.asList(0), Arrays.asList(2), ba); SVPA<ICharPred, Character> svpa5 = SVPA.MkSVPA(transitions5, Arrays.asList(0), Arrays.asList(2), ba); SVPA<ICharPred, Character> result = svpa1.intersectionWith(svpa3, ba); result = result.intersectionWith(svpa4, ba); result = result.intersectionWith(svpa5, ba); assertFalse(result.isEmpty); } catch (AutomataException e) { assertTrue(false); } } }
package org.eclipse.xtext.splitting; import java.io.BufferedReader; import java.io.FileReader; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ValidateSplitting { public static final Set<String> REPOSITORIES = Collections.unmodifiableSet(new LinkedHashSet<>(Arrays.asList( "core", "extras", "lib", "xtend", "eclipse", "idea", "web", "maven" ))); public static final String DELETE = "delete"; public static void main(String[] args) { if (args.length != 2) { fail("Expected paths to splitting.txt and output files as arguments."); } String outputDir = args[1]; try { // Validate repositories and gather all paths from the splitting file final Set<String> specifiedPaths = new HashSet<>(); try (BufferedReader reader = new BufferedReader(new FileReader(args[0]))) { String line; while ((line = reader.readLine()) != null) { if (!line.isEmpty()) { String[] parts = line.split(">>"); if (parts.length != 2) fail("Invalid line: " + line); if (!DELETE.equals(parts[1].trim())) { String[] repos = parts[1].split(","); if (repos.length == 0) fail("Invalid line: " + line); for (String repo : repos) { String trimmed = repo.trim(); if (!REPOSITORIES.contains(trimmed)) fail("Invalid repository: " + trimmed); } } String path = parts[0].trim(); specifiedPaths.add(path); } } } // Check whether any path has an ambiguous specification final Pattern segmentPattern = Pattern.compile("/"); for (String path : specifiedPaths) { Matcher matcher = segmentPattern.matcher(path); while (matcher.find()) { if (specifiedPaths.contains(path.substring(0, matcher.start()))) fail("Path has ambiguous specification: " + path); } } // Check whether each file has a specified path as prefix try (BufferedReader reader = new BufferedReader(new FileReader(outputDir + "/" + FindProjects.ALL_FILES))) { String line; while ((line = reader.readLine()) != null) { if (!line.isEmpty()) { String file = line.replaceAll("\"|\\\\.", ""); if (!specifiedPaths.contains(file)) { Matcher matcher = segmentPattern.matcher(file); boolean foundSplitting = false; while (!foundSplitting && matcher.find()) { if (specifiedPaths.contains(file.substring(0, matcher.start()))) foundSplitting = true; } if (!foundSplitting) fail("File not covered by splitting: " + file); } } } } } catch (Exception e) { e.printStackTrace(); System.exit(1); } } private static void fail(String message) { System.err.print("ERROR: "); System.err.println(message); System.exit(1); } }
package org.pentaho.di.ui.core.widget; import java.util.Arrays; import org.eclipse.jface.window.DefaultToolTip; import org.eclipse.jface.window.ToolTip; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CCombo; import org.eclipse.swt.events.FocusAdapter; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.List; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.pentaho.di.core.Const; import org.pentaho.di.core.variables.VariableSpace; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.ui.core.PropsUI; import org.pentaho.di.ui.core.gui.GUIResource; public class ControlSpaceKeyAdapter extends KeyAdapter { private static Class<?> PKG = ControlSpaceKeyAdapter.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$ private static final PropsUI props = PropsUI.getInstance(); private GetCaretPositionInterface getCaretPositionInterface; private InsertTextInterface insertTextInterface; private VariableSpace variables; private Control control; /** * @param space * @param control a Text or CCombo box object */ public ControlSpaceKeyAdapter(final VariableSpace space, final Control control) { this(space, control, null, null); } /** * * @param space * @param control a Text or CCombo box object * @param getCaretPositionInterface * @param insertTextInterface */ public ControlSpaceKeyAdapter(VariableSpace space, final Control control, final GetCaretPositionInterface getCaretPositionInterface, final InsertTextInterface insertTextInterface) { this.variables = space; this.control = control; this.getCaretPositionInterface = getCaretPositionInterface; this.insertTextInterface = insertTextInterface; } /** * PDI-1284 * in chinese window, Ctrl-SPACE is reversed by system for input chinese character. * use Ctrl-ALT-SPACE instead. * @param e * @return */ private boolean isHotKey(KeyEvent e) { if (System.getProperty("user.language").equals("zh")) return e.character == ' ' && ((e.stateMask & SWT.CONTROL) != 0) && ((e.stateMask & SWT.ALT) != 0); // Detect Command-space on Mac OS X to fix PDI-4319 else if (System.getProperty("os.name").startsWith("Mac OS X")) return e.character == ' ' && ((e.stateMask & SWT.MOD1) != 0) && ((e.stateMask & SWT.ALT) == 0); else return e.character == ' ' && ((e.stateMask & SWT.CONTROL) != 0) && ((e.stateMask & SWT.ALT) == 0); } public void keyPressed(KeyEvent e) { // CTRL-<SPACE> --> Insert a variable if (isHotKey(e)) { e.doit = false; // textField.setData(TRUE) indicates we have transitioned from the textbox to list mode... // This will be set to false when the list selection has been processed // and the list is being disposed of. control.setData(Boolean.TRUE); final int position; if (getCaretPositionInterface != null) position = getCaretPositionInterface.getCaretPosition(); else position = -1; // Drop down a list of variables... Rectangle bounds = control.getBounds(); Point location = GUIResource.calculateControlPosition(control); final Shell shell = new Shell(control.getShell(), SWT.NONE); shell.setSize(bounds.width, 200); shell.setLocation(location.x, location.y + bounds.height); shell.setLayout(new FillLayout()); final List list = new List(shell, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL); props.setLook(list); list.setItems(getVariableNames(variables)); final DefaultToolTip toolTip = new DefaultToolTip(list, ToolTip.RECREATE, true); toolTip.setImage(GUIResource.getInstance().getImageSpoon()); toolTip.setHideOnMouseDown(true); toolTip.setRespectMonitorBounds(true); toolTip.setRespectDisplayBounds(true); toolTip.setPopupDelay(350); list.addSelectionListener(new SelectionAdapter() { // Enter or double-click: picks the variable public synchronized void widgetDefaultSelected(SelectionEvent e) { applyChanges(shell, list, control, position, insertTextInterface); } // Select a variable name: display the value in a tool tip public void widgetSelected(SelectionEvent event) { if (list.getSelectionCount() <= 0) return; String name = list.getSelection()[0]; String value = variables.getVariable(name); Rectangle shellBounds = shell.getBounds(); String message = BaseMessages.getString(PKG, "TextVar.VariableValue.Message", name, value); if (name.startsWith(Const.INTERNAL_VARIABLE_PREFIX)) message += BaseMessages.getString(PKG, "TextVar.InternalVariable.Message"); toolTip.setText(message); toolTip.hide(); toolTip.show(new Point(shellBounds.width, 0)); } }); list.addKeyListener(new KeyAdapter() { public synchronized void keyPressed(KeyEvent e) { if (e.keyCode == SWT.CR && ((e.keyCode & SWT.CONTROL) == 0) && ((e.keyCode & SWT.SHIFT) == 0)) { applyChanges(shell, list, control, position, insertTextInterface); } } }); list.addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent event) { shell.dispose(); if (!control.isDisposed()) control.setData(Boolean.FALSE); } }); shell.open(); } ; } private static final void applyChanges(Shell shell, List list, Control control, int position, InsertTextInterface insertTextInterface) { String extra = "${" + list.getSelection()[0] + "}"; if (insertTextInterface != null) { insertTextInterface.insertText(extra, position); } else { if (control.isDisposed()) return; if (list.getSelectionCount() <= 0) return; if (control instanceof Text) { ((Text)control).insert(extra); } else if (control instanceof CCombo) { CCombo combo = (CCombo)control; combo.setText(extra); // We can't know the location of the cursor yet. All we can do is overwrite. } } if (!shell.isDisposed()) shell.dispose(); if (!control.isDisposed()) control.setData(Boolean.FALSE); } public static final String[] getVariableNames(VariableSpace space) { String variableNames[] = space.listVariables(); Arrays.sort(variableNames); // repeat a few entries at the top, for convenience... String[] array = new String[variableNames.length+2]; int index=0; array[index++]= Const.INTERNAL_VARIABLE_TRANSFORMATION_FILENAME_DIRECTORY; array[index++]= Const.INTERNAL_VARIABLE_JOB_FILENAME_DIRECTORY; for (String name : variableNames) array[index++] = name; return array; } public void setVariables(VariableSpace vars){ variables = vars; } }
package org.evilbinary.tv.widget; import android.content.Context; import android.util.AttributeSet; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.GridView; import android.widget.ListView; import android.widget.RelativeLayout; /** * :evilbinary on 1/31/16. * :rootdebug@163.com */ public class BorderView extends RelativeLayout implements ViewTreeObserver.OnGlobalFocusChangeListener, ViewTreeObserver.OnScrollChangedListener, ViewTreeObserver.OnGlobalLayoutListener, ViewTreeObserver.OnTouchModeChangeListener { private static String TAG = "BorderView"; private BorderBaseEffect mEffect; private BorderView mBorderView; private boolean mEnableBorder = true; private ViewGroup mViewGroup; private boolean mInTouchMode = false; private boolean mFocusLimit=false; private AdapterView.OnItemSelectedListener mOnItemSelectedListener; public BorderView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public BorderView(Context context) { super(context); init(); } private void init() { mBorderView = this; if (mEffect == null) mEffect = BorderBaseEffect.getDefault(); setVisibility(INVISIBLE); } public BorderBaseEffect getEffect() { return mEffect; } public void setEffect(BorderBaseEffect effect) { mEffect = effect; } public void attachTo(ViewGroup viewGroup) { mViewGroup = viewGroup; mViewGroup.getViewTreeObserver().addOnGlobalFocusChangeListener(this); mViewGroup.getViewTreeObserver().addOnScrollChangedListener(this); mViewGroup.getViewTreeObserver().addOnGlobalLayoutListener(this); mViewGroup.getViewTreeObserver().addOnTouchModeChangeListener(this); } public void detachFrom(ViewGroup viewGroup) { if (viewGroup == mViewGroup) { mViewGroup.getViewTreeObserver().removeOnGlobalFocusChangeListener(this); mViewGroup.getViewTreeObserver().removeOnScrollChangedListener(this); mViewGroup.getViewTreeObserver().removeOnGlobalLayoutListener(this); mViewGroup.getViewTreeObserver().removeOnTouchModeChangeListener(this); if (getParent() == mViewGroup) { mViewGroup.removeView(this); } } } public boolean isFocusLimit() { return mFocusLimit; } public void setFocusLimit(boolean focusLimit) { this.mFocusLimit = focusLimit; } @Override public void onGlobalFocusChanged(View oldFocus, View newFocus) { // Log.d(TAG, "onGlobalFocusChanged"); if (!mEnableBorder) return; if (mInTouchMode) return; if(mFocusLimit){ if(mViewGroup.indexOfChild(newFocus)<0 ){ return ; } } if (mViewGroup instanceof GridView || mViewGroup instanceof ListView) { AbsListView gridView = (AbsListView) mViewGroup; if (mOnItemSelectedListener == null) { mOnItemSelectedListener = gridView.getOnItemSelectedListener(); if (gridView.getSelectedView() != null) { newFocus = gridView.getSelectedView(); } final View tempFocus = newFocus; gridView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { private View oldFocus = tempFocus; private View newFocus = null; @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { newFocus = view; mEffect.start(mBorderView, oldFocus, newFocus); oldFocus = newFocus; if (mOnItemSelectedListener != null) mOnItemSelectedListener.onItemSelected(parent, view, position, id); } @Override public void onNothingSelected(AdapterView<?> parent) { mOnItemSelectedListener.onNothingSelected(parent); } }); } } mEffect.getAnimatorSet().cancel(); mEffect.start(this, oldFocus, newFocus); } @Override public void onScrollChanged() { // Log.d(TAG, "onScrollChanged"); //if (mViewGroup instanceof RecyclerView) { mEffect.notifyChangeAnimation(); } @Override public void onGlobalLayout() { // Log.d(TAG, "onGlobalLayout"); } @Override public void onTouchModeChanged(boolean isInTouchMode) { // Log.d(TAG, "onTouchModeChanged=" + isInTouchMode); if (mViewGroup != null) { if (isInTouchMode) { mInTouchMode = true; mEffect.end(this); } else { mInTouchMode = false; } } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { Log.d(TAG, "onKeyDown"); return super.onKeyDown(keyCode, event); } }
package replicant.spy.tools; import elemental2.dom.DomGlobal; import javax.annotation.Nonnull; import org.realityforge.anodoc.Unsupported; import replicant.Channel; import replicant.FilterUtil; import replicant.spy.AreaOfInterestCreatedEvent; import replicant.spy.AreaOfInterestDisposedEvent; import replicant.spy.AreaOfInterestUpdatedEvent; import replicant.spy.SubscriptionCreatedEvent; import replicant.spy.SubscriptionDisposedEvent; /** * A SpyEventHandler that prints spy events to the tools console. * The events are colored to make them easy to digest. This class is designed to be easy to sub-class. */ @Unsupported( "This class relies on unstable spy API and will likely evolve as the api evolves" ) public class ConsoleSpyEventProcessor extends AbstractSpyEventProcessor { @CssRules private static final String ENTITY_COLOR = "color: #CF8A3B; font-weight: normal;"; @CssRules private static final String SUBSCRIPTION_COLOR = "color: #0FA13B; font-weight: normal;"; @CssRules private static final String AREA_OF_INTEREST_COLOR = "color: #006AEB; font-weight: normal;"; @CssRules private static final String ERROR_COLOR = "color: #A10001; font-weight: normal;"; /** * Create the processor. */ public ConsoleSpyEventProcessor() { on( AreaOfInterestCreatedEvent.class, this::onAreaOfInterestCreated ); on( AreaOfInterestUpdatedEvent.class, this::onAreaOfInterestUpdated ); on( AreaOfInterestDisposedEvent.class, this::onAreaOfInterestDisposed ); on( SubscriptionCreatedEvent.class, this::onSubscriptionCreated ); on( SubscriptionDisposedEvent.class, this::onSubscriptionDisposed ); } /** * Handle the AreaOfInterestCreatedEvent. * * @param e the event. */ protected void onAreaOfInterestCreated( @Nonnull final AreaOfInterestCreatedEvent e ) { final Channel channel = e.getAreaOfInterest().getChannel(); final Object filter = channel.getFilter(); final String filterString = null == filter ? "" : " - " + FilterUtil.filterToString( filter ); log( "%cAreaOfInterest Created " + channel.getAddress() + filterString, AREA_OF_INTEREST_COLOR ); } /** * Handle the AreaOfInterestUpdatedEvent. * * @param e the event. */ protected void onAreaOfInterestUpdated( @Nonnull final AreaOfInterestUpdatedEvent e ) { final Channel channel = e.getAreaOfInterest().getChannel(); final Object filter = channel.getFilter(); final String filterString = FilterUtil.filterToString( filter ); log( "%cAreaOfInterest Updated " + channel.getAddress() + " - " + filterString, AREA_OF_INTEREST_COLOR ); } /** * Handle the AreaOfInterestDisposedEvent. * * @param e the event. */ protected void onAreaOfInterestDisposed( @Nonnull final AreaOfInterestDisposedEvent e ) { log( "%cAreaOfInterest Disposed " + e.getAreaOfInterest().getChannel().getAddress(), AREA_OF_INTEREST_COLOR ); } /** * Handle the SubscriptionCreatedEvent. * * @param e the event. */ protected void onSubscriptionCreated( @Nonnull final SubscriptionCreatedEvent e ) { final Channel channel = e.getSubscription().getChannel(); final Object filter = channel.getFilter(); final String filterString = null == filter ? "" : " - " + FilterUtil.filterToString( filter ); log( "%cSubscription Created " + channel.getAddress() + filterString, SUBSCRIPTION_COLOR ); } /** * Handle the SubscriptionDisposedEvent. * * @param e the event. */ protected void onSubscriptionDisposed( @Nonnull final SubscriptionDisposedEvent e ) { log( "%cSubscription Disposed " + e.getSubscription().getChannel().getAddress(), SUBSCRIPTION_COLOR ); } /** * Log specified message with parameters * * @param message the message. * @param styling the styling parameter. It is assumed that the message has a %c somewhere in it to identify the start of the styling. */ protected void log( @Nonnull final String message, @CssRules @Nonnull final String styling ) { DomGlobal.console.log( message, styling ); } /** * {@inheritDoc} */ @Override protected void handleUnhandledEvent( @Nonnull final Object event ) { DomGlobal.console.log( event ); } }
package nl.nl2312.rxcupboard; import android.database.sqlite.SQLiteDatabase; import nl.qbusict.cupboard.Cupboard; import nl.qbusict.cupboard.DatabaseCompartment; import nl.qbusict.cupboard.QueryResultIterable; import nl.qbusict.cupboard.convert.EntityConverter; import rx.Observable; import rx.functions.Action0; import rx.functions.Action1; import rx.functions.Func0; import rx.functions.Func1; import rx.subjects.PublishSubject; public class RxDatabase { private final Cupboard cupboard; private final DatabaseCompartment dc; private final SQLiteDatabase db; private final PublishSubject<DatabaseChange> triggers = PublishSubject.create(); RxDatabase(Cupboard cupboard, DatabaseCompartment dc, SQLiteDatabase db) { this.cupboard = cupboard; this.dc = dc; this.db = db; } public Observable<DatabaseChange> changes() { return triggers.asObservable(); } public <T> Observable<DatabaseChange<T>> changes(final Class<T> entityClass) { return triggers.filter(new Func1<DatabaseChange, Boolean>() { @Override public Boolean call(DatabaseChange event) { // Only let through change events for a specific table/class return entityClass.isAssignableFrom(event.entityClass()); } }).map(new Func1<DatabaseChange, DatabaseChange<T>>() { @Override public DatabaseChange<T> call(DatabaseChange raw) { // Cast as we are now sure to have only DatabaseChange events of type T //noinspection unchecked return raw; } }).asObservable(); } @SuppressWarnings("unchecked") // Cupboard EntityConverter type is lost as it only accepts Class<?> public <T> long put(T entity) { EntityConverter<T> entityConverter = cupboard.getEntityConverter((Class<T>) entity.getClass()); Long existing = entityConverter.getId(entity); long inserted = dc.put(entity); if (existing == null) { triggers.onNext(DatabaseChange.insert(entity)); return inserted; } else { triggers.onNext(DatabaseChange.update(entity)); return existing; } } public <T> Observable<T> putRx(final T entity) { return Observable.defer(new Func0<Observable<T>>() { @Override public Observable<T> call() { put(entity); return Observable.just(entity); } }); } public <T> Action1<T> put() { return new Action1<T>() { @Override public void call(T t) { put(t); } }; } public <T> boolean delete(T entity) { boolean result = dc.delete(entity); if (result) { triggers.onNext(DatabaseChange.delete(entity)); } return result; } public <T> Observable<T> deleteRx(final T entity) { return Observable.defer(new Func0<Observable<T>>() { @Override public Observable<T> call() { delete(entity); return Observable.just(entity); } }); } public <T> boolean delete(Class<T> entityClass, long id) { boolean result; if (triggers.hasObservers()) { // We have subscribers to database change events, so we need to look up the item to report it back T entity = dc.get(entityClass, id); result = dc.delete(entity); if (result) { triggers.onNext(DatabaseChange.delete(entity)); } } else { // Straightforward delete without change propagation result = dc.delete(entityClass, id); } return result; } public <T> Action1<T> delete() { return new Action1<T>() { @Override public void call(T t) { delete(t); } }; } public <T> Action1<Long> delete(final Class<T> entityClass) { return new Action1<Long>() { @Override public void call(Long t) { delete(entityClass, t); } }; } public <T> Observable<T> get(final Class<T> entityClass, final long id) { return Observable.defer(new Func0<Observable<T>>() { @Override public Observable<T> call() { return Observable.just(dc.get(entityClass, id)); } }); } public <T> Observable<T> query(Class<T> entityClass) { return createObservable(dc.query(entityClass).query()); } public <T> Observable<T> query(Class<T> entityClass, String selection, String... args) { return createObservable(dc.query(entityClass).withSelection(selection, args).query()); } public <T> Observable<T> query(DatabaseCompartment.QueryBuilder<T> preparedQuery) { return createObservable(preparedQuery.query()); } private <T> Observable<T> createObservable(final QueryResultIterable<T> iterable) { return Observable.from(iterable).doOnTerminate(new Action0() { @Override public void call() { iterable.close(); } }); } public <T> DatabaseCompartment.QueryBuilder<T> buildQuery(Class<T> entityClass) { return dc.query(entityClass); } public <T> Observable<Long> count(final Class<T> entityClass) { return Observable.defer(new Func0<Observable<Long>>() { @Override public Observable<Long> call() { String table = cupboard.getTable(entityClass); return Observable.just(db.compileStatement("select count(*) from " + table).simpleQueryForLong()); } }); } }
package me.enat.coffee.mackern; import com.apple.eawt.AppEvent; import com.apple.eawt.Application; import com.apple.eawt.QuitHandler; import com.apple.eawt.QuitResponse; import java.io.File; import java.lang.*; import java.lang.Class; import java.lang.ClassLoader; import java.lang.ClassNotFoundException; import java.lang.Exception; import java.lang.IllegalAccessException; import java.lang.IllegalArgumentException; import java.lang.NoSuchMethodException; import java.lang.Object; import java.lang.SecurityException; import java.lang.String; import java.lang.System; import java.lang.Throwable; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.net.URI; import java.util.List; public class Mackern { private static AboutEventHandler aboutEventHandler; private static QuitEventHandler quitEventHandler; private static OpenURIEventHandler openURIEventHandler; private static OpenFileEventHandler openFileEventHandler; private static NoMacEvent noMacEvent = new NoMacEvent() { @Override public void noMacClassesFound(Exception e) { System.out.println("No Mac Classes Found"); } }; public static void setOpenURIEventHandler(final OpenURIEventHandler openURIEventHandler) { Mackern.openURIEventHandler = openURIEventHandler; try { final InvocationHandler ih = new InvocationHandler() { @Override public java.lang.Object invoke(Object proxy, Method method, Object[] args) throws java.lang.Throwable { Class<?> class_openFilesEvent = getEventClassWithName(EVENT_TYPES.OPEN_URI_EVENT.eventClassname); Method filesMethod = class_openFilesEvent.getMethod("getURI"); URI uri = (URI) filesMethod.invoke(args[0]); openURIEventHandler.recivedOpenURIEvent(uri); return null; } }; setInvocationHandler(ih, EVENT_TYPES.OPEN_FILES_EVENT); } catch (ClassNotFoundException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { noMacEvent.noMacClassesFound(e); } } public static void setOpenFileEventHandler(final OpenFileEventHandler openFileEventHandler) { Mackern.openFileEventHandler = openFileEventHandler; try { final InvocationHandler ih = new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Class<?> class_openFilesEvent = getEventClassWithName(EVENT_TYPES.OPEN_FILES_EVENT.eventClassname); Method filesMethod = class_openFilesEvent.getMethod("getFiles"); List<File> files = (List<File>) filesMethod.invoke(args[0]); openFileEventHandler.recivedOpenFileEvent(files); return null; } }; setInvocationHandler(ih, EVENT_TYPES.OPEN_FILES_EVENT); } catch (ClassNotFoundException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { noMacEvent.noMacClassesFound(e); } } private static void setInvocationHandler(InvocationHandler ih, EVENT_TYPES type) throws ClassNotFoundException, InvocationTargetException, IllegalAccessException, NoSuchMethodException { Class<?> class_application = getApplicationClass(); Object instance_application = getApplication(); Object proxy = Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(), new Class[]{Class.forName(type.handlerClassName)}, ih); Method method_setOpenFileHandler = class_application.getMethod(type.setterMethod, Class.forName(type.handlerClassName)); method_setOpenFileHandler.invoke(instance_application, proxy); } public static void setAboutEventHandler(final AboutEventHandler aboutEventHandler) { Mackern.aboutEventHandler = aboutEventHandler; try { final InvocationHandler ih = new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Class<?> class_openFilesEvent = getEventClassWithName(EVENT_TYPES.ABOUT_EVENT.eventClassname); aboutEventHandler.recivedAboutEvent(); return null; } }; setInvocationHandler(ih, EVENT_TYPES.OPEN_FILES_EVENT); } catch (ClassNotFoundException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { noMacEvent.noMacClassesFound(e); } } private static Object getApplication() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { Class<?> class_application = getApplicationClass(); Method method_getApplication = class_application.getMethod("getApplication"); Object instance_application = method_getApplication.invoke(class_application); return instance_application; } private static Class<?> getApplicationClass() throws ClassNotFoundException { return Class.forName("com.apple.eawt.Application"); } private static Class<?> getEventClassWithName(String name) throws ClassNotFoundException { Class<?> class_appEvent = Class.forName("com.apple.eawt.AppEvent"); Class<?>[] classesOf_class_appEvent = class_appEvent.getDeclaredClasses(); for (Class<?> currentClass : classesOf_class_appEvent) { if (currentClass.getSimpleName().equals(name)) { return currentClass; } } return null; } public static void setNoMacEvent(NoMacEvent noMacEvent) { Mackern.noMacEvent = noMacEvent; } private enum EVENT_TYPES { OPEN_FILES_EVENT("OpenFilesEvent", "setOpenFileHandler", "com.apple.eawt.OpenFilesHandler"), OPEN_URI_EVENT ("OpenURIEvent" , "setOpenURIHandler" , "com.apple.eawt.OpenURIHandler"), ABOUT_EVENT ("AboutEvent" , "setAboutHandler" , "com.apple.eawt.Abouthandler"); public final String eventClassname; public final String setterMethod; public final String handlerClassName; private EVENT_TYPES(String i, String j, String k) { eventClassname = i; setterMethod = j; handlerClassName = k; } } public interface OpenFileEventHandler { public void recivedOpenFileEvent(List<File> files); } public interface OpenURIEventHandler { public void recivedOpenURIEvent(URI uri); } public interface QuitEventHandler { public void recivedQuitEvent(/* TODO: INSERT EVENT DATA */); } public interface AboutEventHandler { public void recivedAboutEvent(); } public interface NoMacEvent { public void noMacClassesFound(Exception e); } //public static final String APP_REOPENED_EVENT = "AppReOpenedEvent"; //public static final String APP_FOREGROUND_EVENT = "AppForegroundEvent"; //public static final String APP_HIDDEN_EVENT = "AppHiddenEvent"; //public static final String USER_SESSION_EVENT = "UserSessionEvent"; //public static final String SCREEN_SLEEP_EVENT = "ScreenSleepEvent"; //public static final String SYSTEM_SLEEP_EVENT = "SystemSleepEvent"; //public static final String OPEN_FILES_EVENT = "OpenFilesEvent"; //public static final String FILES_EVENT = "FilesEvent"; //public static final String OPEN_URI_EVENT = "OpenURIEvent"; //public static final String ABOUT_EVENT = "AboutEvent"; //public static final String PREFERENCES_EVENT = "PreferencesEvent"; //public static final String QUIT_EVENT = "QuitEvent"; }
package org.jetel.interpreter.extensions; import org.jetel.data.primitive.CloverDouble; import org.jetel.interpreter.TransformLangExecutorRuntimeException; import org.jetel.interpreter.data.TLContext; import org.jetel.interpreter.data.TLValue; import org.jetel.interpreter.data.TLValueType; public class MathLib implements ITLFunctionLibrary { private static final String LIBRARY_NAME = "Math"; enum Function { SQRT("sqrt"), LOG("log"), LOG10("log10"), EXP("exp"), ROUND("round"), POW("pow"), PI("pi"), RANDOM("random"); public String name; private Function(String name) { this.name = name; } public static Function fromString(String s) { for(Function function : Function.values()) { if(s.equalsIgnoreCase(function.name) || s.equalsIgnoreCase(LIBRARY_NAME + "." + function.name)) { return function; } } return null; } } public MathLib() { super(); } public TLFunctionPrototype getFunction(String functionName) { switch(Function.fromString(functionName)) { case SQRT: return new SqrtFunction(); case LOG: return new LogFunction(); case LOG10: return new Log10Function(); case EXP: return new ExpFunction(); case ROUND: return new RoundFunction(); case POW: return new PowFunction(); case PI: return new PiFunction(); case RANDOM: return new RandomFunction(); default: return null; } } // SQRT class SqrtFunction extends TLFunctionPrototype { public SqrtFunction() { super("math", "sqrt", new TLValueType[] { TLValueType.DECIMAL }, TLValueType.DOUBLE); } @Override public TLValue execute(TLValue[] params, TLContext context) { if (params[0].type.isNumeric()) { TLValue retVal; try { retVal = new TLValue(TLValueType.DOUBLE, new CloverDouble(Math.sqrt(params[0] .getDouble()))); return retVal; } catch (Exception ex) { throw new TransformLangExecutorRuntimeException( "Error when executing SQRT function", ex); } } throw new TransformLangExecutorRuntimeException(null, params, "sqrt - wrong type of literal(s)"); } } // LOG class LogFunction extends TLFunctionPrototype { public LogFunction() { super("math", "log", new TLValueType[] { TLValueType.DECIMAL }, TLValueType.DOUBLE); } @Override public TLValue execute(TLValue[] params, TLContext context) { if (params[0].type.isNumeric()) { TLValue retVal; try { retVal = new TLValue(TLValueType.DOUBLE, new CloverDouble(Math.log((params[0] .getDouble())))); return retVal; } catch (Exception ex) { throw new TransformLangExecutorRuntimeException( "Error when executing LOG function", ex); } } throw new TransformLangExecutorRuntimeException(null, params, "log - wrong type of literal(s)"); } } // LOG10 class Log10Function extends TLFunctionPrototype { public Log10Function() { super("math", "log10", new TLValueType[] { TLValueType.DECIMAL }, TLValueType.DOUBLE); } @Override public TLValue execute(TLValue[] params, TLContext context) { if (params[0].type.isNumeric()) { TLValue retVal; try { retVal = new TLValue(TLValueType.DOUBLE, new CloverDouble(Math.log10((params[0] .getDouble())))); return retVal; } catch (Exception ex) { throw new TransformLangExecutorRuntimeException( "Error when executing LOG10 function", ex); } } throw new TransformLangExecutorRuntimeException(null, params, "log10 - wrong type of literal(s)"); } } // EXP class ExpFunction extends TLFunctionPrototype { public ExpFunction() { super("math", "exp", new TLValueType[] { TLValueType.DECIMAL }, TLValueType.DOUBLE); } @Override public TLValue execute(TLValue[] params, TLContext context) { if (params[0].type.isNumeric()) { TLValue retVal; try { retVal = new TLValue(TLValueType.DOUBLE, new CloverDouble(Math.exp((params[0] .getDouble())))); return retVal; } catch (Exception ex) { throw new TransformLangExecutorRuntimeException( "Error when executing EXP function", ex); } } throw new TransformLangExecutorRuntimeException(null, params, "exp - wrong type of literal(s)"); } } // ROUND class RoundFunction extends TLFunctionPrototype { public RoundFunction() { super("math", "round", new TLValueType[] { TLValueType.DECIMAL }, TLValueType.DOUBLE); } @Override public TLValue execute(TLValue[] params, TLContext context) { if (params[0].type.isNumeric()) { TLValue retVal; try { retVal = new TLValue(TLValueType.DOUBLE, new CloverDouble(Math.round((params[0] .getDouble())))); return retVal; } catch (Exception ex) { throw new TransformLangExecutorRuntimeException( "Error when executing ROUND function", ex); } } throw new TransformLangExecutorRuntimeException(null, params, "round - wrong type of literal(s)"); } } // POW class PowFunction extends TLFunctionPrototype { public PowFunction() { super("math", "pow", new TLValueType[] { TLValueType.DECIMAL, TLValueType.DECIMAL }, TLValueType.DOUBLE); } @Override public TLValue execute(TLValue[] params, TLContext context) { if (params[0].type.isNumeric()) { TLValue retVal; try { retVal = new TLValue(TLValueType.DOUBLE, new CloverDouble(Math.pow(params[0].getDouble(),params[1].getDouble()))); return retVal; } catch (Exception ex) { throw new TransformLangExecutorRuntimeException( "Error when executing POW function", ex); } } throw new TransformLangExecutorRuntimeException(null, params, "pow - wrong type of literal(s)"); } } class PiFunction extends TLFunctionPrototype { public PiFunction() { super("math", "pi", new TLValueType[] { }, TLValueType.DOUBLE); } @Override public TLValue execute(TLValue[] params, TLContext context) { if (params[0].type.isNumeric()) { TLValue retVal; try { retVal = new TLValue(TLValueType.DOUBLE, new CloverDouble(Math.PI)); return retVal; } catch (Exception ex) { throw new TransformLangExecutorRuntimeException( "Error when executing PI function", ex); } } throw new TransformLangExecutorRuntimeException(null, params, "pi - wrong type of literal(s)"); } } // RANDOM class RandomFunction extends TLFunctionPrototype { public RandomFunction() { super("math", "random", new TLValueType[] { }, TLValueType.DOUBLE); } @Override public TLValue execute(TLValue[] params, TLContext context) { if (params[0].type.isNumeric()) { TLValue retVal; try { retVal = new TLValue(TLValueType.DOUBLE, new CloverDouble(Math.random())); return retVal; } catch (Exception ex) { throw new TransformLangExecutorRuntimeException( "Error when executing RANDOM function", ex); } } throw new TransformLangExecutorRuntimeException(null, params, "random - wrong type of literal(s)"); } } }
package controllers.listeners; import java.awt.event.ActionEvent; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.JFileChooser; import process.IProcessAdapter; import algorithms.AbstractAlgorithm; import models.PictureParts; import models.ProcessManagerModel; import tools.Log; import views.MainWindowView; import views.filters.ImageFileFilter; /** * Action listener dedicated to the chosenFileButton (image choice) of the MainWindowView * The role this class has to handle the chose of a new image file when the user click on the loading button. * @author Corentin Legros * */ public class ChosenFileButtonListener extends AbstractActionListener<MainWindowView>{ protected JFileChooser dialogFileChooser; public ChosenFileButtonListener(MainWindowView parentView) { super(parentView); } @Override public void actionPerformed(ActionEvent arg0) { if (dialogFileChooser == null) { dialogFileChooser = new JFileChooser(System.getProperty("user.home")); dialogFileChooser.addChoosableFileFilter(new ImageFileFilter(new String[] {"gif","tif", "jpeg", "jpg", "tiff", "png", "bmp"}, "All files with an image extension")); } dialogFileChooser.showOpenDialog(parentView.getChosenFileButton()); File loadedFile = dialogFileChooser.getSelectedFile(); if (loadedFile == null) { parentView.getProcessButton().setEnabled(false); parentView.getChosenFileLabel().setText("No file specified"); } else { BufferedImage tmpImg = null; try { tmpImg = ImageIO.read(loadedFile); } catch (IOException e) { Log.warn(String.format("Unable to read image source file (%s)", loadedFile.getPath())); } if (tmpImg != null) { // if file ok : we put it's name in the label object and enable reset button parentView.getResetButton().setEnabled(true); parentView.getChosenFileLabel().setText(loadedFile.getName()); parentView.setImageToDisplay(tmpImg); parentView.getImagePanel().updateImage(tmpImg); // this fix a fucking bug! ProcessManagerModel model = (ProcessManagerModel) parentView.getModel(); model.setData(new PictureParts(tmpImg)); Log.info(String.format("File chosen : %s", loadedFile.getPath())); // active process button if the file criteria is ok if (parentView.getTypesAlgorithmComboBox().getSelectedIndex() != AbstractAlgorithm.ALGORITHM_TYPE_UNSELECTED && parentView.getTypesProcessComboBox().getSelectedIndex() != IProcessAdapter.PROCESS_TYPE_UNSELECTED && parentView.getNWComboBox().getSelectedIndex() != 0) { if (parentView.getImageToDisplay() != null) { parentView.getProcessButton().setEnabled(true); } } } } } }
package net.java.otr4j.context.auth; import java.io.IOException; import java.math.BigInteger; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.KeyPair; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import javax.crypto.BadPaddingException; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.interfaces.DHPublicKey; import org.apache.log4j.Logger; import net.java.otr4j.Utils; import net.java.otr4j.crypto.CryptoConstants; import net.java.otr4j.crypto.CryptoUtils; public class AuthenticationInfo { private static Logger logger = Logger.getLogger(AuthenticationInfo.class); public AuthenticationInfo() { this.setAuthenticationState(AuthenticationState.NONE); } private AuthenticationState authenticationState; private byte[] r; private DHPublicKey remoteDHPublicKey; private int remoteDHPPublicKeyID; private byte[] remoteDHPublicKeyEncrypted; private byte[] remoteDHPublicKeyHash; private KeyPair localDHKeyPair; private int localDHPrivateKeyID; private byte[] localDHPublicKeyHash; private byte[] localDHPublicKeyEncrypted; private BigInteger s; private byte[] c; private byte[] m1; private byte[] m2; private byte[] cp; private byte[] m1p; private byte[] m2p; private byte[] localXEncrypted; private byte[] localXEncryptedMac; private KeyPair localLongTermKeyPair; public void initialize() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, NoSuchProviderException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { this.setAuthenticationState(AuthenticationState.NONE); logger.debug("Picking random key r."); this.setR(Utils.getRandomBytes(CryptoConstants.AES_KEY_BYTE_LENGTH)); logger.debug("Generating own D-H key pair."); this.setLocalDHKeyPair(CryptoUtils.generateDHKeyPair()); logger.debug("Setting our keyID to 1."); this.setLocalDHPrivateKeyID(1); byte[] gx = ((DHPublicKey) getLocalDHKeyPair().getPublic()).getY() .toByteArray(); logger.debug("Hashing gx"); this.setLocalDHPublicKeyHash(CryptoUtils.sha256Hash(gx)); logger.debug("Encrypting gx"); this.setLocalDHPublicKeyEncrypted(CryptoUtils.aesEncrypt(getR(), gx)); } public void setAuthenticationState(AuthenticationState authenticationState) { this.authenticationState = authenticationState; } public AuthenticationState getAuthenticationState() { return authenticationState; } public void setR(byte[] r) { this.r = r; } public byte[] getR() { return r; } public void setRemoteDHPublicKey(DHPublicKey remoteDHPublicKey) { this.remoteDHPublicKey = remoteDHPublicKey; } public DHPublicKey getRemoteDHPublicKey() { return remoteDHPublicKey; } public void setRemoteDHPublicKeyEncrypted( byte[] remoteDHPublicKeyEncrypted) { this.remoteDHPublicKeyEncrypted = remoteDHPublicKeyEncrypted; } public byte[] getRemoteDHPublicKeyEncrypted() { return remoteDHPublicKeyEncrypted; } public void setRemoteDHPublicKeyHash(byte[] remoteDHPublicKeyHash) { this.remoteDHPublicKeyHash = remoteDHPublicKeyHash; } public byte[] getRemoteDHPublicKeyHash() { return remoteDHPublicKeyHash; } public void setLocalDHKeyPair(KeyPair localDHKeyPair) { this.localDHKeyPair = localDHKeyPair; } public KeyPair getLocalDHKeyPair() { return localDHKeyPair; } public void setLocalDHPrivateKeyID(int localDHPrivateKeyID) { this.localDHPrivateKeyID = localDHPrivateKeyID; } public int getLocalDHPrivateKeyID() { return localDHPrivateKeyID; } public void setLocalDHPublicKeyHash(byte[] localDHPublicKeyHash) { this.localDHPublicKeyHash = localDHPublicKeyHash; } public byte[] getLocalDHPublicKeyHash() { return localDHPublicKeyHash; } public void setLocalDHPublicKeyEncrypted(byte[] localDHPublicKeyEncrypted) { this.localDHPublicKeyEncrypted = localDHPublicKeyEncrypted; } public byte[] getLocalDHPublicKeyEncrypted() { return localDHPublicKeyEncrypted; } public void setS(BigInteger s) throws NoSuchAlgorithmException, IOException { this.s = s; this.setC(AuthenticationInfoUtils.getC(s)); this.setCp(AuthenticationInfoUtils.getCp(s)); this.setM1(AuthenticationInfoUtils.getM1(s)); this.setM1p(AuthenticationInfoUtils.getM1p(s)); this.setM2(AuthenticationInfoUtils.getM2(s)); this.setM2p(AuthenticationInfoUtils.getM2p(s)); } public BigInteger getS() { return s; } private void setC(byte[] c) { this.c = c; } public byte[] getC() { return c; } private void setM1(byte[] m1) { this.m1 = m1; } public byte[] getM1() { return m1; } private void setM2(byte[] m2) { this.m2 = m2; } public byte[] getM2() { return m2; } private void setCp(byte[] cp) { this.cp = cp; } public byte[] getCp() { return cp; } private void setM1p(byte[] m1p) { this.m1p = m1p; } public byte[] getM1p() { return m1p; } private void setM2p(byte[] m2p) { this.m2p = m2p; } public byte[] getM2p() { return m2p; } public void setLocalXEncrypted(byte[] localXEncrypted) { this.localXEncrypted = localXEncrypted; } public byte[] getLocalXEncrypted() { return localXEncrypted; } public void setLocalXEncryptedMac(byte[] localXEncryptedMac) { this.localXEncryptedMac = localXEncryptedMac; } public byte[] getLocalXEncryptedMac() { return localXEncryptedMac; } public void setLocalLongTermKeyPair(KeyPair localLongTermKeyPair) { this.localLongTermKeyPair = localLongTermKeyPair; } public KeyPair getLocalLongTermKeyPair() { return localLongTermKeyPair; } public void setRemoteDHPPublicKeyID(int remoteDHPPublicKeyID) { this.remoteDHPPublicKeyID = remoteDHPPublicKeyID; } public int getRemoteDHPPublicKeyID() { return remoteDHPPublicKeyID; } }
package nl.exl.doomidgamesarchive.idgamesapi; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; /** * An IdgamesApi file entry. Contains a title, author, description, rating and more. */ public class FileEntry extends Entry { // File database id. private int mId = -1; // Title of this entry. private String mTitle = ""; // The author of this entry. private String mAuthor; // The email of this entry's author. private String mEmail; // A description of this entry. private String mDescription; // File info of this entry. private String mFileName; private String mFilePath; private int mFileSize; // Temporal info of this entry. mDate can be null. private int mTimestamp; private String mDate; private String mLocaleDate; // Rating info of this entry. private double mRating; private int mVoteCount; // The URL at which to view this entry. Points to doomworld.com/idgames private String mUrl; // The idgames protocol URL of this entry. private String mIdgamesUrl; // Miscellaneous info of this entry. private String mCredits; private String mBase; private String mBuildTime; private String mEditorsUsed; private String mBugs; // The complete contents of the text file describing this entry. private String mTextFileContents; // List of associated reviews private List<Review> reviews; public FileEntry() { reviews = new ArrayList<Review>(); } /** * {@inheritDoc} */ @Override public void toJSON(JSONObject obj) throws JSONException { obj.put("id", mId); obj.put("title", mTitle); obj.put("author", mAuthor); obj.put("description", mDescription); obj.put("email", mEmail); obj.put("fileName", mFileName); obj.put("filePath", mFilePath); obj.put("fileSize", mFileSize); obj.put("timestamp", mTimestamp); obj.put("date", mDate); obj.put("rating", mRating); obj.put("voteCount", mVoteCount); obj.put("url", mUrl); obj.put("idgamesUrl", mIdgamesUrl); obj.put("credits", mCredits); obj.put("base", mBase); obj.put("buildTime", mBuildTime); obj.put("editorsUsed", mEditorsUsed); obj.put("bugs", mBugs); obj.put("textFileContents", mTextFileContents); // Store reviews. JSONObject reviewObj; JSONArray reviewArray = new JSONArray(); for (Review review : reviews) { reviewObj = new JSONObject(); review.toJSON(reviewObj); reviewArray.put(reviewObj); } obj.put("reviews", reviewArray); } /** * {@inheritDoc} */ @Override public void fromJSON(JSONObject obj) throws JSONException { mId = obj.getInt("id"); mTitle = obj.optString("title", null); mAuthor = obj.optString("author", null); mDescription = obj.optString("description", null); mEmail = obj.optString("email", null); mFileName = obj.optString("fileName", null); mFilePath = obj.optString("filePath", null); mFileSize = obj.optInt("fileSize"); mTimestamp = obj.optInt("timestamp"); mDate = obj.optString("date", null); mRating = obj.optDouble("rating"); mVoteCount = obj.optInt("voteCount"); mUrl = obj.optString("url", null); mIdgamesUrl = obj.optString("idgamesUrl", null); mCredits = obj.optString("credits", null); mBase = obj.optString("base", null); mBuildTime = obj.optString("buildTime", null); mEditorsUsed = obj.optString("editorsUsed", null); mBugs = obj.optString("bugs", null); mTextFileContents = obj.optString("textFileContents", null); // Read reviews. JSONObject reviewObj; JSONArray reviewArray = obj.optJSONArray("reviews"); for (int i = 0; i < reviewArray.length(); i++) { reviewObj = reviewArray.getJSONObject(i); Review review = new Review(); review.fromJSON(reviewObj); reviews.add(review); } } public void setId(int id) { mId = id; } public void addTitle(String title) { if (mTitle == null) { mTitle = title; } else { mTitle += title; } } public void addAuthor(String author) { if (mAuthor == null) { mAuthor = author; } else { mAuthor += author; } } public void addDescription(String description) { if (mDescription == null) { mDescription = description; } else { mDescription += description; } } public void addEmail(String email) { if (mEmail == null) { mEmail = email; } else { mEmail += email; } } public void addFileName(String fileName) { if (mFileName == null) { mFileName = fileName; } else { mFileName += fileName; } } public void addFilePath(String filePath) { if (mFilePath == null) { mFilePath = filePath; } else { mFilePath += filePath; } } public void setFileSize(int fileSize) { mFileSize = fileSize; } public void setTimeStamp(int timeStamp) { mTimestamp = timeStamp; } public void addDate(String date) { if (mDate == null) { mDate = date; } else { mDate += date; } } public void setRating(double rating) { mRating = rating; } public void setVoteCount(int voteCount) { mVoteCount = voteCount; } public void addUrl(String url) { if (mUrl == null) { mUrl = url; } else { mUrl += url; } } public void addIdgamesUrl(String idgamesUrl) { if (mIdgamesUrl == null) { mIdgamesUrl = idgamesUrl; } else { mIdgamesUrl += idgamesUrl; } } public void addCredits(String credits) { if (mCredits == null) { mCredits = credits; } else { mCredits += credits; } } public void addBase(String base) { if (mBase == null) { mBase = base; } else { mBase += base; } } public void addBuildTime(String buildTime) { if (mBuildTime == null) { mBuildTime = buildTime; } else { mBuildTime += buildTime; } } public void addEditorsUsed(String editorsUsed) { if (mEditorsUsed == null) { mEditorsUsed = editorsUsed; } else { mEditorsUsed += editorsUsed; } } public void addBugs(String bugs) { if (mBugs == null) { mBugs = bugs; } else { mBugs += bugs; } } public void addTextFileContents(String textFileContents) { if (mTextFileContents == null) { mTextFileContents = textFileContents; } else { mTextFileContents += textFileContents; } } public void addReview(Review review) { reviews.add(review); } public int getId() { return mId; } public String getTitle() { return mTitle; } /** * Returns this entry's author name. * * @return "Unknown" if there is no author name, the author name otherwise. */ public String getAuthor() { if (mAuthor == null || mAuthor.length() == 0) { return "Unknown"; } else { return mAuthor; } } public String getDescription() { return mDescription; } public String getEmail() { return mEmail; } public String getFileName() { return mFileName; } public String getFilePath() { return mFilePath; } public int getFileSize() { return mFileSize; } /** * Returns the size of this file as a formatted size string. * * @return */ public String getFileSizeString() { if (mFileSize < 1024) { return mFileSize + " B"; } int exp = (int) (Math.log(mFileSize) / Math.log(1024)); String pre = "kMGTPE".charAt(exp - 1) + ""; return String.format(Locale.getDefault(), "%.1f %sB", mFileSize / Math.pow(1024, exp), pre); } public int getTimeStamp() { return mTimestamp; } public String getDate() { return mDate; } /** * Returns this entry's date as a locale formatted date. * * @return The locale formatted date of this entry. */ public String getLocaleDate() { if (mDate == null) { return null; } // Parse the date string and construct a localized date string. if (mLocaleDate == null) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.US); Date date = null; try { date = dateFormat.parse(mDate); } catch (ParseException e) { Log.w("FileEntry", "Could not parse date " + mDate); } // Store the localized string to prevent date parsing next time it is needed. if (date != null) { mLocaleDate = DateFormat.getDateInstance().format(date); } else { mLocaleDate = "Unknown"; } } return mLocaleDate; } public double getRating() { return mRating; } public int getVoteCount() { return mVoteCount; } public String getUrl() { return mUrl; } public String getIdgamesUrl() { return mIdgamesUrl; } public String getCredits() { return mCredits; } public String getBase() { return mBase; } public String getBuildTime() { return mBuildTime; } public String getEditorsUsed() { return mEditorsUsed; } public String getBugs() { return mBugs; } public String getTextFileContents() { return mTextFileContents; } /** * Returns this entry's title. If the entry has no title, the filename is returned instead. */ public String toString() { if (mTitle == null) { if (mFileName == null) { return ""; } else { return mFileName; } } else { return mTitle; } } public List<Review> getReviews() { return reviews; } }
package nl.mpi.arbil.FieldEditors; import nl.mpi.arbil.data.ImdiTreeObject; import java.awt.BorderLayout; import java.awt.Component; import java.awt.FontMetrics; import java.awt.Rectangle; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.util.Vector; import javax.swing.AbstractCellEditor; import javax.swing.BoxLayout; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTable; import javax.swing.SwingUtilities; import javax.swing.event.PopupMenuEvent; import javax.swing.event.PopupMenuListener; import javax.swing.table.TableCellEditor; import nl.mpi.arbil.GuiHelper; import nl.mpi.arbil.ImdiField; import nl.mpi.arbil.ImdiTable; import nl.mpi.arbil.ImdiTableCellRenderer; import nl.mpi.arbil.LinorgWindowManager; public class ArbilTableCellEditor extends AbstractCellEditor implements TableCellEditor { ImdiTable parentTable = null; Rectangle parentCellRect = null; ImdiTreeObject registeredOwner = null; JPanel editorPanel; JLabel button; String fieldName; Component editorComponent = null; // boolean receivedKeyDown = false; Object[] cellValue; int selectedField = -1; Vector<Component> componentsWithFocusListners = new Vector(); public ArbilTableCellEditor() { button = new JLabel("..."); editorPanel = new JPanel(); button.addKeyListener(new java.awt.event.KeyListener() { public void keyTyped(KeyEvent evt) { } public void keyPressed(KeyEvent evt) { // receivedKeyDown = true; // this is to prevent reopening the editor after a ctrl_w has closed the editor } public void keyReleased(KeyEvent evt) { if (!cellHasControlledVocabulary() && isStartLongFieldKey(evt)) {// prevent ctrl key events getting through etc. startEditorMode(true, KeyEvent.CHAR_UNDEFINED, KeyEvent.CHAR_UNDEFINED); } else if (!evt.isActionKey() && !evt.isMetaDown() && // these key down checks will not catch a key up event hence the key codes below which work for up and down events !evt.isAltDown() && !evt.isAltGraphDown() && !evt.isControlDown() && evt.getKeyCode() != 16 && /* 16 is a shift key up or down event */ evt.getKeyCode() != 17 && /* 17 is the ctrl key*/ evt.getKeyCode() != 18 && /* 18 is the alt key*/ evt.getKeyCode() != 157 &&/* 157 is the meta key*/ evt.getKeyCode() != 27 /* 27 is the esc key*/) { startEditorMode(false, evt.getKeyCode(), evt.getKeyChar()); } } }); button.addMouseListener(new java.awt.event.MouseAdapter() { @Override public void mouseReleased(MouseEvent evt) { parentTable.checkPopup(evt, false); } @Override public void mousePressed(MouseEvent evt) { parentTable.checkPopup(evt, false); } public void mouseClicked(java.awt.event.MouseEvent evt) { if (evt.getButton() == MouseEvent.BUTTON1) { startEditorMode(isStartLongFieldModifier(evt), KeyEvent.CHAR_UNDEFINED, KeyEvent.CHAR_UNDEFINED); } else { parentTable.checkPopup(evt, false); //super.mousePressed(evt); } } }); } private boolean requiresLongFieldEditor() { boolean requiresLongFieldEditor = false; if (cellValue instanceof ImdiField[]) { FontMetrics fontMetrics = button.getGraphics().getFontMetrics(); double availableWidth = parentCellRect.getWidth() + 20; // let a few chars over be ok for the short editor ImdiField[] iterableFields; if (selectedField == -1) { // when a single filed is edited only check that field otherwise check all fields iterableFields = (ImdiField[]) cellValue; } else { iterableFields = new ImdiField[]{((ImdiField[]) cellValue)[selectedField]}; } for (ImdiField currentField : iterableFields) { // if (!currentField.hasVocabulary()) { // the vocabulary type field should not get here String fieldValue = currentField.getFieldValue(); // calculate length and look for line breaks if (fieldValue.contains("\n")) { requiresLongFieldEditor = true; break; } else { int requiredWidth = fontMetrics.stringWidth(fieldValue); System.out.println("requiredWidth: " + requiredWidth + " availableWidth: " + availableWidth); String fieldLanguageId = currentField.getLanguageId(); if (fieldLanguageId != null) { requiredWidth += LanguageIdBox.languageSelectWidth; } if (requiredWidth > availableWidth) { requiresLongFieldEditor = true; break; } } } } return requiresLongFieldEditor; } private boolean isCellEditable() { boolean returnValue = false; if (cellValue instanceof ImdiField[]) { ImdiTreeObject parentObject = ((ImdiField[]) cellValue)[0].parentImdi; // check that the field id exists and that the file is in the local cache or in the favourites not loose on a drive, as the determinator of editability returnValue = !parentObject.isLoading() && parentObject.isEditable() && parentObject.isMetaDataNode(); // todo: consider limiting editing to files withing the cache only } return (returnValue); } private boolean isStartLongFieldKey(KeyEvent evt) { return (isStartLongFieldModifier(evt) && (evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER || evt.getKeyCode() == java.awt.event.KeyEvent.VK_SPACE)); } private boolean isStartLongFieldModifier(InputEvent evt) { return ((evt.isAltDown() || evt.isControlDown())); } private void removeAllFocusListners() { while (componentsWithFocusListners.size() > 0) { Component currentComponent = componentsWithFocusListners.remove(0); if (currentComponent != null) { System.out.println("removeAllFocusListners:currentComponent:" + currentComponent.getClass()); for (FocusListener currentListner : currentComponent.getFocusListeners()) { currentComponent.removeFocusListener(currentListner); } } } } private void addFocusListener(Component targetComponent) { componentsWithFocusListners.add(targetComponent); targetComponent.addFocusListener(new FocusListener() { public void focusGained(FocusEvent e) { } public void focusLost(FocusEvent e) { boolean oppositeIsParent = false; try { oppositeIsParent = (e.getComponent().equals(e.getOppositeComponent().getParent()) || e.getComponent().getParent().equals(e.getOppositeComponent())); if (!oppositeIsParent && e.getComponent().getParent() != null) { if (!e.getOppositeComponent().getParent().equals(editorPanel)) { ArbilTableCellEditor.this.stopCellEditing(); } } } catch (Exception ex) { System.out.println("OppositeComponent or parent container not set"); } } }); } private String getEditorText(int lastKeyInt, char lastKeyChar, String currentCellString) { switch (lastKeyInt) { case KeyEvent.VK_DELETE: currentCellString = ""; break; case KeyEvent.VK_BACK_SPACE: currentCellString = ""; break; case KeyEvent.VK_INSERT: break; case KeyEvent.VK_ESCAPE: break; case KeyEvent.VK_NUM_LOCK: break; case KeyEvent.VK_CAPS_LOCK: break; case KeyEvent.CHAR_UNDEFINED: break; default: if (lastKeyChar != KeyEvent.CHAR_UNDEFINED) { currentCellString = currentCellString + lastKeyChar; } break; } return currentCellString; } private boolean cellHasControlledVocabulary() { return ((ImdiField) cellValue[0]).hasVocabulary(); } public void startLongfieldEditor(JTable table, Object value, boolean isSelected, int row, int column) { getTableCellEditorComponent(table, value, isSelected, row, column); // startEditorMode(true, KeyEvent.CHAR_UNDEFINED, KeyEvent.CHAR_UNDEFINED); fireEditingStopped(); if (cellValue instanceof ImdiField[]) { int currentFieldIndex = selectedField; if (currentFieldIndex < 0) { currentFieldIndex = 0; } new ArbilLongFieldEditor(parentTable).showEditor((ImdiField[]) cellValue, getEditorText(KeyEvent.CHAR_UNDEFINED, KeyEvent.CHAR_UNDEFINED, ((ImdiField) cellValue[currentFieldIndex]).getFieldValue()), currentFieldIndex); } } private void startEditorMode(boolean ctrlDown, int lastKeyInt, char lastKeyChar) { // System.out.println("startEditorMode: " + selectedField + " lastKeyInt: " + lastKeyInt + " lastKeyChar: " + lastKeyChar); removeAllFocusListners(); if (cellValue instanceof ImdiField[]) { if (cellHasControlledVocabulary()) { if (isCellEditable()) { // if the cell has a vocabulary then prevent the long field editor System.out.println("Has Vocabulary"); ControlledVocabularyComboBox cvComboBox = new ControlledVocabularyComboBox((ImdiField) cellValue[selectedField]); editorPanel.remove(button); editorPanel.add(cvComboBox); editorPanel.doLayout(); cvComboBox.setPopupVisible(true); cvComboBox.addPopupMenuListener(new PopupMenuListener() { public void popupMenuWillBecomeVisible(PopupMenuEvent e) { } public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { fireEditingStopped(); } public void popupMenuCanceled(PopupMenuEvent e) { fireEditingStopped(); } }); editorComponent = cvComboBox; addFocusListener(cvComboBox); addFocusListener(cvComboBox.getEditor().getEditorComponent()); cvComboBox.getEditor().getEditorComponent().requestFocusInWindow(); } } else if (!ctrlDown && selectedField != -1 && (!requiresLongFieldEditor() || getEditorText(lastKeyInt, lastKeyChar, "anystring").length() == 0)) { // make sure the long field editor is not shown when the contents of the field are being deleted if (isCellEditable()) { editorPanel.remove(button); editorPanel.setLayout(new BoxLayout(editorPanel, BoxLayout.X_AXIS)); String currentCellString = cellValue[selectedField].toString(); ArbilFieldEditor editorTextField = new ArbilFieldEditor(getEditorText(lastKeyInt, lastKeyChar, currentCellString)); editorTextField.addKeyListener(new java.awt.event.KeyListener() { public void keyTyped(KeyEvent evt) { if (isStartLongFieldKey(evt)) { // if this is a long start long field event the we don't want that key appended so it is not passed on here if (cellValue instanceof ImdiField[]) { int currentFieldIndex = selectedField; if (currentFieldIndex < 0) { currentFieldIndex = 0; } new ArbilLongFieldEditor(parentTable).showEditor((ImdiField[]) cellValue, getEditorText(KeyEvent.CHAR_UNDEFINED, KeyEvent.CHAR_UNDEFINED, ((ImdiField) cellValue[currentFieldIndex]).getFieldValue()), currentFieldIndex); } } } public void keyPressed(KeyEvent evt) { } public void keyReleased(KeyEvent evt) { } }); editorPanel.setBorder(null); editorPanel.add(editorTextField); addFocusListener(editorTextField); if (cellValue[selectedField] instanceof ImdiField) { if (((ImdiField) cellValue[selectedField]).getLanguageId() != null) { // this is an ImdiField that has a fieldLanguageId JComboBox fieldLanguageBox = new LanguageIdBox((ImdiField) cellValue[selectedField], parentCellRect); editorPanel.add(fieldLanguageBox); addFocusListener(fieldLanguageBox); } } editorPanel.doLayout(); editorTextField.requestFocusInWindow(); editorComponent = editorTextField; } } else { fireEditingStopped(); if (cellValue instanceof ImdiField[]) { int currentFieldIndex = selectedField; if (currentFieldIndex < 0) { currentFieldIndex = 0; } new ArbilLongFieldEditor(parentTable).showEditor((ImdiField[]) cellValue, getEditorText(lastKeyInt, lastKeyChar, ((ImdiField) cellValue[currentFieldIndex]).getFieldValue()), currentFieldIndex); } // ArbilTableCellEditor.this.stopCellEditing(); } } else if (cellValue instanceof ImdiTreeObject[]) { LinorgWindowManager.getSingleInstance().openFloatingTableOnce((ImdiTreeObject[]) cellValue, fieldName + " in " + registeredOwner); } else { try { throw new Exception("Edit cell type not supported"); } catch (Exception ex) { GuiHelper.linorgBugCatcher.logError(ex); } } } public Object getCellEditorValue() { // System.out.println("getCellEditorValue"); if (selectedField != -1) { if (editorComponent != null) { if (editorComponent instanceof ControlledVocabularyComboBox) { ((ImdiField[]) cellValue)[selectedField].setFieldValue(((ControlledVocabularyComboBox) editorComponent).getCurrentValue(), true, false); } else if (editorComponent instanceof ArbilFieldEditor) { ((ImdiField[]) cellValue)[selectedField].setFieldValue(((ArbilFieldEditor) editorComponent).getText(), true, false); } } return cellValue[selectedField]; } else { return cellValue; } } private void convertCellValue(Object value) { if (value != null) { if (value instanceof ImdiField) { // TODO: get the whole array from the parent and select the correct tab for editing fieldName = ((ImdiField) value).getTranslateFieldName(); cellValue = ((ImdiField) value).parentImdi.getFields().get(fieldName); // TODO: find the chosen fields index in the array and store for (int cellFieldCounter = 0; cellFieldCounter < cellValue.length; cellFieldCounter++) { System.out.println("selectedField: " + cellValue[cellFieldCounter] + " : " + value); if (cellValue[cellFieldCounter].equals(value)) { System.out.println("selectedField found"); selectedField = cellFieldCounter; } } } else { cellValue = (Object[]) value; if (cellValue[0] instanceof ImdiField) { fieldName = ((ImdiField[]) cellValue)[0].getTranslateFieldName(); } } if (cellValue[0] instanceof ImdiField) { registeredOwner = ((ImdiField) cellValue[0]).parentImdi; } } else { GuiHelper.linorgBugCatcher.logError(new Exception("value is null in convertCellValue")); } } public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { // TODO: something in this area is preventing the table selection change listener firing ergo the tree selection does not get updated (this symptom can also be caused by a node not being loaded into the tree) // receivedKeyDown = true; parentTable = (ImdiTable) table; parentCellRect = parentTable.getCellRect(row, column, false); ImdiTableCellRenderer cellRenderer = new ImdiTableCellRenderer(value); convertCellValue(value); // columnName = table.getColumnName(column); // rowImdi = table.getValueAt(row, 0); button.setText(cellRenderer.getText()); button.setForeground(cellRenderer.getForeground()); button.setIcon(cellRenderer.getIcon()); editorPanel.setBackground(table.getSelectionBackground()); editorPanel.setLayout(new BorderLayout()); editorPanel.add(button); addFocusListener(button); //table.requestFocusInWindow(); SwingUtilities.invokeLater(new Runnable() { public void run() { button.requestFocusInWindow(); } }); return editorPanel; } }
package org.apache.xerces.utils; /** * A class representing properties of characters according to various * W3C recommendations * * XMLCharacterProperties provides convenience methods for commonly used * character tests. * * For performance reasons, the tables used by the convenience methods are * also public, and are directly accessed by performance critical routines. * */ public final class XMLCharacterProperties { /* * [26] VersionNum ::= ([a-zA-Z0-9_.:] | '-')+ * * Note: This is the same as the ascii portion of the * NameChar definition. */ /** * Check to see if a string is a valid version string according to * [26] in the XML 1.0 Recommendation * * @param version string to check * @return true if version is a valid version string */ public static boolean validVersionNum(String version) { int len = version.length(); if (len == 0) return false; for (int i = 0; i < len; i++) { char ch = version.charAt(i); if (ch > 'z' || fgAsciiNameChar[ch] == 0) return false; } return true; } /* * [81] EncName ::= [A-Za-z] ([A-Za-z0-9._] | '-')* */ /** * Check to see if a string is a valid encoding name according to [81] * in the XML 1.0 Recommendation * * @param encoding string to check * @return true if encoding is a valid encoding name */ public static boolean validEncName(String encoding) { int len = encoding.length(); if (len == 0) return false; char ch = encoding.charAt(0); if (ch > 'z' || fgAsciiAlphaChar[ch] == 0) return false; for (int i = 1; i < len; i++) { ch = encoding.charAt(i); if (ch > 'z' || fgAsciiEncNameChar[ch] == 0) return false; } return true; } /* * [13] PubidChar ::= #x20 | #xD | #xA | [a-zA-Z0-9] | [-'()+,./:=?;!*#@$_%] */ /** * Check to see if a string is a valid public identifier according to [13] * in the XML 1.0 Recommendation * * @param publicId string to check * @return true if publicId is a valid public identifier */ public static int validPublicId(String publicId) { int len = publicId.length(); if (len == 0) return -1; for (int i = 0; i < len; i++) { char ch = publicId.charAt(i); if (ch > 'z' || fgAsciiPubidChar[ch] == 0) return i; } return -1; } /* * [5] Name ::= (Letter | '_' | ':') (NameChar)* */ /** * Check to see if a string is a valid Name according to [5] * in the XML 1.0 Recommendation * * @param name string to check * @return true if name is a valid Name */ public static boolean validName(String name) { int len = name.length(); if (len == 0) return false; char ch = name.charAt(0); if (ch > 'z') { if ((fgCharFlags[ch] & E_InitialNameCharFlag) == 0) return false; } else if (fgAsciiInitialNameChar[ch] == 0) return false; for (int i = 1; i < len; i++) { ch = name.charAt(i); if (ch > 'z') { if ((fgCharFlags[ch] & E_NameCharFlag) == 0) return false; } else if (fgAsciiNameChar[ch] == 0) return false; } return true; } /* * from the namespace rec * [5] NCName ::= (Letter | '_' | ':') (NameNCChar)* */ /** * Check to see if a string is a valid NCName according to [5] * from the XML Namespaces 1.0 Recommendation * * @param name string to check * @return true if name is a valid NCName */ public static boolean validNCName(String name) { int len = name.length(); if (len == 0) return false; char ch = name.charAt(0); if (ch > 'z') { if ((fgCharFlags[ch] & E_InitialNameCharFlag) == 0) return false; } else if (fgAsciiInitialNCNameChar[ch] == 0) return false; for (int i = 1; i < len; i++) { ch = name.charAt(i); if (ch > 'z') { if ((fgCharFlags[ch] & E_NameCharFlag) == 0) return false; } else if (fgAsciiNCNameChar[ch] == 0) return false; } return true; } /* * [7] Nmtoken ::= (NameChar)+ */ /** * Check to see if a string is a valid Nmtoken according to [7] * in the XML 1.0 Recommendation * * @param nmtoken string to checj * @return true if nmtoken is a valid Nmtoken */ public static boolean validNmtoken(String nmtoken) { int len = nmtoken.length(); if (len == 0) return false; for (int i = 0; i < len; i++) { char ch = nmtoken.charAt(i); if (ch > 'z') { if ((fgCharFlags[ch] & E_NameCharFlag) == 0) return false; } else if (fgAsciiNameChar[ch] == 0) { return false; } } return true; } /* * Here are tables used to build character properties. */ public static final byte fgAsciiXDigitChar[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // '0' - '9' 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'A' - 'F' 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'a' - 'f' 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; public static final byte fgAsciiAlphaChar[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 'A' - 'O' 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, // 'P' - 'Z' 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 'a' - 'o' 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 // 'p' - 'z' }; public static final byte fgAsciiEncNameChar[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, // '-' is 0x2D and '.' is 0x2E 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // '0' - '9' 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 'A' - 'O' 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, // 'P' - 'Z' and '_' is 0x5F 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 'a' - 'o' 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 // 'p' - 'z' }; public static final byte fgAsciiPubidChar[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, // ' ', '!', ' 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, // '0' - '9', ':', ';', '=', '?' 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // '@', 'A' - 'O' 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, // 'P' - 'Z' and '_' is 0x5F 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 'a' - 'o' 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 // 'p' - 'z' }; public static final byte fgAsciiInitialNameChar[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, // ':' is 0x3A 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 'A' - 'O' 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, // 'P' - 'Z' and '_' is 0x5F 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 'a' - 'o' 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 // 'p' - 'z' }; public static final byte fgAsciiNameChar[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, // '-' is 0x2D and '.' is 0x2E 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, // '0' - '9' and ':' is 0x3A 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 'A' - 'O' 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, // 'P' - 'Z' and '_' is 0x5F 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 'a' - 'o' 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 // 'p' - 'z' }; public static final byte fgAsciiInitialNCNameChar[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // ':' is 0x3A 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 'A' - 'O' 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, // 'P' - 'Z' and '_' is 0x5F 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 'a' - 'o' 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 // 'p' - 'z' }; public static final byte fgAsciiNCNameChar[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, // '-' is 0x2D and '.' is 0x2E 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // '0' - '9' and ':' is 0x3A 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 'A' - 'O' 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, // 'P' - 'Z' and '_' is 0x5F 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 'a' - 'o' 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 // 'p' - 'z' }; public static final byte fgAsciiCharData[] = { 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 4, 4, 4, 4, 4, 4, // tab is 0x09 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, // '&' is 0x26 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, // '<' is 0x3C 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, // ']' is 0x5D 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; public static final byte fgAsciiWSCharData[] = { 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 4, 4, 5, 4, 4, // tab is 0x09, LF is 0x0A, CR is 0x0D 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, // ' ' is 0x20, '&' is 0x26 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, // '<' is 0x3C 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, // ']' is 0x5D 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; public static final byte E_CharDataFlag = 1<<0; public static final byte E_InitialNameCharFlag = 1<<1; public static final byte E_NameCharFlag = 1<<2; public static byte[] fgCharFlags = null; public static synchronized void initCharFlags() { if (fgCharFlags == null) { fgCharFlags = new byte[0x10000]; setFlagForRange(fgCharDataRanges, E_CharDataFlag); setFlagForRange(fgInitialNameCharRanges, (byte)(E_InitialNameCharFlag | E_NameCharFlag)); setFlagForRange(fgNameCharRanges, E_NameCharFlag); } } private static void setFlagForRange(char[] ranges, byte flag) { int i; int ch; for (i = 0; (ch = ranges[i]) != 0; i += 2) { int endch = ranges[i+1]; while (ch <= endch) fgCharFlags[ch++] |= flag; } for (i++; (ch = ranges[i]) != 0; i++) fgCharFlags[ch] |= flag; } /* * [2] Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] // any Unicode character, excluding the * | [#xE000-#xFFFD] | [#x10000-#x10FFFF] // surrogate blocks, FFFE, and FFFF. * [14] CharData ::= [^<&]* - ([^<&]* ']]>' [^<&]*) * * We will use Char - ( [^<&] | ']' | #xA | #xD ) and handle the special cases inline. */ private static final char fgCharDataRanges[] = { 0x0020, 0x0025, // '&' is 0x0026 0x0027, 0x003B, // '<' is 0x003C 0x003D, 0x005C, // ']' is 0x005D 0x005E, 0xD7FF, 0xE000, 0xFFFD, 0x0000, 0x0009, // tab 0x0000 }; /* * [5] Name ::= (Letter | '_' | ':') (NameChar)* * [4] NameChar ::= Letter | Digit | '.' | '-' | '_' | ':' | CombiningChar | Extender * [84] Letter ::= BaseChar | Ideographic * [85] BaseChar ::= <see standard> * [86] Ideographic ::= <see standard> * [87] CombiningChar ::= <see standard> * [88] Digit ::= <see standard> * [89] Extender ::= <see standard> */ private static final char fgInitialNameCharRanges[] = { // Ranges: // BaseChar ranges 0x0041, 0x005A, 0x0061, 0x007A, 0x00C0, 0x00D6, 0x00D8, 0x00F6, 0x00F8, 0x0131, 0x0134, 0x013E, 0x0141, 0x0148, 0x014A, 0x017E, 0x0180, 0x01C3, 0x01CD, 0x01F0, 0x01F4, 0x01F5, 0x01FA, 0x0217, 0x0250, 0x02A8, 0x02BB, 0x02C1, 0x0388, 0x038A, 0x038E, 0x03A1, 0x03A3, 0x03CE, 0x03D0, 0x03D6, 0x03E2, 0x03F3, 0x0401, 0x040C, 0x040E, 0x044F, 0x0451, 0x045C, 0x045E, 0x0481, 0x0490, 0x04C4, 0x04C7, 0x04C8, 0x04CB, 0x04CC, 0x04D0, 0x04EB, 0x04EE, 0x04F5, 0x04F8, 0x04F9, 0x0531, 0x0556, 0x0561, 0x0586, 0x05D0, 0x05EA, 0x05F0, 0x05F2, 0x0621, 0x063A, 0x0641, 0x064A, 0x0671, 0x06B7, 0x06BA, 0x06BE, 0x06C0, 0x06CE, 0x06D0, 0x06D3, 0x06E5, 0x06E6, 0x0905, 0x0939, 0x0958, 0x0961, 0x0985, 0x098C, 0x098F, 0x0990, 0x0993, 0x09A8, 0x09AA, 0x09B0, 0x09B6, 0x09B9, 0x09DC, 0x09DD, 0x09DF, 0x09E1, 0x09F0, 0x09F1, 0x0A05, 0x0A0A, 0x0A0F, 0x0A10, 0x0A13, 0x0A28, 0x0A2A, 0x0A30, 0x0A32, 0x0A33, 0x0A35, 0x0A36, 0x0A38, 0x0A39, 0x0A59, 0x0A5C, 0x0A72, 0x0A74, 0x0A85, 0x0A8B, 0x0A8F, 0x0A91, 0x0A93, 0x0AA8, 0x0AAA, 0x0AB0, 0x0AB2, 0x0AB3, 0x0AB5, 0x0AB9, 0x0B05, 0x0B0C, 0x0B0F, 0x0B10, 0x0B13, 0x0B28, 0x0B2A, 0x0B30, 0x0B32, 0x0B33, 0x0B36, 0x0B39, 0x0B5C, 0x0B5D, 0x0B5F, 0x0B61, 0x0B85, 0x0B8A, 0x0B8E, 0x0B90, 0x0B92, 0x0B95, 0x0B99, 0x0B9A, 0x0B9E, 0x0B9F, 0x0BA3, 0x0BA4, 0x0BA8, 0x0BAA, 0x0BAE, 0x0BB5, 0x0BB7, 0x0BB9, 0x0C05, 0x0C0C, 0x0C0E, 0x0C10, 0x0C12, 0x0C28, 0x0C2A, 0x0C33, 0x0C35, 0x0C39, 0x0C60, 0x0C61, 0x0C85, 0x0C8C, 0x0C8E, 0x0C90, 0x0C92, 0x0CA8, 0x0CAA, 0x0CB3, 0x0CB5, 0x0CB9, 0x0CE0, 0x0CE1, 0x0D05, 0x0D0C, 0x0D0E, 0x0D10, 0x0D12, 0x0D28, 0x0D2A, 0x0D39, 0x0D60, 0x0D61, 0x0E01, 0x0E2E, 0x0E32, 0x0E33, 0x0E40, 0x0E45, 0x0E81, 0x0E82, 0x0E87, 0x0E88, 0x0E94, 0x0E97, 0x0E99, 0x0E9F, 0x0EA1, 0x0EA3, 0x0EAA, 0x0EAB, 0x0EAD, 0x0EAE, 0x0EB2, 0x0EB3, 0x0EC0, 0x0EC4, 0x0F40, 0x0F47, 0x0F49, 0x0F69, 0x10A0, 0x10C5, 0x10D0, 0x10F6, 0x1102, 0x1103, 0x1105, 0x1107, 0x110B, 0x110C, 0x110E, 0x1112, 0x1154, 0x1155, 0x115F, 0x1161, 0x116D, 0x116E, 0x1172, 0x1173, 0x11AE, 0x11AF, 0x11B7, 0x11B8, 0x11BC, 0x11C2, 0x1E00, 0x1E9B, 0x1EA0, 0x1EF9, 0x1F00, 0x1F15, 0x1F18, 0x1F1D, 0x1F20, 0x1F45, 0x1F48, 0x1F4D, 0x1F50, 0x1F57, 0x1F5F, 0x1F7D, 0x1F80, 0x1FB4, 0x1FB6, 0x1FBC, 0x1FC2, 0x1FC4, 0x1FC6, 0x1FCC, 0x1FD0, 0x1FD3, 0x1FD6, 0x1FDB, 0x1FE0, 0x1FEC, 0x1FF2, 0x1FF4, 0x1FF6, 0x1FFC, 0x212A, 0x212B, 0x2180, 0x2182, 0x3041, 0x3094, 0x30A1, 0x30FA, 0x3105, 0x312C, 0xAC00, 0xD7A3, // Ideographic ranges 0x3021, 0x3029, 0x4E00, 0x9FA5, // Ranges end marker 0x0000, // Single char values 0x003A, 0x005F, // BaseChar singles 0x0386, 0x038C, 0x03DA, 0x03DC, 0x03DE, 0x03E0, 0x0559, 0x06D5, 0x093D, 0x09B2, 0x0A5E, 0x0A8D, 0x0ABD, 0x0AE0, 0x0B3D, 0x0B9C, 0x0CDE, 0x0E30, 0x0E84, 0x0E8A, 0x0E8D, 0x0EA5, 0x0EA7, 0x0EB0, 0x0EBD, 0x1100, 0x1109, 0x113C, 0x113E, 0x1140, 0x114C, 0x114E, 0x1150, 0x1159, 0x1163, 0x1165, 0x1167, 0x1169, 0x1175, 0x119E, 0x11A8, 0x11AB, 0x11BA, 0x11EB, 0x11F0, 0x11F9, 0x1F59, 0x1F5B, 0x1F5D, 0x1FBE, 0x2126, 0x212E, // Ideographic singles 0x3007, // Singles end marker 0x0000 }; private static final char fgNameCharRanges[] = { // Ranges: 0x002D, 0x002E, // '-' and '.' // CombiningChar ranges 0x0300, 0x0345, 0x0360, 0x0361, 0x0483, 0x0486, 0x0591, 0x05A1, 0x05A3, 0x05B9, 0x05BB, 0x05BD, 0x05C1, 0x05C2, 0x064B, 0x0652, 0x06D6, 0x06DC, 0x06DD, 0x06DF, 0x06E0, 0x06E4, 0x06E7, 0x06E8, 0x06EA, 0x06ED, 0x0901, 0x0903, 0x093E, 0x094C, 0x0951, 0x0954, 0x0962, 0x0963, 0x0981, 0x0983, 0x09C0, 0x09C4, 0x09C7, 0x09C8, 0x09CB, 0x09CD, 0x09E2, 0x09E3, 0x0A40, 0x0A42, 0x0A47, 0x0A48, 0x0A4B, 0x0A4D, 0x0A70, 0x0A71, 0x0A81, 0x0A83, 0x0ABE, 0x0AC5, 0x0AC7, 0x0AC9, 0x0ACB, 0x0ACD, 0x0B01, 0x0B03, 0x0B3E, 0x0B43, 0x0B47, 0x0B48, 0x0B4B, 0x0B4D, 0x0B56, 0x0B57, 0x0B82, 0x0B83, 0x0BBE, 0x0BC2, 0x0BC6, 0x0BC8, 0x0BCA, 0x0BCD, 0x0C01, 0x0C03, 0x0C3E, 0x0C44, 0x0C46, 0x0C48, 0x0C4A, 0x0C4D, 0x0C55, 0x0C56, 0x0C82, 0x0C83, 0x0CBE, 0x0CC4, 0x0CC6, 0x0CC8, 0x0CCA, 0x0CCD, 0x0CD5, 0x0CD6, 0x0D02, 0x0D03, 0x0D3E, 0x0D43, 0x0D46, 0x0D48, 0x0D4A, 0x0D4D, 0x0E34, 0x0E3A, 0x0E47, 0x0E4E, 0x0EB4, 0x0EB9, 0x0EBB, 0x0EBC, 0x0EC8, 0x0ECD, 0x0F18, 0x0F19, 0x0F71, 0x0F84, 0x0F86, 0x0F8B, 0x0F90, 0x0F95, 0x0F99, 0x0FAD, 0x0FB1, 0x0FB7, 0x20D0, 0x20DC, 0x302A, 0x302F, // Digit ranges 0x0030, 0x0039, 0x0660, 0x0669, 0x06F0, 0x06F9, 0x0966, 0x096F, 0x09E6, 0x09EF, 0x0A66, 0x0A6F, 0x0AE6, 0x0AEF, 0x0B66, 0x0B6F, 0x0BE7, 0x0BEF, 0x0C66, 0x0C6F, 0x0CE6, 0x0CEF, 0x0D66, 0x0D6F, 0x0E50, 0x0E59, 0x0ED0, 0x0ED9, 0x0F20, 0x0F29, // Extender ranges 0x3031, 0x3035, 0x309D, 0x309E, 0x30FC, 0x30FE, // Ranges end marker 0x0000, // Single char values // CombiningChar singles 0x05BF, 0x05C4, 0x0670, 0x093C, 0x094D, 0x09BC, 0x09BE, 0x09BF, 0x09D7, 0x0A02, 0x0A3C, 0x0A3E, 0x0A3F, 0x0ABC, 0x0B3C, 0x0BD7, 0x0D57, 0x0E31, 0x0EB1, 0x0F35, 0x0F37, 0x0F39, 0x0F3E, 0x0F3F, 0x0F97, 0x0FB9, 0x20E1, 0x3099, 0x309A, // Extender singles 0x00B7, 0x02D0, 0x02D1, 0x0387, 0x0640, 0x0E46, 0x0EC6, 0x3005, // Singles end marker 0x0000 }; }
package org.bouncycastle.crypto.tls; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.math.BigInteger; import java.security.SecureRandom; import java.util.Enumeration; import java.util.Hashtable; import org.bouncycastle.asn1.DERBitString; import org.bouncycastle.asn1.x509.KeyUsage; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.asn1.x509.X509CertificateStructure; import org.bouncycastle.asn1.x509.X509Extension; import org.bouncycastle.asn1.x509.X509Extensions; import org.bouncycastle.crypto.AsymmetricCipherKeyPair; import org.bouncycastle.crypto.CryptoException; import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.Signer; import org.bouncycastle.crypto.agreement.DHBasicAgreement; import org.bouncycastle.crypto.agreement.srp.SRP6Client; import org.bouncycastle.crypto.digests.SHA1Digest; import org.bouncycastle.crypto.encodings.PKCS1Encoding; import org.bouncycastle.crypto.engines.RSABlindedEngine; import org.bouncycastle.crypto.generators.DHBasicKeyPairGenerator; import org.bouncycastle.crypto.io.SignerInputStream; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.crypto.params.DHKeyGenerationParameters; import org.bouncycastle.crypto.params.DHParameters; import org.bouncycastle.crypto.params.DHPublicKeyParameters; import org.bouncycastle.crypto.params.DSAPublicKeyParameters; import org.bouncycastle.crypto.params.ParametersWithRandom; import org.bouncycastle.crypto.params.RSAKeyParameters; import org.bouncycastle.crypto.prng.ThreadedSeedGenerator; import org.bouncycastle.crypto.util.PublicKeyFactory; import org.bouncycastle.util.BigIntegers; /** * An implementation of all high level protocols in TLS 1.0. */ public class TlsProtocolHandler { private static final BigInteger ONE = BigInteger.valueOf(1); private static final BigInteger TWO = BigInteger.valueOf(2); private static final short RL_CHANGE_CIPHER_SPEC = 20; private static final short RL_ALERT = 21; private static final short RL_HANDSHAKE = 22; private static final short RL_APPLICATION_DATA = 23; /* hello_request(0), client_hello(1), server_hello(2), certificate(11), server_key_exchange (12), certificate_request(13), server_hello_done(14), certificate_verify(15), client_key_exchange(16), finished(20), (255) */ private static final short HP_HELLO_REQUEST = 0; private static final short HP_CLIENT_HELLO = 1; private static final short HP_SERVER_HELLO = 2; private static final short HP_CERTIFICATE = 11; private static final short HP_SERVER_KEY_EXCHANGE = 12; private static final short HP_CERTIFICATE_REQUEST = 13; private static final short HP_SERVER_HELLO_DONE = 14; private static final short HP_CERTIFICATE_VERIFY = 15; private static final short HP_CLIENT_KEY_EXCHANGE = 16; private static final short HP_FINISHED = 20; /* * Our Connection states */ private static final short CS_CLIENT_HELLO_SEND = 1; private static final short CS_SERVER_HELLO_RECEIVED = 2; private static final short CS_SERVER_CERTIFICATE_RECEIVED = 3; private static final short CS_SERVER_KEY_EXCHANGE_RECEIVED = 4; private static final short CS_CERTIFICATE_REQUEST_RECEIVED = 5; private static final short CS_SERVER_HELLO_DONE_RECEIVED = 6; private static final short CS_CLIENT_KEY_EXCHANGE_SEND = 7; private static final short CS_CLIENT_VERIFICATION_SEND = 8; private static final short CS_CLIENT_CHANGE_CIPHER_SPEC_SEND = 9; private static final short CS_CLIENT_FINISHED_SEND = 10; private static final short CS_SERVER_CHANGE_CIPHER_SPEC_RECEIVED = 11; private static final short CS_DONE = 12; protected static final short AP_close_notify = 0; protected static final short AP_unexpected_message = 10; protected static final short AP_bad_record_mac = 20; protected static final short AP_decryption_failed = 21; protected static final short AP_record_overflow = 22; protected static final short AP_decompression_failure = 30; protected static final short AP_handshake_failure = 40; protected static final short AP_bad_certificate = 42; protected static final short AP_unsupported_certificate = 43; protected static final short AP_certificate_revoked = 44; protected static final short AP_certificate_expired = 45; protected static final short AP_certificate_unknown = 46; protected static final short AP_illegal_parameter = 47; protected static final short AP_unknown_ca = 48; protected static final short AP_access_denied = 49; protected static final short AP_decode_error = 50; protected static final short AP_decrypt_error = 51; protected static final short AP_export_restriction = 60; protected static final short AP_protocol_version = 70; protected static final short AP_insufficient_security = 71; protected static final short AP_internal_error = 80; protected static final short AP_user_canceled = 90; protected static final short AP_no_renegotiation = 100; protected static final short AL_warning = 1; protected static final short AL_fatal = 2; private static final byte[] emptybuf = new byte[0]; private static final String TLS_ERROR_MESSAGE = "Internal TLS error, this could be an attack"; /* * Queues for data from some protocols. */ private ByteQueue applicationDataQueue = new ByteQueue(); private ByteQueue changeCipherSpecQueue = new ByteQueue(); private ByteQueue alertQueue = new ByteQueue(); private ByteQueue handshakeQueue = new ByteQueue(); /* * The Record Stream we use */ private RecordStream rs; private SecureRandom random; /* * The public key of the server. */ private AsymmetricKeyParameter serverPublicKey = null; private TlsInputStream tlsInputStream = null; private TlsOuputStream tlsOutputStream = null; private boolean closed = false; private boolean failedWithError = false; private boolean appDataReady = false; private boolean extendedClientHello; private byte[] clientRandom; private byte[] serverRandom; private byte[] ms; private TlsCipherSuite chosenCipherSuite = null; private BigInteger SRP_A; private byte[] SRP_identity, SRP_password; private BigInteger Yc; private byte[] pms; private CertificateVerifyer verifyer = null; public TlsProtocolHandler(InputStream is, OutputStream os) { /* * We use our threaded seed generator to generate a good random * seed. If the user has a better random seed, he should use * the constructor with a SecureRandom. */ ThreadedSeedGenerator tsg = new ThreadedSeedGenerator(); this.random = new SecureRandom(); /* * Hopefully, 20 bytes in fast mode are good enough. */ this.random.setSeed(tsg.generateSeed(20, true)); this.rs = new RecordStream(this, is, os); } public TlsProtocolHandler(InputStream is, OutputStream os, SecureRandom sr) { this.random = sr; this.rs = new RecordStream(this, is, os); } private short connection_state; protected void processData(short protocol, byte[] buf, int offset, int len) throws IOException { /* * Have a look at the protocol type, and add it to the correct queue. */ switch (protocol) { case RL_CHANGE_CIPHER_SPEC: changeCipherSpecQueue.addData(buf, offset, len); processChangeCipherSpec(); break; case RL_ALERT: alertQueue.addData(buf, offset, len); processAlert(); break; case RL_HANDSHAKE: handshakeQueue.addData(buf, offset, len); processHandshake(); break; case RL_APPLICATION_DATA: if (!appDataReady) { this.failWithError(AL_fatal, AP_unexpected_message); } applicationDataQueue.addData(buf, offset, len); processApplicationData(); break; default: /* * Uh, we don't know this protocol. * * RFC2246 defines on page 13, that we should ignore this. */ } } private void processHandshake() throws IOException { boolean read; do { read = false; /* * We need the first 4 bytes, they contain type and length of * the message. */ if (handshakeQueue.size() >= 4) { byte[] beginning = new byte[4]; handshakeQueue.read(beginning, 0, 4, 0); ByteArrayInputStream bis = new ByteArrayInputStream(beginning); short type = TlsUtils.readUint8(bis); int len = TlsUtils.readUint24(bis); /* * Check if we have enough bytes in the buffer to read * the full message. */ if (handshakeQueue.size() >= (len + 4)) { /* * Read the message. */ byte[] buf = new byte[len]; handshakeQueue.read(buf, 0, len, 4); handshakeQueue.removeData(len + 4); /* * If it is not a finished message, update our hashes * we prepare for the finish message. */ if (type != HP_FINISHED) { rs.hash1.update(beginning, 0, 4); rs.hash2.update(beginning, 0, 4); rs.hash1.update(buf, 0, len); rs.hash2.update(buf, 0, len); } /* * Now, parse the message. */ ByteArrayInputStream is = new ByteArrayInputStream(buf); /* * Check the type. */ switch (type) { case HP_CERTIFICATE: { switch (connection_state) { case CS_SERVER_HELLO_RECEIVED: { /* * Parse the certificates. */ Certificate cert = Certificate.parse(is); assertEmpty(is); X509CertificateStructure x509Cert = cert.certs[0]; SubjectPublicKeyInfo keyInfo = x509Cert.getSubjectPublicKeyInfo(); try { this.serverPublicKey = PublicKeyFactory.createKey(keyInfo); } catch (RuntimeException e) { this.failWithError(AL_fatal, AP_unsupported_certificate); } // Sanity check the PublicKeyFactory if (this.serverPublicKey.isPrivate()) { this.failWithError(AL_fatal, AP_internal_error); } /* * Perform various checks per RFC2246 7.4.2 * TODO "Unless otherwise specified, the signing algorithm for the certificate * must be the same as the algorithm for the certificate key." */ switch (this.chosenCipherSuite.getKeyExchangeAlgorithm()) { case TlsCipherSuite.KE_RSA: if (!(this.serverPublicKey instanceof RSAKeyParameters)) { this.failWithError(AL_fatal, AP_certificate_unknown); } validateKeyUsage(x509Cert, KeyUsage.keyEncipherment); break; case TlsCipherSuite.KE_DHE_RSA: case TlsCipherSuite.KE_SRP_RSA: if (!(this.serverPublicKey instanceof RSAKeyParameters)) { this.failWithError(AL_fatal, AP_certificate_unknown); } validateKeyUsage(x509Cert, KeyUsage.digitalSignature); break; case TlsCipherSuite.KE_DHE_DSS: case TlsCipherSuite.KE_SRP_DSS: if (!(this.serverPublicKey instanceof DSAPublicKeyParameters)) { this.failWithError(AL_fatal, AP_certificate_unknown); } break; default: this.failWithError(AL_fatal, AP_unsupported_certificate); } /* * Verify them. */ if (!this.verifyer.isValid(cert.getCerts())) { this.failWithError(AL_fatal, AP_user_canceled); } break; } default: this.failWithError(AL_fatal, AP_unexpected_message); } connection_state = CS_SERVER_CERTIFICATE_RECEIVED; read = true; break; } case HP_FINISHED: switch (connection_state) { case CS_SERVER_CHANGE_CIPHER_SPEC_RECEIVED: /* * Read the checksum from the finished message, * it has always 12 bytes. */ byte[] receivedChecksum = new byte[12]; TlsUtils.readFully(receivedChecksum, is); assertEmpty(is); /* * Calculate our own checksum. */ byte[] checksum = new byte[12]; byte[] md5andsha1 = new byte[16 + 20]; rs.hash2.doFinal(md5andsha1, 0); TlsUtils.PRF(this.ms, TlsUtils.toByteArray("server finished"), md5andsha1, checksum); /* * Compare both checksums. */ for (int i = 0; i < receivedChecksum.length; i++) { if (receivedChecksum[i] != checksum[i]) { /* * Wrong checksum in the finished message. */ this.failWithError(AL_fatal, AP_handshake_failure); } } connection_state = CS_DONE; /* * We are now ready to receive application data. */ this.appDataReady = true; read = true; break; default: this.failWithError(AL_fatal, AP_unexpected_message); } break; case HP_SERVER_HELLO: switch (connection_state) { case CS_CLIENT_HELLO_SEND: /* * Read the server hello message */ TlsUtils.checkVersion(is, this); /* * Read the server random */ this.serverRandom = new byte[32]; TlsUtils.readFully(this.serverRandom, is); /* * Currently, we don't support session ids */ byte[] sessionId = TlsUtils.readOpaque8(is); /* * Find out which ciphersuite the server has * chosen. If we don't support this ciphersuite, * the TlsCipherSuiteManager will throw an * exception. */ this.chosenCipherSuite = TlsCipherSuiteManager.getCipherSuite(TlsUtils.readUint16(is), this); /* * We support only the null compression which * means no compression. */ short compressionMethod = TlsUtils.readUint8(is); if (compressionMethod != 0) { this.failWithError(TlsProtocolHandler.AL_fatal, TlsProtocolHandler.AP_illegal_parameter); } /* * RFC4366 2.2 * The extended server hello message format MAY be sent * in place of the server hello message when the client * has requested extended functionality via the extended * client hello message specified in Section 2.1. */ if (extendedClientHello && is.available() > 0) { // Process extensions from extended server hello byte[] extBytes = TlsUtils.readOpaque16(is); // Integer -> byte[] Hashtable serverExtensions = new Hashtable(); ByteArrayInputStream ext = new ByteArrayInputStream(extBytes); while (ext.available() > 0) { int extType = TlsUtils.readUint16(ext); byte[] extValue = TlsUtils.readOpaque16(ext); serverExtensions.put(new Integer(extType), extValue); } // TODO Validate/process serverExtensions (via client?) // TODO[SRP] } assertEmpty(is); connection_state = CS_SERVER_HELLO_RECEIVED; read = true; break; default: this.failWithError(AL_fatal, AP_unexpected_message); } break; case HP_SERVER_HELLO_DONE: switch (connection_state) { case CS_SERVER_CERTIFICATE_RECEIVED: /* * There was no server key exchange message, check * that we are doing RSA key exchange. */ if (this.chosenCipherSuite.getKeyExchangeAlgorithm() != TlsCipherSuite.KE_RSA) { this.failWithError(AL_fatal, AP_unexpected_message); } /* * NB: Fall through to next case label to continue RSA key exchange */ case CS_SERVER_KEY_EXCHANGE_RECEIVED: case CS_CERTIFICATE_REQUEST_RECEIVED: assertEmpty(is); boolean isCertReq = (connection_state == CS_CERTIFICATE_REQUEST_RECEIVED); connection_state = CS_SERVER_HELLO_DONE_RECEIVED; if (isCertReq) { sendClientCertificate(); } /* * Send the client key exchange message, depending * on the key exchange we are using in our * ciphersuite. */ switch (this.chosenCipherSuite.getKeyExchangeAlgorithm()) { case TlsCipherSuite.KE_RSA: { /* * We are doing RSA key exchange. We will * choose a pre master secret and send it * rsa encrypted to the server. * * Prepare pre master secret. */ pms = new byte[48]; random.nextBytes(pms); pms[0] = 3; pms[1] = 1; /* * Encode the pms and send it to the server. * * Prepare an PKCS1Encoding with good random * padding. */ RSABlindedEngine rsa = new RSABlindedEngine(); PKCS1Encoding encoding = new PKCS1Encoding(rsa); encoding.init(true, new ParametersWithRandom(this.serverPublicKey, this.random)); byte[] encrypted = null; try { encrypted = encoding.processBlock(pms, 0, pms.length); } catch (InvalidCipherTextException e) { /* * This should never happen, only during decryption. */ this.failWithError(AL_fatal, AP_internal_error); } /* * Send the encrypted pms. */ sendClientKeyExchange(encrypted); break; } case TlsCipherSuite.KE_DHE_DSS: case TlsCipherSuite.KE_DHE_RSA: { /* * Send the Client Key Exchange message for * DHE key exchange. */ byte[] YcByte = BigIntegers.asUnsignedByteArray(this.Yc); sendClientKeyExchange(YcByte); break; } case TlsCipherSuite.KE_SRP: case TlsCipherSuite.KE_SRP_RSA: case TlsCipherSuite.KE_SRP_DSS: { /* * Send the Client Key Exchange message for * SRP key exchange. */ byte[] bytes = BigIntegers.asUnsignedByteArray(this.SRP_A); sendClientKeyExchange(bytes); break; } default: /* * Problem during handshake, we don't know * how to handle this key exchange method. */ this.failWithError(AL_fatal, AP_unexpected_message); } connection_state = CS_CLIENT_KEY_EXCHANGE_SEND; /* * Now, we send change cipher state */ byte[] cmessage = new byte[1]; cmessage[0] = 1; rs.writeMessage((short)RL_CHANGE_CIPHER_SPEC, cmessage, 0, cmessage.length); connection_state = CS_CLIENT_CHANGE_CIPHER_SPEC_SEND; /* * Calculate the ms */ this.ms = new byte[48]; byte[] random = new byte[clientRandom.length + serverRandom.length]; System.arraycopy(clientRandom, 0, random, 0, clientRandom.length); System.arraycopy(serverRandom, 0, random, clientRandom.length, serverRandom.length); TlsUtils.PRF(pms, TlsUtils.toByteArray("master secret"), random, this.ms); /* * Initialize our cipher suite */ rs.writeSuite = this.chosenCipherSuite; rs.writeSuite.init(this.ms, clientRandom, serverRandom); /* * Send our finished message. */ byte[] checksum = new byte[12]; byte[] md5andsha1 = new byte[16 + 20]; rs.hash1.doFinal(md5andsha1, 0); TlsUtils.PRF(this.ms, TlsUtils.toByteArray("client finished"), md5andsha1, checksum); ByteArrayOutputStream bos = new ByteArrayOutputStream(); TlsUtils.writeUint8(HP_FINISHED, bos); TlsUtils.writeUint24(12, bos); bos.write(checksum); byte[] message = bos.toByteArray(); rs.writeMessage((short)RL_HANDSHAKE, message, 0, message.length); this.connection_state = CS_CLIENT_FINISHED_SEND; read = true; break; default: this.failWithError(AL_fatal, AP_handshake_failure); } break; case HP_SERVER_KEY_EXCHANGE: { switch (connection_state) { case CS_SERVER_HELLO_RECEIVED: /* * Check that we are doing SRP key exchange */ if (this.chosenCipherSuite.getKeyExchangeAlgorithm() != TlsCipherSuite.KE_SRP) { this.failWithError(AL_fatal, AP_unexpected_message); } // NB: Fall through to next case label case CS_SERVER_CERTIFICATE_RECEIVED: { /* * Check that we are doing DHE key exchange */ switch (this.chosenCipherSuite.getKeyExchangeAlgorithm()) { case TlsCipherSuite.KE_DHE_RSA: { processDHEKeyExchange(is, new TlsRSASigner()); break; } case TlsCipherSuite.KE_DHE_DSS: { processDHEKeyExchange(is, new TlsDSSSigner()); break; } case TlsCipherSuite.KE_SRP: { processSRPKeyExchange(is, null); break; } case TlsCipherSuite.KE_SRP_RSA: { processSRPKeyExchange(is, new TlsRSASigner()); break; } case TlsCipherSuite.KE_SRP_DSS: { processSRPKeyExchange(is, new TlsDSSSigner()); break; } default: this.failWithError(AL_fatal, AP_unexpected_message); } break; } default: this.failWithError(AL_fatal, AP_unexpected_message); } this.connection_state = CS_SERVER_KEY_EXCHANGE_RECEIVED; read = true; break; } case HP_CERTIFICATE_REQUEST: { switch (connection_state) { case CS_SERVER_CERTIFICATE_RECEIVED: /* * There was no server key exchange message, check * that we are doing RSA key exchange. */ if (this.chosenCipherSuite.getKeyExchangeAlgorithm() != TlsCipherSuite.KE_RSA) { this.failWithError(AL_fatal, AP_unexpected_message); } /* * NB: Fall through to next case label to continue RSA key exchange */ case CS_SERVER_KEY_EXCHANGE_RECEIVED: { byte[] types = TlsUtils.readOpaque8(is); byte[] auths = TlsUtils.readOpaque16(is); // TODO Validate/process assertEmpty(is); break; } default: this.failWithError(AL_fatal, AP_unexpected_message); } this.connection_state = CS_CERTIFICATE_REQUEST_RECEIVED; read = true; break; } case HP_HELLO_REQUEST: case HP_CLIENT_KEY_EXCHANGE: case HP_CERTIFICATE_VERIFY: case HP_CLIENT_HELLO: default: // We do not support this! this.failWithError(AL_fatal, AP_unexpected_message); break; } } } } while (read); } private void processApplicationData() { /* * There is nothing we need to do here. * * This function could be used for callbacks when application * data arrives in the future. */ } private void processAlert() throws IOException { while (alertQueue.size() >= 2) { /* * An alert is always 2 bytes. Read the alert. */ byte[] tmp = new byte[2]; alertQueue.read(tmp, 0, 2, 0); alertQueue.removeData(2); short level = tmp[0]; short description = tmp[1]; if (level == AL_fatal) { /* * This is a fatal error. */ this.failedWithError = true; this.closed = true; /* * Now try to close the stream, ignore errors. */ try { rs.close(); } catch (Exception e) { } throw new IOException(TLS_ERROR_MESSAGE); } else { /* * This is just a warning. */ if (description == AP_close_notify) { /* * Close notify */ this.failWithError(AL_warning, AP_close_notify); } /* * If it is just a warning, we continue. */ } } } /** * This method is called, when a change cipher spec message is received. * * @throws IOException If the message has an invalid content or the * handshake is not in the correct state. */ private void processChangeCipherSpec() throws IOException { while (changeCipherSpecQueue.size() > 0) { /* * A change cipher spec message is only one byte with the value 1. */ byte[] b = new byte[1]; changeCipherSpecQueue.read(b, 0, 1, 0); changeCipherSpecQueue.removeData(1); if (b[0] != 1) { /* * This should never happen. */ this.failWithError(AL_fatal, AP_unexpected_message); } else { /* * Check if we are in the correct connection state. */ if (this.connection_state == CS_CLIENT_FINISHED_SEND) { rs.readSuite = rs.writeSuite; this.connection_state = CS_SERVER_CHANGE_CIPHER_SPEC_RECEIVED; } else { /* * We are not in the correct connection state. */ this.failWithError(AL_fatal, AP_handshake_failure); } } } } private void processDHEKeyExchange(ByteArrayInputStream is, Signer signer) throws IOException { InputStream sigIn = is; if (signer != null) { signer.init(false, this.serverPublicKey); signer.update(this.clientRandom, 0, this.clientRandom.length); signer.update(this.serverRandom, 0, this.serverRandom.length); sigIn = new SignerInputStream(is, signer); } /* * Parse the Structure */ byte[] pByte = TlsUtils.readOpaque16(sigIn); byte[] gByte = TlsUtils.readOpaque16(sigIn); byte[] YsByte = TlsUtils.readOpaque16(sigIn); if (signer != null) { byte[] sigByte = TlsUtils.readOpaque16(is); /* * Verify the Signature. */ if (!signer.verifySignature(sigByte)) { this.failWithError(AL_fatal, AP_bad_certificate); } } this.assertEmpty(is); /* * Do the DH calculation. */ BigInteger p = new BigInteger(1, pByte); BigInteger g = new BigInteger(1, gByte); BigInteger Ys = new BigInteger(1, YsByte); /* * Check the DH parameter values */ if (!p.isProbablePrime(10)) { this.failWithError(AL_fatal, AP_illegal_parameter); } if (g.compareTo(TWO) < 0 || g.compareTo(p.subtract(TWO)) > 0) { this.failWithError(AL_fatal, AP_illegal_parameter); } // TODO For static DH public values, see additional checks in RFC 2631 2.1.5 if (Ys.compareTo(TWO) < 0 || Ys.compareTo(p.subtract(ONE)) > 0) { this.failWithError(AL_fatal, AP_illegal_parameter); } /* * Diffie-Hellman basic key agreement */ DHParameters dhParams = new DHParameters(p, g); // Generate a keypair DHBasicKeyPairGenerator dhGen = new DHBasicKeyPairGenerator(); dhGen.init(new DHKeyGenerationParameters(random, dhParams)); AsymmetricCipherKeyPair dhPair = dhGen.generateKeyPair(); // Store the public value to send to server this.Yc = ((DHPublicKeyParameters)dhPair.getPublic()).getY(); // Calculate the shared secret DHBasicAgreement dhAgree = new DHBasicAgreement(); dhAgree.init(dhPair.getPrivate()); BigInteger agreement = dhAgree.calculateAgreement(new DHPublicKeyParameters(Ys, dhParams)); this.pms = BigIntegers.asUnsignedByteArray(agreement); } private void processSRPKeyExchange(ByteArrayInputStream is, Signer signer) throws IOException { InputStream sigIn = is; if (signer != null) { signer.init(false, this.serverPublicKey); signer.update(this.clientRandom, 0, this.clientRandom.length); signer.update(this.serverRandom, 0, this.serverRandom.length); sigIn = new SignerInputStream(is, signer); } /* * Parse the Structure */ byte[] NByte = TlsUtils.readOpaque16(sigIn); byte[] gByte = TlsUtils.readOpaque16(sigIn); byte[] sByte = TlsUtils.readOpaque8(sigIn); byte[] BByte = TlsUtils.readOpaque16(sigIn); if (signer != null) { byte[] sigByte = TlsUtils.readOpaque16(is); /* * Verify the Signature. */ if (!signer.verifySignature(sigByte)) { this.failWithError(AL_fatal, AP_bad_certificate); } } this.assertEmpty(is); BigInteger N = new BigInteger(1, NByte); BigInteger g = new BigInteger(1, gByte); byte[] s = sByte; BigInteger B = new BigInteger(1, BByte); SRP6Client srpClient = new SRP6Client(); srpClient.init(N, g, new SHA1Digest(), random); this.SRP_A = srpClient.generateClientCredentials(s, this.SRP_identity, this.SRP_password); try { BigInteger S = srpClient.calculateSecret(B); this.pms = BigIntegers.asUnsignedByteArray(S); } catch (CryptoException e) { this.failWithError(AL_fatal, AP_illegal_parameter); } } private void validateKeyUsage(X509CertificateStructure c, int keyUsageBits) throws IOException { X509Extensions exts = c.getTBSCertificate().getExtensions(); if (exts != null) { X509Extension ext = exts.getExtension(X509Extensions.KeyUsage); if (ext != null) { DERBitString ku = KeyUsage.getInstance(ext); int bits = ku.getBytes()[0] & 0xff; if ((bits & keyUsageBits) != keyUsageBits) { this.failWithError(AL_fatal, AP_certificate_unknown); } } } } private void sendClientCertificate() throws IOException { /* * just write back the "no client certificate" message * see also gnutls, auth_cert.c:643 (0B 00 00 03 00 00 00) */ ByteArrayOutputStream bos = new ByteArrayOutputStream(); TlsUtils.writeUint8(HP_CERTIFICATE, bos); TlsUtils.writeUint24(3, bos); TlsUtils.writeUint24(0, bos); byte[] message = bos.toByteArray(); rs.writeMessage((short)RL_HANDSHAKE, message, 0, message.length); } private void sendClientKeyExchange(byte[] keData) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); TlsUtils.writeUint8(HP_CLIENT_KEY_EXCHANGE, bos); TlsUtils.writeUint24(keData.length + 2, bos); TlsUtils.writeOpaque16(keData, bos); byte[] message = bos.toByteArray(); rs.writeMessage((short)RL_HANDSHAKE, message, 0, message.length); } /** * Connects to the remote system. * * @param verifyer Will be used when a certificate is received to verify * that this certificate is accepted by the client. * @throws IOException If handshake was not successful. */ public void connect(CertificateVerifyer verifyer) throws IOException { this.verifyer = verifyer; /* * Send Client hello * * First, generate some random data. */ this.clientRandom = new byte[32]; random.nextBytes(this.clientRandom); int t = (int)(System.currentTimeMillis() / 1000); this.clientRandom[0] = (byte)(t >> 24); this.clientRandom[1] = (byte)(t >> 16); this.clientRandom[2] = (byte)(t >> 8); this.clientRandom[3] = (byte)t; ByteArrayOutputStream os = new ByteArrayOutputStream(); TlsUtils.writeVersion(os); os.write(this.clientRandom); /* * Length of Session id */ TlsUtils.writeUint8((short)0, os); /* * Cipher suites */ TlsCipherSuiteManager.writeCipherSuites(os); /* * Compression methods, just the null method. */ byte[] compressionMethods = new byte[]{0x00}; TlsUtils.writeOpaque8(compressionMethods, os); /* * Extensions */ // TODO Collect extensions from client // Integer -> byte[] Hashtable clientExtensions = new Hashtable(); // TODO[SRP] // ByteArrayOutputStream srpData = new ByteArrayOutputStream(); // TlsUtils.writeOpaque8(SRP_identity, srpData); // // TODO[SRP] RFC5054 2.8.1: ExtensionType.srp = 12 // clientExtensions.put(Integer.valueOf(12), srpData.toByteArray()); this.extendedClientHello = !clientExtensions.isEmpty(); if (extendedClientHello) { ByteArrayOutputStream ext = new ByteArrayOutputStream(); Enumeration keys = clientExtensions.keys(); while (keys.hasMoreElements()) { Integer extType = (Integer)keys.nextElement(); byte[] extValue = (byte[])clientExtensions.get(extType); TlsUtils.writeUint16(extType.intValue(), ext); TlsUtils.writeOpaque16(extValue, ext); } TlsUtils.writeOpaque16(ext.toByteArray(), os); } ByteArrayOutputStream bos = new ByteArrayOutputStream(); TlsUtils.writeUint8(HP_CLIENT_HELLO, bos); TlsUtils.writeUint24(os.size(), bos); bos.write(os.toByteArray()); byte[] message = bos.toByteArray(); rs.writeMessage(RL_HANDSHAKE, message, 0, message.length); connection_state = CS_CLIENT_HELLO_SEND; /* * We will now read data, until we have completed the handshake. */ while (connection_state != CS_DONE) { rs.readData(); } this.tlsInputStream = new TlsInputStream(this); this.tlsOutputStream = new TlsOuputStream(this); } /** * Read data from the network. The method will return immediately, if there is * still some data left in the buffer, or block until some application * data has been read from the network. * * @param buf The buffer where the data will be copied to. * @param offset The position where the data will be placed in the buffer. * @param len The maximum number of bytes to read. * @return The number of bytes read. * @throws IOException If something goes wrong during reading data. */ protected int readApplicationData(byte[] buf, int offset, int len) throws IOException { while (applicationDataQueue.size() == 0) { /* * We need to read some data. */ if (this.failedWithError) { /* * Something went terribly wrong, we should throw an IOException */ throw new IOException(TLS_ERROR_MESSAGE); } if (this.closed) { /* * Connection has been closed, there is no more data to read. */ return -1; } try { rs.readData(); } catch (IOException e) { if (!this.closed) { this.failWithError(AL_fatal, AP_internal_error); } throw e; } catch (RuntimeException e) { if (!this.closed) { this.failWithError(AL_fatal, AP_internal_error); } throw e; } } len = Math.min(len, applicationDataQueue.size()); applicationDataQueue.read(buf, offset, len, 0); applicationDataQueue.removeData(len); return len; } /** * Send some application data to the remote system. * <p/> * The method will handle fragmentation internally. * * @param buf The buffer with the data. * @param offset The position in the buffer where the data is placed. * @param len The length of the data. * @throws IOException If something goes wrong during sending. */ protected void writeData(byte[] buf, int offset, int len) throws IOException { if (this.failedWithError) { throw new IOException(TLS_ERROR_MESSAGE); } if (this.closed) { throw new IOException("Sorry, connection has been closed, you cannot write more data"); } /* * Protect against known IV attack! * * DO NOT REMOVE THIS LINE, EXCEPT YOU KNOW EXACTLY WHAT * YOU ARE DOING HERE. */ rs.writeMessage(RL_APPLICATION_DATA, emptybuf, 0, 0); do { /* * We are only allowed to write fragments up to 2^14 bytes. */ int toWrite = Math.min(len, 1 << 14); try { rs.writeMessage(RL_APPLICATION_DATA, buf, offset, toWrite); } catch (IOException e) { if (!closed) { this.failWithError(AL_fatal, AP_internal_error); } throw e; } catch (RuntimeException e) { if (!closed) { this.failWithError(AL_fatal, AP_internal_error); } throw e; } offset += toWrite; len -= toWrite; } while (len > 0); } /** @deprecated use 'getOutputStream' instead */ public TlsOuputStream getTlsOuputStream() { return this.tlsOutputStream; } /** * @return An OutputStream which can be used to send data. */ public OutputStream getOutputStream() { return this.tlsOutputStream; } /** @deprecated use 'getInputStream' instead */ public TlsInputStream getTlsInputStream() { return this.tlsInputStream; } /** * @return An InputStream which can be used to read data. */ public InputStream getInputStream() { return this.tlsInputStream; } /** * Terminate this connection with an alert. * <p/> * Can be used for normal closure too. * * @param alertLevel The level of the alert, an be AL_fatal or AL_warning. * @param alertDescription The exact alert message. * @throws IOException If alert was fatal. */ protected void failWithError(short alertLevel, short alertDescription) throws IOException { /* * Check if the connection is still open. */ if (!closed) { /* * Prepare the message */ byte[] error = new byte[2]; error[0] = (byte)alertLevel; error[1] = (byte)alertDescription; this.closed = true; if (alertLevel == AL_fatal) { /* * This is a fatal message. */ this.failedWithError = true; } rs.writeMessage(RL_ALERT, error, 0, 2); rs.close(); if (alertLevel == AL_fatal) { throw new IOException(TLS_ERROR_MESSAGE); } } else { throw new IOException(TLS_ERROR_MESSAGE); } } /** * Closes this connection. * * @throws IOException If something goes wrong during closing. */ public void close() throws IOException { if (!closed) { this.failWithError((short)1, (short)0); } } /** * Make sure the InputStream is now empty. Fail otherwise. * * @param is The InputStream to check. * @throws IOException If is is not empty. */ protected void assertEmpty(ByteArrayInputStream is) throws IOException { if (is.available() > 0) { this.failWithError(AL_fatal, AP_decode_error); } } protected void flush() throws IOException { rs.flush(); } }
package org.jmist.packages; import org.jmist.framework.IIntersection; import org.jmist.framework.IIntersectionRecorder; /** * An intersection recorder that only keeps the nearest intersection * recorded. * @author bkimmel */ public final class NearestIntersectionRecorder implements IIntersectionRecorder { /* (non-Javadoc) * @see org.jmist.framework.IIntersectionRecorder#needAllIntersections() */ public boolean needAllIntersections() { return false; } /* (non-Javadoc) * @see org.jmist.framework.IIntersectionRecorder#record(org.jmist.framework.IIntersection) */ public void record(IIntersection intersection) { if (this.nearest == null || intersection.rayParameter() < this.nearest.rayParameter()) { this.nearest = intersection; } } /** * Determines if this intersection recorder is empty. * @return A value indicating if this intersection recorder is * empty. */ public boolean isEmpty() { return (this.nearest == null); } /** * Gets the intersection with the smallest ray parameter that has * been recorded. * @return The nearest intersection that has been recorded. */ public IIntersection nearestIntersection() { return this.nearest; } /** The nearest intersection that has been recorded so far. */ private IIntersection nearest = null; }
package org.objectweb.asm.attrs; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.objectweb.asm.Attribute; import org.objectweb.asm.ByteVector; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Label; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; /** * The stack map attribute is used during the process of * verification by typechecking (4.11.1). * <br><br> * A stack map attribute consists of zero or more stack map frames. Each stack map * frame specifies (either explicitly or implicitly) a bytecode offset, the verification * types (4.11.1) for the local variables, and the verification types for the operand * stack. * <br><br> * The type checker deals with and manipulates the expected types of a method's * local variables and operand stack. Throughout this section, a location refers to * either a single local variable or to a single operand stack entry. * <br><br> * We will use the terms stack frame map and type state interchangeably to describe * a mapping from locations in the operand stack and local variables of a method to * verification types. We will usually use the term stack frame map when such a * mapping is provided in the class file, and the term type state when the mapping is * inferred by the type checker. * <br><br> * If a method's Code attribute does not have a StackMapTable attribute, it has an * implicit stack map attribute. This implicit stack map attribute is equivalent to a * StackMapTable attribute with number_of_entries equal to zero. A method's Code * attribute may have at most one StackMapTable attribute, otherwise a * java.lang.ClassFormatError is thrown. * <br><br> * The format of the stack map in the class file is given below. In the following, if the * length of the method's byte code is 65535 or less, then uoffset represents the type * u2; otherwise uoffset represents the type u4. * If the maximum number of local variables for the method is 65535 or less, * then <code>ulocalvar</code> represents the type u2; * otherwise ulocalvar represents the type u4. * If the maximum size of the operand stack is 65535 or less, then <code>ustack</code> * represents the type u2; otherwise ustack represents the type u4. * * <pre> * stack_map { // attribute StackMapTable * u2 attribute_name_index; * u4 attribute_length * uoffset number_of_entries; * stack_map_frame entries[number_of_entries]; * } * </pre> * * Each stack_map_frame structure specifies the type state at a particular byte code * offset. Each frame type specifies (explicitly or implicitly) a value, offset_delta, that * is used to calulate the actual byte code offset at which it applies. The byte code * offset at which the frame applies is given by adding <code>1 + offset_delta</code> * to the <code>offset</code> of the previous frame, unless the previous frame is the * initial frame of the method, in which case the byte code offset is <code>offset_delta</code>. * <br><br> * <i>Note that the length of the byte codes is not the same as the length of the Code * attribute. The byte codes are embedded in the Code attribute, along with other * information.</i> * <br><br> * By using an offset delta rather than the actual byte code offset we * ensure, by definition, that stack map frames are in the correctly sorted * order. Furthermore, by consistently using the formula <code>offset_delta + 1</code> for * all explicit frames, we guarantee the absence of duplicates. * <br><br> * All frame types, even full_frame, rely on the previous frame for some of * their semantics. This raises the question of what is the very first frame? * The initial frame is implicit, and computed from the method descriptor. * See the Prolog code for methodInitialStacFrame. * <br><br> * The stack_map_frame structure consists of a one-byte tag followed by zero or more * bytes, giving more information, depending upon the tag. * <br><br> * A stack map frame may belong to one of several frame types * * <pre> * union stack_map_frame { * same_frame; * same_locals_1_stack_item_frame; * chop_frame; * same_frame_extended; * append_frame; * full_frame; * } * </pre> * * The frame type same_frame is represented by tags in the range [0-63]. If the frame * type is same_frame, it means the frame has exactly the same locals as the previous * stack map frame and that the number of stack items is zero. The offset_delta value * for the frame is the value of the tag field, frame_type. The form of such a frame is * then: * * <pre> * same_frame { * u1 frame_type = SAME; // 0-63 * } * </pre> * * The frame type same_locals_1_stack_item_frame is represented by tags in the range * [64, 127]. If the frame_type is same_locals_1_stack_item_frame, it means the frame * has exactly the same locals as the previous stack map frame and that the number * of stack items is 1. The offset_delta value for the frame is the value * (frame_type - 64). There is a verification_type_info following the frame_type * for the one stack item. The form of such a frame is then: * * <pre> * same_locals_1_stack_item_frame { * u1 frame_type = SAME_LOCALS_1_STACK_ITEM; // 64-127 * verification_type_info stack[1]; * } * </pre> * * Tags in the range [128-247] are reserved for future use. * <br><br> * The frame type chop_frame is represented by tags in the range [248-250]. If the * frame_type is chop_frame, it means that the current locals are the same as the locals * in the previous frame, except that the k last locals are absent. The value of k is * given by the formula 251-frame_type. * <br><br> * The form of such a frame is then: * * <pre> * chop_frame { * u1 frame_type=CHOP; // 248-250 * uoffset offset_delta; * } * </pre> * * The frame type same_frame_extended is represented by the tag value 251. If the * frame type is same_frame_extended, it means the frame has exactly the same locals * as the previous stack map frame and that the number of stack items is zero. * The form of such a frame is then: * * <pre> * same_frame_extended { * u1 frame_type = SAME_FRAME_EXTENDED; // 251 * uoffset offset_delta; * } * </pre> * * The frame type append_frame is represented by tags in the range [252-254]. If the * frame_type is append_frame, it means that the current locals are the same as the * locals in the previous frame, except that k additional locals are defined. The value * of k is given by the formula frame_type-251. * <br><br> * The form of such a frame is then: * * <pre> * append_frame { * u1 frame_type =APPEND; // 252-254 * uoffset offset_delta; * verification_type_info locals[frame_type -251]; * } * </pre> * * The 0th entry in locals represents the type of the first additional local variable. If * locals[M] represents local variable N, then locals[M+1] represents local variable N+1 * if locals[M] is one of Top_variable_info, Integer_variable_info, Float_variable_info, * Null_variable_info, UninitializedThis_variable_info, Object_variable_info, or * Uninitialized_variable_info, otherwise locals[M+1] represents local variable N+2. It is * an error if, for any index i, locals[i] represents a local variable whose index is * greater than the maximum number of local variables for the method. * <br><br> * The frame type full_frame is represented by the tag value 255. The form of such a * frame is then: * * <pre> * full_frame { * u1 frame_type = FULL_FRAME; // 255 * uoffset offset_delta; * ulocalvar number_of_locals; * verification_type_info locals[number_of_locals]; * ustack number_of_stack_items; * verification_type_info stack[number_of_stack_items]; * } * </pre> * * The 0th entry in locals represents the type of local variable 0. If locals[M] represents * local variable N, then locals[M+1] represents local variable N+1 if locals[M] is one * of Top_variable_info, Integer_variable_info, Float_variable_info, Null_variable_info, * UninitializedThis_variable_info, Object_variable_info, or Uninitialized_variable_info, * otherwise locals[M+1] represents local variable N+2. It is an error if, for any index * i, locals[i] represents a local variable whose index is greater than the maximum * number of local variables for the method. * <br><br> * The 0th entry in stack represents the type of the bottom of the stack, and * subsequent entries represent types of stack elements closer to the top of the * operand stack. We shall refer to the bottom element of the stack as stack element * 0, and to subsequent elements as stack element 1, 2 etc. If stack[M] represents stack * element N, then stack[M+1] represents stack element N+1 if stack[M] is one of * Top_variable_info, Integer_variable_info, Float_variable_info, Null_variable_info, * UninitializedThis_variable_info, Object_variable_info, or Uninitialized_variable_info, * otherwise stack[M+1] represents stack element N+2. It is an error if, for any index i, * stack[i] represents a stack entry whose index is greater than the maximum operand * stack size for the method. * <br><br> * We say that an instruction in the byte code has a corresponding stack map frame if * the offset in the offset field of the stack map frame is the same as the offset of the * instruction in the byte codes. * <br><br> * The verification_type_info structure consists of a one-byte tag followed by zero or * more bytes, giving more information about the tag. Each verification_type_info * structure specifies the verification type of one or two locations. * * <pre> * union verification_type_info { * Top_variable_info; * Integer_variable_info; * Float_variable_info; * Long_variable_info; * Double_variable_info; * Null_variable_info; * UninitializedThis_variable_info; * Object_variable_info; * Uninitialized_variable_info; * } * </pre> * * The Top_variable_info type indicates that the local variable has the verification type * top (T.) * * <pre> * Top_variable_info { * u1 tag = ITEM_Top; // 0 * } * </pre> * * The Integer_variable_info type indicates that the location contains the verification * type int. * * <pre> * Integer_variable_info { * u1 tag = ITEM_Integer; // 1 * } * </pre> * * The Float_variable_info type indicates that the location contains the verification type * float. * * <pre> * Float_variable_info { * u1 tag = ITEM_Float; // 2 * } * </pre> * * The Long_variable_info type indicates that the location contains the verification type * long. If the location is a local variable, then: * * <ul> * <li>It must not be the local variable with the highest index.</li> * <li>The next higher numbered local variable contains the verification type T.</li> * </ul> * * If the location is an operand stack entry, then: * * <ul> * <li>The current location must not be the topmost location of the operand stack.</li> * <li>the next location closer to the top of the operand stack contains the verification type T.</li> * </ul> * * This structure gives the contents of two locations in the operand stack or in the * local variables. * * <pre> * Long_variable_info { * u1 tag = ITEM_Long; // 4 * } * </pre> * * The Double_variable_info type indicates that the location contains the verification * type double. If the location is a local variable, then: * * <ul> * <li>It must not be the local variable with the highest index.</li> * <li>The next higher numbered local variable contains the verification type T.<li> * </ul> * * If the location is an operand stack entry, then: * * <ul> * <li>The current location must not be the topmost location of the operand stack.</li> * <li>the next location closer to the top of the operand stack contains the verification type T.</li> * </ul> * * This structure gives the contents of two locations in in the operand stack or in the * local variables. * * <pre> * Double_variable_info { * u1 tag = ITEM_Double; // 3 * } * </pre> * * The Null_variable_info type indicates that location contains the verification type null. * * <pre> * Null_variable_info { * u1 tag = ITEM_Null; // 5 * } * </pre> * * The UninitializedThis_variable_info type indicates that the location contains the * verification type uninitializedThis. * * <pre> * UninitializedThis_variable_info { * u1 tag = ITEM_UninitializedThis; // 6 * } * </pre> * * The Object_variable_info type indicates that the location contains an instance of the * class referenced by the constant pool entry. * * <pre> * Object_variable_info { * u1 tag = ITEM_Object; // 7 * u2 cpool_index; * } * </pre> * * The Uninitialized_variable_info indicates that the location contains the verification * type uninitialized(offset). The offset item indicates the offset of the new instruction * that created the object being stored in the location. * * <pre> * Uninitialized_variable_info { * u1 tag = ITEM_Uninitialized // 8 * uoffset offset; * } * </pre> * * @see "ClassFileFormat-Java6.fm Page 138 Friday, April 15, 2005 3:22 PM" * * @author Eugene Kuleshov */ public class StackMapTableAttribute extends Attribute { /** * Frame has exactly the same locals as the previous stack map frame and * number of stack items is zero. */ public static final int SAME_FRAME = 0; // to 63 (0-3f) /** * Frame has exactly the same locals as the previous stack map frame and * number of stack items is 1 */ public static final int SAME_LOCALS_1_STACK_ITEM_FRAME = 64; // to 127 (40-7f) /** * Reserved for future use */ public static final int RESERVED = 128; /** * Frame has exactly the same locals as the previous stack map frame and * number of stack items is 1. Offset is bigger then 63; */ public static final int SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED = 247; /** * Frame where current locals are the same as the locals in the previous * frame, except that the k last locals are absent. * The value of k is given by the formula 251-frame_type. */ public static final int CHOP_FRAME = 248; // to 250 (f8-fA) /** * Frame has exactly the same locals as the previous stack map frame and * number of stack items is zero. Offset is bigger then 63; */ public static final int SAME_FRAME_EXTENDED = 251; /** * Frame where current locals are the same as the locals in the previous frame, * except that k additional locals are defined. * The value of k is given by the formula frame_type-251. */ public static final int APPEND_FRAME = 252; // to 254 // fc-fe /** * Full frame */ public static final int FULL_FRAME = 255; private static final int MAX_SHORT = 65535; /** * A <code>List</code> of <code>StackMapFrame</code> instances. */ private List frames; public StackMapTableAttribute() { super( "StackMapTable"); } public StackMapTableAttribute( List frames) { this(); this.frames = frames; } public List getFrames() { return frames; } public StackMapFrame getFrame (Label label) { for (int i = 0; i < frames.size(); i++) { StackMapFrame frame = (StackMapFrame)frames.get(i); if (frame.label == label) { return frame; } } return null; } public boolean isUnknown () { return false; } public boolean isCodeAttribute () { return true; } protected Attribute read( ClassReader cr, int off, int len, char[] buf, int codeOff, Label[] labels) { ArrayList frames = new ArrayList(); // note that this is not the size of Code attribute boolean isExtCodeSize = cr.readInt(codeOff + 4) > MAX_SHORT; boolean isExtLocals = cr.readUnsignedShort(codeOff + 2) > MAX_SHORT; boolean isExtStack = cr.readUnsignedShort(codeOff) > MAX_SHORT; int offset = 0; int methodOff = getMethodOff( cr, codeOff, buf); StackMapFrame frame = new StackMapFrame( getLabel(offset, labels), calculateLocals( cr.readClass( cr.header + 2, buf), // class name cr.readUnsignedShort( methodOff), // method access cr.readUTF8( methodOff + 2, buf), // method name cr.readUTF8( methodOff + 4, buf)), // method desc Collections.EMPTY_LIST); frames.add( frame); System.err.println( offset +" delta:" + 0 +" : "+ frame); int size; if (isExtCodeSize) { size = cr.readInt(off); off += 4; } else { size = cr.readUnsignedShort(off); off += 2; } for ( ; size>0; size int tag = cr.readByte(off); // & 0xff; off++; List stack; List locals; int offsetDelta; int frameType; if( tag<SAME_LOCALS_1_STACK_ITEM_FRAME) { frameType = SAME_FRAME; offsetDelta = tag; locals = new ArrayList( frame.locals); stack = Collections.EMPTY_LIST; } else if( tag<RESERVED) { frameType = SAME_LOCALS_1_STACK_ITEM_FRAME; offsetDelta = tag - SAME_LOCALS_1_STACK_ITEM_FRAME; locals = new ArrayList( frame.locals); stack = new ArrayList(); // read verification_type_info stack[1]; off = readType( stack, isExtCodeSize, cr, off, labels, buf); } else { if( isExtCodeSize) { offsetDelta = cr.readInt( off); off += 4; } else { offsetDelta = cr.readUnsignedShort( off); off += 2; } if( tag==SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED) { frameType = SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED; locals = new ArrayList( frame.locals); stack = new ArrayList(); // read verification_type_info stack[1]; off = readType( stack, isExtCodeSize, cr, off, labels, buf); } else if( tag>=CHOP_FRAME && tag<SAME_FRAME_EXTENDED) { frameType = CHOP_FRAME; stack = Collections.EMPTY_LIST; int k = SAME_FRAME_EXTENDED - tag; // copy locals from prev frame and chop last k locals = new ArrayList( frame.locals.subList( 0, frame.locals.size()-k)); } else if( tag==SAME_FRAME_EXTENDED) { frameType = SAME_FRAME_EXTENDED; stack = Collections.EMPTY_LIST; locals = new ArrayList( frame.locals); } else if( /* tag>=APPEND && */ tag<FULL_FRAME) { frameType = APPEND_FRAME; stack = Collections.EMPTY_LIST; // copy locals from prev frame and append new k locals = new ArrayList( frame.locals); for( int k = tag - SAME_FRAME_EXTENDED; k>0; k off = readType(locals, isExtCodeSize, cr, off, labels, buf); } } else if( tag==FULL_FRAME) { frameType = FULL_FRAME; // read verification_type_info locals[number_of_locals]; locals = new ArrayList(); off = readTypes(locals, isExtLocals, isExtCodeSize, cr, off, labels, buf); // read verification_type_info stack[number_of_stack_items]; stack = new ArrayList(); off = readTypes(stack, isExtStack, isExtCodeSize, cr, off, labels, buf); } else { throw new RuntimeException( "Unknown frame type "+tag+" after offset "+offset); } } offset += offsetDelta; Label offsetLabel = getLabel( offset, labels); frame = new StackMapFrame( offsetLabel, locals, stack); frames.add( frame); System.err.println( offset +" label:" +offsetLabel+" delta:" + offsetDelta + " frameType:"+ frameType+" : "+ frame); offset++; } return new StackMapTableAttribute( frames); } protected ByteVector write( ClassWriter cw, byte[] code, int len, int maxStack, int maxLocals) { ByteVector bv = new ByteVector(); boolean isExtCodeSize = code != null && code.length > MAX_SHORT; // TODO verify this value writeSize(frames.size(), bv, isExtCodeSize); if( frames.size()<2) { return bv; } boolean isExtLocals = maxLocals > MAX_SHORT; boolean isExtStack = maxStack > MAX_SHORT; // skip the first frame StackMapFrame frame = ( StackMapFrame) frames.get( 0); for( int i = 1; i < frames.size(); i++) { StackMapFrame cframe = ( StackMapFrame) frames.get( i); int localsSize = frame.locals.size(); int stackSize = frame.stack.size(); int clocalsSize = cframe.locals.size(); int cstackSize = cframe.stack.size(); int delta = cframe.label.getOffset() - frame.label.getOffset() - 1; int type = FULL_FRAME; int k = 0; if( stackSize==cstackSize) { k = clocalsSize-localsSize; switch( k) { case -3: case -2: case -1: type = CHOP_FRAME; // CHOP or FULL localsSize = clocalsSize; break; case 0: type = delta<64 ? SAME_FRAME : SAME_FRAME_EXTENDED; // SAME, SAME_EXTENDED or FULL break; case 1: case 2: case 3: type = APPEND_FRAME; // APPEND or FULL break; } } else if( localsSize==clocalsSize && stackSize==cstackSize+1) { type = delta<63 ? SAME_LOCALS_1_STACK_ITEM_FRAME : SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED; // SAME_LOCAL_1_STACK or FULL } if( type!=FULL_FRAME) { // verify if stack and locals are the same for( int j = 0; j<localsSize && type!=FULL_FRAME; j++) { if( frame.locals.get( j).equals( cframe.locals.get( j))) type = FULL_FRAME; } for( int j = 0; j<stackSize && type!=FULL_FRAME; j++) { if( frame.stack.get( j).equals( cframe.stack.get( j))) type = FULL_FRAME; } } switch(type) { case SAME_FRAME: bv.putByte( delta); break; case SAME_LOCALS_1_STACK_ITEM_FRAME: bv.putByte( SAME_LOCALS_1_STACK_ITEM_FRAME + delta); writeTypeInfos( bv, cw, cframe.stack, stackSize, stackSize+1); // cstackSize-1 break; case SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED: bv.putByte( SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED); writeSize( delta, bv, isExtCodeSize); writeTypeInfos( bv, cw, cframe.stack, stackSize, stackSize+1); // cstackSize-1 break; case SAME_FRAME_EXTENDED: bv.putByte( SAME_FRAME_EXTENDED); writeSize( delta, bv, isExtCodeSize); break; case CHOP_FRAME: bv.putByte( SAME_FRAME_EXTENDED + k); // negative k writeSize( delta, bv, isExtCodeSize); break; case APPEND_FRAME: bv.putByte( SAME_FRAME_EXTENDED + k); // positive k writeSize( delta, bv, isExtCodeSize); writeTypeInfos( bv, cw, cframe.stack, localsSize-1, clocalsSize); break; case FULL_FRAME: bv.putByte( FULL_FRAME); writeSize( delta, bv, isExtCodeSize); writeSize( clocalsSize, bv, isExtLocals); writeTypeInfos( bv, cw, frame.locals, 0, clocalsSize); writeSize( cstackSize, bv, isExtStack); writeTypeInfos( bv, cw, frame.stack, 0, cstackSize); break; default: throw new RuntimeException(); } frame = cframe; } return bv; } private void writeSize( int delta, ByteVector bv, boolean isExt) { if( isExt) { bv.putInt( delta); } else { bv.putShort( delta); } } private void writeTypeInfos( ByteVector bv, ClassWriter cw, List info, int start, int end) { for( int j = start; j < end; j++) { StackMapType typeInfo = ( StackMapType) info.get( j); bv.putByte( typeInfo.getType()); switch( typeInfo.getType()) { case StackMapType.ITEM_Object: bv.putShort( cw.newClass( typeInfo.getObject())); break; case StackMapType.ITEM_Uninitialized: bv.putShort( typeInfo.getLabel().getOffset()); break; } } } public static int getMethodOff( ClassReader cr, int codeOff, char[] buf) { int off = cr.header + 6; int interfacesCount = cr.readUnsignedShort( off); off += 2 + interfacesCount * 2; int fieldsCount = cr.readUnsignedShort( off); off += 2; for( ; fieldsCount > 0; --fieldsCount) { int attrCount = cr.readUnsignedShort(off + 6); // field attributes off += 8; for ( ; attrCount > 0; --attrCount) { off += 6 + cr.readInt( off + 2); } } int methodsCount = cr.readUnsignedShort( off); off += 2; for ( ; methodsCount > 0; --methodsCount) { int methodOff = off; int attrCount = cr.readUnsignedShort( off + 6); // method attributes off += 8; for ( ; attrCount > 0; --attrCount) { String attrName = cr.readUTF8( off, buf); off += 6; if (attrName.equals("Code")) { if( codeOff==off) { return methodOff; } } off += cr.readInt( off - 4); } } return -1; } /** * Use method signature and access flags to resolve initial locals state. * * @return list of <code>StackMapType</code> instances representing locals for an initial frame. */ public static List calculateLocals( String className, int access, String methodName, String methodDesc) { List locals = new ArrayList(); // TODO if( "<init>".equals( methodName) && !className.equals( "java/lang/Object")) { StackMapType typeInfo = StackMapType.getTypeInfo( StackMapType.ITEM_UninitializedThis); typeInfo.setObject( className); // this locals.add( typeInfo); } else if(( access & Opcodes.ACC_STATIC)==0) { StackMapType typeInfo = StackMapType.getTypeInfo( StackMapType.ITEM_Object); typeInfo.setObject( className); // this locals.add( typeInfo); } Type[] types = Type.getArgumentTypes(methodDesc); for( int i = 0; i < types.length; i++) { Type t = types[ i]; StackMapType smt; switch( t.getSort()) { case Type.LONG: smt = StackMapType.getTypeInfo( StackMapType.ITEM_Long); break; case Type.DOUBLE: smt = StackMapType.getTypeInfo( StackMapType.ITEM_Double); break; case Type.FLOAT: smt = StackMapType.getTypeInfo( StackMapType.ITEM_Float); break; case Type.ARRAY: case Type.OBJECT: smt = StackMapType.getTypeInfo( StackMapType.ITEM_Object); smt.setObject( t.getDescriptor()); // TODO verify class name break; default: smt = StackMapType.getTypeInfo( StackMapType.ITEM_Integer); break; } } return locals; } private int readTypes( List info, boolean isExt, boolean isExtCodeSize, ClassReader cr, int off, Label[] labels, char[] buf) { int n = 0; if( isExt) { n = cr.readInt( off); off += 4; } else { n = cr.readUnsignedShort( off); off += 2; } for( ; n>0; n off = readType( info, isExtCodeSize, cr, off, labels, buf); } return off; } private int readType( List info, boolean isExtCodeSize, ClassReader cr, int off, Label[] labels, char[] buf) { int itemType = cr.readByte( off++); StackMapType typeInfo = StackMapType.getTypeInfo( itemType); info.add( typeInfo); switch( itemType) { // case StackMapType.ITEM_Long: // // case StackMapType.ITEM_Double: // // info.add(StackMapType.getTypeInfo(StackMapType.ITEM_Top)); // break; case StackMapType.ITEM_Object: typeInfo.setObject( cr.readClass( off, buf)); off += 2; break; case StackMapType.ITEM_Uninitialized: int offset; if( isExtCodeSize) { offset = cr.readInt( off); off += 4; } else { offset = cr.readUnsignedShort( off); off += 2; } typeInfo.setLabel( getLabel( offset, labels)); break; } return off; } private Label getLabel( int offset, Label[] labels) { Label l = labels[ offset]; if( l!=null) { return l; } return labels[ offset] = new Label(); } public String toString () { StringBuffer sb = new StringBuffer("StackMapTable["); for (int i = 0; i < frames.size(); i++) { sb.append('\n').append('[').append(frames.get(i)).append(']'); } sb.append("\n]"); return sb.toString(); } }
package org.objectweb.asm.commons; import org.objectweb.asm.AnnotationVisitor; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.TypePath; /** * A {@link MethodVisitor} that renumbers local variables in their order of * appearance. This adapter allows one to easily add new local variables to a * method. It may be used by inheriting from this class, but the preferred way * of using it is via delegation: the next visitor in the chain can indeed add * new locals when needed by calling {@link #newLocal} on this adapter (this * requires a reference back to this {@link LocalVariablesSorter}). * * @author Chris Nokleberg * @author Eugene Kuleshov * @author Eric Bruneton */ public class LocalVariablesSorter extends MethodVisitor { private static final Type OBJECT_TYPE = Type .getObjectType("java/lang/Object"); /** * Mapping from old to new local variable indexes. A local variable at index * i of size 1 is remapped to 'mapping[2*i]', while a local variable at * index i of size 2 is remapped to 'mapping[2*i+1]'. */ private int[] mapping = new int[40]; /** * Array used to store stack map local variable types after remapping. */ private Object[] newLocals = new Object[20]; /** * Index of the first local variable, after formal parameters. */ protected final int firstLocal; protected int nextLocal; public LocalVariablesSorter(final int access, final String desc, final MethodVisitor mv) { this(Opcodes.ASM5, access, desc, mv); if (getClass() != LocalVariablesSorter.class) { throw new IllegalStateException(); } } /** * Creates a new {@link LocalVariablesSorter}. * * @param api * the ASM API version implemented by this visitor. Must be one * of {@link Opcodes#ASM4} or {@link Opcodes#ASM5}. * @param access * access flags of the adapted method. * @param desc * the method's descriptor (see {@link Type Type}). * @param mv * the method visitor to which this adapter delegates calls. */ protected LocalVariablesSorter(final int api, final int access, final String desc, final MethodVisitor mv) { super(api, mv); Type[] args = Type.getArgumentTypes(desc); nextLocal = (Opcodes.ACC_STATIC & access) == 0 ? 1 : 0; for (int i = 0; i < args.length; i++) { nextLocal += args[i].getSize(); } firstLocal = nextLocal; } @Override public void visitVarInsn(final int opcode, final int var) { Type type; switch (opcode) { case Opcodes.LLOAD: case Opcodes.LSTORE: type = Type.LONG_TYPE; break; case Opcodes.DLOAD: case Opcodes.DSTORE: type = Type.DOUBLE_TYPE; break; case Opcodes.FLOAD: case Opcodes.FSTORE: type = Type.FLOAT_TYPE; break; case Opcodes.ILOAD: case Opcodes.ISTORE: type = Type.INT_TYPE; break; default: // case Opcodes.ALOAD: // case Opcodes.ASTORE: // case RET: type = OBJECT_TYPE; break; } mv.visitVarInsn(opcode, remap(var, type)); } @Override public void visitIincInsn(final int var, final int increment) { mv.visitIincInsn(remap(var, Type.INT_TYPE), increment); } @Override public void visitMaxs(final int maxStack, final int maxLocals) { mv.visitMaxs(maxStack, nextLocal); } @Override public void visitLocalVariable(final String name, final String desc, final String signature, final Label start, final Label end, final int index) { int newIndex = remap(index, Type.getType(desc)); mv.visitLocalVariable(name, desc, signature, start, end, newIndex); } @Override public AnnotationVisitor visitLocalVariableAnnotation(int typeRef, TypePath typePath, Label[] start, Label[] end, int[] index, String desc, boolean visible) { Type t = Type.getType(desc); int[] newIndex = new int[index.length]; for (int i = 0; i < newIndex.length; ++i) { newIndex[i] = remap(index[i], t); } return mv.visitLocalVariableAnnotation(typeRef, typePath, start, end, newIndex, desc, visible); } @Override public void visitFrame(final int type, final int nLocal, final Object[] local, final int nStack, final Object[] stack) { if (type != Opcodes.F_NEW) { // uncompressed frame throw new IllegalStateException( "ClassReader.accept() should be called with EXPAND_FRAMES flag"); } // creates a copy of newLocals Object[] oldLocals = new Object[newLocals.length]; System.arraycopy(newLocals, 0, oldLocals, 0, oldLocals.length); updateNewLocals(newLocals); // copies types from 'local' to 'newLocals' // 'newLocals' already contains the variables added with 'newLocal' int index = 0; // old local variable index int number = 0; // old local variable number for (; number < nLocal; ++number) { Object t = local[number]; int size = t == Opcodes.LONG || t == Opcodes.DOUBLE ? 2 : 1; if (t != Opcodes.TOP) { Type typ = OBJECT_TYPE; if (t == Opcodes.INTEGER) { typ = Type.INT_TYPE; } else if (t == Opcodes.FLOAT) { typ = Type.FLOAT_TYPE; } else if (t == Opcodes.LONG) { typ = Type.LONG_TYPE; } else if (t == Opcodes.DOUBLE) { typ = Type.DOUBLE_TYPE; } else if (t instanceof String) { typ = Type.getObjectType((String) t); } setFrameLocal(remap(index, typ), t); } index += size; } // removes TOP after long and double types as well as trailing TOPs index = 0; number = 0; for (int i = 0; index < newLocals.length; ++i) { Object t = newLocals[index++]; if (t != null && t != Opcodes.TOP) { newLocals[i] = t; number = i + 1; if (t == Opcodes.LONG || t == Opcodes.DOUBLE) { index += 1; } } else { newLocals[i] = Opcodes.TOP; } } // visits remapped frame mv.visitFrame(type, number, newLocals, nStack, stack); // restores original value of 'newLocals' newLocals = oldLocals; } /** * Creates a new local variable of the given type. * * @param type * the type of the local variable to be created. * @return the identifier of the newly created local variable. */ public int newLocal(final Type type) { Object t; switch (type.getSort()) { case Type.BOOLEAN: case Type.CHAR: case Type.BYTE: case Type.SHORT: case Type.INT: t = Opcodes.INTEGER; break; case Type.FLOAT: t = Opcodes.FLOAT; break; case Type.LONG: t = Opcodes.LONG; break; case Type.DOUBLE: t = Opcodes.DOUBLE; break; case Type.ARRAY: t = type.getDescriptor(); break; // case Type.OBJECT: default: t = type.getInternalName(); break; } int local = newLocalMapping(type); setLocalType(local, type); setFrameLocal(local, t); return local; } /** * Notifies subclasses that a new stack map frame is being visited. The * array argument contains the stack map frame types corresponding to the * local variables added with {@link #newLocal}. This method can update * these types in place for the stack map frame being visited. The default * implementation of this method does nothing, i.e. a local variable added * with {@link #newLocal} will have the same type in all stack map frames. * But this behavior is not always the desired one, for instance if a local * variable is added in the middle of a try/catch block: the frame for the * exception handler should have a TOP type for this new local. * * @param newLocals * the stack map frame types corresponding to the local variables * added with {@link #newLocal} (and null for the others). The * format of this array is the same as in * {@link MethodVisitor#visitFrame}, except that long and double * types use two slots. The types for the current stack map frame * must be updated in place in this array. */ protected void updateNewLocals(Object[] newLocals) { } /** * Notifies subclasses that a local variable has been added or remapped. The * default implementation of this method does nothing. * * @param local * a local variable identifier, as returned by {@link #newLocal * newLocal()}. * @param type * the type of the value being stored in the local variable. */ protected void setLocalType(final int local, final Type type) { } private void setFrameLocal(final int local, final Object type) { int l = newLocals.length; if (local >= l) { Object[] a = new Object[Math.max(2 * l, local + 1)]; System.arraycopy(newLocals, 0, a, 0, l); newLocals = a; } newLocals[local] = type; } private int remap(final int var, final Type type) { if (var + type.getSize() <= firstLocal) { return var; } int key = 2 * var + type.getSize() - 1; int size = mapping.length; if (key >= size) { int[] newMapping = new int[Math.max(2 * size, key + 1)]; System.arraycopy(mapping, 0, newMapping, 0, size); mapping = newMapping; } int value = mapping[key]; if (value == 0) { value = newLocalMapping(type); setLocalType(value, type); mapping[key] = value + 1; } else { value } return value; } protected int newLocalMapping(final Type type) { int local = nextLocal; nextLocal += type.getSize(); return local; } }