answer stringlengths 17 10.2M |
|---|
package org.openbmap.activity;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import org.mapsforge.core.graphics.Color;
import org.mapsforge.core.graphics.Paint;
import org.mapsforge.core.graphics.Style;
import org.mapsforge.core.model.BoundingBox;
import org.mapsforge.core.model.LatLong;
import org.mapsforge.map.android.AndroidPreferences;
import org.mapsforge.map.android.graphics.AndroidGraphicFactory;
import org.mapsforge.map.android.view.MapView;
import org.mapsforge.map.layer.Layer;
import org.mapsforge.map.layer.LayerManager;
import org.mapsforge.map.layer.Layers;
import org.mapsforge.map.layer.cache.TileCache;
import org.mapsforge.map.layer.overlay.Circle;
import org.mapsforge.map.layer.overlay.Polyline;
import org.mapsforge.map.model.MapViewPosition;
import org.mapsforge.map.model.common.Observer;
import org.mapsforge.map.util.MapPositionUtil;
import org.openbmap.Preferences;
import org.openbmap.R;
import org.openbmap.RadioBeacon;
import org.openbmap.db.DataHelper;
import org.openbmap.db.Schema;
import org.openbmap.db.model.Session;
import org.openbmap.db.model.WifiRecord;
import org.openbmap.utils.GpxMapObjectsLoader;
import org.openbmap.utils.GpxMapObjectsLoader.OnGpxLoadedListener;
import org.openbmap.utils.LatLongHelper;
import org.openbmap.utils.MapUtils;
import org.openbmap.utils.SessionMapObjectsLoader;
import org.openbmap.utils.SessionMapObjectsLoader.OnSessionLoadedListener;
import org.openbmap.utils.WifiCatalogMapObjectsLoader;
import org.openbmap.utils.WifiCatalogMapObjectsLoader.OnCatalogLoadedListener;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Matrix;
import android.location.Location;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.ToggleButton;
/**
* Activity for displaying session's GPX track and wifis
*/
public class MapViewActivity extends Activity implements
OnCatalogLoadedListener,
OnSessionLoadedListener,
OnGpxLoadedListener {
private static final String TAG = MapViewActivity.class.getSimpleName();
/**
* If zoom level < MIN_OBJECT_ZOOM session wifis and wifi catalog objects won't be displayed for performance reasons
*/
private static final int MIN_OBJECT_ZOOM = 12;
private static final Color COLOR_GPX = Color.BLACK;
private static final int ALPHA_WIFI_CATALOG_FILL = 90;
private static final int ALPHA_WIFI_CATALOG_STROKE = 100;
private static final int ALPHA_SESSION_FILL = 50;
private static final int ALPHA_SESSION_STROKE = 100;
private static final int CIRCLE_WIFI_CATALOG_WIDTH = 20;
private static final int CIRCLE_SESSION_WIDTH = 30;
private static final int STROKE_GPX_WIDTH = 5;
/**
* Keeps the SharedPreferences.
*/
private SharedPreferences prefs = null;
/**
* Database helper for retrieving session wifi scan results.
*/
private DataHelper dbHelper;
/**
* Minimum time (in millis) between automatic overlay refresh
*/
protected static final float SESSION_REFRESH_INTERVAL = 2000;
/**
* Minimum distance (in meter) between automatic session overlay refresh
*/
protected static final float SESSION_REFRESH_DISTANCE = 10;
/**
* Minimum distance (in meter) between automatic catalog overlay refresh
* Please note: catalog objects are static, thus updates aren't necessary that often
*/
protected static final float CATALOG_REFRESH_DISTANCE = 200;
/**
* Minimum time (in millis) between automatic catalog refresh
* Please note: catalog objects are static, thus updates aren't necessary that often
*/
protected static final float CATALOG_REFRESH_INTERVAL = 5000;
/**
* Minimum time (in millis) between gpx position refresh
*/
protected static final float GPX_REFRESH_INTERVAL = 1000;
/**
* Load more than currently visible objects?
*/
private static final boolean PREFETCH_MAP_OBJECTS = true;
/**
* Session currently displayed
*/
private int sessionId;
/**
* System time of last gpx refresh (in millis)
*/
private long gpxRefreshTime;
private AndroidPreferences preferencesFacade;
private byte lastZoom;
// [start] UI controls
/**
* MapView
*/
private MapView mMapView;
/**
* When checked map view will automatically focus current location
*/
private ToggleButton btnSnapToLocation;
private ImageButton btnZoom;
private ImageButton btnUnzoom;
//[end]
// [start] Map styles
/**
* Baselayer cache
*/
private TileCache tileCache;
private Paint paintCatalogFill;
private Paint paintCatalogStroke;
private Paint paintSessionFill;
private ArrayList<Layer> catalogObjects;
private ArrayList<Layer> sessionObjects;
private Polyline gpxObjects;
//[end]
// [start] Dynamic map variables
/**
* Another wifi catalog overlay refresh is taking place
*/
private boolean mRefreshCatalogPending = false;
/**
* Another session overlay refresh is taking place
*/
private boolean mRefreshSessionPending = false;
/**
* Direction marker is currently updated
*/
private boolean mRefreshDirectionPending;
/**
* Another gpx overlay refresh is taking place
*/
private boolean mRefreshGpxPending;
/**
* System time of last session overlay refresh (in millis)
*/
private long sessionObjectsRefreshTime;
/**
* System time of last catalog overlay refresh (in millis)
*/
private long catalogObjectsRefreshTime;
/**
* Location of last session overlay refresh
*/
private Location sessionObjectsRefreshedAt = new Location("DUMMY");
/**
* Location of last session overlay refresh
*/
private Location catalogObjectsRefreshedAt = new Location("DUMMY");
// [end]
/**
* Receives GPS location updates.
*/
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(final Context context, final Intent intent) {
// handling GPS broadcasts
if (RadioBeacon.INTENT_BROADCAST_POSITION.equals(intent.getAction())) {
Location location = intent.getExtras().getParcelable("android.location.Location");
// if btnSnapToLocation is checked, move map
if (btnSnapToLocation.isChecked() && mMapView != null) {
LatLong currentPos = new LatLong(location.getLatitude(), location.getLongitude());
mMapView.getModel().mapViewPosition.setCenter(currentPos);
}
// update overlays
if (LatLongHelper.isValidLocation(location)) {
/*
* Update overlays if necessary, but only if
* 1.) current zoom level >= 12 (otherwise single points not visible, huge performance impact)
* 2.) overlay items haven't been refreshed for a while AND user has moved a bit
*/
if ((mMapView.getModel().mapViewPosition.getZoomLevel() >= MIN_OBJECT_ZOOM) && (needSessionObjectsRefresh(location))) {
refreshSessionOverlays(location);
}
if ((mMapView.getModel().mapViewPosition.getZoomLevel() >= MIN_OBJECT_ZOOM) && (needCatalogObjectsRefresh(location))) {
refreshCatalogOverlay(location);
}
if (needGpxRefresh()) {
refreshGpxTrace(location);
}
// indicate bearing
refreshCompass(location);
} else {
Log.e(TAG, "Invalid positon! Cycle skipped");
}
location = null;
}
}
};
@Override
public final void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mapview);
// get shared preferences
prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences sharedPreferences = this.getSharedPreferences(getPersistableId(), MODE_PRIVATE);
preferencesFacade = new AndroidPreferences(sharedPreferences);
// Register our gps broadcast mReceiver
registerReceiver();
initUi();
catalogObjects = new ArrayList<Layer>();
sessionObjects = new ArrayList<Layer>();
gpxObjects = new Polyline(MapUtils.createPaint(AndroidGraphicFactory.INSTANCE.createColor(Color.BLACK), STROKE_GPX_WIDTH,
Style.STROKE), AndroidGraphicFactory.INSTANCE);
}
@Override
protected final void onResume() {
super.onResume();
initDb();
initMap();
registerReceiver();
if (this.getIntent().hasExtra(Schema.COL_ID)) {
int focusWifi = this.getIntent().getExtras().getInt(Schema.COL_ID);
Log.d(TAG, "Zooming onto " + focusWifi);
if (focusWifi != 0) {
loadSingleObject(focusWifi);
}
}
}
private void initDb() {
dbHelper = new DataHelper(this);
Session tmp = dbHelper.loadActiveSession();
if (tmp != null) {
sessionId = tmp.getId();
Log.i(TAG, "Displaying session " + sessionId);
tmp = null;
} else {
Log.w(TAG, "No active session?");
sessionId = RadioBeacon.SESSION_NOT_TRACKING;
}
}
/**
* Initializes map components
*/
private void initMap() {
mMapView = (MapView) findViewById(R.id.map);
mMapView.getModel().init(preferencesFacade);
mMapView.setClickable(true);
mMapView.getMapScaleBar().setVisible(true);
this.tileCache = createTileCache();
LayerManager layerManager = this.mMapView.getLayerManager();
Layers layers = layerManager.getLayers();
MapViewPosition mapViewPosition = this.mMapView.getModel().mapViewPosition;
//mapViewPosition.setZoomLevel((byte) 16);
//mapViewPosition.setCenter(this.dummyItem.location);
layers.add(MapUtils.createTileRendererLayer(this.tileCache, mapViewPosition, getMapFile()));
Observer observer = new Observer() {
@Override
public void onChange() {
byte zoom = mMapView.getModel().mapViewPosition.getZoomLevel();
if (zoom != lastZoom && zoom >= MIN_OBJECT_ZOOM) {
// update overlays on zoom level changed
Log.i(TAG, "New zoom level " + zoom + ", reloading map objects");
Location mapCenter = new Location("DUMMY");
mapCenter.setLatitude(mMapView.getModel().mapViewPosition.getCenter().latitude);
mapCenter.setLongitude(mMapView.getModel().mapViewPosition.getCenter().longitude);
refreshSessionOverlays(mapCenter);
refreshCatalogOverlay(mapCenter);
lastZoom = zoom;
}
if (!btnSnapToLocation.isChecked()) {
// update overlay in free-move mode
LatLong tmp = mMapView.getModel().mapViewPosition.getCenter();
Location position = new Location("DUMMY");
position.setLatitude(tmp.latitude);
position.setLongitude(tmp.longitude);
if (needSessionObjectsRefresh(position)) {
refreshSessionOverlays(position);
}
if (needCatalogObjectsRefresh(position)) {
refreshCatalogOverlay(position);
}
}
}
};
mMapView.getModel().mapViewPosition.addObserver(observer);
/*
mWifiCatalogOverlay = new ListOverlay();
mSessionOverlay = new ListOverlay();
mGpxOverlay = new ListOverlay();
mMapView.getOverlays().add(mWifiCatalogOverlay);
mMapView.getOverlays().add(mSessionOverlay);
mMapView.getOverlays().add(mGpxOverlay);
*/
}
@Override
protected final void onPause() {
releaseMap();
unregisterReceiver();
super.onPause();
}
@Override
protected final void onDestroy() {
releaseMap();
super.onDestroy();
}
/**
* Initializes UI componensts
*/
private void initUi() {
btnSnapToLocation = (ToggleButton) findViewById(R.id.mapview_tb_snap_to_location);
btnZoom = (ImageButton) findViewById(R.id.btnZoom);
btnZoom.setOnClickListener(new OnClickListener() {
@Override
public void onClick(final View v) {
byte zoom = mMapView.getModel().mapViewPosition.getZoomLevel();
if (zoom < mMapView.getModel().mapViewPosition.getZoomLevelMax()) {
mMapView.getModel().mapViewPosition.setZoomLevel((byte) (zoom + 1));
}
}
});
btnUnzoom = (ImageButton) findViewById(R.id.btnUnzoom);
btnUnzoom.setOnClickListener(new OnClickListener() {
@Override
public void onClick(final View v) {
byte zoom = mMapView.getModel().mapViewPosition.getZoomLevel();
if (zoom > mMapView.getModel().mapViewPosition.getZoomLevelMin()) {
mMapView.getModel().mapViewPosition.setZoomLevel((byte) (zoom - 1));
}
}
});
paintCatalogFill = MapUtils.createPaint(AndroidGraphicFactory.INSTANCE.createColor(ALPHA_WIFI_CATALOG_FILL, 120, 150, 120), 2, Style.FILL);
paintCatalogStroke = MapUtils.createPaint(AndroidGraphicFactory.INSTANCE.createColor(ALPHA_WIFI_CATALOG_STROKE, 120, 150, 120), 2, Style.STROKE);
paintSessionFill = MapUtils.createPaint(AndroidGraphicFactory.INSTANCE.createColor(ALPHA_SESSION_FILL, 0, 0, 255), 2, Style.FILL);
}
private void registerReceiver() {
IntentFilter filter = new IntentFilter();
filter.addAction(RadioBeacon.INTENT_BROADCAST_POSITION);
registerReceiver(mReceiver, filter);
}
/**
* Unregisters receivers for GPS and wifi scan results.
*/
private void unregisterReceiver() {
try {
unregisterReceiver(mReceiver);
} catch (IllegalArgumentException e) {
return;
}
}
protected final void refreshCatalogOverlay(final Location location) {
if (!mRefreshCatalogPending) {
Log.d(TAG, "Updating wifi catalog overlay");
mRefreshCatalogPending = true;
proceedAfterCatalogLoaded();
catalogObjectsRefreshedAt = location;
catalogObjectsRefreshTime = System.currentTimeMillis();
} else {
Log.v(TAG, "Reference overlay refresh in progress. Skipping refresh..");
}
}
/**
* Is new location far enough from last refresh location?
* @return true if catalog overlay needs refresh
*/
private boolean needCatalogObjectsRefresh(final Location current) {
if (current == null) {
// fail safe: draw if something went wrong
return true;
}
return (
(catalogObjectsRefreshedAt.distanceTo(current) > CATALOG_REFRESH_DISTANCE)
&& ((System.currentTimeMillis() - catalogObjectsRefreshTime) > CATALOG_REFRESH_INTERVAL)
);
}
/**
* Loads reference wifis around location from openbmap wifi catalog.
* Callback function, upon completion onCatalogLoaded is called for drawing
* @param center
* For performance reasons only wifis around specified location are displayed.
*/
private void proceedAfterCatalogLoaded() {
BoundingBox bbox = MapPositionUtil.getBoundingBox(
mMapView.getModel().mapViewPosition.getMapPosition(),
mMapView.getDimension());
double minLatitude = bbox.minLatitude;
double maxLatitude = bbox.maxLatitude;
double minLongitude = bbox.minLongitude;
double maxLongitude = bbox.maxLongitude;
// query more than visible objects for smoother data scrolling / less database queries?
if (PREFETCH_MAP_OBJECTS) {
double latSpan = maxLatitude - minLatitude;
double lonSpan = maxLongitude - minLongitude;
minLatitude -= latSpan * 0.5;
maxLatitude += latSpan * 0.5;
minLongitude -= lonSpan * 0.5;
maxLongitude += lonSpan * 0.5;
}
WifiCatalogMapObjectsLoader task = new WifiCatalogMapObjectsLoader(this);
task.execute(minLatitude, maxLatitude, minLongitude, maxLongitude);
}
/* (non-Javadoc)
* @see org.openbmap.utils.WifiCatalogMapObjectsLoader.OnCatalogLoadedListener#onComplete(java.util.ArrayList)
*/
@Override
public final void onCatalogLoaded(final ArrayList<LatLong> points) {
Log.d(TAG, "Loaded catalog objects");
Layers layers = this.mMapView.getLayerManager().getLayers();
// clear overlay
for (Iterator<Layer> iterator = catalogObjects.iterator(); iterator.hasNext();) {
Layer layer = (Layer) iterator.next();
this.mMapView.getLayerManager().getLayers().remove(layer);
}
catalogObjects.clear();
// redraw
for (int i = 0; i < points.size(); i++) {
Circle circle = new Circle(points.get(i), CIRCLE_WIFI_CATALOG_WIDTH, paintCatalogFill, paintCatalogStroke);
catalogObjects.add(circle);
}
int insertAfter = -1;
if (layers.size() > 0) {
// map
insertAfter = 1;
} else {
// no map
insertAfter = 0;
}
for (int i = 0; i < catalogObjects.size(); i++) {
layers.add(insertAfter + i, catalogObjects.get(i));
}
// enable next refresh
mRefreshCatalogPending = false;
Log.d(TAG, "Drawed catalog objects");
}
/**
* Refreshes reference and session overlays.
* If another refresh is in progress, update is skipped.
* @param location
*/
protected final void refreshSessionOverlays(final Location location) {
if (!mRefreshSessionPending) {
Log.d(TAG, "Updating session overlay");
mRefreshSessionPending = true;
proceedAfterSessionObjectsLoaded(null);
sessionObjectsRefreshTime = System.currentTimeMillis();
sessionObjectsRefreshedAt = location;
} else {
Log.v(TAG, "Session overlay refresh in progress. Skipping refresh..");
}
}
/**
* Is new location far enough from last refresh location and is last refresh to old?
* @return true if session overlay needs refresh
*/
private boolean needSessionObjectsRefresh(final Location current) {
if (current == null) {
// fail safe: draw if something went wrong
return true;
}
return (
(sessionObjectsRefreshedAt.distanceTo(current) > SESSION_REFRESH_DISTANCE)
&& ((System.currentTimeMillis() - sessionObjectsRefreshTime) > SESSION_REFRESH_INTERVAL)
);
}
/**
* Loads session wifis in visible range.
* Will call onSessionLoaded callback upon completion
* @param highlight
* If highlight is specified only this wifi is displayed
*/
private void proceedAfterSessionObjectsLoaded(final WifiRecord highlight) {
BoundingBox bbox = MapPositionUtil.getBoundingBox(
mMapView.getModel().mapViewPosition.getMapPosition(),
mMapView.getDimension());
if (highlight == null) {
// load all session wifis
double minLatitude = bbox.minLatitude;
double maxLatitude = bbox.maxLatitude;
double minLongitude = bbox.minLongitude;
double maxLongitude = bbox.maxLongitude;
// query more than visible objects for smoother data scrolling / less database queries?
if (PREFETCH_MAP_OBJECTS) {
double latSpan = maxLatitude - minLatitude;
double lonSpan = maxLongitude - minLongitude;
minLatitude -= latSpan * 0.5;
maxLatitude += latSpan * 0.5;
minLongitude -= lonSpan * 0.5;
maxLongitude += lonSpan * 0.5;
}
SessionMapObjectsLoader task = new SessionMapObjectsLoader(this);
task.execute(sessionId, minLatitude, maxLatitude, minLongitude, maxLatitude, null);
} else {
// draw specific wifi
SessionMapObjectsLoader task = new SessionMapObjectsLoader(this);
task.execute(sessionId, bbox.minLatitude, bbox.maxLatitude, bbox.minLongitude, bbox.maxLatitude, highlight.getBssid());
}
}
/* (non-Javadoc)
* @see org.openbmap.utils.SessionMapObjectsLoader.OnSessionLoadedListener#onSessionLoaded(java.util.ArrayList)
*/
@Override
public final void onSessionLoaded(final ArrayList<LatLong> points) {
Log.d(TAG, "Loaded session objects");
Layers layers = this.mMapView.getLayerManager().getLayers();
// clear overlay
for (Iterator<Layer> iterator = sessionObjects.iterator(); iterator.hasNext();) {
Layer layer = (Layer) iterator.next();
layers.remove(layer);
}
sessionObjects.clear();
for (int i = 0; i < points.size(); i++) {
Circle circle = new Circle(points.get(i), CIRCLE_SESSION_WIDTH, paintSessionFill, null);
sessionObjects.add(circle);
}
int insertAfter = -1;
if (layers.size() > 0 && catalogObjects.size() > 0) {
// map + catalog objects
insertAfter = layers.indexOf((Layer) catalogObjects.get(catalogObjects.size() - 1));
} else if (layers.size() > 0 && catalogObjects.size() == 0) {
// map + no catalog objects
insertAfter = 1;
} else {
// no map + no catalog objects
insertAfter = 0;
}
for (int i = 0; i < sessionObjects.size(); i++) {
layers.add(insertAfter + i, sessionObjects.get(i));
}
// if we have just loaded on point, set map center
if (points.size() == 1) {
mMapView.getModel().mapViewPosition.setCenter((LatLong) points.get(0));
}
// enable next refresh
mRefreshSessionPending = false;
Log.d(TAG, "Drawed catalog objects");
}
/**
* @param location
*/
private void refreshGpxTrace(final Location location) {
if (!mRefreshGpxPending) {
Log.d(TAG, "Updating gpx overlay");
mRefreshGpxPending = true;
proceedAfterGpxObjectsLoaded();
gpxRefreshTime = System.currentTimeMillis();
} else {
Log.v(TAG, "Gpx overlay refresh in progress. Skipping refresh..");
}
}
/**
* Is last gpx overlay update to old?
* @return true if overlay needs refresh
*/
private boolean needGpxRefresh() {
return ((System.currentTimeMillis() - gpxRefreshTime) > GPX_REFRESH_INTERVAL);
}
/*
* Loads gpx points in visible range.
*/
private void proceedAfterGpxObjectsLoaded() {
BoundingBox bbox = MapPositionUtil.getBoundingBox(
mMapView.getModel().mapViewPosition.getMapPosition(),
mMapView.getDimension());
GpxMapObjectsLoader task = new GpxMapObjectsLoader(this);
// query with some extra space
task.execute(bbox.minLatitude - 0.01, bbox.maxLatitude + 0.01, bbox.minLongitude - 0.15, bbox.maxLatitude + 0.15);
//task.execute(null, null, null, null);
}
/**
* Callback function for loadGpxObjects()
*/
@Override
public final void onGpxLoaded(final ArrayList<LatLong> points) {
Log.d(TAG, "Loaded gpx objects");
// clear overlay
gpxObjects.getLatLongs().clear();
this.mMapView.getLayerManager().getLayers().remove(gpxObjects);
for (int i = 0; i < points.size(); i++) {
gpxObjects.getLatLongs().add(points.get(i));
}
this.mMapView.getLayerManager().getLayers().add(gpxObjects);
mRefreshGpxPending = false;
}
/**
* Highlights single wifi on map.
* @param id wifi id to highlight
*/
public final void loadSingleObject(final int id) {
Log.d(TAG, "Adding selected wifi to overlay: " + id);
WifiRecord wifi = dbHelper.loadWifiById(id);
if (wifi != null) {
proceedAfterSessionObjectsLoaded(wifi);
}
}
/**
* Draws arrow in direction of travel. If bearing is unavailable a generic position symbol is used.
* If another refresh is taking place, update is skipped
*/
private void refreshCompass(final Location location) {
// ensure that previous refresh has been finished
if (mRefreshDirectionPending) {
return;
}
mRefreshDirectionPending = true;
// determine which drawable we currently
ImageView iv = (ImageView) findViewById(R.id.position_marker);
Integer id = (Integer) iv.getTag() == null ? 0 : (Integer) iv.getTag();
if (location.hasBearing()) {
// determine which drawable we currently use
drawCompass(iv, id, location.getBearing());
} else {
// refresh only if needed
if (id != R.drawable.cross) {
iv.setImageResource(R.drawable.cross);
}
//Log.i(TAG, "Can't draw direction marker: no bearing provided");
}
mRefreshDirectionPending = false;
}
/**
* Draws compass
* @param iv image view used for compass
* @param ressourceId resource id compass needle
* @param bearing bearing (azimuth)
*/
private void drawCompass(final ImageView iv, final Integer ressourceId, final float bearing) {
// refresh only if needed
if (ressourceId != R.drawable.arrow) {
iv.setImageResource(R.drawable.arrow);
}
// rotate arrow
Matrix matrix = new Matrix();
iv.setScaleType(ScaleType.MATRIX); //required
matrix.postRotate(bearing, iv.getWidth() / 2f, iv.getHeight() / 2f);
iv.setImageMatrix(matrix);
}
/**
* Opens selected map file
* @return a map file
*/
protected final File getMapFile() {
File mapFile = new File(
Environment.getExternalStorageDirectory().getPath()
+ prefs.getString(Preferences.KEY_DATA_DIR, Preferences.VAL_DATA_DIR)
+ Preferences.MAPS_SUBDIR,
prefs.getString(Preferences.KEY_MAP_FILE, Preferences.VAL_MAP_FILE));
/*
if (mapFile.exists()) {
mMapView.setClickable(true);
//mMapView.setBuiltInZoomControls(true);
//mMapView.setMapFile(mapFile);
} else {
Log.i(TAG, "No map file found!");
Toast.makeText(this.getBaseContext(), R.string.please_select_map, Toast.LENGTH_LONG).show();
mMapView.setClickable(false);
//mMapView.setBuiltInZoomControls(false);
mMapView.setVisibility(View.GONE);
}
*/
return mapFile;
}
protected final void addLayers(final LayerManager layerManager, final TileCache tileCache, final MapViewPosition mapViewPosition) {
layerManager.getLayers().add(MapUtils.createTileRendererLayer(tileCache, mapViewPosition, getMapFile()));
}
protected final TileCache createTileCache() {
return MapUtils.createExternalStorageTileCache(this, getPersistableId());
}
/**
* @return the id that is used to save this mapview
*/
protected final String getPersistableId() {
return this.getClass().getSimpleName();
}
/**
* Sets map-related object to null to enable garbage collection.
*/
private void releaseMap() {
Log.i(TAG, "Releasing map components");
// save map settings
mMapView.getModel().save(this.preferencesFacade);
this.preferencesFacade.save();
if (mMapView != null) {
mMapView.destroy();
}
}
/**
* Creates gpx overlay line
* @param points
* @return
*/
/*
private static Polyline createGpxSymbol(final ArrayList<LatLong> points) {
Paint paintStroke = new Paint(Paint.ANTI_ALIAS_FLAG);
paintStroke.setStyle(Paint.Style.STROKE);
paintStroke.setColor(Color.BLACK);
paintStroke.setAlpha(255);
paintStroke.setStrokeWidth(3);
paintStroke.setStrokeCap(Cap.ROUND);
paintStroke.setStrokeJoin(Paint.Join.ROUND);
Polygon chain = new Polygon(points);
Polyline line = new Polyline(chain, paintStroke);
return line;
}
*/
static Paint createPaint(final int color, final int strokeWidth, final Style style) {
Paint paint = AndroidGraphicFactory.INSTANCE.createPaint();
paint.setColor(color);
paint.setStrokeWidth(strokeWidth);
paint.setStyle(style);
return paint;
}
} |
package com.carlosefonseca.common.utils;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.View;
import android.widget.ImageView;
import com.carlosefonseca.common.CFApp;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.disc.naming.FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.ImageSize;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.imageaware.ImageViewAware;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
public final class UIL {
private static final String TAG = CodeUtils.getTag(UIL.class);
private static File sExternalFilesDir;
private static HashSet<String> sAssets;
private static ImageLoader sIL;
private UIL() {}
public static void initUIL(Context context) {
// The name for images is the last part of the URL
FileNameGenerator fileNameGenerator = new FileNameGenerator() {
@Override
public String generate(String imageUri) {
return imageUri.substring(imageUri.lastIndexOf("/") + 1);
}
};
// Do disk cache on the files dir
sExternalFilesDir = context.getExternalFilesDir(null);
UnlimitedDiscCache diskCache = new UnlimitedDiscCache(sExternalFilesDir, null, fileNameGenerator);
ImageLoaderConfiguration.Builder builder = new ImageLoaderConfiguration.Builder(context);
if (CFApp.isTestDevice()) builder.writeDebugLogs();
ImageLoaderConfiguration config = builder.threadPriority(Thread.NORM_PRIORITY - 2)
.memoryCacheSize((int) (CodeUtils.getFreeMem() / 6))
.diskCache(diskCache)
.tasksProcessingOrder(QueueProcessingType.LIFO)
.build();
sIL = ImageLoader.getInstance();
sIL.init(config);
sAssets = ResourceUtils.getAssets(context);
}
public static DisplayImageOptions mOptionsForPhotos = new DisplayImageOptions.Builder().resetViewBeforeLoading(true)
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true)
.imageScaleType(ImageScaleType.EXACTLY)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
static DisplayImageOptions mOptionsForIcons = new DisplayImageOptions.Builder().resetViewBeforeLoading(true)
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(false)
.imageScaleType(ImageScaleType.EXACTLY)
.bitmapConfig(Bitmap.Config.ARGB_8888)
.build();
public static SimpleImageLoadingListener getAnimateFirstDisplayListener() {
return new SimpleImageLoadingListener() {
final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);
displayedImages.add(imageUri);
}
}
}
};
}
@Nullable
public static String getUri(@Nullable String str) {
if (str == null) return null;
final String uri;
if (str.startsWith("http")) { // Full URL
String lastSegmentOfURL = NetworkingUtils.getLastSegmentOfURL(str);
if (sAssets.contains(lastSegmentOfURL)) {
uri = "assets://" + lastSegmentOfURL;
} else {
uri = str;
}
} else {
if (!str.startsWith("/")) { // only filename
if (sAssets.contains(str)) {
uri = "assets://" + str;
} else { // set full path to ext/files
uri = "file://" + sExternalFilesDir + "/" + str;
}
}
// we have a full path
else {
uri = "file://" + str;
}
}
return uri;
}
@Nullable
public static String getUri(File file) {
final String uri;
if (file.exists()) {
uri = "file://" + file.getAbsolutePath();
} else {
String name = file.getName();
if (sAssets.contains(name)) {
uri = "assets://" + name;
} else {
Log.w(TAG, "File " + file.getAbsolutePath() + " doesn't exist on ext or assets!");
uri = null;
}
}
return uri;
}
@Nullable
public static Bitmap loadSync(String str) {return loadSync(str, 0, 0);}
@Nullable
public static Bitmap loadSync(String str, int widthPx, int heightPx) {
if (str == null) return null;
String uri = getUri(str);
ImageSize targetImageSize = widthPx > 0 && heightPx > 0 ? new ImageSize(widthPx, heightPx) : null;
return sIL.loadImageSync(uri, targetImageSize);
}
public static void display(@Nullable String str, ImageView imageView) {
if (StringUtils.isNotBlank(str)) {
sIL.displayImage(UIL.getUri(str), new ImageViewAware(imageView), null, null);
}
}
public static void displayPhoto(@Nullable String str, ImageView imageView) {
if (StringUtils.isNotBlank(str)) {
sIL.displayImage(UIL.getUri(str), new ImageViewAware(imageView), mOptionsForPhotos, null);
}
}
public static void displayIcon(@Nullable String str, ImageView imageView) {
if (StringUtils.isNotBlank(str)) {
sIL.displayImage(UIL.getUri(str), new ImageViewAware(imageView), mOptionsForIcons, null);
}
}
public static void display(@Nullable String str, ImageView imageView, ImageLoadingListener listener) {
if (StringUtils.isNotBlank(str)) {
sIL.displayImage(UIL.getUri(str), new ImageViewAware(imageView), null, listener);
}
}
public static void displayPhoto(@Nullable String str, ImageView imageView, ImageLoadingListener listener) {
if (StringUtils.isNotBlank(str)) {
sIL.displayImage(UIL.getUri(str), new ImageViewAware(imageView), mOptionsForPhotos, listener);
}
}
@Nullable
public static Bitmap getIcon(@Nullable String str, int w, int h) {
if (StringUtils.isNotBlank(str)) {
return sIL.loadImageSync(getUri(str), new ImageSize(w, h), mOptionsForIcons);
}
return null;
}
} |
package lan.dk.podcastserver.service;
import lan.dk.podcastserver.entity.Cover;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageInputStream;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ImageService {
final UrlService urlService;
public Cover getCoverFromURL(String url) {
if (StringUtils.isEmpty(url))
return null;
try {
return getCoverFromURL(new URL(url));
} catch (IOException e) {
log.error("Error during fetching Cover information for {}", url, e);
return null;
}
}
public Cover getCoverFromURL (URL url) throws IOException {
Cover cover = new Cover(url.toString());
try (InputStream urlInputStream = urlService.getConnectionWithTimeOut(cover.getUrl(), 5000).getInputStream() ){
ImageInputStream imageInputStream = ImageIO.createImageInputStream(urlInputStream);
final BufferedImage image = ImageIO.read(imageInputStream);
cover.setWidth(image.getWidth());
cover.setHeight(image.getHeight());
}
return cover;
}
} |
package com.chipcollector.data;
import com.avaje.ebean.EbeanServer;
import com.avaje.ebean.event.BeanPersistListener;
import com.chipcollector.domain.*;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class PokerChipDAO {
private EbeanServer ebeanServer;
public PokerChipDAO(EbeanServer ebeanServer) {
this.ebeanServer = ebeanServer;
}
public List<PokerChip> getAllPokerChips() {
return ebeanServer.find(PokerChip.class).findList();
}
public List<Casino> getAllCasinos() {
return ebeanServer.find(Casino.class).findList();
}
public List<Country> getAllCountries() {
return ebeanServer.find(Country.class).findList();
}
public void savePokerChip(PokerChip pokerChip) {
ebeanServer.save(pokerChip);
pokerChip.resetDirty();
}
public void updatePokerChip(PokerChip pokerChip) {
long oldFrontImageId = -1;
long oldBackImageId = -1;
Set<Long> validIds = new HashSet<>();
if (pokerChip.isImagesChanged()) {
PokerChip oldPokerChip = getPokerChip(pokerChip.getId());
oldFrontImageId = oldPokerChip.getFrontImage().map(BlobImage::getId).orElse(-1l);
oldBackImageId = oldPokerChip.getBackImage().map(BlobImage::getId).orElse(-1l);
pokerChip.getFrontImage().map(BlobImage::getId).ifPresent(validIds::add);
pokerChip.getBackImage().map(BlobImage::getId).ifPresent(validIds::add);
}
ebeanServer.update(pokerChip);
if (oldFrontImageId > -1 && !validIds.contains(oldFrontImageId)) {
deleteImage(oldFrontImageId);
}
if (oldBackImageId > -1 && oldFrontImageId != oldBackImageId && !validIds.contains(oldBackImageId)) {
deleteImage(oldBackImageId);
}
pokerChip.resetDirty();
}
public void deletePokerChip(PokerChip pokerChip) {
ebeanServer.beginTransaction();
try {
ebeanServer.delete(pokerChip);
pokerChip.getBackImage().ifPresent(this::deleteImage);
pokerChip.getFrontImage().ifPresent(this::deleteImage);
ebeanServer.commitTransaction();
} finally {
ebeanServer.endTransaction();
}
}
private void deleteImage(BlobImage image) {
deleteImage(image.getId());
}
private void deleteImage(long imageId) {
ebeanServer.delete(BlobImage.class, imageId);
}
public PokerChip getPokerChip(long chipId) {
return ebeanServer.find(PokerChip.class, chipId);
}
} |
package lemming.context.inbound;
import lemming.context.Context;
import lemming.data.EntityManagerListener;
import lemming.data.GenericDao;
import org.hibernate.StaleObjectStateException;
import org.hibernate.UnresolvableObjectException;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.TypedQuery;
import java.util.ArrayList;
import java.util.List;
/**
* Represents a Data Access Object providing data operations for inbound contexts.
*/
@SuppressWarnings("unused")
public class InboundContextDao extends GenericDao<InboundContext> implements IInboundContextDao {
/**
* {@inheritDoc}
*/
@Override
public Boolean isTransient(InboundContext context) {
return context.getId() == null;
}
/**
* {@inheritDoc}
*
* @throws RuntimeException
*/
public void persist(InboundContext context) throws RuntimeException {
EntityManager entityManager = EntityManagerListener.createEntityManager();
EntityTransaction transaction = null;
try {
transaction = entityManager.getTransaction();
transaction.begin();
entityManager.persist(context);
transaction.commit();
} catch (RuntimeException e) {
e.printStackTrace();
if (transaction != null && transaction.isActive()) {
transaction.rollback();
}
if (e instanceof StaleObjectStateException) {
panicOnSaveLockingError(context, e);
} else if (e instanceof UnresolvableObjectException) {
panicOnSaveUnresolvableObjectError(context, e);
} else {
throw e;
}
} finally {
entityManager.close();
}
}
/**
* {@inheritDoc}
*
* @throws RuntimeException
*/
public void batchPersist(List<InboundContext> contexts) throws RuntimeException {
EntityManager entityManager = EntityManagerListener.createEntityManager();
EntityTransaction transaction = null;
InboundContext currentContext = null;
Integer batchSize = 50;
Integer counter = 0;
try {
transaction = entityManager.getTransaction();
transaction.begin();
for (InboundContext context : contexts) {
currentContext = context;
entityManager.persist(context);
counter++;
if (counter % batchSize == 0) {
entityManager.flush();
entityManager.clear();
}
}
transaction.commit();
} catch (RuntimeException e) {
e.printStackTrace();
if (transaction != null && transaction.isActive()) {
transaction.rollback();
}
if (e instanceof StaleObjectStateException) {
panicOnSaveLockingError(currentContext, e);
} else if (e instanceof UnresolvableObjectException) {
panicOnSaveUnresolvableObjectError(currentContext, e);
} else {
throw e;
}
} finally {
entityManager.close();
}
}
/**
* {@inheritDoc}
*
* @throws RuntimeException
*/
public InboundContext merge(InboundContext context) throws RuntimeException {
EntityManager entityManager = EntityManagerListener.createEntityManager();
EntityTransaction transaction = null;
try {
transaction = entityManager.getTransaction();
transaction.begin();
InboundContext mergedContext = entityManager.merge(context);
transaction.commit();
return mergedContext;
} catch (RuntimeException e) {
e.printStackTrace();
if (transaction != null && transaction.isActive()) {
transaction.rollback();
}
if (e instanceof StaleObjectStateException) {
panicOnSaveLockingError(context, e);
} else if (e instanceof UnresolvableObjectException) {
panicOnSaveUnresolvableObjectError(context, e);
} else {
throw e;
}
return null;
} finally {
entityManager.close();
}
}
/**
* Finds the ancestor of an inbound context with the same package and location.
*
* @param entityManager entity manager
* @param context an inbound context
* @return An inbound context or null.
*/
private InboundContext findAncestor(EntityManager entityManager, InboundContext context) {
TypedQuery<InboundContext> query = entityManager.createQuery("SELECT i FROM InboundContext i " +
"LEFT JOIN FETCH i.match WHERE i._package = :package AND i.location = :location " +
"AND i.number < :number ORDER BY i.number DESC", InboundContext.class);
List<InboundContext> ancestors = query.setParameter("package", context.getPackage())
.setParameter("location", context.getLocation()).setParameter("number", context.getNumber())
.setMaxResults(1).getResultList();
return ancestors.isEmpty() ? null : ancestors.get(0);
}
/**
* Finds the successor of an inbound context with the same package and location.
*
* @param entityManager entity manager
* @param context an inbound context
* @return An inbound context or null.
*/
private InboundContext findSuccessor(EntityManager entityManager, InboundContext context) {
TypedQuery<InboundContext> query = entityManager.createQuery("SELECT i FROM InboundContext i " +
"LEFT JOIN FETCH i.match WHERE i._package = :package AND i.location = :location " +
"AND i.number > :number ORDER BY i.number ASC", InboundContext.class);
List<InboundContext> successors = query.setParameter("package", context.getPackage())
.setParameter("location", context.getLocation()).setParameter("number", context.getNumber())
.setMaxResults(1).getResultList();
return successors.isEmpty() ? null : successors.get(0);
}
/**
* Finds a matching context for an inbound context.
*
* @param context an inbound context
* @return A matching context or null.
*/
private Context findMatch(InboundContext context) {
if (context == null) {
return null;
} else {
return context.getMatch();
}
}
/**
* Finds contexts before a successor.
*
* @param entityManager entity manager
* @param successor successor of contexts
* @return A list of contexts.
*/
public List<Context> findBefore(EntityManager entityManager, Context successor) {
if (successor == null) {
throw new IllegalStateException();
}
TypedQuery<Context> query = entityManager.createQuery("SELECT i FROM Context i " +
"WHERE i.location = :location AND i.number < :number ORDER BY i.number ASC", Context.class);
List<Context> contexts = query.setParameter("location", successor.getLocation())
.setParameter("number", successor.getNumber()).getResultList();
return contexts;
}
/**
* Finds contexts after an ancestor.
*
* @param entityManager entity manager
* @param ancestor ancestor of contexts
* @return A list of contexts.
*/
public List<Context> findAfter(EntityManager entityManager, Context ancestor) {
if (ancestor == null) {
throw new IllegalStateException();
}
TypedQuery<Context> query = entityManager.createQuery("SELECT i FROM Context i " +
"WHERE i.location = :location AND i.number > :number ORDER BY i.number ASC", Context.class);
List<Context> contexts = query.setParameter("location", ancestor.getLocation())
.setParameter("number", ancestor.getNumber()).getResultList();
return contexts;
}
/**
* Finds contexts between an ancestor and a successor.
*
* @param entityManager entity manager
* @param ancestor ancestor of contexts
* @param successor successor of contexts
* @return A list of contexts.
*/
private List<Context> findBetween(EntityManager entityManager, Context ancestor, Context successor) {
if (ancestor == null && successor == null) {
throw new IllegalArgumentException();
} else if (ancestor == null) {
return findBefore(entityManager, successor);
} else if (successor == null) {
return findAfter(entityManager, ancestor);
} else {
if (!ancestor.getLocation().equals(successor.getLocation())) {
throw new IllegalArgumentException();
}
if (ancestor.getNumber() >= successor.getNumber()) {
throw new IllegalArgumentException();
}
}
TypedQuery<Context> query = entityManager.createQuery("SELECT i FROM Context i " +
"WHERE i.location = :location AND i.number > :number1 AND i.number < :number2 " +
"ORDER BY i.number ASC", Context.class);
List<Context> contexts = query.setParameter("location", ancestor.getLocation())
.setParameter("number1", ancestor.getNumber()).setParameter("number2", successor.getNumber())
.getResultList();
return contexts;
}
/**
* {@inheritDoc}
*
* @throws RuntimeException
*/
@Override
public List<Context> findPossibleComplements(List<InboundContext> unmatchedContexts) {
InboundContext firstUnmatchedContext = unmatchedContexts.get(0);
InboundContext lastUnmatchedContext = unmatchedContexts.get(unmatchedContexts.size() - 1);
EntityManager entityManager = EntityManagerListener.createEntityManager();
EntityTransaction transaction = null;
try {
transaction = entityManager.getTransaction();
transaction.begin();
InboundContext ancestor = findAncestor(entityManager, firstUnmatchedContext);
InboundContext successor = findSuccessor(entityManager, lastUnmatchedContext);
Context ancestorMatch = findMatch(ancestor);
Context successorMatch = findMatch(successor);
List<Context> complements = new ArrayList<>();
if (ancestorMatch != null || successorMatch != null) {
complements = findBetween(entityManager, ancestorMatch, successorMatch);
}
transaction.commit();
return complements;
} catch (RuntimeException e) {
e.printStackTrace();
if (transaction != null && transaction.isActive()) {
transaction.rollback();
}
throw e;
} finally {
entityManager.close();
}
}
} |
package com.cjmalloy.torrentfs.model;
import com.cjmalloy.torrentfs.util.JsonUtil.Factory;
import com.cjmalloy.torrentfs.util.JsonUtil.HasJson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.turn.ttorrent.common.Torrent;
public class Nested implements HasJson
{
public static final Factory<Nested> FACTORY = new Factory<Nested>()
{
@Override
public Nested create()
{
return new Nested();
}
};
public Encoding encoding;
public String mount;
public JsonElement torrent;
public Torrent getTorrent()
{
// TODO Auto-generated method stub
return null;
}
public Nested parseJson(JsonObject o)
{
if (o.has("encoding"))
{
encoding = getEncoding(o.get("encoding").getAsString());
}
if (o.has("mount"))
{
mount = o.get("mount").getAsString();
}
if (o.has("torrent"))
{
torrentSource = o.get("torrent");
}
return this;
}
private static Encoding getEncoding(String enc)
{
if (enc.equalsIgnoreCase("bencode")) return Encoding.BENCODE_BASE64;
if (enc.equalsIgnoreCase("magnet")) return Encoding.MAGNET;
if (enc.equalsIgnoreCase("json")) return Encoding.JSON;
return null;
}
public enum Encoding
{
BENCODE_BASE64,
MAGNET,
JSON;
}
} |
package lucene4ir.indexer;
import lucene4ir.Lucene4IRConstants;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
public class TRECNEWSDocumentIndexer extends DocumentIndexer {
private Field docnumField;
private Field titleField;
private Field textField;
private Field authorField;
private Field allField;
private Document doc;
public TRECNEWSDocumentIndexer(String indexPath, String tokenFilterFile, boolean positional) {
super(indexPath, tokenFilterFile, positional);
doc = new Document();
initFields();
initNEWSDoc();
}
private void initFields() {
docnumField = new StringField(Lucene4IRConstants.FIELD_DOCNUM, "", Field.Store.YES);
if (indexPositions) {
titleField = new TermVectorEnabledTextField(Lucene4IRConstants.FIELD_TITLE, "", Field.Store.YES);
textField = new TermVectorEnabledTextField(Lucene4IRConstants.FIELD_CONTENT, "", Field.Store.YES);
allField = new TermVectorEnabledTextField(Lucene4IRConstants.FIELD_ALL, "", Field.Store.YES);
authorField = new TermVectorEnabledTextField(Lucene4IRConstants.FIELD_AUTHOR, "", Field.Store.YES);
} else {
titleField = new TextField(Lucene4IRConstants.FIELD_TITLE, "", Field.Store.YES);
textField = new TextField(Lucene4IRConstants.FIELD_CONTENT, "", Field.Store.YES);
allField = new TextField(Lucene4IRConstants.FIELD_ALL, "", Field.Store.YES);
authorField = new TextField(Lucene4IRConstants.FIELD_AUTHOR, "", Field.Store.YES);
}
}
private void initNEWSDoc() {
doc.add(docnumField);
doc.add(titleField);
doc.add(textField);
doc.add(allField);
doc.add(authorField);
}
public Document createNEWSDocument(String docid, String author, String title, String content, String all) {
doc.clear();
docnumField.setStringValue(docid);
titleField.setStringValue(title);
allField.setStringValue(all);
textField.setStringValue(content);
authorField.setStringValue(author);
doc.add(docnumField);
doc.add(authorField);
doc.add(titleField);
doc.add(textField);
doc.add(allField);
return doc;
}
public void indexDocumentsFromFile(String filename) {
String line;
java.lang.StringBuilder text = new StringBuilder();
try (BufferedReader br = openDocumentFile(filename)) {
line = br.readLine();
while (line != null) {
if (line.startsWith("<DOC>")) {
text = new StringBuilder();
}
text.append(line).append("\n");
if (line.startsWith("</DOC>")) {
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
String docString = text.toString();
// Remove all escaped entities from the string.
docString = docString.replaceAll("&[a-zA-Z0-9]+;", "");
docString = docString.replaceAll("&", "");
// Remove P and ID attributes for FB94
docString = docString.replaceAll("P=[0-9]+", "");
docString = docString.replaceAll("ID=[-a-zA-Z0-9]+", "");
// Remove some random tag for FBIS
docString = docString.replaceAll("<3>", "");
docString = docString.replaceAll("</3>", "");
org.w3c.dom.Document xmlDocument = builder.parse(new InputSource(new StringReader(docString)));
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "/DOC/DOCNO";
String docid = xPath.compile(expression).evaluate(xmlDocument).trim();
// The title can either be a HEAD tag or a HL tag.
expression = "/DOC/HEAD/descendant-or-self::*/text()|/DOC/HL/descendant-or-self::*/text()|/DOC/HEADLINE/descendant-or-self::*/text()|/DOC/DOCTITLE/descendant-or-self::*/text()|/DOC/HT/descendant-or-self::*/text()";
//String title = xPath.compile(expression).evaluate(xmlDocument).trim();
StringBuilder title = new StringBuilder();
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
Node currentNode = nodeList.item(i);
title.append(" ").append(currentNode.getNodeValue());
}
title = new StringBuilder(title.toString().trim());
//String title = xPath.compile(expression).evaluate(xmlDocument).trim();
System.out.println(docid + " :" + title + ":");
expression = "/DOC/TEXT/descendant-or-self::*/text()";
StringBuilder content = new StringBuilder();
nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
Node currentNode = nodeList.item(i);
content.append(" ").append(currentNode.getNodeValue());
}
content = new StringBuilder(content.toString().trim());
// Similar to title, the author field can be represented as multiple tags.
expression = "/DOC/BYLINE/descendant-or-self::*/text()|/DOC/SO/descendant-or-self::*/text()";
String author = xPath.compile(expression).evaluate(xmlDocument).trim();
expression = "/DOC/descendant-or-self::*/text()";
StringBuilder all = new StringBuilder();
nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
Node currentNode = nodeList.item(i);
all.append(" ").append(currentNode.getNodeValue());
}
all = new StringBuilder(all.toString().trim());
System.out.println(all);
createNEWSDocument(docid, author, title.toString(), content.toString(), all.toString());
addDocumentToIndex(doc);
text = new StringBuilder();
}
line = br.readLine();
}
} catch (IOException | SAXException | XPathExpressionException | ParserConfigurationException e) {
e.printStackTrace();
System.exit(1);
}
}
} |
// @author A0112725N
/**
* This interface specifies any undoable actions
*/
package com.epictodo.model.command;
public interface Undoable {
/**
* This method enforces the ability to undo an action
*
* @return the result
*/
public String undo();
/**
* This method enforces the ability to redo an action
*
* @return the result
*/
public String redo();
} |
package mho.wheels.numberUtils;
import mho.wheels.math.BinaryFraction;
import mho.wheels.structures.Pair;
import org.jetbrains.annotations.NotNull;
import java.math.BigInteger;
import java.util.Optional;
/**
* Methods for manipulating and analyzing {@link float}s and {@link double}s.
*/
public final strictfp class FloatingPointUtils {
/**
* The bit size of a {@code float}'s exponent
*/
public static final int FLOAT_EXPONENT_WIDTH = 8;
/**
* The bit size of a {@code double}'s exponent
*/
public static final int DOUBLE_EXPONENT_WIDTH = 11;
/**
* The bit size of a {@code float}'s fraction
*/
public static final int FLOAT_FRACTION_WIDTH = 23;
/**
* The bit size of a {@code double}'s fraction
*/
public static final int DOUBLE_FRACTION_WIDTH = 52;
/**
* The exponent of the smallest {@code float} value
*/
public static final int MIN_SUBNORMAL_FLOAT_EXPONENT = Float.MIN_EXPONENT - FLOAT_FRACTION_WIDTH;
/**
* The exponent of the smallest {@code double} value
*/
public static final int MIN_SUBNORMAL_DOUBLE_EXPONENT = Double.MIN_EXPONENT - DOUBLE_FRACTION_WIDTH;
public static final int POSITIVE_FINITE_FLOAT_COUNT = Float.floatToIntBits(Float.MAX_VALUE);
public static final long POSITIVE_FINITE_DOUBLE_COUNT = Double.doubleToRawLongBits(Double.MAX_VALUE);
public static final @NotNull BigInteger SCALED_UP_MAX_FLOAT = scaleUp(Float.MAX_VALUE).get();
public static final @NotNull BigInteger SCALED_UP_MAX_DOUBLE = scaleUp(Double.MAX_VALUE).get();
/**
* Disallow instantiation
*/
private FloatingPointUtils() {}
/**
* Determines whether a {@code float} is negative zero.
*
* <ul>
* <li>{@code f} may be any {@code float}.</li>
* <li>The result may be either {@code boolean}.</li>
* </ul>
*
* @param f a {@code float}
* @return whether {@code f} is -0.0f
*/
public static boolean isNegativeZero(float f) {
return Float.floatToIntBits(f) == Integer.MIN_VALUE;
}
/**
* Determines whether a {@code double} is negative zero.
*
* <ul>
* <li>{@code d} may be any {@code double}.</li>
* <li>The result may be either {@code boolean}.</li>
* </ul>
*
* @param d a {@code double}
* @return whether {@code d} is -0.0
*/
public static boolean isNegativeZero(double d) {
return Double.doubleToLongBits(d) == Long.MIN_VALUE;
}
/**
* Determines whether a {@code float} is positive zero.
*
* <ul>
* <li>{@code f} may be any {@code float}.</li>
* <li>The result may be either {@code boolean}.</li>
* </ul>
*
* @param f a {@code float}
* @return whether {@code f} is 0.0f
*/
public static boolean isPositiveZero(float f) {
return Float.floatToIntBits(f) == 0;
}
/**
* Determines whether a {@code double} is positive zero.
*
* <ul>
* <li>{@code d} may be any {@code double}.</li>
* <li>The result may be either {@code boolean}.</li>
* </ul>
*
* @param d a {@code double}
* @return whether {@code d} is 0.0
*/
public static boolean isPositiveZero(double d) {
return Double.doubleToLongBits(d) == 0;
}
/**
* Returns the next-largest {@code float} after {@code f}. The successor of {@code -Float.MIN_VALUE} is negative
* zero. The successor of negative infinity is {@code -Float.MAX_VALUE}.
*
* <ul>
* <li>{@code f} may not be {@code NaN} or {@code Infinity}.</li>
* <li>The result may be any {@code float} other than 0.0, {@code NaN}, or {@code -Infinity}.</li>
* </ul>
*
* @param f a {@code float}
* @return min{g|g{@literal >}{@code f}}
*/
public static float successor(float f) {
if (Float.isNaN(f) || f > 0 && Float.isInfinite(f)) {
throw new ArithmeticException(f + " may not be NaN or Infinity.");
}
if (f == 0.0f) return Float.MIN_VALUE;
int floatBits = Float.floatToIntBits(f);
return Float.intBitsToFloat(f > 0 ? floatBits + 1 : floatBits - 1);
}
/**
* Returns the next-smallest {@code float} before {@code f}. The predecessor of positive infinity is
* {@code Float.MAX_VALUE}.
*
* <ul>
* <li>{@code f} may not be {@code NaN} or {@code -Infinity}.</li>
* <li>The result may be any {@code float} other than negative zero, {@code NaN}, or {@code +Infinity}.</li>
* </ul>
*
* @param f a {@code float}
* @return max{g|g{@literal <}{@code f}}
*/
public static float predecessor(float f) {
if (Float.isNaN(f) || f < 0 && Float.isInfinite(f)) {
throw new ArithmeticException(f + " may not be NaN or -Infinity.");
}
if (f == 0.0f) return -Float.MIN_VALUE;
int floatBits = Float.floatToIntBits(f);
return Float.intBitsToFloat(f > 0 ? floatBits - 1 : floatBits + 1);
}
/**
* Returns the next-largest {@code double} after {@code d}. The successor of {@code -Double.MIN_VALUE} is negative
* zero. The successor of negative infinity is {@code -Double.MAX_VALUE}.
*
* <ul>
* <li>{@code d} may not be {@code NaN} or {@code Infinity}.</li>
* <li>The result may be any {@code double} other than 0.0, {@code NaN} or {@code -Infinity}.</li>
* </ul>
*
* @param d a {@code double}
* @return min{e|e{@literal >}{@code d}}
*/
public static double successor(double d) {
if (Double.isNaN(d) || d > 0 && Double.isInfinite(d)) {
throw new ArithmeticException(d + " may not be NaN or Infinity.");
}
if (d == 0.0) return Double.MIN_VALUE;
long doubleBits = Double.doubleToLongBits(d);
return Double.longBitsToDouble(d > 0 ? doubleBits + 1 : doubleBits - 1);
}
/**
* Returns the next-smallest {@code double} before {@code d}. The predecessor of positive infinity is
* {@code Double.MAX_VALUE}.
*
* <ul>
* <li>{@code d} may not be {@code NaN} or {@code -Infinity}.</li>
* <li>The result may be any {@code double} other than negative zero, {@code NaN}, or {@code +Infinity}.</li>
* </ul>
*
* @param d a {@code double}
* @return max{e|e{@literal <}{@code d}}
*/
public static double predecessor(double d) {
if (Double.isNaN(d) || d < 0 && Double.isInfinite(d)) {
throw new ArithmeticException(d + " may not be NaN or -Infinity.");
}
if (d == 0.0) return -Double.MIN_VALUE;
long doubleBits = Double.doubleToLongBits(d);
return Double.longBitsToDouble(d > 0 ? doubleBits - 1 : doubleBits + 1);
}
public static int toOrderedRepresentation(float f) {
if (Float.isNaN(f)) {
throw new ArithmeticException("f cannot be NaN.");
}
if (f >= 0) {
return Float.floatToIntBits(absNegativeZeros(f));
} else {
return -Float.floatToIntBits(-f);
}
}
public static float floatFromOrderedRepresentation(int n) {
float f = n >= 0 ? Float.intBitsToFloat(n) : -Float.intBitsToFloat(-n);
if (Float.isNaN(f)) {
throw new ArithmeticException("n must have an absolute value less than or equal to 2^31 - 2^23. Invalid" +
" n: " + n);
}
return f;
}
public static long toOrderedRepresentation(double d) {
if (Double.isNaN(d)) {
throw new ArithmeticException("d cannot be NaN.");
}
if (d >= 0) {
return Double.doubleToLongBits(absNegativeZeros(d));
} else {
return -Double.doubleToLongBits(-d);
}
}
public static double doubleFromOrderedRepresentation(long n) {
double d = n >= 0 ? Double.longBitsToDouble(n) : -Double.longBitsToDouble(-n);
if (Double.isNaN(d)) {
throw new ArithmeticException("n must have an absolute value less than or equal to 2^63 - 2^52. Invalid" +
" n: " + n);
}
return d;
}
public static @NotNull Optional<Float> floatFromMantissaAndExponent(int mantissa, int exponent) {
if (mantissa == 0) {
if (exponent != 0) {
return Optional.empty();
}
} else if ((mantissa & 1) == 0) {
return Optional.empty();
}
Pair<Float, Float> range = BinaryFraction.of(BigInteger.valueOf(mantissa), exponent).floatRange();
return range.a.equals(range.b) ? Optional.of(range.a) : Optional.<Float>empty();
}
public static @NotNull Optional<Double> doubleFromMantissaAndExponent(long mantissa, int exponent) {
if (mantissa == 0) {
if (exponent != 0) {
return Optional.empty();
}
} else if ((mantissa & 1) == 0) {
return Optional.empty();
}
Pair<Double, Double> range = BinaryFraction.of(BigInteger.valueOf(mantissa), exponent).doubleRange();
return range.a.equals(range.b) ? Optional.of(range.a) : Optional.<Double>empty();
}
public static @NotNull Optional<Pair<Integer, Integer>> toMantissaAndExponent(float f) {
Optional<BinaryFraction> obf = BinaryFraction.of(f);
if (!obf.isPresent()) return Optional.empty();
BinaryFraction bf = obf.get();
return Optional.of(new Pair<>(bf.getMantissa().intValueExact(), bf.getExponent()));
}
public static @NotNull Optional<Pair<Long, Integer>> toMantissaAndExponent(double d) {
Optional<BinaryFraction> obf = BinaryFraction.of(d);
if (!obf.isPresent()) return Optional.empty();
BinaryFraction bf = obf.get();
return Optional.of(new Pair<>(bf.getMantissa().longValueExact(), bf.getExponent()));
}
/**
* If {@code f} is -0.0f, return 0.0f; otherwise, return {@code f}.
*
* <ul>
* <li>{@code f} may be any {@code float}.</li>
* <li>The result is not negative zero.</li>
* </ul>
*
* @param f a {@code float}
* @return a {@code float} equal to {@code f} and not -0.0f
*/
public static float absNegativeZeros(float f) {
return f == 0.0f ? 0.0f : f;
}
/**
* If {@code d} is -0.0, return 0.0; otherwise, return {@code d}.
*
* <ul>
* <li>{@code d} may be any {@code double}.</li>
* <li>The result is not negative zero.</li>
* </ul>
*
* @param d a {@code double}
* @return a {@code double} equal to {@code d} and not -0.0
*/
public static double absNegativeZeros(double d) {
return d == 0.0 ? 0.0 : d;
}
/**
* Return how many multiples of {@link Float#MIN_VALUE} a given {@code float} is. Returns an empty result if
* {@code f} is infinite or {@code NaN}.
*
* <ul>
* <li>{@code f} may be any {@code float}.</li>
* <li>The result is empty or a {@code BigInteger} whose absolute value is less than or equal to
* {@link FloatingPointUtils#SCALED_UP_MAX_FLOAT}.</li>
* </ul>
*
* @param f a {@code float}
* @return {@code f}/{@code Float.MIN_VALUE}
*/
public static @NotNull Optional<BigInteger> scaleUp(float f) {
return BinaryFraction.of(f).map(bf -> bf.shiftRight(MIN_SUBNORMAL_FLOAT_EXPONENT).bigIntegerValueExact());
}
/**
* Return how many multiples of {@link Double#MIN_VALUE} a given {@code double} is. Returns an empty result if
* {@code d} is infinite or {@code NaN}.
*
* <ul>
* <li>{@code d} may be any {@code double}.</li>
* <li>The result is empty or a {@code BigInteger} whose absolute value is less than or equal to
* {@link FloatingPointUtils#SCALED_UP_MAX_DOUBLE}.</li>
* </ul>
*
* @param d a {@code double}
* @return {@code d}/{@code Double.MIN_VALUE}
*/
public static @NotNull Optional<BigInteger> scaleUp(double d) {
return BinaryFraction.of(d).map(bf -> bf.shiftRight(MIN_SUBNORMAL_DOUBLE_EXPONENT).bigIntegerValueExact());
}
/**
* Converts a {@code float} to a {@code String} in the same way as {@link Float#toString()}, but with no trailing
* {@code ".0"}.
*
* <ul>
* <li>{@code f} may be any {@code float}.</li>
* <li>The result is a {@code String s} such that either {@code Float.toString(}x{@code )} is equal to {@code s}
* for some {@code float} x, or {@code Float.toString(}x{@code )} is equal to {@code s + ".0"} for some
* {@code float} x.</li>
* </ul>
*
* @param f a {@code float}
* @return a compact {@code String} representation of {@code f}
*/
public static @NotNull String toStringCompact(float f) {
String s = Float.toString(f);
return s.endsWith(".0") ? s.substring(0, s.length() - 2) : s;
}
/**
* Converts a {@code double} to a {@code String} in the same way as {@link Double#toString()}, but with no trailing
* {@code ".0"}.
*
* <ul>
* <li>{@code d} may be any {@code double}.</li>
* <li>The result is a {@code String s} such that either {@code Double.toString(}x{@code )} is equal to {@code s}
* for some {@code double} x, or {@code Double.toString(}x{@code )} is equal to {@code s + ".0"} for some
* {@code double} x.</li>
* </ul>
*
* @param d a {@code double}
* @return a compact {@code String} representation of {@code d}
*/
public static @NotNull String toStringCompact(double d) {
String s = Double.toString(d);
return s.endsWith(".0") ? s.substring(0, s.length() - 2) : s;
}
} |
package ml.duncte123.skybot.objects;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.google.gson.internal.Primitives;
/**
* Make fake interfaces
*
* @author ramidzkh
*/
public class FakeInterface<T> {
protected final Class<T> type;
protected final Map<Method, InvocationFunction> handlers;
public FakeInterface(Class<T> type) {
this(type, new HashMap<>());
}
public FakeInterface(Class<T> type, Map<Method, InvocationFunction> handlers) {
if(type == null) throw new NullPointerException("Type of interface is null");
if(!type.isInterface())
throw new IllegalArgumentException("Type " + type + " is not an interface");
if(type.isAnnotation())
throw new IllegalArgumentException("Type " + type + " is an annotation");
this.type = type;
this.handlers = (handlers != null) ? handlers : new HashMap<>();
}
public Class<T> getType() {
return type;
}
public Map<Method, InvocationFunction> getCustomHandlers() {
return handlers;
}
@SuppressWarnings("unchecked")
public T create() {
return (T) Proxy.newProxyInstance(type.getClassLoader(),
new Class<?>[] {type}, new IH(handlers));
}
/**
* An invocation handler to try and return the proper result type
*
* @author ramidzkh
*
*/
protected static class IH implements InvocationHandler {
protected final Map<Method, InvocationFunction> handlers;
protected IH (Map<Method, InvocationFunction> handlers) {
this.handlers = handlers;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
for(Method m : handlers.keySet())
if(m.equals(method))
return handlers.get(m).handle(proxy, method, args);
// The return type
Class<?> r = Primitives.unwrap(method.getReturnType());
// Primitives
if(r.isPrimitive()) {
if(r == boolean.class)
return Boolean.FALSE;
else if(r == byte.class)
return new Byte((byte) 0);
else if(r == char.class)
return '\u0000';
else if(r == short.class)
return new Short((short) 0);
else if(r == int.class)
return new Integer(0);
else if(r == float.class)
return new Float(0F);
else if(r == long.class)
return new Long(0L);
else if(r == double.class)
return new Double(0D);
}
// String
if(r == String.class
| r == CharSequence.class)
return "";
// Arrays
if(r.isArray())
return Array.newInstance(r.getComponentType(), 0);
// List | ArrayList
if(r == List.class
| r == ArrayList.class)
return new ArrayList<>();
// Set | HashSet
if(r == Set.class
| r == HashSet.class)
return new HashSet<>();
// Map | HashMap
if(r == Map.class
| r == HashMap.class)
return new HashMap<>();
// Entry | SimpleEntry
if(r == Map.Entry.class
| r == AbstractMap.SimpleEntry.class)
return new AbstractMap.SimpleEntry<Object, Object>(null, null);
// Create a fake for that interface
if(r.isInterface() && !r.isAnnotation())
return new FakeInterface<>(r).create();
// Constructors
Stream<Constructor<?>> constructors;
// Try to create an instance
if((constructors = Arrays.stream(r.getConstructors())
// public
.filter(Constructor::isAccessible)
// No parameters
.filter(c -> c.getParameterTypes().length == 0)
// No exceptions
.filter(c -> c.getExceptionTypes().length == 0))
// If any
.count() > 0)
// For each constructor
for(Constructor<?> c : constructors.collect(Collectors.toList()))
try {
// Try to create
return c.newInstance();
} catch (Throwable thr) {
// If we get an Error or RuntimeException, continue
}
// Null if we couldn't find
return null;
}
}
} |
package com.gamingmesh.jobs.dao;
import java.io.IOException;
import com.gamingmesh.jobs.Jobs;
import com.gamingmesh.jobs.container.LoadStatus;
import net.Zrips.CMILib.FileHandler.ConfigReader;
import net.Zrips.CMILib.Logs.CMIDebug;
public class JobsManager {
private JobsDAO dao;
private Jobs plugin;
private DataBaseType dbType = DataBaseType.SqLite;
public enum DataBaseType {
MySQL, SqLite
}
public JobsManager(Jobs plugin) {
this.plugin = plugin;
}
public JobsDAO getDB() {
return dao;
}
public void switchDataBase() {
if (dao != null)
dao.closeConnections();
// Picking opposite database then it is currently
switch (dbType) {
case MySQL:
// If it MySQL lets change to SqLite
dbType = DataBaseType.SqLite;
dao = startSqlite();
if (dao != null)
dao.setDbType(dbType);
break;
case SqLite:
// If it SqLite lets change to MySQL
dbType = DataBaseType.MySQL;
dao = startMysql();
if (dao != null)
dao.setDbType(dbType);
break;
default:
break;
}
ConfigReader config = Jobs.getGCManager().getConfig();
config.set("storage.method", dbType.toString().toLowerCase());
try {
config.save(config.getFile());
} catch (IOException e) {
e.printStackTrace();
}
Jobs.setDAO(dao);
}
private String username = "root", password = "", hostname = "localhost:3306", database = "minecraft", prefix = "jobs_",
characterEncoding = "utf8", encoding = "UTF-8";
private boolean certificate = false, ssl = false, autoReconnect = false;
public void start() {
if (Jobs.getJobsDAO() != null) {
Jobs.consoleMsg("&eClosing existing database connection...");
Jobs.getJobsDAO().closeConnections();
Jobs.consoleMsg("&eClosed");
}
ConfigReader c = Jobs.getGCManager().getConfig();
c.addComment("storage.method", "storage method, can be MySQL or sqlite");
String storageMethod = c.get("storage.method", "sqlite");
c.addComment("mysql", "Requires Mysql");
username = c.get("mysql.username", c.getC().getString("mysql-username", "root"));
password = c.get("mysql.password", c.getC().getString("mysql-password", ""));
hostname = c.get("mysql.hostname", c.getC().getString("mysql-hostname", "localhost:3306"));
database = c.get("mysql.database", c.getC().getString("mysql-database", "minecraft"));
prefix = c.get("mysql.table-prefix", c.getC().getString("mysql-table-prefix", "jobs_"));
certificate = c.get("mysql.verify-server-certificate", c.getC().getBoolean("verify-server-certificate"));
ssl = c.get("mysql.use-ssl", c.getC().getBoolean("use-ssl"));
autoReconnect = c.get("mysql.auto-reconnect", c.getC().getBoolean("auto-reconnect", true));
characterEncoding = c.get("mysql.characterEncoding", "utf8");
encoding = c.get("mysql.encoding", "UTF-8");
if (storageMethod.equalsIgnoreCase("mysql")) {
dbType = DataBaseType.MySQL;
dao = startMysql();
if (dao == null || dao.getConnection() == null) {
Jobs.status = LoadStatus.MYSQLFailure;
}
} else {
if (!storageMethod.equalsIgnoreCase("sqlite")) {
Jobs.consoleMsg("&cInvalid storage method! Changing method to sqlite!");
c.set("storage.method", "sqlite");
}
dbType = DataBaseType.SqLite;
dao = startSqlite();
if (dao.getConnection() == null) {
Jobs.status = LoadStatus.SQLITEFailure;
}
}
Jobs.setDAO(dao);
}
private synchronized JobsMySQL startMysql() {
ConfigReader c = Jobs.getGCManager().getConfig();
String legacyUrl = c.getC().getString("mysql.url");
if (legacyUrl != null) {
String jdbcString = "jdbc:mysql:
if (legacyUrl.toLowerCase().startsWith(jdbcString)) {
legacyUrl = legacyUrl.substring(jdbcString.length());
String[] parts = legacyUrl.split("/", 2);
if (parts.length >= 2) {
hostname = c.get("mysql.hostname", parts[0]);
database = c.get("mysql.database", parts[1]);
}
}
}
if (username == null) {
username = "root";
}
if (plugin.isEnabled()) {
JobsMySQL data = new JobsMySQL(plugin, hostname, database, username, password, prefix, certificate, ssl, autoReconnect,
characterEncoding, encoding);
data.initialize();
return data;
}
return null;
}
private synchronized JobsSQLite startSqlite() {
JobsSQLite data = new JobsSQLite(plugin, Jobs.getFolder());
data.initialize();
return data;
}
public DataBaseType getDbType() {
return dbType;
}
} |
package network.aika.neuron.activation;
import network.aika.Thought;
import network.aika.neuron.phase.Phase;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.TreeSet;
public class QueueState<P extends Phase> {
private TreeSet<P> pendingPhases = new TreeSet<>(Comparator.comparing(p -> p.getRank()));
private QueueEntry<P> entryToQueue;
private QueueEntry<P> queuedEntry;
private boolean marked;
public QueueState() {
}
public QueueState(QueueEntry<P> entry, P... initialPhases) {
entryToQueue = entry;
pendingPhases.addAll(Arrays.asList(initialPhases));
}
public QueueState(QueueEntry<P> entry, Collection<P> initialPhases) {
entryToQueue = entry;
pendingPhases.addAll(initialPhases);
}
public boolean isMarked() {
return marked;
}
public void setMarked(boolean marked) {
this.marked = marked;
}
public void setEntryToQueue(QueueEntry<P> entryToQueue) {
this.entryToQueue = entryToQueue;
}
public void addPhase(QueueEntry<P> e, P... p) {
entryToQueue = e;
pendingPhases.addAll(Arrays.asList(p));
updateThoughtQueue();
}
public void updateThoughtQueue() {
if(pendingPhases.isEmpty())
return;
P nextPhase = pendingPhases.first();
removeFromQueue();
addToQueue(nextPhase);
}
public void addToQueue(P nextPhase) {
entryToQueue.setPhase(nextPhase);
getThought().addToQueue(entryToQueue);
queuedEntry = entryToQueue;
}
public void removeFromQueue() {
if(queuedEntry != null) {
getThought().removeActivationFromQueue(queuedEntry);
queuedEntry = null;
}
}
public Thought getThought() {
return entryToQueue.getThought();
}
public void removePendingPhase() {
queuedEntry = null;
pendingPhases.pollFirst();
}
public QueueState copy(QueueEntry<P> newEntry) {
QueueState qs = new QueueState();
qs.pendingPhases.addAll(pendingPhases);
qs.entryToQueue = newEntry;
return qs;
}
public String toString() {
StringBuilder sb = new StringBuilder();
pendingPhases.forEach(p -> sb.append(p.getClass().getSimpleName() + ", "));
return sb.toString();
}
} |
package com.github.intangir.Tweaks;
import java.io.File;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Boat;
import org.bukkit.entity.Horse;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Minecart;
import org.bukkit.entity.Player;
import org.bukkit.entity.Vehicle;
import org.bukkit.event.EventHandler;
import org.bukkit.event.vehicle.VehicleExitEvent;
import org.bukkit.inventory.ItemStack;
public class Vehicles extends Tweak
{
Vehicles(Tweaks plugin) {
super(plugin);
CONFIG_FILE = new File(plugin.getDataFolder(), "vehicles.yml");
TWEAK_NAME = "Tweak_Vehicles";
TWEAK_VERSION = "1.0";
fixExitMinecart = true;
fixExitBoat = true;
fixExitHorse = true;
breakSwordInHand = true;
}
private boolean fixExitMinecart;
private boolean fixExitBoat;
private boolean fixExitHorse;
private boolean breakSwordInHand;
@EventHandler(ignoreCancelled = true)
public void onVehicleExit(VehicleExitEvent e) {
final LivingEntity exiter = e.getExited();
final Vehicle vehicle = e.getVehicle();
if(exiter instanceof Player) {
if( (fixExitMinecart && vehicle instanceof Minecart) ||
(fixExitBoat && vehicle instanceof Boat) ||
(fixExitHorse && vehicle instanceof Horse)) {
final Location fixLoc = exiter.getLocation().add(0, 0.5, 0);
server.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
public void run() {
if(!exiter.isInsideVehicle())
{
exiter.teleport(fixLoc);
ItemStack hand = ((Player)exiter).getItemInHand();
// auto destroy boat/minecart if they are a holding a sword
if(breakSwordInHand && hand != null && hand.getType().toString().contains("SWORD")) {
ItemStack item = null;
if(vehicle instanceof Minecart) {
item = new ItemStack(Material.MINECART);
} else if(vehicle instanceof Boat) {
item = new ItemStack(Material.BOAT);
}
if(item != null) {
exiter.getWorld().dropItem(fixLoc, item);
vehicle.remove();
}
}
}
}
}, 2);
}
}
}
} |
package nl.hsac.fitnesse.fixture.slim;
import nl.hsac.fitnesse.fixture.util.FileUtil;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* Utility fixture to work with files.
*/
public class FileFixture extends SlimFixtureWithMap {
private String directory = "";
public void setDirectory(String directory) {
if (!directory.endsWith(File.separator)) {
directory += File.separator;
}
this.directory = directory;
}
public String createContaining(String filename, String content) {
String fullName = getFullName(filename);
ensureParentExists(fullName);
File f = FileUtil.writeFile(fullName, content);
return linkToFile(f);
}
public String contentOf(String filename) throws IOException {
String fullName = getFullName(filename);
try {
FileInputStream s = new FileInputStream(fullName);
return FileUtil.streamToString(s, fullName);
} catch (FileNotFoundException e) {
throw new SlimFixtureException(false, "Unable to find: " + fullName);
}
}
public String createUsing(String filename, String templateName) {
String content = getEnvironment().processTemplate(templateName, getCurrentValues());
return createContaining(filename, content);
}
public String copyTo(String sourceName, String targetName) throws IOException {
String fullSource = getFullName(sourceName);
// ensure file exists
getFile(fullSource);
String fullTarget = getFullName(targetName);
ensureParentExists(fullTarget);
File destFile = FileUtil.copyFile(fullSource, fullTarget);
return linkToFile(destFile);
}
public long sizeOf(String filename) {
String fullName = getFullName(filename);
File file = getFile(fullName);
return file.length();
}
protected File getFile(String fullName) {
File file = new File(fullName);
if (!file.exists()) {
throw new SlimFixtureException(false, "Unable to find: " + file.getAbsolutePath());
}
return file;
}
protected void ensureParentExists(String fullName) {
File f = new File(fullName);
File parentFile = f.getParentFile();
parentFile.mkdirs();
}
protected String getFullName(String filename) {
String name;
if (filename.startsWith(File.separator)
|| ":\\".equals(filename.substring(1, 3))) {
name = filename;
} else if (isFilesUrl(filename)){
name = getFilePathFromWikiUrl(filename);
} else {
name = directory + filename;
}
return cleanupPath(name);
}
private boolean isFilesUrl(String filename) {
String url = getUrl(filename);
return !filename.equals(url) && url.startsWith("files/");
}
private String cleanupPath(String fullPath) {
String clean;
if ("\\".equals(File.separator)) {
clean = fullPath.replaceAll("/", File.separator);
} else {
clean = fullPath.replaceAll("\\\\", File.separator);
}
return clean;
}
protected String linkToFile(File f) {
String url = getWikiUrl(f.getAbsolutePath());
if (url == null) {
url = f.toURI().toString();
}
return String.format("<a href=\"%s\">%s</a>", url, f.getName());
}
} |
package com.github.sbouclier;
import com.github.sbouclier.utils.Base64Utils;
import com.github.sbouclier.utils.ByteUtils;
import com.github.sbouclier.utils.CryptoUtils;
import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.util.Map;
public class HttpJsonClient {
private String apiKey;
private String secret;
// - CONSTRUCTORS -
public HttpJsonClient() {
}
public HttpJsonClient(String apiKey, String secret) {
this.apiKey = apiKey;
this.secret = secret;
}
// - METHODS -
public String executePublicQuery(String baseUrl, String urlMethod) throws IOException {
return executePublicQuery(baseUrl, urlMethod, null);
}
public String executePublicQuery(String baseUrl, String urlMethod, Map<String, String> params) throws IOException {
final StringBuilder url = new StringBuilder(baseUrl).append(urlMethod).append("?");
if (params != null && !params.isEmpty()) {
params.forEach((k, v) -> {
url.append(k).append("=").append(v).append("&");
});
}
return getPublicJsonResponse(new URL(url.toString()));
}
public String getPublicJsonResponse(URL url) throws IOException {
final HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
try {
connection.setRequestMethod("GET");
return getJsonResponse(connection);
} finally {
connection.disconnect();
}
}
public String executePrivateQuery(String baseUrl, String urlMethod) throws IOException, KrakenApiException {
return executePrivateQuery(baseUrl, urlMethod, null);
}
public String executePrivateQuery(String baseUrl, String urlMethod, Map<String, String> params) throws IOException, KrakenApiException {
if (this.apiKey == null || this.secret == null) {
throw new KrakenApiException("must provide API key and secret");
}
final String nonce = generateNonce();
final String postData = buildPostData(params, nonce);
final String signature = generateSignature(urlMethod, nonce, postData);
return getPrivateJsonResponse(new URL(baseUrl + urlMethod), postData, signature);
}
public String getPrivateJsonResponse(URL url, String postData, String signature) throws IOException {
HttpsURLConnection connection = null;
try {
connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.addRequestProperty("API-Key", apiKey);
connection.addRequestProperty("API-Sign", signature);
if (postData != null && !postData.toString().isEmpty()) {
connection.setDoOutput(true);
try (OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream())) {
out.write(postData.toString());
}
}
return getJsonResponse(connection);
} finally {
connection.disconnect();
}
}
private String buildPostData(Map<String, String> params, String nonce) {
final StringBuilder postData = new StringBuilder();
if (params != null && !params.isEmpty()) {
params.forEach((k, v) -> {
postData.append(k).append("=").append(v).append("&");
});
}
postData.append("nonce=").append(nonce);
return postData.toString();
}
public String generateNonce() {
return String.valueOf(System.currentTimeMillis() * 1000);
}
/**
* Generate signature
*
* @param path URI path
* @param nonce
* @param postData POST data
* @return generated signature
* @throws KrakenApiException
*/
private String generateSignature(String path, String nonce, String postData) throws KrakenApiException {
// Algorithm: HMAC-SHA512 of (URI path + SHA256(nonce + POST data)) and base64 decoded secret API key
String hmacDigest = null;
try {
byte[] bytePath = ByteUtils.stringToBytes(path);
byte[] sha256 = CryptoUtils.sha256(nonce + postData);
byte[] hmacMessage = ByteUtils.concatArrays(bytePath, sha256);
byte[] hmacKey = Base64Utils.base64Decode(this.secret);
hmacDigest = Base64Utils.base64Encode(CryptoUtils.hmacSha512(hmacKey, hmacMessage));
} catch (Throwable ex) {
throw new KrakenApiException("unable to generate signature");
}
return hmacDigest;
}
public String getJsonResponse(HttpsURLConnection connection) throws IOException {
try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
StringBuilder response = new StringBuilder();
String line;
while ((line = in.readLine()) != null) {
response.append(line);
}
System.out.println(response);
return response.toString();
}
}
} |
package fr.tpt.s3.ls_mxc.generator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import fr.tpt.s3.ls_mxc.model.Actor;
import fr.tpt.s3.ls_mxc.model.ActorSched;
import fr.tpt.s3.ls_mxc.model.DAG;
import fr.tpt.s3.ls_mxc.model.Edge;
import fr.tpt.s3.ls_mxc.util.RandomNumberGenerator;
public class MCSystemGenerator {
// Set of generated graphs
private Set<DAG> gennedDAGs;
private int nbDAGs;
// Parameters for the generation
private double edgeProb;
private double userMaxU;
private int nbLevels;
private int parallelismDegree;
private int rfactor;
private int nbTasks;
// Utilities
private RandomNumberGenerator rng;
private boolean debug;
private int possibleDeadlines[] = {30, 50, 60, 80, 100};
public MCSystemGenerator (double maxU, int nbTasks,
double eProb, int levels, int paraDegree, int nbDAGs,
int rfactor, boolean debug) {
setUserMaxU(maxU);
setNbTasks(nbTasks);
setEdgeProb(eProb);
setNbLevels(levels);
setParallelismDegree(paraDegree);
setNbDAGs(nbDAGs);
setDebug(debug);
setRfactor(rfactor);
rng = new RandomNumberGenerator();
gennedDAGs = new HashSet<>();
}
/**
* Function that prints the current parameters of the node
* @param a
*/
private void debugNode (Actor a, String func) {
System.out.print("[DEBUG "+Thread.currentThread().getName()+"] "+func+": Node "+a.getId());
for (int i = nbLevels - 1; i >= 0; i
System.out.print(" C("+i+") = "+a.getCI(i)+";");
System.out.println(" Rank "+ ((ActorSched) a).getRank());
for (Edge e : a.getRcvEdges())
System.out.println("\t Rcv Edge "+e.getSrc().getId()+" -> "+a.getId());
for (Edge e : a.getSndEdges())
System.out.println("\t Snd Edge "+a.getId()+" -> "+e.getDest().getId());
}
/**
* UUnifast implementation
* @param uSet
* @param u
*/
private void uunifast (double uSet[], double u) {
double sum = u;
double nextSum;
for (int i = 0; i < uSet.length; i++) {
nextSum = sum * Math.pow(rng.randomUnifDouble(0.0, 1.0), 1.0 / (uSet.length - (i + 1)));
uSet[i] = sum - nextSum;
sum = nextSum;
}
}
/**
* UunifastDiscard implementation
* @param uSet
* @param u
* @return
*/
private boolean uunifastDiscard (double uSet[], double u) {
double sum = u;
double nextSum;
for (int i = 0; i < uSet.length; i++) {
nextSum = sum * Math.pow(rng.randomUnifDouble(0.0, 1.0), 1.0 / (uSet.length - i));
uSet[i] = sum - nextSum;
sum = nextSum;
}
for (int i = 0; i < uSet.length; i++) {
if (uSet[i] > 1)
return false;
}
return true;
}
/**
* Debug function for utilization given to tasks
* @param uSet
*/
private void printUset (double uSet[]) {
System.out.print("[DEBUG "+Thread.currentThread().getName()+"] GenerateGraph():");
for (int i = 0; i < uSet.length; i++)
System.out.print(" U_Task["+ i + "] = " + uSet[i]);
System.out.println("");
}
/**
* Method that resets Ranks on nodes that have no edges
* -> They become source edges
* @param level
*/
private void resetRanks (Set<Actor> nodes, int level) {
for (Actor a : nodes) {
if (a.getSndEdges().size() == 0 && a.getRcvEdges().size() == 0)
((ActorSched) a).setRank(0);
}
}
/**
* Method that generates a random graph
*/
protected void GenerateGraph(double utilization) {
int id = 0;
DAG d = new DAG();
Set<Actor> nodes = new HashSet<Actor>();
int rank;
int prevRank;
int idxDeadline = rng.randomUnifInt(0, possibleDeadlines.length - 1);
int rDead = possibleDeadlines[idxDeadline];
/* Init phase:
* Utilization per mode + budgets per mode
* Deadline given to graph
*/
double rU[] = new double[nbLevels];
int budgets[] = new int[nbLevels];
int cBounds[] = new int[nbLevels];
int tasks[] = new int[nbLevels];
/* Random distribution of utilization between the bounds
*/
for (int i = 0; i < nbLevels; i++) {
tasks[i] = (int) (nbTasks / nbLevels);
rU[i] = utilization;
budgets[i] = (int) Math.ceil(rDead * rU[i]);
cBounds[i] = (int) Math.ceil(rDead);
}
if (isDebug()) {
System.out.print("[DEBUG "+Thread.currentThread().getName()+"] GenerateGraph: Generating a graph with parameters ");
for (int i = 0; i < nbLevels; i++)
System.out.print("U["+i+"] = "+rU[i]+"; ");
System.out.println("deadline = "+rDead);
System.out.print("[DEBUG "+Thread.currentThread().getName()+"] GenerateGraph: Number of tasks per mode");
for (int i = 0; i < nbLevels; i++)
System.out.print("NbTasks["+i+"] = "+tasks[i]+"; ");
System.out.println(" buget "+budgets[1]);
}
// Generate nodes for all levels
prevRank = 0;
for (int i = nbLevels - 1; i >= 0; i
// Node generation block
rank = rng.randomUnifInt(0, prevRank);
// Number of tasks to generate in mode i
int tasksToGen = tasks[i];
double uSet[] = new double[tasksToGen];
double uInMode = (double) budgets[i] / rDead;
while (!uunifastDiscard(uSet, uInMode)) {
if (isDebug()) {
System.out.println("[DEBUG "+Thread.currentThread().getName()+"] GenerateGraph: Running uunifastDiscard for mode "+i);
}
}
if (isDebug()) printUset(uSet);
while (budgets[i] > 0 && tasksToGen > 0) {
int nodesPerRank = rng.randomUnifInt(1, parallelismDegree);
for (int j = 0; j < nodesPerRank || budgets[i] < 0; j++) {
ActorSched n = new ActorSched(id, Integer.toString(id), nbLevels);
// Transform uSet to budget
n.getcIs()[i] = (int) Math.ceil((rDead * uSet[tasks[i] - tasksToGen]));
if (budgets[i] - n.getCI(i) > 0) {
budgets[i] -= n.getCI(i);
} else {
n.getcIs()[i] = budgets[i];
budgets[i] = 0;
}
n.setRank(rank);
// Not a source node
if (rank != 0) {
// Iterate through the nodes to create an edge
Iterator<Actor> it_n = nodes.iterator();
while (it_n.hasNext()) {
ActorSched src = (ActorSched) it_n.next();
/* Roll a probability of having an edge between nodes
* Make sure that the deadline is not reached
*/
if (rng.randomUnifDouble(0, 100) <= edgeProb
&& n.getRank() > src.getRank()
&& src.getCpFromNode()[i] + n.getCI(i) <= rDead) {
@SuppressWarnings("unused")
Edge e = new Edge(src,n);
/* Once the edge is added the critical path needs to
* be updated
*/
src.CPfromNode(i);
}
}
}
// Set the Ci for inferior levels
if (i >= 1)
n.getcIs()[i - 1] = n.getCI(i);
nodes.add(n);
tasksToGen
n.CPfromNode(i);
id++;
if (isDebug())
debugNode(n, "GenerateGraph()");
}
rank++;
}
prevRank = rank;
// Shrinking procedure only for HI tasks
if (i >= 1) {
// Shrinking depends on the reduction factor
double minU = rU[i - 1] / getRfactor();
int wantedBudget = (int) Math.ceil(minU * rDead);
int actualBudget = (int) Math.ceil(rU[i] * rDead);
Iterator<Actor> it_n;
while (wantedBudget < actualBudget && !allNodesAreMin(nodes, i)) {
it_n = nodes.iterator();
while (it_n.hasNext()) {
ActorSched n = (ActorSched) it_n.next();
n.getcIs()[i - 1] = rng.randomUnifInt(1, n.getCI(i));
actualBudget -= n.getCI(i - 1);
if (actualBudget < 0)
actualBudget = 0;
}
}
if (isDebug()) {
System.out.println("[DEBUG "+Thread.currentThread().getName()+"] GenerateGraph(): >>> Deflation of tasks in mode "+i+" finished");
for (Actor a : nodes)
debugNode(a, "GenerateGraph()");
}
it_n = nodes.iterator();
actualBudget = 0;
while (it_n.hasNext()) {
Actor a = it_n.next();
a.CPfromNode(i - 1);
actualBudget += a.getCI(i - 1);
}
// Update remaining budgets
budgets[i - 1] -= actualBudget;
}
// Nodes that have no edges become source nodes
// their rank is reset
resetRanks(nodes, i);
}
d.setNodes(nodes);
d.setDeadline(rDead);
d.setId(getGennedDAGs().size());
getGennedDAGs().add(d);
if (isDebug())
System.out.println("[DEBUG "+Thread.currentThread().getName()+"] GenerateGraph(): DAG generation completed");
}
/**
* Verifies if all the nodes in the set have the minimum execution time
* @param nodes
* @param level
* @return
*/
private boolean allNodesAreMin(Set<Actor> nodes, int level) {
for (Actor a : nodes) {
if (a.getCI(level) != 1)
return false;
}
return true;
}
/**
* Method that generates all DAGs in the system
* the utilization for the system is uniformly distributed between
* the set of DAGs
* @return
*/
protected void genAllDags () {
// Apply Uunifast on the utilization for the DAGs
double[] uSet = new double[getNbDAGs()];
uunifast(uSet, getUserMaxU());
// Call genDAG with the utilization found
for (int i = 0; i < getNbDAGs(); i++) {
if (isDebug()) System.out.println("[DEBUG "+Thread.currentThread().getName()+"] Generating DAG #"+(i+1)+" of "+getNbDAGs());
GenerateGraph(uSet[i]);
}
}
/*
* Getters and setters
*/
public Set<DAG> getGennedDAGs() {
return gennedDAGs;
}
public void setGennedDAGs(Set<DAG> gennedDAGs) {
this.gennedDAGs = gennedDAGs;
}
public double getEdgeProb() {
return edgeProb;
}
public void setEdgeProb(double edgeProb) {
this.edgeProb = edgeProb;
}
public boolean isDebug() {
return debug;
}
public void setDebug(boolean debug) {
this.debug = debug;
}
public int getParallelismDegree() {
return parallelismDegree;
}
public void setParallelismDegree(int parallelismDegree) {
this.parallelismDegree = parallelismDegree;
}
public double getUserMaxU() {
return userMaxU;
}
public void setUserMaxU(double userMaxU) {
this.userMaxU = userMaxU;
}
public RandomNumberGenerator getRng() {
return rng;
}
public void setRng(RandomNumberGenerator rng) {
this.rng = rng;
}
public int getNbLevels() {
return nbLevels;
}
public void setNbLevels(int nbLevels) {
this.nbLevels = nbLevels;
}
public int getNbDAGs() {
return nbDAGs;
}
public void setNbDAGs(int nbDAGs) {
this.nbDAGs = nbDAGs;
}
public int getRfactor() {
return rfactor;
}
public void setRfactor(int rfactor) {
this.rfactor = rfactor;
}
public int getNbTasks() {
return nbTasks;
}
public void setNbTasks(int nbTasks) {
this.nbTasks = nbTasks;
}
} |
package com.google.sps.servlets;
import com.google.gson.Gson;
import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Provides interaction between front-end part of the application
* and the storage.
*/
@WebServlet("/data")
public class DataServlet extends HttpServlet {
private final static Object STORAGE_CONTROLLER = null;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("application/json");
response.getWriter().println(new Gson().toJson(""));
}
} |
package com.doos.commons.core;
import com.doos.commons.ApplicationConstants;
import com.doos.commons.registry.RegistryCanNotReadInfoException;
import com.doos.commons.registry.RegistryCanNotWriteInfoException;
import com.doos.commons.registry.RegistryManager;
import org.apache.log4j.Logger;
import static com.doos.commons.utils.Logging.getCurrentClassName;
public class SettingsManager {
private static final Logger log = Logger.getLogger(getCurrentClassName());
//You can not call this, method can be deleted
public static void loadInfo() throws RegistryCanNotReadInfoException, RegistryCanNotWriteInfoException {
log.info("Loading info from registry");
RegistryManager.getAppNameValue();
RegistryManager.getAppVersionValue();
RegistryManager.getInstallLocationValue();
RegistryManager.getURLUpdateValue();
//Fixes registry after update (if needed)
if (!RegistryManager.getAppVersionValue().equals(ApplicationConstants.APP_VERSION)) {
RegistryManager.setAppVersionValue(ApplicationConstants.APP_VERSION);
}
}
} |
package boundary.Question;
import boundary.Point.PointResource;
import entity.Point;
import entity.Question;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ws.rs.*;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.List;
@Path("/question")
@Stateless
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class QuestionRepresentation {
@EJB
private QuestionResource pathResource;
@EJB
private PointResource pointResource;
@GET
public Response get() {
GenericEntity<List<Question>> list = new GenericEntity<List<Question>>(pathResource.findAll()){};
return Response.ok(list, MediaType.APPLICATION_JSON).build();
}
@POST
public Response add(Question question) {
for (Point point : question.getPoints()) {
if (pointResource.findById(point.getId()) == null)
return Response.status(400)
.type(MediaType.TEXT_PLAIN_TYPE)
.entity("One or many points do not exist")
.build();
// ToDo : Links to Point + Add Link List in Question
}
if (question.getPoints().size() == Question.PATH_LENGTH)
return Response.status(400)
.type(MediaType.TEXT_PLAIN_TYPE)
.entity("Your question does not have enough point (" + Question.PATH_LENGTH + " required)")
.build();
question = pathResource.insert(question);
return Response.ok(question, MediaType.APPLICATION_JSON).build();
}
@DELETE
public Response delete(Question question) {
for(Point point : question.getPoints()) {
if(pointResource.findById(point.getId()) == null) {
return Response.status(400)
.type(MediaType.TEXT_PLAIN_TYPE)
.entity("One or many points do not exist")
.build();
}
}
if(question.getPoints().size() == Question.PATH_LENGTH)
return Response.status(400)
.type(MediaType.TEXT_PLAIN_TYPE)
.entity("Your question does not have enough point ("+Question.PATH_LENGTH+" required)")
.build();
pathResource.delete(question);
return Response.ok(question, MediaType.APPLICATION_JSON).build();
}
} |
package com.j256.ormlite.jdbc;
import java.sql.SQLException;
import java.sql.Types;
import java.util.HashMap;
import java.util.Map;
import com.j256.ormlite.field.SqlType;
import com.j256.ormlite.misc.VersionUtils;
/**
* Map from {@link SqlType} to the constants in the {@link Types} class.
*
* @author graywatson
*/
public class TypeValMapper {
private static final Map<SqlType, int[]> typeToValMap = new HashMap<SqlType, int[]>();
static {
// verifies that we have the right version -- not sure where else to do this
VersionUtils.checkCoreVersusJdbcVersions();
}
static {
for (SqlType sqlType : SqlType.values()) {
int[] values;
switch (sqlType) {
case STRING :
values = new int[] { Types.VARCHAR };
break;
case LONG_STRING :
values = new int[] { Types.LONGVARCHAR };
break;
case DATE :
values = new int[] { Types.TIMESTAMP };
break;
case BOOLEAN :
values = new int[] { Types.BOOLEAN };
break;
case CHAR :
values = new int[] { Types.CHAR };
break;
case BYTE :
values = new int[] { Types.TINYINT };
break;
case BYTE_ARRAY :
values = new int[] { Types.VARBINARY };
break;
case SHORT :
values = new int[] { Types.SMALLINT };
break;
case INTEGER :
values = new int[] { Types.INTEGER };
break;
case LONG :
values = new int[] { Types.BIGINT };
break;
case FLOAT :
values = new int[] { Types.FLOAT };
break;
case DOUBLE :
values = new int[] { Types.DOUBLE };
break;
case SERIALIZABLE :
values = new int[] { Types.VARBINARY };
break;
case BLOB :
// the following do not need to be handled except in specific situations
values = new int[] { Types.BLOB };
break;
case BIG_DECIMAL :
values = new int[] { Types.DECIMAL, Types.NUMERIC };
break;
case OTHER :
values = new int[] { Types.OTHER };
break;
case UNKNOWN :
values = new int[] {};
break;
default :
throw new IllegalArgumentException("No JDBC mapping for unknown SqlType " + sqlType);
}
typeToValMap.put(sqlType, values);
}
}
/**
* Returns the primary type value associated with the SqlType argument.
*/
public static int getTypeValForSqlType(SqlType sqlType) throws SQLException {
int[] typeVals = typeToValMap.get(sqlType);
if (typeVals == null) {
throw new SQLException("SqlType is unknown to type val mapping: " + sqlType);
}
if (typeVals.length == 0) {
throw new SQLException("SqlType does not have any JDBC type value mapping: " + sqlType);
} else {
return typeVals[0];
}
}
/**
* Returns the SqlType value associated with the typeVal argument. Can be slow-er.
*/
public static SqlType getSqlTypeForTypeVal(int typeVal) {
// iterate through to save on the extra HashMap since only for errors
for (Map.Entry<SqlType, int[]> entry : typeToValMap.entrySet()) {
for (int val : entry.getValue()) {
if (val == typeVal) {
return entry.getKey();
}
}
}
return SqlType.UNKNOWN;
}
} |
package com.jaamsim.BasicObjects;
import com.jaamsim.Thresholds.Threshold;
import com.jaamsim.Thresholds.ThresholdUser;
import com.jaamsim.input.Keyword;
import com.jaamsim.input.ValueInput;
import com.jaamsim.units.TimeUnit;
import com.sandwell.JavaSimulation.EntityInput;
import com.sandwell.JavaSimulation.EntityTarget;
import com.sandwell.JavaSimulation.InputErrorException;
import com.sandwell.JavaSimulation3D.DisplayEntity;
import com.sandwell.JavaSimulation3D.Queue;
public class EntityGate extends LinkedComponent implements ThresholdUser {
@Keyword(description = "The queue in which the waiting DisplayEntities will be placed.",
example = "EntityGate1 WaitQueue { Queue1 }")
private final EntityInput<Queue> waitQueue;
@Keyword(description = "The time delay before each queued entity is released.\n" +
"Entities arriving at an open gate are not delayed.",
example = "EntityGate1 ReleaseDelay { 5.0 s }")
private final ValueInput releaseDelay;
private boolean gateOpen; // TRUE if the gate is open
private boolean busy; // TRUE if the process of emptying the queue has started
{
waitQueue = new EntityInput<Queue>( Queue.class, "WaitQueue", "Key Inputs", null);
this.addInput( waitQueue);
releaseDelay = new ValueInput( "ReleaseDelay", "Key Inputs", 0.0);
releaseDelay.setUnitType(TimeUnit.class);
releaseDelay.setValidRange(0.0, Double.POSITIVE_INFINITY);
this.addInput( releaseDelay);
}
@Override
public void validate() {
super.validate();
// Confirm that the target queue has been specified
if( waitQueue.getValue() == null ) {
throw new InputErrorException( "The keyword WaitQueue must be set." );
}
}
@Override
public void earlyInit() {
super.earlyInit();
busy = false;
}
/**
* Add a DisplayEntity from upstream
* @param ent = entity to be added
*/
@Override
public void addDisplayEntity( DisplayEntity ent ) {
super.addDisplayEntity(ent);
// If the gate is closed or other entities are already queued, then add the entity to the queue
Queue queue = waitQueue.getValue();
if( queue.getCount() > 0 || !gateOpen ) {
queue.addLast( ent );
return;
}
// If the gate is open and there are no other entities still in the queue, then send the entity to the next component
this.sendToNextComponent( ent );
}
@Override
public void thresholdChanged() {
// Are any of the thresholds closed?
boolean threshOpen = true;
for( Threshold thr : this.getThresholds() ) {
if( thr.isClosed() ) {
threshOpen = false;
break;
}
}
// Should the gate's state be changed?
if( threshOpen == gateOpen )
return;
// Open or close the gate
if (threshOpen)
this.open();
else
this.close();
}
/**
* Close the gate.
*/
public void close() {
gateOpen = false;
}
/**
* Open the gate and release any entities in the queue.
*/
public void open() {
gateOpen = true;
// Release any entities that are in the queue
if( busy || waitQueue.getValue().getCount() == 0 )
return;
busy = true;
this.scheduleProcess(releaseDelay.getValue(), 5, new ReleaseQueuedEntityTarget(this, "releaseQueuedEntity"));
}
private static class ReleaseQueuedEntityTarget extends EntityTarget<EntityGate> {
public ReleaseQueuedEntityTarget(EntityGate gate, String method) {
super(gate,method);
}
@Override
public void process() {
ent.releaseQueuedEntity();
}
}
/**
* Loop recursively through the queued entities, releasing them one by one.
*/
private void releaseQueuedEntity() {
// Stop the recursive loop if the gate has closed or the queue has become empty
Queue queue = waitQueue.getValue();
if( !gateOpen || queue.getCount() == 0 ) {
busy = false;
return;
}
// Release the first element in the queue and send to the next component
DisplayEntity ent = queue.removeFirst();
this.sendToNextComponent( ent );
// Stop the recursive loop if the queue is now empty
if( queue.getCount() == 0 ) {
busy = false;
return;
}
// Continue the recursive loop by scheduling the release of the next queued entity
this.scheduleProcess(releaseDelay.getValue(), 5, new ReleaseQueuedEntityTarget(this, "releaseQueuedEntity"));
}
} |
package com.eddysystems.eddy.engine;
import com.eddysystems.eddy.EddyThread;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.PsiShortNamesCache;
import com.intellij.util.Processor;
import com.intellij.util.indexing.IdFilter;
import org.jetbrains.annotations.NotNull;
import tarski.Items;
import tarski.JavaTrie.Generator;
import java.util.ArrayList;
import java.util.List;
import static com.eddysystems.eddy.engine.Utility.log;
class ItemGenerator implements Generator<Items.Item> {
static final int cacheSize = 10000;
final LRUCache<String, Items.Item[]> cache = new LRUCache<String, Items.Item[]>(cacheSize);
final Project project;
final GlobalSearchScope scope;
final boolean checkVisibility;
final PsiShortNamesCache psicache;
final IdFilter filter = new IdFilter() { @Override public boolean containsFileId(int id) { return true; } };
final Converter converter;
// true if there's a chance that element is visible from outside its file. Only elements that are private or
// inside private or anonymous elements or that are local are not potentially visible.
boolean possiblyVisible(PsiModifierListOwner element) {
PsiElement container = null;
try {
container = Place.containing(element, project);
} catch (Place.UnexpectedContainerError e) {
log(e.getMessage());
return false;
}
// anything toplevel in a package is at most protected
if (container instanceof PsiPackage) {
return true;
}
// anything private is out
if (element.hasModifierProperty(PsiModifier.PRIVATE)) {
return false;
}
// everything else, depends on the container
if (container instanceof PsiModifierListOwner) {
return possiblyVisible((PsiModifierListOwner)container);
} else
return false;
}
ItemGenerator(Project project, GlobalSearchScope scope, Converter conv, boolean checkVisibility) {
this.project = project;
this.scope = scope;
this.checkVisibility = checkVisibility;
this.psicache = PsiShortNamesCache.getInstance(project);
converter = conv;
}
private Items.Item[] generate(String s) {
final EddyThread thread = EddyThread.getEddyThread();
final List<Items.Item> results = new ArrayList<Items.Item>();
final Processor<PsiClass> classProc = new Processor<PsiClass>() {
@Override
public boolean process(PsiClass cls) {
if (thread != null && thread.canceled())
return false;
if (!checkVisibility || possiblyVisible(cls))
results.add(converter.addClass(cls));
return true;
}
};
final Processor<PsiMethod> methodProc = new Processor<PsiMethod>() {
@Override
public boolean process(PsiMethod method) {
if (thread != null && thread.canceled())
return false;
if (!checkVisibility || possiblyVisible(method) && !Converter.isConstructor(method))
results.add(converter.addMethod(method));
return true;
}
};
final Processor<PsiField> fieldProc = new Processor<PsiField>() {
@Override
public boolean process(PsiField fld) {
if (thread != null && thread.canceled())
return false;
if (!checkVisibility || possiblyVisible(fld))
results.add(converter.addField(fld));
return true;
}
};
if (thread != null) thread.pushSoftInterrupts();
try {
psicache.processClassesWithName(s, classProc, scope, filter);
psicache.processMethodsWithName(s, methodProc, scope, filter);
psicache.processFieldsWithName(s, fieldProc, scope, filter);
} finally {
if (thread != null) thread.popSoftInterrupts();
}
return results.toArray(new Items.Item[results.size()]);
}
@Override @NotNull
public Items.Item[] lookup(String s) {
Items.Item[] result = cache.get(s);
if (result != null)
return result;
else
result = generate(s);
// add to cache
cache.put(s, result);
return result;
}
} |
package org.domeos.framework.engine.k8s;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.api.model.PodList;
import io.fabric8.kubernetes.api.model.Service;
import org.apache.commons.lang.StringUtils;
import org.domeos.exception.DataBaseContentException;
import org.domeos.exception.DeploymentEventException;
import org.domeos.exception.DeploymentTerminatedException;
import org.domeos.exception.K8sDriverException;
import org.domeos.framework.api.biz.deployment.DeployEventBiz;
import org.domeos.framework.api.biz.deployment.DeploymentBiz;
import org.domeos.framework.api.biz.deployment.DeploymentStatusBiz;
import org.domeos.framework.api.biz.deployment.VersionBiz;
import org.domeos.framework.api.biz.global.GlobalBiz;
import org.domeos.framework.api.biz.loadBalancer.LoadBalancerBiz;
import org.domeos.framework.api.consolemodel.deployment.EnvDraft;
import org.domeos.framework.api.model.auth.User;
import org.domeos.framework.api.model.cluster.Cluster;
import org.domeos.framework.api.model.deployment.DeployEvent;
import org.domeos.framework.api.model.deployment.Deployment;
import org.domeos.framework.api.model.deployment.Policy;
import org.domeos.framework.api.model.deployment.Version;
import org.domeos.framework.api.model.deployment.related.DeployEventStatus;
import org.domeos.framework.api.model.deployment.related.DeployOperation;
import org.domeos.framework.api.model.deployment.related.DeploymentSnapshot;
import org.domeos.framework.api.model.deployment.related.DeploymentStatus;
import org.domeos.framework.api.model.deployment.related.NetworkMode;
import org.domeos.framework.api.model.global.Server;
import org.domeos.framework.api.model.loadBalancer.LoadBalancer;
import org.domeos.framework.api.service.deployment.DeploymentStatusManager;
import org.domeos.framework.engine.RuntimeDriver;
import org.domeos.framework.engine.coderepo.ReflectFactory;
import org.domeos.framework.engine.exception.DriverException;
import org.domeos.framework.engine.k8s.handler.DeployResourceHandler;
import org.domeos.framework.engine.k8s.util.Fabric8KubeUtils;
import org.domeos.framework.engine.k8s.util.KubeUtils;
import org.domeos.framework.engine.k8s.util.PodUtils;
import org.domeos.framework.engine.k8s.util.SecretUtils;
import org.domeos.global.GlobalConstant;
import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.text.ParseException;
import java.util.*;
@Component
@Scope("prototype")
public class K8sDriver implements RuntimeDriver {
private Logger logger = LoggerFactory.getLogger(K8sDriver.class);
private Cluster cluster;
@Autowired
private DeploymentStatusManager deploymentStatusManager;
@Autowired
private DeployEventBiz deployEventBiz;
@Autowired
private DeploymentStatusBiz deploymentStatusBiz;
@Autowired
private DeploymentBiz deploymentBiz;
@Autowired
private VersionBiz versionBiz;
@Autowired
private LoadBalancerBiz loadBalancerBiz;
@Autowired
private GlobalBiz globalBiz;
@Override
public RuntimeDriver init(Cluster cluster) {
this.cluster = cluster;
return this;
}
@Override
public boolean isDriverLatest(Cluster cluster) {
boolean equal = cluster.equalWith(this.cluster);
this.cluster = cluster;
return equal;
}
@Override
public void updateList(Cluster cluster) {
this.cluster = cluster;
}
private static List<DeploymentSnapshot> buildSingleDeploymentSnapshot(long version, int replicas) {
List<DeploymentSnapshot> snapshots = new LinkedList<>();
snapshots.add(new DeploymentSnapshot(version, replicas));
return snapshots;
}
@Override
public void startDeploy(Deployment deployment, Version version, User user, List<EnvDraft> allExtraEnvs)
throws DriverException, DeploymentEventException, IOException {
KubeUtils client;
DeployResourceHandler deployResourceHandler;
try {
client = Fabric8KubeUtils.buildKubeUtils(cluster, deployment.getNamespace());
deployResourceHandler = getDeployResourceHandler(deployment, client);
} catch (K8sDriverException e) {
throw new DriverException(e.getMessage());
}
long eventId = deploymentStatusManager.registerEvent(deployment.getId(),
DeployOperation.START,
user,
null,
null,
buildSingleDeploymentSnapshot(version.getVersion(), deployment.getDefaultReplicas()));
deploymentStatusManager.freshEvent(eventId, null);
DeployEvent event = deployEventBiz.getEvent(eventId);
try {
//loadBalancer
if (deployment.getNetworkMode() != NetworkMode.HOST && deployment.getUsedLoadBalancer() == 0) {
List<LoadBalancer> lbs = loadBalancerBiz.getInnerAndExternalLoadBalancerByDeployId(deployment.getId());
checkLoadBalancer(client, lbs);
}
// create secret before the create of rc
// judge the registry is belong to domeos or not
checkSecret(client, version, deployment);
deployResourceHandler.create(version, allExtraEnvs);
} catch (Exception e) {
failedDeployment(deployment.getId(), event, e);
}
}
@Override
public void abortDeployOperation(Deployment deployment, User user)
throws IOException, DeploymentEventException, DeploymentTerminatedException {
KubeUtils kubeUtils;
DeployResourceHandler deployResourceHandler;
try {
kubeUtils = Fabric8KubeUtils.buildKubeUtils(cluster, deployment.getNamespace());
deployResourceHandler = getDeployResourceHandler(deployment, kubeUtils);
} catch (K8sDriverException e) {
throw new DeploymentEventException(e);
}
long abortDeployEventId = deploymentStatusManager.registerAbortEvent(deployment.getId(), user);
PodList podList = getPodListByDeployment(kubeUtils, deployment);
deploymentStatusManager.freshEvent(abortDeployEventId, queryCurrentSnapshotWithPodRunning(podList));
DeployEvent abortEvent = deployEventBiz.getEvent(abortDeployEventId);
if (abortEvent.getEventStatus().equals(DeployEventStatus.PROCESSING)) {
switch (abortEvent.getOperation()) {
case ABORT_START:
try {
//loadBalancer
try {
LoadBalancer lb = loadBalancerBiz.getInnerLoadBalancerByDeployId(deployment.getId());
if (lb != null) {
kubeUtils.deleteService(GlobalConstant.RC_NAME_PREFIX + deployment.getName());
}
} catch (Exception e) {
throw new DeploymentEventException(e.getMessage());
}
deployResourceHandler.delete();
podList = getPodListByDeployment(kubeUtils, deployment);
deploymentStatusManager.succeedEvent(abortDeployEventId, queryCurrentSnapshotWithPodRunning(podList));
} catch (Exception e) {
podList = getPodListByDeployment(kubeUtils, deployment);
deploymentStatusManager.failedEvent(abortDeployEventId, queryCurrentSnapshotWithPodRunning(podList),
"abort " + abortEvent.getOperation() + " failed");
}
break;
case ABORT_UPDATE:
case ABORT_ROLLBACK:
try {
Boolean updateDone = deployResourceHandler.abortUpdateOrRollBack();
if (updateDone) {
podList = getPodListByDeployment(kubeUtils, deployment);
deploymentStatusManager.succeedEvent(abortDeployEventId, queryCurrentSnapshotWithPodRunning(podList));
}
} catch (Exception e) {
podList = getPodListByDeployment(kubeUtils, deployment);
deploymentStatusManager.failedEvent(abortDeployEventId, queryCurrentSnapshotWithPodRunning(podList),
"abort " + abortEvent.getOperation() + " failed");
}
break;
case ABORT_SCALE_UP:
case ABORT_SCALE_DOWN:
try {
deployResourceHandler.abortScales();
} catch (Exception e) {
podList = getPodListByDeployment(kubeUtils, deployment);
deploymentStatusManager.failedEvent(abortDeployEventId, queryCurrentSnapshotWithPodRunning(podList),
"abort " + abortEvent.getOperation() + " failed");
}
break;
default:
throw new DeploymentEventException("There is no deploy event operation named " + abortEvent.getOperation());
}
}
}
@Override
public void stopDeploy(Deployment deployment, User user)
throws DeploymentEventException, IOException {
KubeUtils kubeUtils;
DeployResourceHandler deployResourceHandler;
try {
kubeUtils = Fabric8KubeUtils.buildKubeUtils(cluster, deployment.getNamespace());
deployResourceHandler = getDeployResourceHandler(deployment, kubeUtils);
} catch (K8sDriverException e) {
throw new DeploymentEventException(e);
}
PodList podList = getPodListByDeployment(kubeUtils, deployment);
List<DeploymentSnapshot> currentSnapshot = queryCurrentSnapshotWithPodRunning(podList);
long eventId = deploymentStatusManager.registerEvent(deployment.getId(),
DeployOperation.STOP,
user,
currentSnapshot,
currentSnapshot,
null);
deploymentStatusManager.freshEvent(eventId, currentSnapshot);
//loadBalancer
try {
if (deployment.getNetworkMode() != NetworkMode.HOST && deployment.getUsedLoadBalancer() == 0) {
List<LoadBalancer> lbs = loadBalancerBiz.getInnerAndExternalLoadBalancerByDeployId(deployment.getId());
if (lbs != null) {
for (LoadBalancer lb : lbs) {
if (lb.getName().equals(deployment.getName())) {
kubeUtils.deleteService(GlobalConstant.RC_NAME_PREFIX + deployment.getName());
break;
}
}
}
}
deployResourceHandler.delete();
} catch (Exception e) {
throw new DeploymentEventException(e.getMessage());
}
}
@Override
public void rollbackDeploy(Deployment deployment, int versionId, List<EnvDraft> allExtraEnvs, User user, Policy policy)
throws IOException, DeploymentEventException, DeploymentTerminatedException {
KubeUtils kubeUtils;
DeployResourceHandler deployResourceHandler;
try {
kubeUtils = Fabric8KubeUtils.buildKubeUtils(cluster, deployment.getNamespace());
deployResourceHandler = getDeployResourceHandler(deployment, kubeUtils);
} catch (K8sDriverException e) {
throw new DeploymentEventException(e);
}
Version version = versionBiz.getVersion(deployment.getId(), versionId);
// check status
PodList podList = getPodListByDeployment(kubeUtils, deployment);
List<DeploymentSnapshot> currentRunningSnapshot = queryCurrentSnapshotWithPodRunning(podList);
int totalReplicas = getTotalReplicas(currentRunningSnapshot);
if (deployment.getDefaultReplicas() != -1) {
totalReplicas = deployment.getDefaultReplicas();
}
long eventId = deploymentStatusManager.registerEvent(deployment.getId(),
DeployOperation.ROLLBACK,
user,
currentRunningSnapshot,
currentRunningSnapshot,
buildSingleDeploymentSnapshot(versionId, totalReplicas));
deploymentStatusManager.freshEvent(eventId, currentRunningSnapshot);
// create secret before the create of rc
// judge the registry is belong to domeos or not
checkSecret(kubeUtils, version, deployment);
DeployEvent event = deployEventBiz.getEvent(eventId);
List<LoadBalancer> lbs = null;
try {
//loadBalancer
if (deployment.getNetworkMode() != NetworkMode.HOST && deployment.getUsedLoadBalancer() == 0) {
lbs = loadBalancerBiz.getInnerAndExternalLoadBalancerByDeployId(deployment.getId());
checkLoadBalancer(kubeUtils, lbs);
}
deployResourceHandler.rollback(version, lbs, allExtraEnvs, policy, eventId, versionId);
} catch (K8sDriverException | DriverException e) {
deploymentStatusBiz.setDeploymentStatus(deployment.getId(), DeploymentStatus.ERROR);
event.setLastModify(System.currentTimeMillis());
event.setEventStatus(DeployEventStatus.FAILED);
event.setCurrentSnapshot(new ArrayList<DeploymentSnapshot>());
event.setMessage(e.getMessage());
deployEventBiz.updateEvent(event);
}
}
@Override
public void startUpdate(Deployment deployment, int versionId, List<EnvDraft> allExtraEnvs, User user, Policy policy)
throws IOException, DeploymentEventException, DeploymentTerminatedException {
// ** create KubernetesClient
KubeUtils kubeUtils;
DeployResourceHandler deployResourceHandler;
try {
kubeUtils = Fabric8KubeUtils.buildKubeUtils(cluster, deployment.getNamespace());
deployResourceHandler = getDeployResourceHandler(deployment, kubeUtils);
} catch (K8sDriverException e) {
throw new DeploymentEventException(e);
}
Version dstVersion = versionBiz.getVersion(deployment.getId(), versionId);
// ** check status
PodList podList = getPodListByDeployment(kubeUtils, deployment);
List<DeploymentSnapshot> currentRunningSnapshot = queryCurrentSnapshotWithPodRunning(podList);
int totalReplicas = getTotalReplicas(currentRunningSnapshot);
if (deployment.getDefaultReplicas() != -1) {
totalReplicas = deployment.getDefaultReplicas();
}
// if (deployment.isStateful()) {
// totalReplicas = dstVersion.getHostList().size();
long eventId = deploymentStatusManager.registerEvent(deployment.getId(),
DeployOperation.UPDATE,
user,
currentRunningSnapshot,
currentRunningSnapshot,
buildSingleDeploymentSnapshot(versionId, totalReplicas));
deploymentStatusManager.freshEvent(eventId, currentRunningSnapshot);
checkSecret(kubeUtils, dstVersion, deployment);
Version version = versionBiz.getVersion(deployment.getId(), versionId);
DeployEvent event = deployEventBiz.getEvent(eventId);
List<LoadBalancer> lbs = null;
try {
//loadBalancer
if (deployment.getNetworkMode() != NetworkMode.HOST && deployment.getUsedLoadBalancer() == 0) {
lbs = loadBalancerBiz.getInnerAndExternalLoadBalancerByDeployId(deployment.getId());
checkLoadBalancer(kubeUtils, lbs);
}
deployResourceHandler.update(version, lbs, allExtraEnvs, policy, event.getEid(), versionId);
} catch (K8sDriverException | DriverException e) {
failedDeployment(deployment.getId(), event, e);
}
}
@Override
public void scaleUpDeployment(Deployment deployment, int versionId, int replicas, List<EnvDraft> allExtraEnvs, User user)
throws DeploymentEventException, IOException, DeploymentTerminatedException {
KubeUtils client;
DeployResourceHandler deployResourceHandler;
try {
client = Fabric8KubeUtils.buildKubeUtils(cluster, deployment.getNamespace());
deployResourceHandler = getDeployResourceHandler(deployment, client);
} catch (K8sDriverException e) {
throw new DeploymentEventException(e);
}
List<DeploymentSnapshot> currentRunningSnapshot = null;
try {
// ** find rc
PodList podList = getPodListByDeployment(client, deployment);
currentRunningSnapshot = queryCurrentSnapshotWithPodRunning(podList);
List<DeploymentSnapshot> dstSnapshot = buildDeploymentSnapshotWith(currentRunningSnapshot, versionId, replicas);
long eventId = deploymentStatusManager.registerEvent(deployment.getId(),
DeployOperation.SCALE_UP,
user,
currentRunningSnapshot,
currentRunningSnapshot,
dstSnapshot);
deploymentStatusManager.freshEvent(eventId, currentRunningSnapshot);
Version version = versionBiz.getVersion(deployment.getId(), versionId);
checkSecret(client, version, deployment);
//loadBalancer
if (deployment.getNetworkMode() != NetworkMode.HOST && deployment.getUsedLoadBalancer() == 0) {
List<LoadBalancer> lbs = loadBalancerBiz.getInnerAndExternalLoadBalancerByDeployId(deployment.getId());
checkLoadBalancer(client, lbs);
}
if (deployment.getUsedLoadBalancer() == 0) {
deployResourceHandler.scaleUp(version, replicas);
deployResourceHandler.removeOtherDeploy(versionId);
}
} catch (IOException | K8sDriverException | DriverException e) {
deploymentStatusManager.failedEventForDeployment(deployment.getId(), currentRunningSnapshot, e.getMessage());
throw new DeploymentEventException("kubernetes exception with message=" + e.getMessage());
}
}
@Override
public void scaleDownDeployment(Deployment deployment, int versionId, int replicas, List<EnvDraft> allExtraEnvs, User user)
throws DeploymentEventException, IOException, DeploymentTerminatedException {
KubeUtils client;
DeployResourceHandler deployResourceHandler;
try {
client = Fabric8KubeUtils.buildKubeUtils(cluster, deployment.getNamespace());
deployResourceHandler = getDeployResourceHandler(deployment, client);
} catch (K8sDriverException e) {
throw new DeploymentEventException(e);
}
List<DeploymentSnapshot> currentRunningSnapshot = null;
try {
PodList podList = getPodListByDeployment(client, deployment);
currentRunningSnapshot = queryCurrentSnapshotWithPodRunning(podList);
List<DeploymentSnapshot> dstSnapshot = buildDeploymentSnapshotWith(currentRunningSnapshot, versionId, replicas);
long eventId = deploymentStatusManager.registerEvent(deployment.getId(),
DeployOperation.SCALE_DOWN,
user,
currentRunningSnapshot,
currentRunningSnapshot,
dstSnapshot);
deploymentStatusManager.freshEvent(eventId, currentRunningSnapshot);
Version version = versionBiz.getVersion(deployment.getId(), versionId);
checkSecret(client, version, deployment);
//loadBalancer
if (deployment.getNetworkMode() != NetworkMode.HOST && deployment.getUsedLoadBalancer() == 0) {
List<LoadBalancer> lbs = loadBalancerBiz.getInnerAndExternalLoadBalancerByDeployId(deployment.getId());
checkLoadBalancer(client, lbs);
}
if (deployment.getUsedLoadBalancer() == 0) {
deployResourceHandler.scaleDown(version, replicas);
deployResourceHandler.removeOtherDeploy(versionId);
}
} catch (IOException | K8sDriverException | DriverException e) {
deploymentStatusManager.failedEventForDeployment(deployment.getId(), currentRunningSnapshot, e.getMessage());
throw new DeploymentEventException("kubernetes exception with message=" + e.getMessage());
}
}
private DeployResourceHandler getDeployResourceHandler(Deployment deployment, KubeUtils kubeUtils) throws K8sDriverException {
String deployClass = deployment.getDeploymentType().getDeployClassName();
if (deployClass == null) {
throw new K8sDriverException("A deployment must have deployment type");
}
Server server = globalBiz.getServer();
if (server == null) {
throw new K8sDriverException("Global configuration of Server not set!");
}
DeployResourceHandler deployResourceHandler = ReflectFactory.createDeployResourceHandler(deployClass, kubeUtils, deployment, server.getUrl());
if (deployResourceHandler == null) {
throw new K8sDriverException("Cannot create deploy handler with deployment :" + deployment);
}
return deployResourceHandler;
}
private Map<String, String> buildDeploySelector(Deployment deployment) {
Map<String, String> selector = new HashMap<>();
selector.put(GlobalConstant.DEPLOY_ID_STR, String.valueOf(deployment.getId()));
return selector;
}
private PodList getPodListByDeployment(KubeUtils kubeUtils, Deployment deployment)
throws DeploymentEventException {
try {
return kubeUtils.listPod(buildDeploySelector(deployment));
} catch (K8sDriverException e) {
throw new DeploymentEventException("kubernetes exception with message=" + e.getMessage());
}
}
private List<DeploymentSnapshot> queryCurrentSnapshot(PodList podList) {
if (podList == null || podList.getItems() == null || podList.getItems().size() == 0) {
return null;
}
Map<Long, Long> snapshots = new HashMap<>();
for (Pod pod : podList.getItems()) {
if (pod == null || pod.getMetadata() == null || pod.getMetadata().getLabels() == null) {
continue;
}
String longData = pod.getMetadata().getLabels().get(GlobalConstant.VERSION_STR);
if (StringUtils.isBlank(longData)) {
continue;
}
Long version = Long.parseLong(longData);
if (!snapshots.containsKey(version)) {
snapshots.put(version, 1L);
} else {
snapshots.put(version, snapshots.get(version) + 1);
}
}
List<DeploymentSnapshot> snapshotList = new LinkedList<>();
for (Map.Entry<Long, Long> entry : snapshots.entrySet()) {
snapshotList.add(new DeploymentSnapshot(entry.getKey(), entry.getValue()));
}
return snapshotList;
}
private List<DeploymentSnapshot> queryCurrentSnapshotWithPodRunning(PodList podList) {
if (podList == null || podList.getItems() == null || podList.getItems().size() == 0) {
return null;
}
Map<Long, Long> snapshots = new HashMap<>();
for (Pod pod : podList.getItems()) {
if (pod == null || pod.getMetadata() == null || pod.getMetadata().getLabels() == null) {
continue;
}
String longData = pod.getMetadata().getLabels().get(GlobalConstant.VERSION_STR);
if (StringUtils.isBlank(longData)) {
continue;
}
if (!PodUtils.isPodReady(pod)) {
continue;
}
Long version = Long.parseLong(longData);
if (!snapshots.containsKey(version)) {
snapshots.put(version, 1L);
} else {
snapshots.put(version, snapshots.get(version) + 1);
}
}
List<DeploymentSnapshot> snapshotList = new LinkedList<>();
for (Map.Entry<Long, Long> entry : snapshots.entrySet()) {
snapshotList.add(new DeploymentSnapshot(entry.getKey(), entry.getValue()));
}
return snapshotList;
}
private int getTotalReplicas(List<DeploymentSnapshot> snapshots) {
int replicas = 0;
if (snapshots == null || snapshots.size() == 0) {
return replicas;
}
for (DeploymentSnapshot snapshot : snapshots) {
replicas += snapshot.getReplicas();
}
return replicas;
}
private boolean checkAnyInstanceFailed(int deploymentId, long versionId)
throws ParseException, K8sDriverException {
Deployment deployment = deploymentBiz.getDeployment(deploymentId);
KubeUtils client = Fabric8KubeUtils.buildKubeUtils(cluster, deployment.getNamespace());
Map<String, String> rcSelector = buildDeploySelectorWithSpecifyVersion(deployment, versionId);
PodList podList = client.listPod(rcSelector);
return PodUtils.isAnyFailed(podList);
}
@Override
public void checkBasicEvent(Deployment deployment, DeployEvent event)
throws DeploymentEventException, IOException, DataBaseContentException, ParseException, DeploymentTerminatedException {
KubeUtils client;
try {
client = Fabric8KubeUtils.buildKubeUtils(cluster, deployment.getNamespace());
} catch (K8sDriverException e) {
throw new DeploymentEventException(e);
}
try {
PodList podList = getPodListByDeployment(client, deployment);
List<DeploymentSnapshot> currentSnapshot = queryCurrentSnapshot(podList);
List<DeploymentSnapshot> currentRunningSnapshot = queryCurrentSnapshotWithPodRunning(podList);
List<DeploymentSnapshot> desiredSnapshot = event.getTargetSnapshot();
if (currentSnapshot == null && PodUtils.isExpireForEventNotReallyHappen(event.getStartTime())) {
deleteUpdaterJob(client, deployment.getId());
deploymentStatusManager.failedEvent(event.getEid(), null, "no replication controller found for event(eid="
+ event.getEid() + ")");
return;
}
if (desiredSnapshot == null) {
deleteUpdaterJob(client, deployment.getId());
deploymentStatusManager.failedEvent(event.getEid(), currentRunningSnapshot, "null desired snapshot");
return;
}
for (DeploymentSnapshot deploymentSnapshot : desiredSnapshot) {
if (checkAnyInstanceFailed(event.getDeployId(), deploymentSnapshot.getVersion())) {
deleteUpdaterJob(client, deployment.getId());
deploymentStatusManager.failedEvent(event.getEid(), currentRunningSnapshot, "one of pod is start failed");
return;
}
}
if (isSnapshotEquals(currentSnapshot, event.getTargetSnapshot()) && isSnapshotEquals(currentRunningSnapshot, event.getTargetSnapshot())) {
deleteUpdaterJob(client, deployment.getId());
deploymentStatusManager.succeedEvent(event.getEid(), currentSnapshot);
} else {
deploymentStatusManager.freshEvent(event.getEid(), currentRunningSnapshot);
}
} catch (K8sDriverException e) {
throw new DeploymentEventException("kubernetes exception with message=" + e.getMessage());
}
}
@Override
public void checkAbortEvent(Deployment deployment, DeployEvent event)
throws DeploymentEventException, IOException, DeploymentTerminatedException {
KubeUtils client;
DeployResourceHandler deployResourceHandler;
try {
client = Fabric8KubeUtils.buildKubeUtils(cluster, deployment.getNamespace());
deployResourceHandler = getDeployResourceHandler(deployment, client);
} catch (K8sDriverException e) {
throw new DeploymentEventException(e);
}
PodList podList = getPodListByDeployment(client, deployment);
List<DeploymentSnapshot> currentSnapshot = queryCurrentSnapshot(podList);
List<DeploymentSnapshot> currentRunningSnapshot = queryCurrentSnapshotWithPodRunning(podList);
switch (event.getOperation()) {
case ABORT_START:
if (currentSnapshot == null || currentSnapshot.isEmpty()) {
deploymentStatusManager.succeedEvent(event.getEid(), currentSnapshot);
} else {
try {
deployResourceHandler.delete();
} catch (K8sDriverException e) {
throw new DeploymentEventException("kubernetes exception with message=" + e.getMessage());
}
deploymentStatusManager.freshEvent(event.getEid(), currentRunningSnapshot);
}
break;
case ABORT_UPDATE:
case ABORT_ROLLBACK:
try {
deployResourceHandler.abortUpdateOrRollBack();
deploymentStatusManager.succeedEvent(event.getEid(), currentRunningSnapshot);
} catch (K8sDriverException e) {
deploymentStatusManager.failedEvent(event.getEid(), currentRunningSnapshot, "Abort failed of rolling operation.");
}
break;
case ABORT_SCALE_UP:
case ABORT_SCALE_DOWN:
try {
deployResourceHandler.abortScales();
deploymentStatusManager.succeedEvent(event.getEid(), currentRunningSnapshot);
} catch (Exception e) {
deploymentStatusManager.failedEvent(event.getEid(), currentRunningSnapshot,
"Adjust deployment replicas failed when abort scale operation.");
}
break;
default:
throw new DeploymentEventException("Deploy event operation '" + event.getOperation() + "' can not be check as abort event");
}
}
@Override
public void checkStopEvent(Deployment deployment, DeployEvent event)
throws DeploymentEventException, IOException, DeploymentTerminatedException {
KubeUtils client;
DeployResourceHandler deployResourceHandler;
try {
client = Fabric8KubeUtils.buildKubeUtils(cluster, deployment.getNamespace());
deployResourceHandler = getDeployResourceHandler(deployment, client);
} catch (K8sDriverException e) {
throw new DeploymentEventException(e);
}
PodList podList = getPodListByDeployment(client, deployment);
List<DeploymentSnapshot> currentSnapshot = queryCurrentSnapshot(podList);
if (currentSnapshot == null || currentSnapshot.isEmpty()) {
deploymentStatusManager.succeedEvent(event.getEid(), currentSnapshot);
} else {
try {
deployResourceHandler.delete();
} catch (K8sDriverException e) {
throw new DeploymentEventException("kubernetes exception with message=" + e.getMessage());
}
deploymentStatusManager.freshEvent(event.getEid(), currentSnapshot);
}
}
@Override
public void expiredEvent(Deployment deployment, DeployEvent event) throws DeploymentEventException, IOException, DeploymentTerminatedException {
KubeUtils client;
try {
client = Fabric8KubeUtils.buildKubeUtils(cluster, deployment.getNamespace());
} catch (K8sDriverException e) {
throw new DeploymentEventException(e);
}
PodList podList = getPodListByDeployment(client, deployment);
deploymentStatusManager.failedEvent(event.getEid(), queryCurrentSnapshotWithPodRunning(podList), "Operation expired. " + event.getMessage());
}
@Override
public List<Version> getCurrnetVersionsByDeployment(Deployment deployment) throws DeploymentEventException {
if (deployment == null) {
return null;
}
KubeUtils client = null;
DeployResourceHandler deployResourceHandler;
try {
client = Fabric8KubeUtils.buildKubeUtils(cluster, deployment.getNamespace());
deployResourceHandler = getDeployResourceHandler(deployment, client);
} catch (K8sDriverException e) {
throw new DeploymentEventException(e);
}
// get current versions
PodList podList = getPodListByDeployment(client, deployment);
List<DeploymentSnapshot> deploymentSnapshots = queryCurrentSnapshot(podList);
if (deploymentSnapshots != null && deploymentSnapshots.isEmpty()) {
try {
deploymentSnapshots = deployResourceHandler.queryDesiredSnapshot();
} catch (K8sDriverException e) {
throw new DeploymentEventException(e);
}
}
List<Version> versions = null;
if (deploymentSnapshots != null) {
versions = new ArrayList<>(deploymentSnapshots.size());
for (DeploymentSnapshot deploymentSnapshot : deploymentSnapshots) {
Version version = versionBiz.getVersion(deployment.getId(), (int) deploymentSnapshot.getVersion());
versions.add(version);
}
}
return versions;
}
@Override
public long getTotalReplicasByDeployment(Deployment deployment) throws DeploymentEventException {
if (deployment == null) {
return 0;
}
KubeUtils client = null;
try {
client = Fabric8KubeUtils.buildKubeUtils(cluster, deployment.getNamespace());
} catch (K8sDriverException e) {
throw new DeploymentEventException(e);
}
// get current versions
PodList podList = getPodListByDeployment(client, deployment);
List<DeploymentSnapshot> deploymentSnapshots = queryCurrentSnapshot(podList);
return getTotalReplicas(deploymentSnapshots);
}
private Map<String, String> buildDeploySelectorWithSpecifyVersion(Deployment deployment, long versionV) {
Map<String, String> selector = buildDeploySelector(deployment);
selector.put(GlobalConstant.VERSION_STR, String.valueOf(versionV));
return selector;
}
private void failedDeployment(int deployId, DeployEvent event, Exception e) {
deploymentStatusBiz.setDeploymentStatus(deployId, DeploymentStatus.ERROR);
event.setLastModify(System.currentTimeMillis());
event.setEventStatus(DeployEventStatus.FAILED);
event.setCurrentSnapshot(new ArrayList<DeploymentSnapshot>());
event.setMessage(e.getMessage());
deployEventBiz.updateEvent(event);
}
// this function will add or replace version in oldSnapshot
private List<DeploymentSnapshot> buildDeploymentSnapshotWith(
List<DeploymentSnapshot> oldSnapshot, long version, long replicas) {
List<DeploymentSnapshot> result = new LinkedList<>();
if (oldSnapshot == null) {
return null;
}
boolean isFind = false;
for (DeploymentSnapshot oneSnapshot : oldSnapshot) {
if (oneSnapshot.getVersion() == version) {
result.add(new DeploymentSnapshot(version, replicas));
isFind = true;
} else {
result.add(new DeploymentSnapshot(oneSnapshot));
}
}
if (!isFind) {
result.add(new DeploymentSnapshot(version, replicas));
}
return result;
}
private boolean isSnapshotEquals(List<DeploymentSnapshot> one, List<DeploymentSnapshot> another) {
if (one == null || another == null) {
return false;
}
Map<Long, Long> versionCount = new HashMap<>();
for (DeploymentSnapshot deploymentSnapshot : one) {
if (deploymentSnapshot.getReplicas() > 0) {
// ignore zero replicas
versionCount.put(deploymentSnapshot.getVersion(), deploymentSnapshot.getReplicas());
}
}
for (DeploymentSnapshot deploymentSnapshot : another) {
if (deploymentSnapshot.getReplicas() <= 0) {
// ignore zero replicas
continue;
}
if (!versionCount.containsKey(deploymentSnapshot.getVersion())) {
return false;
}
if (versionCount.get(deploymentSnapshot.getVersion()) != deploymentSnapshot.getReplicas()) {
return false;
}
versionCount.remove(deploymentSnapshot.getVersion());
}
return versionCount.isEmpty();
}
private void checkSecret(KubeUtils client, Version version, Deployment deployment) throws DeploymentEventException {
if (version != null && SecretUtils.haveDomeOSRegistry(version.getContainerDrafts())) {
try {
if (client.secretInfo(GlobalConstant.SECRET_NAME_PREFIX + deployment.getNamespace()) == null) {
Map<String, String> dataMap = new HashMap<>();
dataMap.put(GlobalConstant.SECRET_DOCKERCFG_DATA_KEY, SecretUtils.getDomeOSImageSecretData());
client.createSecret(GlobalConstant.SECRET_NAME_PREFIX + deployment.getNamespace(),
GlobalConstant.SECRET_DOCKERCFG_TYPE, dataMap);
}
} catch (K8sDriverException | JSONException e) {
throw new DeploymentEventException("kubernetes exception with message=" + e.getMessage());
}
}
}
private Map<String, String> buildJobSelector(int deployId) {
Map<String, String> selector = new HashMap<>();
selector.put(GlobalConstant.JOB_DEPLOY_ID_STR, String.valueOf(deployId));
return selector;
}
private void deleteUpdaterJob(KubeUtils client, int deployId) {
try {
client.deleteJob(buildJobSelector(deployId));
} catch (Exception ignored) {
}
}
private void checkLoadBalancer(KubeUtils client, List<LoadBalancer> lbs) throws K8sDriverException, DriverException {
if (lbs != null && lbs.size() > 0) {
for (LoadBalancer lb : lbs) {
Service service = new K8sServiceBuilder(lb).build();
Service oldService = client.serviceInfo(service.getMetadata().getName());
if (oldService == null) {
client.createService(service);
logger.info("Service:" + service.getMetadata().getName() + " created successfully");
} else {
logger.info("Service:" + service.getMetadata().getName() + " exists, do not need to create");
}
}
}
}
@Override
public void deletePodByDeployIdAndInsName(Deployment deployment, String insName)
throws DeploymentEventException, IOException {
KubeUtils kubeUtils;
DeployResourceHandler deployResourceHandler;
try {
kubeUtils = Fabric8KubeUtils.buildKubeUtils(cluster, deployment.getNamespace());
kubeUtils.deletePod(insName);
} catch (K8sDriverException e) {
throw new DeploymentEventException(e);
}
}
} |
package org.fedoraproject.jenkins.copr;
import hudson.EnvVars;
import hudson.Extension;
import hudson.Launcher;
import hudson.model.BuildListener;
import hudson.model.Result;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.BuildStepMonitor;
import hudson.tasks.CommandInterpreter;
import hudson.tasks.Notifier;
import hudson.tasks.Publisher;
import hudson.tasks.BatchFile;
import hudson.tasks.Shell;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import org.fedoraproject.copr.Copr;
import org.fedoraproject.copr.CoprRepo;
import org.fedoraproject.copr.CoprUser;
import org.fedoraproject.copr.exception.CoprException;
import org.kohsuke.stapler.DataBoundConstructor;
public class CoprPlugin extends Notifier {
protected static final Logger LOGGER = Logger.getLogger(CoprPlugin.class
.getName());
private final String coprname;
private final String username;
private final String srpm;
private final String apilogin;
private final String apitoken;
private final String apiurl;
private final String srpmscript;
private final boolean prepareSrpm;
@DataBoundConstructor
public CoprPlugin(String coprname, String username, String srpm,
String apilogin, String apitoken, String apiurl, String srpmscript,
boolean prepareSrpm) {
this.coprname = coprname;
this.username = username;
this.srpm = srpm;
this.apilogin = apilogin;
this.apitoken = apitoken;
this.apiurl = apiurl;
this.srpmscript = srpmscript;
this.prepareSrpm = prepareSrpm;
}
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher,
BuildListener listener) throws InterruptedException, IOException {
// TODO:
// create repository in Copr if it doesn't exist yet
// add button to check if provided information are correct (API URL,
// credentials?)
listener.getLogger().println("Running Copr plugin");
if (build.getResult() != Result.SUCCESS) {
listener.getLogger().println(
"Build was unsuccessful. Nothing to build in Copr.");
return true;
}
if (prepareSrpm) {
Result srpmres = prepareSrpm(build, launcher, listener);
listener.getLogger().println("Copr plugin: " + srpmres.toString());
if (srpmres != Result.SUCCESS) {
return false;
}
}
EnvVars env = build.getEnvironment(listener);
String srpmstr = env.expand(srpm);
URL srpmurl = getSrpmUrl(srpmstr, build, listener);
Copr copr = new Copr(apiurl);
try {
CoprUser user = copr.getUser(username, apilogin, apitoken);
CoprRepo repo = user.getRepo(coprname);
List<String> srpms = new ArrayList<String>();
srpms.add(srpmurl.toString());
repo.addNewBuild(srpms);
listener.getLogger().println("New Copr job has been scheduled");
} catch (CoprException e) {
listener.getLogger().println(e);
return false;
}
return true;
}
private Result prepareSrpm(AbstractBuild<?, ?> build, Launcher launcher,
BuildListener listener) throws InterruptedException {
CommandInterpreter shell;
if (launcher.isUnix()) {
shell = new Shell(srpmscript);
} else {
shell = new BatchFile(srpmscript);
}
return shell.perform(build, launcher, listener) ? Result.SUCCESS
: Result.FAILURE;
}
private URL getSrpmUrl(String srpmurl, AbstractBuild<?, ?> build,
BuildListener listener) throws IOException, InterruptedException {
URL url;
try {
url = new URL(srpmurl);
} catch (MalformedURLException e) {
// TODO: what's wrong with JOB_URL?
String jenkinsUrl = build.getEnvironment(listener).get(
"JENKINS_URL");
String jobName = build.getEnvironment(listener).get("JOB_NAME");
if (jenkinsUrl == null || jobName == null) {
// something's really wrong
throw new AssertionError(
String.format(
"JENKINS_URL or JOB_NAME env. variable is not set (%s, %s)",
String.valueOf(jenkinsUrl),
String.valueOf(jobName)));
}
url = new URL(jenkinsUrl + "/job/" + jobName + "/ws/");
url = new URL(url, srpmurl);
}
return url;
}
public BuildStepMonitor getRequiredMonitorService() {
return BuildStepMonitor.NONE;
}
public String getCoprname() {
return coprname;
}
public String getUsername() {
return username;
}
public String getSrpm() {
return srpm;
}
public String getApilogin() {
return apilogin;
}
public String getApitoken() {
return apitoken;
}
public String getApiurl() {
return apiurl;
}
public String getSrpmscript() {
return srpmscript;
}
public boolean getPrepareSrpm() {
return prepareSrpm;
}
@Extension
public static final class DescriptorImpl extends
BuildStepDescriptor<Publisher> {
public DescriptorImpl() {
load();
}
@Override
public boolean isApplicable(Class<? extends AbstractProject> jobType) {
return true;
}
@Override
public String getDisplayName() {
return "Build RPM in Copr";
}
}
} |
package com.devbox.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MotionEvent;
import android.view.View;
import com.devbox.DBApplication;
import com.devbox.R;
import com.devbox.utils.LogUtil;
public class BaseActivity extends AppCompatActivity {
protected Context context;
protected DBApplication application;
protected Toolbar toolbar;
private android.support.v7.app.ActionBar mActionBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LogUtil.log(this, "
this.initVariables();
this.initViews(savedInstanceState);
this.loadData();
this.registerBordcast();
}
protected void initVariables() {
this.context = getApplicationContext();
this.application = (DBApplication) this.getApplication();
}
//The method setContentView: should be called in this method.
protected void initViews(Bundle savedInstanceState) {
}
protected void loadData() {
}
protected void registerBordcast() {
}
@Override
public void setContentView(int layoutResID) {
super.setContentView(layoutResID);
initToolbar();
}
private void initToolbar() {
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
this.mActionBar = getSupportActionBar();
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
// Bugtags.onDispatchTouchEvent(this, event);
return super.dispatchTouchEvent(event);
}
protected void setToolbarDisplayHomeAsUpEnabledAndClickListenner(boolean enabled, View.OnClickListener listener) {
this.mActionBar.setDisplayHomeAsUpEnabled(enabled);
toolbar.setNavigationOnClickListener(listener);
}
protected void setToolbarTitle(CharSequence text) {
this.mActionBar.setTitle(text);
}
@Override
protected void onResume() {
LogUtil.log(this, "
super.onResume();
// Bugtags.onResume(this);
}
@Override
protected void onPause() {
LogUtil.log(this, "
super.onPause();
// Bugtags.onPause(this);
}
@Override
protected void onStop() {
LogUtil.log(this, "
super.onStop();
}
@Override
protected void onDestroy() {
LogUtil.log(this, "
super.onDestroy();
}
public void showSnackbar(String msg) {
View rootView = findViewById(android.R.id.content);
if (rootView != null)
Snackbar.make(rootView, msg, Snackbar.LENGTH_LONG).show();
}
protected void showActivity(Intent intent) {
this.startActivity(intent);
}
protected void showActivity(Class<?> cls) {
Intent intent = new Intent();
intent.setClass(this, cls);
this.startActivity(intent);
}
} |
package net.ME1312.SubServers.Bungee;
import net.ME1312.SubServers.Bungee.Host.Host;
import net.ME1312.SubServers.Bungee.Host.Server;
import net.ME1312.SubServers.Bungee.Host.SubCreator;
import net.ME1312.SubServers.Bungee.Host.SubServer;
import net.ME1312.SubServers.Bungee.Library.Util;
import net.ME1312.SubServers.Bungee.Library.Version.Version;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.plugin.Command;
import net.md_5.bungee.api.plugin.TabExecutor;
import net.md_5.bungee.command.ConsoleCommandSender;
import java.util.*;
/**
* Plugin Command Class
*/
@SuppressWarnings("deprecation")
public final class SubCommand extends Command implements TabExecutor {
private SubPlugin plugin;
private String label;
protected SubCommand(SubPlugin plugin, String command) {
super(command);
this.plugin = plugin;
this.label = "/" + command;
}
/**
* Load /sub in console
*
* @param sender Sender
* @param args Arguments
*/
@Override
public void execute(CommandSender sender, String[] args) {
if (sender instanceof ConsoleCommandSender) {
if (args.length > 0) {
if (args[0].equalsIgnoreCase("help") || args[0].equalsIgnoreCase("?")) {
sender.sendMessages(printHelp());
} else if (args[0].equalsIgnoreCase("version") || args[0].equalsIgnoreCase("ver")) {
sender.sendMessage("SubServers > SubServers.Bungee is running version " + plugin.version.toString() + ((plugin.bversion != null)?" BETA "+plugin.bversion.toString():""));
} else if (args[0].equalsIgnoreCase("list")) {
List<String> hosts = new ArrayList<String>();
for (Host host : plugin.hosts.values()) {
hosts.add(host.getDisplayName() + ((host.getName().equals(host.getDisplayName()))?"":" (" + host.getName() + ')'));
}
List<String> servers = new ArrayList<String>();
for (Server server : plugin.api.getServers().values()) {
servers.add(server.getDisplayName() + ((server.getName().equals(server.getDisplayName()))?"":" (" + server.getName() + ')'));
}
sender.sendMessages(
"SubServers > Host List:", hosts.toString().substring(1, hosts.toString().length() - 1),
"SubServers > Server List:", servers.toString().substring(1, servers.toString().length() - 1));
} else if (args[0].equalsIgnoreCase("start")) {
if (args.length > 1) {
Map<String, Server> servers = plugin.api.getServers();
if (!servers.keySet().contains(args[1].toLowerCase())) {
sender.sendMessage("SubServers > There is no server with that name");
} else if (!(servers.get(args[1].toLowerCase()) instanceof SubServer)) {
sender.sendMessage("SubServers > That Server is not a SubServer");
} else if (!((SubServer) servers.get(args[1].toLowerCase())).getHost().isEnabled()) {
sender.sendMessage("SubServers > That SubServer's Host is not enabled");
} else if (!((SubServer) servers.get(args[1].toLowerCase())).isEnabled()) {
sender.sendMessage("SubServers > That SubServer is not enabled");
} else if (((SubServer) servers.get(args[1].toLowerCase())).isRunning()) {
sender.sendMessage("SubServers > That SubServer is already running");
} else {
((SubServer) servers.get(args[1].toLowerCase())).start();
}
} else {
sender.sendMessage("SubServers > Usage: " + label + " " + args[0].toLowerCase() + " <SubServer>");
}
} else if (args[0].equalsIgnoreCase("stop")) {
if (args.length > 1) {
Map<String, Server> servers = plugin.api.getServers();
if (!servers.keySet().contains(args[1].toLowerCase())) {
sender.sendMessage("SubServers > There is no server with that name");
} else if (!(servers.get(args[1].toLowerCase()) instanceof SubServer)) {
sender.sendMessage("SubServers > That Server is not a SubServer");
} else if (!((SubServer) servers.get(args[1].toLowerCase())).isRunning()) {
sender.sendMessage("SubServers > That SubServer is not running");
} else {
((SubServer) servers.get(args[1].toLowerCase())).stop();
}
} else {
sender.sendMessage("SubServers > Usage: " + label + " " + args[0].toLowerCase() + " <SubServer>");
}
} else if (args[0].equalsIgnoreCase("kill") || args[0].equalsIgnoreCase("terminate")) {
if (args.length > 1) {
Map<String, Server> servers = plugin.api.getServers();
if (!servers.keySet().contains(args[1].toLowerCase())) {
sender.sendMessage("SubServers > There is no server with that name");
} else if (!(servers.get(args[1].toLowerCase()) instanceof SubServer)) {
sender.sendMessage("SubServers > That Server is not a SubServer");
} else if (!((SubServer) servers.get(args[1].toLowerCase())).isRunning()) {
sender.sendMessage("SubServers > That SubServer is not running");
} else {
((SubServer) servers.get(args[1].toLowerCase())).terminate();
}
} else {
sender.sendMessage("SubServers > Usage: " + label + " " + args[0].toLowerCase() + " <SubServer>");
}
} else if (args[0].equalsIgnoreCase("cmd") || args[0].equalsIgnoreCase("command")) {
if (args.length > 2) {
Map<String, Server> servers = plugin.api.getServers();
if (!(servers.keySet().contains(args[1].toLowerCase()) || args[1].equals("*"))) {
sender.sendMessage("SubServers > There is no server with that name");
} else if (!(servers.get(args[1].toLowerCase()) instanceof SubServer)) {
sender.sendMessage("SubServers > That Server is not a SubServer");
} else if (!((SubServer) servers.get(args[1].toLowerCase())).isRunning()) {
sender.sendMessage("SubServers > That SubServer is not running");
} else {
int i = 2;
String str = args[2];
if (args.length > 3) {
do {
i++;
str = str + " " + args[i];
} while ((i + 1) != args.length);
}
if (args[1].equals("*")) {
for (Server server : servers.values()) {
if (((SubServer) server).isRunning()) {
((SubServer) server).command(str);
}
}
} else {
((SubServer) servers.get(args[1].toLowerCase())).command(str);
}
}
} else {
sender.sendMessage("SubServers > Usage: " + label + " " + args[0].toLowerCase() + " <SubServer> <Command> [Args...]");
}
} else if (args[0].equalsIgnoreCase("create")) {
if (args.length > 5) {
if (plugin.api.getSubServers().keySet().contains(args[1].toLowerCase())) {
sender.sendMessage("SubServers > There is already a SubServer with that name");
} else if (!plugin.hosts.keySet().contains(args[2].toLowerCase())) {
sender.sendMessage("SubServers > There is no host with that name");
} else if (plugin.hosts.get(args[2].toLowerCase()).getCreator().isBusy()) {
sender.sendMessage("SubServers > The SubCreator instance on that host is already running");
} else if (Util.isException(() -> SubCreator.ServerType.valueOf(args[3].toUpperCase()))) {
sender.sendMessage("SubServers > There is no server type with that name");
} else if (new Version("1.8").compareTo(new Version(args[4])) > 0) {
sender.sendMessage("SubServers > SubCreator cannot create servers before Minecraft 1.8");
} else if (Util.isException(() -> Integer.parseInt(args[5])) || Integer.parseInt(args[5]) <= 0 || Integer.parseInt(args[5]) > 65535) {
sender.sendMessage("SubServers > Invalid Port Number");
} else if (args.length > 6 && (Util.isException(() -> Integer.parseInt(args[6])) || Integer.parseInt(args[6]) < 256)) {
sender.sendMessage("SubServers > Invalid Ram Amount");
} else {
plugin.hosts.get(args[2].toLowerCase()).getCreator().create(args[1], SubCreator.ServerType.valueOf(args[3].toUpperCase()), new Version(args[4]), (args.length > 6) ? Integer.parseInt(args[6]) : 1024, Integer.parseInt(args[5]));
}
} else {
sender.sendMessage("SubServers > Usage: " + label + " " + args[0].toLowerCase() + " <Name> <Host> <Type> <Version> <Port> [RAM]");
}
} else if (args[0].equalsIgnoreCase("del") || args[0].equalsIgnoreCase("delete")) {
if (args.length > 1) {
Map<String, Server> servers = plugin.api.getServers();
try {
if (!servers.keySet().contains(args[1].toLowerCase())) {
sender.sendMessage("SubServers > There is no server with that name");
} else if (!(servers.get(args[1].toLowerCase()) instanceof SubServer)) {
sender.sendMessage("SubServers > That Server is not a SubServer");
} else if (((SubServer) servers.get(args[1].toLowerCase())).isRunning()) {
sender.sendMessage("SubServers > That SubServer is still running");
} else if (!((SubServer) servers.get(args[1].toLowerCase())).getHost().deleteSubServer(args[1].toLowerCase())){
System.out.println("SubServers > Couldn't remove server from memory.");
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
sender.sendMessage("SubServers > Usage: " + label + " " + args[0].toLowerCase() + " <SubServer>");
}
} else {
sender.sendMessage("SubServers > Unknown sub-command: " + args[0]);
}
} else {
sender.sendMessages(printHelp());
}
} else {
String str = label;
for (String arg : args) str += ' ' + arg;
((ProxiedPlayer) sender).chat(str);
}
}
/**
* Tab complete for players
*
* @param sender Sender
* @param args Arguments
* @return Tab completes
*/
@Override
public Iterable<String> onTabComplete(CommandSender sender, String[] args) {
String last = (args.length > 0)?args[args.length - 1].toLowerCase():"";
if (args.length <= 1) {
List<String> cmds = Arrays.asList("help", "list", "version", "start", "stop", "kill", "terminate", "cmd", "command", "create");
if (last.length() == 0) {
return cmds;
} else {
List<String> list = new ArrayList<String>();
for (String cmd : cmds) {
if (cmd.startsWith(last)) list.add(cmd);
}
return list;
}
} else {
if (args[0].equals("start") ||
args[0].equals("stop") ||
args[0].equals("kill") || args[0].equals("terminate")) {
if (args.length == 2) {
List<String> list = new ArrayList<String>();
if (last.length() == 0) {
for (SubServer server : plugin.api.getSubServers().values()) list.add(server.getName());
} else {
for (SubServer server : plugin.api.getSubServers().values()) {
if (server.getName().toLowerCase().startsWith(last)) list.add(server.getName());
}
}
return list;
}
return Collections.emptyList();
} else if (args[0].equals("cmd") || args[0].equals("command")) {
if (args.length == 2) {
List<String> list = new ArrayList<String>();
if (last.length() == 0) {
for (SubServer server : plugin.api.getSubServers().values()) list.add(server.getName());
} else {
for (SubServer server : plugin.api.getSubServers().values()) {
if (server.getName().toLowerCase().startsWith(last)) list.add(server.getName());
}
}
return list;
} else if (args.length == 3) {
if (last.length() == 0) {
return Collections.singletonList("<Command>");
}
} else {
if (last.length() == 0) {
return Collections.singletonList("[Args...]");
}
}
return Collections.emptyList();
} else if (args[0].equals("create")) {
if (args.length == 2) {
if (last.length() == 0) {
return Collections.singletonList("<Name>");
}
} else if (args.length == 3) {
List<String> list = new ArrayList<String>();
if (last.length() == 0) {
for (Host host : plugin.api.getHosts().values()) list.add(host.getName());
} else {
for (Host host : plugin.api.getHosts().values()) {
if (host.getName().toLowerCase().startsWith(last)) list.add(host.getName());
}
}
return list;
} else if (args.length == 4) {
List<String> list = new ArrayList<String>();
if (last.length() == 0) {
for (SubCreator.ServerType type : SubCreator.ServerType.values()) list.add(type.toString());
} else {
for (SubCreator.ServerType type : SubCreator.ServerType.values()) {
if (type.toString().toLowerCase().startsWith(last)) list.add(type.toString());
}
}
return list;
} else if (args.length == 5) {
if (last.length() == 0) {
return Collections.singletonList("<Version>");
}
} else if (args.length == 6) {
if (last.length() == 0) {
return Collections.singletonList("<Port>");
}
} else if (args.length == 7) {
if (last.length() == 0) {
return Collections.singletonList("[RAM]");
}
}
return Collections.emptyList();
} else {
return Collections.emptyList();
}
}
}
private String[] printHelp() {
return new String[]{
"SubServers > Console Command Help:",
" Help: /sub help",
" List: /sub list",
" Version: /sub version",
" Start Server: /sub start <SubServer>",
" Stop Server: /sub stop <SubServer>",
" Terminate Server: /sub kill <SubServer>",
" Command Server: /sub cmd <SubServer> <Command> [Args...]",
" Create Server: /sub create <Name> <Host> <Type> <Version> <Port> [RAM]",
" Remove Server: /sub delete <SubServer>",
"",
" To see BungeeCord Supplied Commands, please visit:",
" https:
};
}
/**
* BungeeCord /server
*/
public static final class BungeeServer extends Command implements TabExecutor {
private SubPlugin plugin;
protected BungeeServer(SubPlugin plugin, String command) {
super(command, "bungeecord.command.server");
this.plugin = plugin;
}
/**
* Override /server
*
* @param sender Sender
* @param args Arguments
*/
@SuppressWarnings("deprecation")
@Override
public void execute(CommandSender sender, String[] args) {
if (sender instanceof ProxiedPlayer) {
if (args.length > 0) {
Map<String, Server> servers = plugin.api.getServers();
if (servers.keySet().contains(args[0].toLowerCase())) {
((ProxiedPlayer) sender).connect(servers.get(args[0].toLowerCase()));
} else {
sender.sendMessage(plugin.lang.get().getSection("Lang").getColoredString("Bungee.Server.Invalid", '&'));
}
} else {
int i = 0;
TextComponent serverm = new TextComponent(ChatColor.RESET.toString());
TextComponent div = new TextComponent(plugin.lang.get().getSection("Lang").getColoredString("Bungee.Server.Divider", '&'));
for (Server server : plugin.api.getServers().values()) {
if (!server.isHidden() && (!(server instanceof SubServer) || ((SubServer) server).isRunning())) {
if (i != 0) serverm.addExtra(div);
TextComponent message = new TextComponent(plugin.lang.get().getSection("Lang").getColoredString("Bungee.Server.List", '&').replace("$str$", server.getDisplayName()));
message.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TextComponent[]{new TextComponent(plugin.lang.get().getSection("Lang").getColoredString("Bungee.Server.Hover", '&').replace("$int$", Integer.toString(server.getPlayers().size())))}));
message.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/server " + server.getName()));
serverm.addExtra(message);
i++;
}
}
sender.sendMessages(
plugin.lang.get().getSection("Lang").getColoredString("Bungee.Server.Current", '&').replace("$str$", ((ProxiedPlayer) sender).getServer().getInfo().getName()),
plugin.lang.get().getSection("Lang").getColoredString("Bungee.Server.Available", '&'));
sender.sendMessage(serverm);
}
} else {
sender.sendMessage(plugin.lang.get().getSection("Lang").getColoredString("Command.Generic.Player-Only", '&'));
}
}
/**
* Tab completer
*
* @param sender Sender
* @param args Arguments
* @return Tab completes
*/
@Override
public Iterable<String> onTabComplete(CommandSender sender, String[] args) {
if (args.length <= 1) {
String last = (args.length > 0)?args[args.length - 1].toLowerCase():"";
if (last.length() == 0) {
return plugin.getServers().keySet();
} else {
List<String> list = new ArrayList<String>();
for (String server : plugin.getServers().keySet()) {
if (server.toLowerCase().startsWith(last)) list.add(server);
}
return list;
}
} else {
return Collections.emptyList();
}
}
}
/**
* BungeeCord /glist
*/
public static final class BungeeList extends Command {
private SubPlugin plugin;
protected BungeeList(SubPlugin plugin, String command) {
super(command, "bungeecord.command.list");
this.plugin = plugin;
}
/**
* Override /glist
*
* @param sender
* @param args
*/
@SuppressWarnings("deprecation")
@Override
public void execute(CommandSender sender, String[] args) {
List<String> messages = new LinkedList<String>();
int players = 0;
for (Server server : plugin.api.getServers().values()) {
players += server.getPlayers().size();
if (!server.isHidden() && (!(server instanceof SubServer) || ((SubServer) server).isRunning())) {
int i = 0;
String message = plugin.lang.get().getSection("Lang").getColoredString("Bungee.List.Format", '&').replace("$str$", server.getDisplayName()).replace("$int$", Integer.toString(server.getPlayers().size()));
for (ProxiedPlayer player : server.getPlayers()) {
if (i != 0) message += plugin.lang.get().getSection("Lang").getColoredString("Bungee.List.Divider", '&');
message += plugin.lang.get().getSection("Lang").getColoredString("Bungee.List.List", '&').replace("$str$", player.getName());
i++;
}
messages.add(message);
}
}
sender.sendMessages(messages.toArray(new String[messages.size()]));
sender.sendMessage(plugin.lang.get().getSection("Lang").getColoredString("Bungee.List.Total", '&').replace("$int$", Integer.toString(players)));
}
}
} |
package com.silverpop.api.client;
import com.silverpop.api.client.authentication.LogoutCommand;
import com.silverpop.api.client.command.GetListsCommand;
import com.silverpop.api.client.result.GetListsResult;
import com.silverpop.api.client.result.elements.ListElementType;
import com.silverpop.api.client.xmlapi.XmlApiClient;
import java.util.Collection;
public class ClientDemo {
public static void main(String[] args) throws Exception {
System.out.println("Silverpop API Client Demo");
String argsString = "";
for (String arg : args) {
argsString = argsString + " " + arg;
}
System.out.println("Args : " + argsString);
XmlApiClient apiClient = new XmlApiClient(args[0], args[1], args[2]);
GetListsResult result = (GetListsResult) apiClient.executeCommand(new GetListsCommand());
Collection<ListElementType> lists = result.getLists();
for (ListElementType list : lists) {
System.out.println(list.getNAME());
}
apiClient.executeCommand(new LogoutCommand());
}
} |
package org.jabref.model.entry.field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.jabref.model.strings.StringUtil;
import org.jabref.model.util.OptionalUtil;
public class FieldFactory {
/**
* Character separating field names that are to be used in sequence as fallbacks for a single column
* (e.g. "author/editor" to use editor where author is not set):
*/
private static final String FIELD_OR_SEPARATOR = "/";
private static final String DELIMITER = ";";
public static String serializeOrFields(Field... fields) {
return serializeOrFields(new OrFields(fields));
}
public static String serializeOrFields(OrFields fields) {
return fields.stream()
.map(Field::getName)
.collect(Collectors.joining(FIELD_OR_SEPARATOR));
}
public static String serializeOrFieldsList(Set<OrFields> fields) {
return fields.stream().map(FieldFactory::serializeOrFields).collect(Collectors.joining(DELIMITER));
}
public static List<Field> getNotTextFieldNames() {
return Arrays.asList(StandardField.DOI, StandardField.FILE, StandardField.URL, StandardField.URI, StandardField.ISBN, StandardField.ISSN, StandardField.MONTH, StandardField.DATE, StandardField.YEAR);
}
public static List<Field> getIdentifierFieldNames() {
return Arrays.asList(StandardField.DOI, StandardField.EPRINT, StandardField.PMID);
}
public static OrFields parseOrFields(String fieldNames) {
Set<Field> fields = Arrays.stream(fieldNames.split(FieldFactory.FIELD_OR_SEPARATOR))
.filter(StringUtil::isNotBlank)
.map(FieldFactory::parseField)
.collect(Collectors.toCollection(LinkedHashSet::new));
return new OrFields(fields);
}
public static Set<OrFields> parseOrFieldsList(String fieldNames) {
return Arrays.stream(fieldNames.split(FieldFactory.DELIMITER))
.filter(StringUtil::isNotBlank)
.map(FieldFactory::parseOrFields)
.collect(Collectors.toCollection(LinkedHashSet::new));
}
public static Set<Field> parseFieldList(String fieldNames) {
return Arrays.stream(fieldNames.split(FieldFactory.DELIMITER))
.filter(StringUtil::isNotBlank)
.map(FieldFactory::parseField)
.collect(Collectors.toCollection(LinkedHashSet::new));
}
public static String serializeFieldsList(Collection<Field> fields) {
return fields.stream()
.map(Field::getName)
.collect(Collectors.joining(DELIMITER));
}
public static Field parseField(String fieldName) {
return OptionalUtil.<Field>orElse(OptionalUtil.<Field>orElse(OptionalUtil.<Field>orElse(
InternalField.fromName(fieldName),
StandardField.fromName(fieldName)),
SpecialField.fromName(fieldName)),
IEEEField.fromName(fieldName))
.orElse(new UnknownField(fieldName));
}
public static Set<Field> getKeyFields() {
return getFieldsFiltered(field -> field.getProperties().contains(FieldProperty.SINGLE_ENTRY_LINK) || field.getProperties().contains(FieldProperty.MULTIPLE_ENTRY_LINK));
}
public static boolean isInternalField(Field field) {
return field.getName().startsWith("__");
}
public static Set<Field> getJournalNameFields() {
return getFieldsFiltered(field -> field.getProperties().contains(FieldProperty.JOURNAL_NAME));
}
/**
* Returns a List with all standard fields and including some common internal fields
*/
public static Set<Field> getCommonFields() {
EnumSet<StandardField> allFields = EnumSet.allOf(StandardField.class);
LinkedHashSet<Field> publicAndInternalFields = new LinkedHashSet<>(allFields.size() + 3);
publicAndInternalFields.add(InternalField.INTERNAL_ALL_FIELD);
publicAndInternalFields.add(InternalField.INTERNAL_ALL_TEXT_FIELDS_FIELD);
publicAndInternalFields.add(InternalField.KEY_FIELD);
publicAndInternalFields.addAll(allFields);
return publicAndInternalFields;
}
/**
* Returns a List with all standard fields and the bibtexkey field
*/
public static Set<Field> getStandardFielsdsWithBibTexKey() {
EnumSet<StandardField> allFields = EnumSet.allOf(StandardField.class);
LinkedHashSet<Field> standardFieldsWithBibtexKey = new LinkedHashSet<>(allFields.size() + 1);
standardFieldsWithBibtexKey.add(InternalField.KEY_FIELD);
standardFieldsWithBibtexKey.addAll(allFields);
return standardFieldsWithBibtexKey;
}
public static Set<Field> getBookNameFields() {
return getFieldsFiltered(field -> field.getProperties().contains(FieldProperty.BOOK_NAME));
}
public static Set<Field> getPersonNameFields() {
return getFieldsFiltered(field -> field.getProperties().contains(FieldProperty.PERSON_NAMES));
}
private static Set<Field> getFieldsFiltered(Predicate<Field> selector) {
return getAllFields().stream()
.filter(selector)
.collect(Collectors.toSet());
}
private static Set<Field> getAllFields() {
Set<Field> fields = new HashSet<>();
fields.addAll(EnumSet.allOf(IEEEField.class));
fields.addAll(EnumSet.allOf(InternalField.class));
fields.addAll(EnumSet.allOf(SpecialField.class));
fields.addAll(EnumSet.allOf(StandardField.class));
return fields;
}
/**
* These are the fields JabRef always displays as default {@link org.jabref.preferences.JabRefPreferences#setLanguageDependentDefaultValues()}
*
* A user can change them. The change is currently stored in the preferences only and not explicitly exposed as
* separate preferences object
*/
public static List<Field> getDefaultGeneralFields() {
List<Field> defaultGeneralFields = new ArrayList<>(Arrays.asList(StandardField.DOI, StandardField.CROSSREF, StandardField.KEYWORDS, StandardField.EPRINT, StandardField.URL, StandardField.FILE, StandardField.GROUPS, StandardField.OWNER, StandardField.TIMESTAMP));
defaultGeneralFields.addAll(EnumSet.allOf(SpecialField.class));
return defaultGeneralFields;
}
// TODO: This should ideally be user configurable! Move somewhere more appropriate in the future
public static boolean isMultiLineField(final Field field, List<Field> nonWrappableFields) {
// Treat unknown fields as multi-line fields
return (field instanceof UnknownField) || nonWrappableFields.contains(field) || field.equals(StandardField.ABSTRACT) || field.equals(StandardField.COMMENT) || field.equals(StandardField.REVIEW);
}
} |
package com.github.noxan.aves.server;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import com.github.noxan.aves.net.Connection;
import com.github.noxan.aves.net.SocketConnection;
import com.github.noxan.aves.util.Tuple;
public class SocketServer implements Server, Runnable {
private String host;
private int port;
private BlockingQueue<Tuple<Connection, Object>> dataEvents;
private ServerHandler handler;
private Set<Connection> connections;
private ServerSocket server;
private Thread serverThread;
public SocketServer(ServerHandler handler) {
this("0.0.0.0", 1666, handler);
}
public SocketServer(String host, int port, ServerHandler handler) {
this.host = host;
this.port = port;
this.handler = handler;
dataEvents = new LinkedBlockingQueue<>();
connections = new HashSet<Connection>();
}
@Override
public void start() {
try {
server = new ServerSocket();
server.setSoTimeout(1000);
server.bind(new InetSocketAddress(host, port));
serverThread = new Thread(this);
serverThread.start();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (true) {
try {
Socket socket = server.accept();
Connection connection = new SocketConnection(this, socket);
connections.add(connection);
connection.start();
} catch (SocketTimeoutException e) {
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public String getHost() {
return host;
}
@Override
public int getPort() {
return port;
}
public void offerData(Connection connection, Object data) {
dataEvents.add(new Tuple<Connection, Object>(connection, data));
}
private class EventManager implements Runnable {
@Override
public void run() {
while (true) {
Tuple<Connection, Object> event = dataEvents.poll();
if (event != null) {
handler.handleData(event.getFirst(), event.getSecond());
}
}
}
}
} |
package com.skraylabs.poker.model;
/**
* The state of a Texas Hold 'Em Poker game.
*/
public class GameState {
/**
* The "board" is the set of 5 community cards shared by all players in a game Texas Hold 'Em
* Poker.
*/
public class Board {
/**
* First of three cards dealt in the second round (the "flop").
*/
public Card flopCard1;
/**
* Second of three cards dealt in the second round (the "flop").
*/
public Card flopCard2;
/**
* Third of three cards dealt in the second round (the "flop").
*/
public Card flopCard3;
/**
* Card dealt in the third round (the "turn").
*/
public Card turnCard;
/**
* Card dealt in the fourth and final round (the "river").
*/
public Card riverCard;
} // end of class Board
/**
* Pair of face-down cards held by each player in a game of Texas Hold 'Em poker.
*/
public class Pocket {
/**
* First of two pocket cards.
*/
public Card card1;
/**
* Second of two pocket cards.
*/
public Card card2;
} // end of class Pocket
/**
* The "board". Community cards.
*/
private Board board;
/**
* Pocket cards. Player cards. There is a maximum of 10 players.
*/
private Pocket[] pockets = new Pocket[10];
/**
* Default constructor.
*/
GameState() {
}
/**
* Accessor: get the board cards.
*
* @return community cards
*/
public Board getBoard() {
return board;
}
/**
* Modifier: set the board cards.
*
* @param board community cards to set
*/
void setBoard(Board board) {
this.board = board;
}
/**
* Accessor: get pocket cards.
*
* @return player cards
*/
public Pocket[] getPockets() {
return pockets;
}
/**
* Modifier: set pocket cards.
*
* @param pockets player cards to set
*/
void setPockets(Pocket[] pockets) {
this.pockets = pockets;
}
} |
package com.tellerulam.hue2mqtt;
import java.nio.charset.*;
import java.util.*;
import java.util.logging.*;
import java.util.regex.*;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.*;
import com.eclipsesource.json.*;
import com.eclipsesource.json.JsonObject.Member;
import com.philips.lighting.model.*;
import com.philips.lighting.model.PHLight.PHLightAlertMode;
import com.philips.lighting.model.PHLight.PHLightColorMode;
import com.philips.lighting.model.PHLight.PHLightEffectMode;
public class MQTTHandler
{
private final Logger L=Logger.getLogger(getClass().getName());
public static void init() throws MqttException
{
instance=new MQTTHandler();
instance.doInit();
}
private static MQTTHandler instance;
private final String topicPrefix;
private MQTTHandler()
{
String tp=System.getProperty("hue2mqtt.mqtt.topic","hue");
if(!tp.endsWith("/"))
tp+="/";
topicPrefix=tp;
}
private MqttClient mqttc;
private void queueConnect()
{
shouldBeConnected=false;
Main.t.schedule(new TimerTask(){
@Override
public void run()
{
doConnect();
}
},10*1000);
}
private class StateChecker extends TimerTask
{
@Override
public void run()
{
if(!mqttc.isConnected() && shouldBeConnected)
{
L.warning("Should be connected but aren't, reconnecting");
queueConnect();
}
}
}
private boolean shouldBeConnected;
private final Pattern topicPattern=Pattern.compile("([^/]+/[^/]+)(?:/((?:on|bri|hue|sat|ct|alert|effect|colormode|reachable|x|y|transitiontime)(?:_inc)?))?");
private final Map<String,Integer> transitionTimeCache=new HashMap<>();
void processSet(String topic,MqttMessage msg)
{
String payload=new String(msg.getPayload());
/*
* Possible formats:
*
* object/name <simple value>
* object/name <json>
* object/name/<datapoint> <simple value>
*/
Matcher m=topicPattern.matcher(topic);
if(!m.matches())
{
L.warning("Received set to unparsable topic "+topic);
return;
}
if(m.group(2)!=null)
{
// Third format
if("transitiontime".equals(m.group(2)))
{
// We only cache that, for future reference
transitionTimeCache.put(m.group(1),Integer.valueOf(payload));
return;
}
if(msg.isRetained())
{
L.fine("Ignoring retained set message "+msg+" to "+topic);
return;
}
processSetDatapoint(m.group(1),m.group(2),payload);
}
else
{
if(msg.isRetained())
{
L.fine("Ignoring retained set message "+msg+" to "+topic);
return;
}
processSetComposite(topic,payload);
}
}
@SuppressWarnings("boxing")
private void processSetComposite(String resource, String payload)
{
PHLightState ls=new PHLightState();
// Attempt to decode payload as a JSON object
if(payload.trim().startsWith("{"))
{
JsonObject jso=(JsonObject)Json.parse(payload);
for(Iterator<Member> mit=jso.iterator();mit.hasNext();)
{
Member m=mit.next();
JsonValue val=m.getValue();
addDatapointToLightState(ls, m.getName(), val.isString()?val.asString():val.toString());
}
}
else
{
double level=Double.parseDouble(payload);
if(level<1)
{
ls.setOn(false);
}
else
{
if(level>254)
level=254;
ls.setOn(true);
ls.setBrightness((int)level);
}
// May be null
ls.setTransitionTime(transitionTimeCache.get(resource));
}
HueHandler.updateLightState(resource,ls);
}
private void addDatapointToLightState(PHLightState ls,String datapoint,String value)
{
switch(datapoint)
{
case "on":
if("1".equals(value)||"on".equals(value)||"true".equals(value))
ls.setOn(Boolean.TRUE);
else
ls.setOn(Boolean.FALSE);
break;
case "bri":
ls.setBrightness(Integer.valueOf(value));
break;
case "bri_inc":
ls.setIncrementBri(Integer.valueOf(value));
break;
case "hue":
ls.setHue(Integer.valueOf(value));
break;
case "hue_inc":
ls.setIncrementHue(Integer.valueOf(value));
break;
case "sat":
ls.setSaturation(Integer.valueOf(value));
break;
case "sat_inc":
ls.setIncrementSat(Integer.valueOf(value));
break;
case "x":
ls.setX(Float.valueOf(value));
break;
case "x_inc":
ls.setIncrementX(Float.valueOf(value));
break;
case "y":
ls.setY(Float.valueOf(value));
break;
case "y_inc":
ls.setIncrementY(Float.valueOf(value));
break;
case "ct":
ls.setCt(Integer.valueOf(value));
break;
case "ct_inc":
ls.setIncrementCt(Integer.valueOf(value));
break;
case "transitiontime":
ls.setTransitionTime(Integer.valueOf(value));
break;
case "colormode":
ls.setColorMode(parseColorMode(value));
break;
case "alert":
ls.setAlertMode(parseAlertMode(value));
break;
case "effectmode":
ls.setEffectMode(parseEffectMode(value));
break;
default:
throw new IllegalArgumentException("Attempting to set unknown datapoint "+datapoint+" to value "+value);
}
}
private PHLightColorMode parseColorMode(String value)
{
switch(value)
{
case "ct":
return PHLightColorMode.COLORMODE_CT;
case "xy":
return PHLightColorMode.COLORMODE_XY;
case "hs":
return PHLightColorMode.COLORMODE_HUE_SATURATION;
default:
throw new IllegalArgumentException("Unknown color mode "+value);
}
}
private PHLightAlertMode parseAlertMode(String value)
{
switch(value)
{
case "lselect":
return PHLightAlertMode.ALERT_LSELECT;
case "select":
return PHLightAlertMode.ALERT_SELECT;
case "none":
return PHLightAlertMode.ALERT_NONE;
default:
throw new IllegalArgumentException("Unknown alert mode "+value);
}
}
private PHLightEffectMode parseEffectMode(String value)
{
switch(value)
{
case "colorloop":
return PHLightEffectMode.EFFECT_COLORLOOP;
case "none":
return PHLightEffectMode.EFFECT_NONE;
default:
throw new IllegalArgumentException("Unknown effect mode "+value);
}
}
private void processSetDatapoint(String resource, String datapoint, String payload)
{
PHLightState ls=new PHLightState();
addDatapointToLightState(ls,datapoint,payload);
// May be null
ls.setTransitionTime(transitionTimeCache.get(resource));
HueHandler.updateLightState(resource,ls);
}
void processMessage(String topic,MqttMessage msg)
{
try
{
topic=topic.substring(topicPrefix.length(),topic.length());
if(topic.startsWith("set/"))
processSet(topic.substring(4),msg);
}
catch(Exception e)
{
L.log(Level.WARNING, "Exception when processing published message to "+topic+": "+msg,e);
}
}
private void doConnect()
{
L.info("Connecting to MQTT broker "+mqttc.getServerURI()+" with CLIENTID="+mqttc.getClientId()+" and TOPIC PREFIX="+topicPrefix);
MqttConnectOptions copts=new MqttConnectOptions();
copts.setWill(topicPrefix+"connected", "0".getBytes(), 2, true);
copts.setCleanSession(true);
try
{
mqttc.connect(copts);
setHueConnectionState(false);
L.info("Successfully connected to broker, subscribing to "+topicPrefix+"set/
try
{
mqttc.subscribe(topicPrefix+"set/
shouldBeConnected=true;
}
catch(MqttException mqe)
{
L.log(Level.WARNING,"Error subscribing to topic hierarchy, check your configuration",mqe);
throw mqe;
}
}
catch(MqttException mqe)
{
L.log(Level.WARNING,"Error while connecting to MQTT broker, will retry: "+mqe.getMessage(),mqe);
queueConnect(); // Attempt reconnect
}
}
private void doInit() throws MqttException
{
String server=System.getProperty("hue2mqtt.mqtt.server","tcp://localhost:1883");
String clientID=System.getProperty("hue2mqtt.mqtt.clientid","hue2mqtt");
mqttc=new MqttClient(server,clientID,new MemoryPersistence());
mqttc.setCallback(new MqttCallback() {
@Override
public void messageArrived(String topic, MqttMessage msg) throws Exception
{
try
{
processMessage(topic,msg);
}
catch(Exception e)
{
L.log(Level.WARNING,"Error when processing message "+msg+" for "+topic,e);
}
}
@Override
public void deliveryComplete(IMqttDeliveryToken token)
{
/* Intentionally ignored */
}
@Override
public void connectionLost(Throwable t)
{
L.log(Level.WARNING,"Connection to MQTT broker lost",t);
queueConnect();
}
});
doConnect();
Main.t.schedule(new StateChecker(),30*1000,30*1000);
}
static private Map<String,String> previouslyPublishedValues=new HashMap<>();
static void publishIfChanged(String name, boolean retain, Object... vals)
{
WrappedJsonObject jso=new WrappedJsonObject();
for(int pix=0;pix<vals.length;pix+=2)
{
String vname=vals[pix].toString();
Object val=vals[pix+1];
jso.add(vname,val);
}
String txtmsg=jso.toString();
if(txtmsg.equals(previouslyPublishedValues.put(name,txtmsg)))
return;
MqttMessage msg=new MqttMessage(txtmsg.getBytes(StandardCharsets.UTF_8));
msg.setQos(0);
msg.setRetained(retain);
try
{
String fullTopic=instance.topicPrefix+"status/"+name;
instance.mqttc.publish(fullTopic, msg);
instance.L.info("Published "+txtmsg+" to "+fullTopic+(retain?" (R)":""));
}
catch(MqttException e)
{
instance.L.log(Level.WARNING,"Error when publishing message "+txtmsg,e);
}
}
public static void setHueConnectionState(boolean connected)
{
try
{
instance.mqttc.publish(instance.topicPrefix+"connected",(connected?"2":"1").getBytes(),1,true);
}
catch(MqttException e)
{
/* Ignore */
}
}
} |
package org.jboss.msc.service;
import java.io.IOException;
import java.io.Writer;
import java.util.Arrays;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;
import org.jboss.msc.value.Value;
/**
* @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a>
* @author <a href="mailto:flavia.rainone@jboss.com">Flavia Rainone</a>
*/
final class ServiceInstanceImpl<S> implements ServiceController<S>, Dependent {
private static final String ILLEGAL_CONTROLLER_STATE = "Illegal controller state";
/**
* The service itself.
*/
private final Value<? extends Service<? extends S>> serviceValue;
/**
* The source location in which this service was defined.
*/
private final Location location;
/**
* The dependencies of this service.
*/
private final Dependency[] dependencies;
/**
* The injections of this service.
*/
private final ValueInjection<?>[] injections;
/**
* The set of registered service listeners.
*/
private final IdentityHashSet<ServiceListener<? super S>> listeners;
/**
* The set of dependents on this instance.
*/
private final IdentityHashSet<Dependent> dependents = new IdentityHashSet<Dependent>(0);
/**
* The primary registration of this service.
*/
private final ServiceRegistrationImpl primaryRegistration;
/**
* The alias registrations of this service.
*/
private final ServiceRegistrationImpl[] aliasRegistrations;
/**
* The start exception.
*/
private StartException startException;
/**
* The controller mode.
*/
private ServiceController.Mode mode = ServiceController.Mode.NEVER;
/**
* The controller state.
*/
private Substate state = Substate.NEW;
/**
* The number of registrations which place a demand-to-start on this instance. If this value is >0, propagate a demand
* up to all parent dependents. If this value is >0 and mode is ON_DEMAND, put a load of +1 on {@code upperCount}.
*/
private int demandedByCount;
/**
* Semaphore count for bringing this dep up. If the value is <= 0, the service is stopped. Each unstarted
* dependency will put a load of -1 on this value. A mode of AUTOMATIC or IMMEDIATE will put a load of +1 on this
* value. A mode of NEVER will cause this value to be ignored. A mode of ON_DEMAND will put a load of +1 on this
* value <b>if</b> {@link #demandedByCount} is >0.
*/
private int upperCount;
/**
* The number of dependents that are currently running. The deployment will not execute the {@code stop()} method
* (and subsequently leave the {@link org.jboss.msc.service.ServiceController.State#STOPPING} state) until all running dependents (and listeners) are stopped.
*/
private int runningDependents;
/**
* Count for failure notification. It indicates how many services have failed to start and are not recovered so far.
* This count monitors failures that happen when starting this service, and dependency related failures as well.
* When incremented from 0 to 1, it is time to notify dependents and listeners that a failure occurred. When
* decremented from 1 to 0, the dependents and listeners are notified that the affected services are retrying to
* start. Values larger than 1 are ignored to avoid multiple notifications.
*/
private int failCount;
/**
* Count for notification of missing (uninstalled) dependencies. Its value indicates how many dependencies are
* missing. When incremented from 0 to 1, dependents and listeners are notified of the missing dependency. When
* decremented from 1 to 0, a notification that the missing dependencies are now installed is sent to dependents and
* listeners. Values larger than 1 are ignored to avoid multiple notifications.
*/
private int missingDependencyCount;
/**
* The number of asynchronous tasks that are currently running. This includes listeners, start/stop methods,
* outstanding asynchronous start/stops, and internal tasks.
*/
private int asyncTasks;
private static final ServiceRegistrationImpl[] NO_REGISTRATIONS = new ServiceRegistrationImpl[0];
private static final Dependent[] NO_DEPENDENTS = new Dependent[0];
private static final ValueInjection<?>[] NO_INJECTIONS = new ValueInjection<?>[0];
ServiceInstanceImpl(final Value<? extends Service<? extends S>> serviceValue, final Location location, final Dependency[] dependencies, final ValueInjection<?>[] injections, final ServiceRegistrationImpl primaryRegistration, final ServiceRegistrationImpl[] aliasRegistrations, final Set<? extends ServiceListener<? super S>> listeners) {
this.serviceValue = serviceValue;
this.location = location;
this.dependencies = dependencies;
this.injections = injections;
this.primaryRegistration = primaryRegistration;
this.aliasRegistrations = aliasRegistrations;
this.listeners = new IdentityHashSet<ServiceListener<? super S>>(listeners);
upperCount = - dependencies.length;
}
ServiceInstanceImpl(final Value<? extends Service<? extends S>> serviceValue, final ServiceRegistrationImpl primaryRegistration) {
this.serviceValue = serviceValue;
this.primaryRegistration = primaryRegistration;
location = null;
dependencies = NO_REGISTRATIONS;
injections = NO_INJECTIONS;
aliasRegistrations = NO_REGISTRATIONS;
listeners = new IdentityHashSet<ServiceListener<? super S>>(0);
upperCount = - dependencies.length;
}
/**
* Determine whether the lock is currently held.
*
* @return {@code true} if the lock is held
*/
boolean lockHeld() {
return Thread.holdsLock(this);
}
Substate getSubstateLocked() {
return state;
}
void addAsyncTask() {
asyncTasks++;
}
void removeAsyncTask() {
asyncTasks
}
/**
* Identify the transition to take. Call under lock.
*
* @return the transition or {@code null} if none is needed at this time
*/
private Transition getTransition() {
assert lockHeld();
if (asyncTasks != 0) {
// no movement possible
return null;
}
switch (state) {
case DOWN: {
if (mode == ServiceController.Mode.REMOVE) {
return Transition.DOWN_to_REMOVING;
} else if (mode != ServiceController.Mode.NEVER) {
if (upperCount > 0) {
return Transition.DOWN_to_START_REQUESTED;
}
}
break;
}
case STOPPING: {
return Transition.STOPPING_to_DOWN;
}
case STOP_REQUESTED: {
if (upperCount > 0) {
return Transition.STOP_REQUESTED_to_UP;
}
if (runningDependents == 0) {
return Transition.STOP_REQUESTED_to_STOPPING;
}
break;
}
case UP: {
if (upperCount <= 0) {
return Transition.UP_to_STOP_REQUESTED;
}
break;
}
case START_FAILED: {
if (upperCount > 0) {
if (startException == null) {
return Transition.START_FAILED_to_STARTING;
}
} else {
return Transition.START_FAILED_to_DOWN;
}
break;
}
case STARTING: {
if (startException == null) {
return Transition.STARTING_to_UP;
} else {
return Transition.STARTING_to_START_FAILED;
}
}
case START_REQUESTED: {
if (upperCount > 0) {
return Transition.START_REQUESTED_to_STARTING;
} else {
return Transition.START_REQUESTED_to_DOWN;
}
}
case REMOVING: {
return Transition.REMOVING_to_REMOVED;
}
case REMOVED: {
// no possible actions
break;
}
}
return null;
}
/**
* Run the locked portion of a transition. Call under lock.
*
* @return the async tasks to start when the lock is not held, {@code null} for none
*/
Runnable[] transition() {
assert lockHeld();
final Transition transition = getTransition();
if (transition == null) {
return null;
}
final Runnable[] tasks;
switch (transition) {
case STOPPING_to_DOWN: {
tasks = getListenerTasks(transition.getAfter().getState(), new DependentStoppedTask());
break;
}
case START_REQUESTED_to_DOWN: {
tasks = new Runnable[] { new DependentStoppedTask() };
break;
}
case START_REQUESTED_to_STARTING: {
tasks = getListenerTasks(transition.getAfter().getState(), new StartTask(true));
break;
}
case UP_to_STOP_REQUESTED: {
tasks = new Runnable[] { new DependencyStoppedTask(dependents.toScatteredArray(NO_DEPENDENTS)) };
break;
}
case STARTING_to_UP: {
tasks = getListenerTasks(transition.getAfter().getState(), new DependencyStartedTask(dependents.toScatteredArray(NO_DEPENDENTS)));
break;
}
case STARTING_to_START_FAILED: {
tasks = getListenerTasks(transition.getAfter().getState(), new DependencyFailedTask(dependents.toScatteredArray(NO_DEPENDENTS)));
break;
}
case START_FAILED_to_STARTING: {
tasks = getListenerTasks(transition.getAfter().getState(), new DependencyRetryingTask(dependents.toScatteredArray(NO_DEPENDENTS)), new StartTask(false));
break;
}
case START_FAILED_to_DOWN: {
startException = null;
failCount
tasks = getListenerTasks(transition.getAfter().getState(), new DependencyRetryingTask(dependents.toScatteredArray(NO_DEPENDENTS)), new StopTask(true), new DependentStoppedTask());
break;
}
case STOP_REQUESTED_to_UP: {
tasks = new Runnable[] { new DependencyStartedTask(dependents.toScatteredArray(NO_DEPENDENTS)) };
break;
}
case STOP_REQUESTED_to_STOPPING: {
tasks = getListenerTasks(transition.getAfter().getState(), new StopTask(false));
break;
}
case DOWN_to_REMOVING: {
tasks = new Runnable[] { new RemoveTask() };
break;
}
case REMOVING_to_REMOVED: {
tasks = getListenerTasks(transition.getAfter().getState());
listeners.clear();
break;
}
case DOWN_to_START_REQUESTED: {
tasks = new Runnable[] { new DependentStartedTask() };
break;
}
default: {
throw new IllegalStateException();
}
}
state = transition.getAfter();
asyncTasks += tasks.length;
return tasks;
}
private Runnable[] getListenerTasks(final ServiceController.State newState, final Runnable extraTask1,
final Runnable extraTask2, final Runnable extraTask3) {
final IdentityHashSet<ServiceListener<? super S>> listeners = this.listeners;
final int size = listeners.size();
final Runnable[] tasks = new Runnable[size + 3];
int i = 0;
for (ServiceListener<? super S> listener : listeners) {
tasks[i++] = new ListenerTask(listener, newState);
}
tasks[i++] = extraTask1;
tasks[i++] = extraTask2;
tasks[i] = extraTask3;
return tasks;
}
private Runnable[] getListenerTasks(final ServiceController.State newState, final Runnable extraTask1, final Runnable extraTask2) {
final IdentityHashSet<ServiceListener<? super S>> listeners = this.listeners;
final int size = listeners.size();
final Runnable[] tasks = new Runnable[size + 2];
int i = 0;
for (ServiceListener<? super S> listener : listeners) {
tasks[i++] = new ListenerTask(listener, newState);
}
tasks[i++] = extraTask1;
tasks[i] = extraTask2;
return tasks;
}
private Runnable[] getListenerTasks(final ServiceController.State newState, final Runnable extraTask) {
final IdentityHashSet<ServiceListener<? super S>> listeners = this.listeners;
final int size = listeners.size();
final Runnable[] tasks = new Runnable[size + 1];
int i = 0;
for (ServiceListener<? super S> listener : listeners) {
tasks[i++] = new ListenerTask(listener, newState);
}
tasks[i] = extraTask;
return tasks;
}
private Runnable[] getListenerTasks(final ServiceController.State newState) {
final IdentityHashSet<ServiceListener<? super S>> listeners = this.listeners;
final int size = listeners.size();
final Runnable[] tasks = new Runnable[size];
int i = 0;
for (ServiceListener<? super S> listener : listeners) {
tasks[i++] = new ListenerTask(listener, newState);
}
return tasks;
}
private Runnable[] getListenerTasks(final ListenerNotification notification, final Runnable extraTask) {
final IdentityHashSet<ServiceListener<? super S>> listeners = this.listeners;
final int size = listeners.size();
final Runnable[] tasks = new Runnable[size + 1];
int i = 0;
for (ServiceListener<? super S> listener : listeners) {
tasks[i++] = new ListenerTask(listener, notification);
}
tasks[i] = extraTask;
return tasks;
}
void doExecute(final Runnable task) {
assert ! lockHeld();
if (task == null) return;
try {
primaryRegistration.getContainer().getExecutor().execute(task);
} catch (RejectedExecutionException e) {
task.run();
}
}
void doExecute(final Runnable... tasks) {
assert ! lockHeld();
if (tasks == null) return;
final Executor executor = primaryRegistration.getContainer().getExecutor();
for (Runnable task : tasks) {
try {
executor.execute(task);
} catch (RejectedExecutionException e) {
task.run();
}
}
}
public void setMode(final ServiceController.Mode newMode) {
internalSetMode(null, newMode);
}
private boolean internalSetMode(final ServiceController.Mode expectedMode, final ServiceController.Mode newMode) {
assert !lockHeld();
if (newMode == null) {
throw new IllegalArgumentException("newMode is null");
}
Runnable[] bootTasks = null;
final Runnable[] tasks;
Runnable specialTask = null;
synchronized (this) {
if (expectedMode != null && expectedMode != mode) {
return false;
}
final Substate oldState = state;
if (oldState == Substate.NEW) {
state = Substate.DOWN;
bootTasks = getListenerTasks(ListenerNotification.LISTENER_ADDED, new InstallTask());
asyncTasks += bootTasks.length;
}
final ServiceController.Mode oldMode = mode;
mode = newMode;
switch (oldMode) {
case REMOVE: {
switch (newMode) {
case REMOVE: {
break;
}
default: {
throw new IllegalStateException("Service removed");
}
}
break;
}
case NEVER: {
switch (newMode) {
case ON_DEMAND: {
if (demandedByCount > 0) {
upperCount++;
}
break;
}
case PASSIVE: {
upperCount++;
break;
}
case ACTIVE: {
specialTask = new DemandParentsTask();
asyncTasks++;
upperCount++;
break;
}
}
break;
}
case ON_DEMAND: {
switch (newMode) {
case REMOVE:
case NEVER: {
if (demandedByCount > 0) {
upperCount
}
break;
}
case PASSIVE: {
if (demandedByCount == 0) {
upperCount++;
}
break;
}
case ACTIVE: {
specialTask = new DemandParentsTask();
asyncTasks++;
if (demandedByCount == 0) {
upperCount++;
}
break;
}
}
break;
}
case PASSIVE: {
switch (newMode) {
case REMOVE:
case NEVER: {
upperCount
break;
}
case ON_DEMAND: {
if (demandedByCount == 0) {
upperCount
}
break;
}
case ACTIVE: {
specialTask = new DemandParentsTask();
asyncTasks++;
break;
}
}
break;
}
case ACTIVE: {
switch (newMode) {
case REMOVE:
case NEVER: {
specialTask = new UndemandParentsTask();
asyncTasks++;
upperCount
break;
}
case ON_DEMAND: {
specialTask = new UndemandParentsTask();
asyncTasks++;
if (demandedByCount == 0) {
upperCount
}
break;
}
case PASSIVE: {
specialTask = new UndemandParentsTask();
asyncTasks++;
break;
}
}
break;
}
}
tasks = (oldMode == newMode) ? null : transition();
}
if (bootTasks != null) {
for (Runnable bootTask : bootTasks) {
bootTask.run();
}
}
doExecute(tasks);
doExecute(specialTask);
return true;
}
Dependency[] getDependencyLinks() {
return dependencies;
}
@Override
public void immediateDependencyInstalled() {
dependencyInstalled();
}
@Override
public void immediateDependencyUninstalled() {
dependencyUninstalled();
}
@Override
public void dependencyInstalled() {
Runnable[] tasks = null;
synchronized (this) {
if (-- missingDependencyCount != 0) {
return;
}
// we dropped it to 0
tasks = getListenerTasks(ListenerNotification.DEPENDENCY_INSTALLED,
new DependencyInstalledTask(dependents.toScatteredArray(NO_DEPENDENTS)));
asyncTasks += tasks.length;
}
doExecute(tasks);
}
@Override
public void dependencyUninstalled() {
Runnable[] tasks = null;
synchronized (this) {
if (++ missingDependencyCount != 1) {
return;
}
// we raised it to 1
tasks = getListenerTasks(ListenerNotification.MISSING_DEPENDENCY,
new DependencyUninstalledTask(dependents.toScatteredArray(NO_DEPENDENTS)));
asyncTasks += tasks.length;
}
doExecute(tasks);
}
@Override
public void immediateDependencyUp() {
Runnable[] tasks = null;
synchronized (this) {
if (++upperCount != 1) {
return;
}
// we raised it to 1
tasks = transition();
}
doExecute(tasks);
}
@Override
public void immediateDependencyDown() {
Runnable[] tasks = null;
synchronized (this) {
if (--upperCount != 0) {
return;
}
// we dropped it below 0
tasks = transition();
}
doExecute(tasks);
}
@Override
public void dependencyFailed() {
Runnable[] tasks = null;
synchronized (this) {
if (++failCount != 1) {
return;
}
// we raised it to 1
tasks = getListenerTasks(ListenerNotification.DEPENDENCY_FAILURE,
new DependencyFailedTask(dependents.toScatteredArray(NO_DEPENDENTS)));
asyncTasks += tasks.length;
}
doExecute(tasks);
}
@Override
public void dependencyFailureCleared() {
Runnable[] tasks = null;
synchronized (this) {
if (--failCount != 0) {
return;
}
// we dropped it to 0
tasks = getListenerTasks(ListenerNotification.DEPENDENCY_FAILURE_CLEAR,
new DependencyRetryingTask(dependents.toScatteredArray(NO_DEPENDENTS)));
asyncTasks += tasks.length;
}
doExecute(tasks);
}
void dependentStarted() {
assert ! lockHeld();
synchronized (this) {
runningDependents++;
}
}
void dependentStopped() {
assert ! lockHeld();
final Runnable[] tasks;
synchronized (this) {
if (--runningDependents != 0) {
return;
}
tasks = transition();
}
doExecute(tasks);
}
Runnable[] addDependent(final Dependent dependent) {
assert lockHeld();
dependents.add(dependent);
final Runnable[] tasks;
if (failCount > 0) {
final Dependent[] dependents = new Dependent[]{dependent};
if (missingDependencyCount > 0) {
tasks = new Runnable[2];
tasks[1] = new DependencyUninstalledTask(dependents);
} else {
tasks = new Runnable[1];
}
tasks[0] = new DependencyFailedTask(dependents);
asyncTasks += tasks.length;
return tasks;
} else if (missingDependencyCount > 0) {
tasks = new Runnable[]{new DependencyUninstalledTask(new Dependent[]{dependent})};
asyncTasks ++;
} else {
tasks = null;
}
return tasks;
}
void removeDependent(final Dependent dependent) {
dependents.remove(dependent);
}
void addDependents(final IdentityHashSet<Dependent> dependents) {
this.dependents.addAll(dependents);
// do not notify dependents of failures and missing dependencies because, at this point,
// failCount and missingDependencyCount must be 0
}
void removeAllDependents(final IdentityHashSet<ServiceInstanceImpl<?>> dependents) {
this.dependents.removeAll(dependents);
}
private void doDemandParents() {
assert ! lockHeld();
for (Dependency dependency : dependencies) {
dependency.addDemand();
}
}
private void doUndemandParents() {
assert ! lockHeld();
for (Dependency dependency : dependencies) {
dependency.removeDemand();
}
}
void addDemand() {
addDemands(1);
}
void addDemands(final int demandedByCount) {
assert ! lockHeld();
final Runnable[] tasks;
final boolean propagate;
synchronized (this) {
final int cnt = this.demandedByCount;
this.demandedByCount += demandedByCount;
propagate = cnt == 0;
if (cnt == 0 && mode == Mode.ON_DEMAND) {
upperCount++;
tasks = transition();
} else {
// no change
tasks = null;
}
if (propagate) asyncTasks++;
}
doExecute(tasks);
if (propagate) doExecute(new DemandParentsTask());
}
void removeDemand() {
assert ! lockHeld();
final Runnable[] tasks;
final boolean propagate;
synchronized (this) {
final int cnt = --demandedByCount;
propagate = cnt == 0;
if (cnt == 0 && mode == Mode.ON_DEMAND) {
upperCount
tasks = transition();
} else {
// no change
tasks = null;
}
if (propagate) asyncTasks++;
}
doExecute(tasks);
if (propagate) doExecute(new UndemandParentsTask());
}
public ServiceContainer getServiceContainer() {
return primaryRegistration.getContainer();
}
public ServiceController.State getState() {
return state.getState();
}
public S getValue() throws IllegalStateException {
return serviceValue.getValue().getValue();
}
public ServiceName getName() {
return primaryRegistration.getName();
}
private static final ServiceName[] NO_NAMES = new ServiceName[0];
public ServiceName[] getAliases() {
final ServiceRegistrationImpl[] aliasRegistrations = this.aliasRegistrations;
final int len = aliasRegistrations.length;
if (len == 0) {
return NO_NAMES;
}
final ServiceName[] names = new ServiceName[len];
for (int i = 0; i < len; i++) {
names[i] = aliasRegistrations[i].getName();
}
return names;
}
public Location getLocation() {
return location;
}
public void addListener(final ServiceListener<? super S> listener) {
assert !lockHeld();
final Substate state;
synchronized (this) {
state = this.state;
// Always run listener if removed.
if (state != Substate.REMOVED) {
if (! listeners.add(listener)) {
// Duplicates not allowed
throw new IllegalArgumentException("Listener " + listener + " already present on controller for " + primaryRegistration.getName());
}
}
asyncTasks++;
}
invokeListener(listener, ListenerNotification.LISTENER_ADDED, null);
}
public void removeListener(final ServiceListener<? super S> listener) {
synchronized (this) {
listeners.remove(listener);
}
}
public StartException getStartException() {
synchronized (this) {
return startException;
}
}
public void retry() {
assert !lockHeld();
final Runnable[] tasks;
synchronized (this) {
if (state.getState() != ServiceController.State.START_FAILED) {
return;
}
startException = null;
failCount
tasks = transition();
}
doExecute(tasks);
}
public ServiceController.Mode getMode() {
synchronized (this) {
return mode;
}
}
public boolean compareAndSetMode(final Mode expectedMode, final Mode newMode) {
if (expectedMode == null) {
throw new IllegalArgumentException("expectedMode is null");
}
return internalSetMode(expectedMode, newMode);
}
private static enum ListenerNotification {
/** Notify the listener that is has been added. */
LISTENER_ADDED,
/** Notifications related to the current state. */
STATE,
/** Notify the listener that a dependency failure occurred. */
DEPENDENCY_FAILURE,
/** Notify the listener that all dependency failures are cleared. */
DEPENDENCY_FAILURE_CLEAR,
/** Notify the listener that a dependency is missing (uninstalled). */
MISSING_DEPENDENCY,
/** Notify the listener that all missing dependencies are now installed. */
DEPENDENCY_INSTALLED}
/**
* Invokes the listener, performing the notification specified.
*
* @param listener listener to be invoked
* @param notification specified notification
* @param state the state to be notified, only relevant if {@code notification} is
* {@link ListenerNotification#STATE}
*/
private void invokeListener(final ServiceListener<? super S> listener, final ListenerNotification notification, final State state ) {
assert !lockHeld();
try {
switch (notification) {
case LISTENER_ADDED:
listener.listenerAdded(this);
break;
case STATE:
switch (state) {
case DOWN: {
listener.serviceStopped(this);
break;
}
case STARTING: {
listener.serviceStarting(this);
break;
}
case START_FAILED: {
listener.serviceFailed(this, startException);
break;
}
case UP: {
listener.serviceStarted(this);
break;
}
case STOPPING: {
listener.serviceStopping(this);
break;
}
case REMOVED: {
listener.serviceRemoved(this);
break;
}
}
break;
case DEPENDENCY_FAILURE:
listener.dependencyFailed(this);
break;
case DEPENDENCY_FAILURE_CLEAR:
listener.dependencyFailureCleared(this);
break;
case MISSING_DEPENDENCY:
listener.dependencyUninstalled(this);
break;
case DEPENDENCY_INSTALLED:
listener.dependencyInstalled(this);
break;
}
} catch (Throwable t) {
ServiceLogger.INSTANCE.listenerFailed(t, listener);
} finally {
final Runnable[] tasks;
synchronized (this) {
asyncTasks
tasks = transition();
}
doExecute(tasks);
}
}
Substate getSubstate() {
synchronized (this) {
return state;
}
}
ServiceRegistrationImpl getPrimaryRegistration() {
return primaryRegistration;
}
ServiceRegistrationImpl[] getAliasRegistrations() {
return aliasRegistrations;
}
enum ContextState {
SYNC,
ASYNC,
COMPLETE,
FAILED,
}
private static <T> void doInject(final ValueInjection<T> injection) {
injection.getTarget().inject(injection.getSource().getValue());
}
private class DemandParentsTask implements Runnable {
public void run() {
try {
doDemandParents();
final Runnable[] tasks;
synchronized (ServiceInstanceImpl.this) {
asyncTasks
tasks = transition();
}
doExecute(tasks);
} catch (Throwable t) {
ServiceLogger.INSTANCE.internalServiceError(t, primaryRegistration.getName());
}
}
}
private class UndemandParentsTask implements Runnable {
public void run() {
try {
doUndemandParents();
final Runnable[] tasks;
synchronized (ServiceInstanceImpl.this) {
asyncTasks
tasks = transition();
}
doExecute(tasks);
} catch (Throwable t) {
ServiceLogger.INSTANCE.internalServiceError(t, primaryRegistration.getName());
}
}
}
private class DependentStoppedTask implements Runnable {
public void run() {
try {
for (Dependency dependency : dependencies) {
dependency.dependentStopped();
}
final Runnable[] tasks;
synchronized (ServiceInstanceImpl.this) {
asyncTasks
tasks = transition();
}
doExecute(tasks);
} catch (Throwable t) {
ServiceLogger.INSTANCE.internalServiceError(t, primaryRegistration.getName());
}
}
}
private class DependentStartedTask implements Runnable {
public void run() {
try {
for (Dependency dependency : dependencies) {
dependency.dependentStarted();
}
final Runnable[] tasks;
synchronized (ServiceInstanceImpl.this) {
asyncTasks
tasks = transition();
}
doExecute(tasks);
} catch (Throwable t) {
ServiceLogger.INSTANCE.internalServiceError(t, primaryRegistration.getName());
}
}
}
private class StartTask implements Runnable {
private final boolean doInjection;
StartTask(final boolean doInjection) {
this.doInjection = doInjection;
}
public void run() {
assert !lockHeld();
final ServiceName serviceName = primaryRegistration.getName();
final long startNanos = System.nanoTime();
final StartContextImpl context = new StartContextImpl(startNanos);
try {
if (doInjection) {
final ValueInjection<?>[] injections = ServiceInstanceImpl.this.injections;
final int injectionsLength = injections.length;
boolean ok = false;
int i = 0;
try {
for (; i < injectionsLength; i++) {
final ValueInjection<?> injection = injections[i];
doInject(injection);
}
ok = true;
} finally {
if (! ok) {
for (; i >= 0; i
injections[i].getTarget().uninject();
}
}
}
}
final Service<? extends S> service = serviceValue.getValue();
if (service == null) {
throw new IllegalArgumentException("Service is null");
}
service.start(context);
final Runnable[] tasks;
synchronized (ServiceInstanceImpl.this) {
if (context.state != ContextState.SYNC) {
return;
}
context.state = ContextState.COMPLETE;
asyncTasks
if (ServiceContainerImpl.PROFILE_OUTPUT != null) {
writeProfileInfo('S', startNanos, System.nanoTime());
}
tasks = transition();
}
doExecute(tasks);
} catch (StartException e) {
e.setServiceName(serviceName);
final Runnable[] tasks;
synchronized (ServiceInstanceImpl.this) {
final ContextState oldState = context.state;
if (oldState != ContextState.SYNC && oldState != ContextState.ASYNC) {
ServiceLogger.INSTANCE.exceptionAfterComplete(e, serviceName);
return;
}
context.state = ContextState.FAILED;
asyncTasks
startException = e;
if (ServiceContainerImpl.PROFILE_OUTPUT != null) {
writeProfileInfo('F', startNanos, System.nanoTime());
}
failCount++;
tasks = transition();
}
doExecute(tasks);
} catch (Throwable t) {
final Runnable[] tasks;
synchronized (ServiceInstanceImpl.this) {
final ContextState oldState = context.state;
if (oldState != ContextState.SYNC && oldState != ContextState.ASYNC) {
ServiceLogger.INSTANCE.exceptionAfterComplete(t, serviceName);
return;
}
context.state = ContextState.FAILED;
asyncTasks
startException = new StartException("Failed to start service", t, location, serviceName);
if (ServiceContainerImpl.PROFILE_OUTPUT != null) {
writeProfileInfo('F', startNanos, System.nanoTime());
}
failCount ++;
tasks = transition();
}
doExecute(tasks);
}
}
}
private class StopTask implements Runnable {
private final boolean onlyUninject;
StopTask(final boolean onlyUninject) {
this.onlyUninject = onlyUninject;
}
public void run() {
assert !lockHeld();
final ServiceName serviceName = primaryRegistration.getName();
final long startNanos = System.nanoTime();
final StopContextImpl context = new StopContextImpl(startNanos);
boolean ok = false;
try {
if (! onlyUninject) {
try {
final Service<? extends S> service = serviceValue.getValue();
if (service != null) {
service.stop(context);
ok = true;
} else {
ServiceLogger.INSTANCE.stopServiceMissing(serviceName);
}
} catch (Throwable t) {
ServiceLogger.INSTANCE.stopFailed(t, serviceName);
}
}
} finally {
Runnable[] tasks = null;
synchronized (ServiceInstanceImpl.this) {
if (ok && context.state != ContextState.SYNC) {
// We want to discard the exception anyway, if there was one. Which there can't be.
//noinspection ReturnInsideFinallyBlock
return;
}
context.state = ContextState.COMPLETE;
}
for (ValueInjection<?> injection : injections) try {
injection.getTarget().uninject();
} catch (Throwable t) {
ServiceLogger.INSTANCE.uninjectFailed(t, serviceName, injection);
}
synchronized (ServiceInstanceImpl.this) {
asyncTasks
if (ServiceContainerImpl.PROFILE_OUTPUT != null) {
writeProfileInfo('X', startNanos, System.nanoTime());
}
tasks = transition();
}
doExecute(tasks);
}
}
}
private class ListenerTask implements Runnable {
private final ListenerNotification notification;
private final ServiceListener<? super S> listener;
private final ServiceController.State state;
ListenerTask(final ServiceListener<? super S> listener, final ServiceController.State state) {
this.listener = listener;
this.state = state;
notification = ListenerNotification.STATE;
}
ListenerTask(final ServiceListener<? super S> listener, final ListenerNotification notification) {
this.listener = listener;
state = null;
this.notification = notification;
}
public void run() {
assert !lockHeld();
if (ServiceContainerImpl.PROFILE_OUTPUT != null) {
final long start = System.nanoTime();
try {
invokeListener(listener, notification, state);
} finally {
writeProfileInfo('L', start, System.nanoTime());
}
} else {
invokeListener(listener, notification, state);
}
}
}
private class DependencyStartedTask implements Runnable {
private final Dependent[] dependents;
DependencyStartedTask(final Dependent[] dependents) {
this.dependents = dependents;
}
public void run() {
try {
for (Dependent dependent : dependents) {
if (dependent != null) dependent.immediateDependencyUp();
}
final Runnable[] tasks;
synchronized (ServiceInstanceImpl.this) {
asyncTasks
tasks = transition();
}
doExecute(tasks);
} catch (Throwable t) {
ServiceLogger.INSTANCE.internalServiceError(t, primaryRegistration.getName());
}
}
}
private class DependencyStoppedTask implements Runnable {
private final Dependent[] dependents;
DependencyStoppedTask(final Dependent[] dependents) {
this.dependents = dependents;
}
public void run() {
try {
for (Dependent dependent : dependents) {
if (dependent != null) dependent.immediateDependencyDown();
}
final Runnable[] tasks;
synchronized (ServiceInstanceImpl.this) {
asyncTasks
tasks = transition();
}
doExecute(tasks);
} catch (Throwable t) {
ServiceLogger.INSTANCE.internalServiceError(t, primaryRegistration.getName());
}
}
}
private class DependencyFailedTask implements Runnable {
private final Dependent[] dependents;
DependencyFailedTask(final Dependent[] dependents) {
this.dependents = dependents;
}
public void run() {
try {
for (Dependent dependent : dependents) {
if (dependent != null) dependent.dependencyFailed();
}
final Runnable[] tasks;
synchronized (ServiceInstanceImpl.this) {
asyncTasks
tasks = transition();
}
doExecute(tasks);
} catch (Throwable t) {
ServiceLogger.INSTANCE.internalServiceError(t, primaryRegistration.getName());
}
}
}
private class DependencyRetryingTask implements Runnable {
private final Dependent[] dependents;
DependencyRetryingTask(final Dependent[] dependents) {
this.dependents = dependents;
}
public void run() {
try {
for (Dependent dependent : dependents) {
if (dependent != null) dependent.dependencyFailureCleared();
}
final Runnable[] tasks;
synchronized (ServiceInstanceImpl.this) {
asyncTasks
tasks = transition();
}
doExecute(tasks);
} catch (Throwable t) {
ServiceLogger.INSTANCE.internalServiceError(t, primaryRegistration.getName());
}
}
}
private class DependencyInstalledTask implements Runnable {
private final Dependent[] dependents;
DependencyInstalledTask(final Dependent[] dependents) {
this.dependents = dependents;
}
public void run() {
try {
for (Dependent dependent : dependents) {
if (dependent != null) dependent.dependencyInstalled();
}
final Runnable[] tasks;
synchronized (ServiceInstanceImpl.this) {
asyncTasks
tasks = transition();
}
doExecute(tasks);
} catch (Throwable t) {
ServiceLogger.INSTANCE.internalServiceError(t, primaryRegistration.getName());
}
}
}
private class DependencyUninstalledTask implements Runnable {
private final Dependent[] dependents;
DependencyUninstalledTask(final Dependent[] dependents) {
this.dependents = dependents;
}
public void run() {
try {
for (Dependent dependent : dependents) {
if (dependent != null) dependent.dependencyUninstalled();
}
final Runnable[] tasks;
synchronized (ServiceInstanceImpl.this) {
asyncTasks
tasks = transition();
}
doExecute(tasks);
} catch (Throwable t) {
ServiceLogger.INSTANCE.internalServiceError(t, primaryRegistration.getName());
}
}
}
private class InstallTask implements Runnable {
private InstallTask() {
}
public void run() {
try {
for (Dependency dependency : dependencies) {
dependency.addDependent(ServiceInstanceImpl.this);
}
final Runnable[] tasks;
synchronized (ServiceInstanceImpl.this) {
asyncTasks
tasks = transition();
}
doExecute(tasks);
} catch (Throwable t) {
ServiceLogger.INSTANCE.internalServiceError(t, primaryRegistration.getName());
}
}
}
private class RemoveTask implements Runnable {
RemoveTask() {
}
public void run() {
try {
assert getMode() == ServiceController.Mode.REMOVE;
assert getSubstate() == Substate.REMOVING;
if (failCount > 0) {
for (Dependent dependent: dependents) {
dependent.dependencyFailureCleared();
}
}
if (missingDependencyCount > 0) {
for (Dependent dependent: dependents) {
dependent.dependencyInstalled();
}
}
primaryRegistration.clearInstance(ServiceInstanceImpl.this);
for (ServiceRegistrationImpl registration : aliasRegistrations) {
registration.clearInstance(ServiceInstanceImpl.this);
}
for (Dependency dependency : dependencies) {
dependency.removeDependent(ServiceInstanceImpl.this);
}
final Runnable[] tasks;
synchronized (ServiceInstanceImpl.this) {
Arrays.fill(dependencies, null);
asyncTasks
tasks = transition();
}
doExecute(tasks);
} catch (Throwable t) {
ServiceLogger.INSTANCE.internalServiceError(t, primaryRegistration.getName());
}
}
}
private class StartContextImpl implements StartContext {
private ContextState state = ContextState.SYNC;
private final long startNanos;
private StartContextImpl(final long startNanos) {
this.startNanos = startNanos;
}
public void failed(final StartException reason) throws IllegalStateException {
final Runnable[] tasks;
synchronized (ServiceInstanceImpl.this) {
if (state != ContextState.ASYNC) {
throw new IllegalStateException(ILLEGAL_CONTROLLER_STATE);
}
state = ContextState.FAILED;
startException = reason;
failCount ++;
asyncTasks
if (ServiceContainerImpl.PROFILE_OUTPUT != null) {
writeProfileInfo('F', startNanos, System.nanoTime());
}
tasks = transition();
}
doExecute(tasks);
}
public void asynchronous() throws IllegalStateException {
synchronized (ServiceInstanceImpl.this) {
if (state == ContextState.SYNC) {
state = ContextState.ASYNC;
} else {
throw new IllegalStateException(ILLEGAL_CONTROLLER_STATE);
}
}
}
public void complete() throws IllegalStateException {
final Runnable[] tasks;
synchronized (ServiceInstanceImpl.this) {
if (state != ContextState.ASYNC) {
throw new IllegalStateException(ILLEGAL_CONTROLLER_STATE);
} else {
state = ContextState.COMPLETE;
asyncTasks
if (ServiceContainerImpl.PROFILE_OUTPUT != null) {
writeProfileInfo('S', startNanos, System.nanoTime());
}
tasks = transition();
}
}
doExecute(tasks);
}
public ServiceController<?> getController() {
return ServiceInstanceImpl.this;
}
}
private void writeProfileInfo(final char statusChar, final long startNanos, final long endNanos) {
final ServiceRegistrationImpl primaryRegistration = this.primaryRegistration;
final ServiceName name = primaryRegistration.getName();
final ServiceContainerImpl container = primaryRegistration.getContainer();
final Writer profileOutput = container.getProfileOutput();
if (profileOutput != null) {
synchronized (profileOutput) {
try {
final long startOffset = startNanos - container.getStart();
final long duration = endNanos - startNanos;
profileOutput.write(String.format("%s\t%s\t%d\t%d\n", name, Character.valueOf(statusChar), Long.valueOf(startOffset), Long.valueOf(duration)));
} catch (IOException e) {
// ignore
}
}
}
}
private class StopContextImpl implements StopContext {
private ContextState state = ContextState.SYNC;
private final long startNanos;
private StopContextImpl(final long startNanos) {
this.startNanos = startNanos;
}
public void asynchronous() throws IllegalStateException {
synchronized (ServiceInstanceImpl.this) {
if (state == ContextState.SYNC) {
state = ContextState.ASYNC;
} else {
throw new IllegalStateException(ILLEGAL_CONTROLLER_STATE);
}
}
}
public void complete() throws IllegalStateException {
synchronized (ServiceInstanceImpl.this) {
if (state != ContextState.ASYNC) {
throw new IllegalStateException(ILLEGAL_CONTROLLER_STATE);
}
state = ContextState.COMPLETE;
}
for (ValueInjection<?> injection : injections) {
injection.getTarget().uninject();
}
final Runnable[] tasks;
synchronized (ServiceInstanceImpl.this) {
asyncTasks
if (ServiceContainerImpl.PROFILE_OUTPUT != null) {
writeProfileInfo('X', startNanos, System.nanoTime());
}
tasks = transition();
}
doExecute(tasks);
}
public ServiceController<?> getController() {
return ServiceInstanceImpl.this;
}
}
enum Substate {
NEW(ServiceController.State.DOWN),
DOWN(ServiceController.State.DOWN),
START_REQUESTED(ServiceController.State.DOWN),
STARTING(ServiceController.State.STARTING),
START_FAILED(ServiceController.State.START_FAILED),
UP(ServiceController.State.UP),
STOP_REQUESTED(ServiceController.State.UP),
STOPPING(ServiceController.State.STOPPING),
REMOVING(ServiceController.State.DOWN),
REMOVED(ServiceController.State.REMOVED),
;
private final ServiceController.State state;
Substate(final ServiceController.State state) {
this.state = state;
}
public ServiceController.State getState() {
return state;
}
}
enum Transition {
START_REQUESTED_to_DOWN(Substate.START_REQUESTED, Substate.DOWN),
START_REQUESTED_to_STARTING(Substate.START_REQUESTED, Substate.STARTING),
STARTING_to_UP(Substate.STARTING, Substate.UP),
STARTING_to_START_FAILED(Substate.STARTING, Substate.START_FAILED),
START_FAILED_to_STARTING(Substate.START_FAILED, Substate.STARTING),
START_FAILED_to_DOWN(Substate.START_FAILED, Substate.DOWN),
UP_to_STOP_REQUESTED(Substate.UP, Substate.STOP_REQUESTED),
STOP_REQUESTED_to_UP(Substate.STOP_REQUESTED, Substate.UP),
STOP_REQUESTED_to_STOPPING(Substate.STOP_REQUESTED, Substate.STOPPING),
STOPPING_to_DOWN(Substate.STOPPING, Substate.DOWN),
REMOVING_to_REMOVED(Substate.REMOVING, Substate.REMOVED),
DOWN_to_REMOVING(Substate.DOWN, Substate.REMOVING),
DOWN_to_START_REQUESTED(Substate.DOWN, Substate.START_REQUESTED),
;
private final Substate before;
private final Substate after;
Transition(final Substate before, final Substate after) {
this.before = before;
this.after = after;
}
public Substate getBefore() {
return before;
}
public Substate getAfter() {
return after;
}
}
} |
package com.googlecode.objectify;
import java.lang.reflect.Field;
import com.google.appengine.api.datastore.AsyncDatastoreService;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreService.KeyRangeState;
import com.google.appengine.api.datastore.DatastoreServiceConfig;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.ReadPolicy;
import com.google.appengine.api.datastore.Transaction;
import com.google.appengine.api.datastore.TransactionOptions;
import com.googlecode.objectify.cache.CachingAsyncDatastoreService;
import com.googlecode.objectify.cache.CachingDatastoreService;
import com.googlecode.objectify.cache.EntityMemcache;
import com.googlecode.objectify.impl.AsyncObjectifyImpl;
import com.googlecode.objectify.impl.CacheControlImpl;
import com.googlecode.objectify.impl.EntityMemcacheStats;
import com.googlecode.objectify.impl.EntityMetadata;
import com.googlecode.objectify.impl.ObjectifyImpl;
import com.googlecode.objectify.impl.Registrar;
import com.googlecode.objectify.impl.SessionCachingAsyncObjectifyImpl;
import com.googlecode.objectify.impl.conv.Conversions;
import com.googlecode.objectify.impl.conv.ConverterSaveContext;
import com.googlecode.objectify.util.FutureHelper;
/**
* <p>Factory which allows us to construct implementations of the Objectify interface.
* Just call {@code begin()}.</p>
*
* <p>Note that unlike the DatastoreService, there is no implicit transaction management.
* You either create an Objectify without a transaction (by calling {@code begin()} or you
* create one with a transaction (by calling {@code beginTransaction()}. If you create
* an Objectify with a transaction, you should use it like this:</p>
* <code><pre>
* Objectify data = factory.beginTransaction()
* try {
* // do work
* data.getTxn().commit();
* }
* finally {
* if (data.getTxn().isActive()) data.getTxn().rollback();
* }
* </pre></code>
*
* <p>It would be fairly easy for someone to implement a ScanningObjectifyFactory
* on top of this class that looks for @Entity annotations based on Scannotation or
* Reflections, but this would add extra dependency jars and need a hook for
* application startup.</p>
*
* @author Jeff Schnitzer <jeff@infohazard.org>
*/
public class ObjectifyFactory
{
/** Default memcache namespace; override getRawMemcacheService() to change */
public static final String MEMCACHE_NAMESPACE = "ObjectifyCache";
/** Encapsulates entity registration info */
protected Registrar registrar = new Registrar(this);
/** All the various converters */
protected Conversions conversions = new Conversions(this);
/** Tracks stats */
protected EntityMemcacheStats memcacheStats = new EntityMemcacheStats();
/** Manages caching of entities at a low level */
protected EntityMemcache entityMemcache = new EntityMemcache(MEMCACHE_NAMESPACE, new CacheControlImpl(this), this.memcacheStats);
/**
* Creates the default options for begin() and beginTransaction(). You can
* override this if, for example, you wanted to enable session caching by default.
*/
protected ObjectifyOpts createDefaultOpts()
{
return new ObjectifyOpts();
}
/**
* Override this in your factory if you wish to use a different impl, say,
* one based on the ObjectifyWrapper.
*
* @param ds the DatastoreService
* @param opts the options for creating this Objectify
* @return an instance of Objectify configured appropriately
*/
protected Objectify createObjectify(AsyncDatastoreService ds, ObjectifyOpts opts)
{
TransactionOptions txnOpts = opts.getTransactionOptions();
Transaction txn = (txnOpts == null) ? null : FutureHelper.quietGet(ds.beginTransaction(txnOpts));
Objectify ofy = (opts.getSessionCache())
? new ObjectifyImpl(opts, new SessionCachingAsyncObjectifyImpl(this, ds, txn))
: new ObjectifyImpl(opts, new AsyncObjectifyImpl(this, ds, txn));
return ofy;
}
/**
* Make a datastore service config that corresponds to the specified options.
* Note that not all options are defined by the config; some options (e.g. caching)
* have no analogue in the native datastore.
*/
protected DatastoreServiceConfig makeConfig(ObjectifyOpts opts)
{
DatastoreServiceConfig cfg = DatastoreServiceConfig.Builder.withReadPolicy(new ReadPolicy(opts.getConsistency()));
if (opts.getDeadline() != null)
cfg.deadline(opts.getDeadline());
return cfg;
}
/**
* Get a DatastoreService facade appropriate to the options. Note that
* Objectify does not itself use DatastoreService; this method solely
* exists to support Objectify.getDatastore().
*
* @return a DatastoreService configured per the specified options.
*/
public DatastoreService getDatastoreService(ObjectifyOpts opts)
{
DatastoreServiceConfig cfg = this.makeConfig(opts);
DatastoreService ds = this.getRawDatastoreService(cfg);
if (opts.getGlobalCache() && this.registrar.isCacheEnabled())
{
CachingAsyncDatastoreService async = new CachingAsyncDatastoreService(this.getRawAsyncDatastoreService(cfg), this.entityMemcache);
return new CachingDatastoreService(ds, async);
}
else
{
return ds;
}
}
/**
* Get an AsyncDatastoreService facade appropriate to the options. All Objectify
* datastore interaction goes through an AsyncDatastoreService, even the synchronous
* methods. The GAE SDK works the same way; DatastoreService is a facade around
* AsyncDatastoreService.
*
* @return an AsyncDatastoreService configured per the specified options.
*/
public AsyncDatastoreService getAsyncDatastoreService(ObjectifyOpts opts)
{
DatastoreServiceConfig cfg = this.makeConfig(opts);
AsyncDatastoreService ads = this.getRawAsyncDatastoreService(cfg);
if (opts.getGlobalCache() && this.registrar.isCacheEnabled())
return new CachingAsyncDatastoreService(ads, this.entityMemcache);
else
return ads;
}
/**
* You can override this to add behavior at the raw datastoreservice level.
*/
protected DatastoreService getRawDatastoreService(DatastoreServiceConfig cfg)
{
return DatastoreServiceFactory.getDatastoreService(cfg);
}
/**
* You can override this to add behavior at the raw datastoreservice level.
*/
protected AsyncDatastoreService getRawAsyncDatastoreService(DatastoreServiceConfig cfg)
{
return DatastoreServiceFactory.getAsyncDatastoreService(cfg);
}
/**
* Create a lightweight Objectify instance with the default options.
* Equivalent to begin(new ObjectifyOpts()).
*/
public Objectify begin()
{
return this.begin(this.createDefaultOpts());
}
/**
* @return an Objectify from the DatastoreService with the specified options.
* This is a lightweight operation and can be used freely.
*/
public Objectify begin(ObjectifyOpts opts)
{
AsyncDatastoreService ds = this.getAsyncDatastoreService(opts);
return this.createObjectify(ds, opts);
}
/**
* @return an Objectify which uses a transaction. The transaction supports cross-group access, but
* this has no extra overhead for a single-entity-group transaction.
*/
public Objectify beginTransaction()
{
return this.begin(this.createDefaultOpts().setBeginTransaction(true));
}
/**
* <p>All POJO entity classes which are to be managed by Objectify
* must be registered first. This method must be called in a single-threaded
* mode sometime around application initialization.</p>
*/
public <T> void register(Class<T> clazz)
{
this.registrar.register(clazz);
}
/**
* Get the object that tracks memcache stats.
*/
public EntityMemcacheStats getMemcacheStats() { return this.memcacheStats; }
// Stuff which should only be necessary internally, but might be useful to others.
public <T> EntityMetadata<T> getMetadata(com.google.appengine.api.datastore.Key key)
{
return this.getMetadata(key.getKind());
}
public <T> EntityMetadata<T> getMetadata(Key<T> key)
{
return this.getMetadata(key.getKind());
}
public <T> EntityMetadata<? extends T> getMetadata(Class<T> clazz)
{
EntityMetadata<T> metadata = this.registrar.getMetadata(clazz);
if (metadata == null)
throw new IllegalArgumentException("No class '" + clazz.getName() + "' was registered");
else
return metadata;
}
/**
* Gets metadata for the specified kind, or throws an exception if the kind is unknown
*/
public <T> EntityMetadata<T> getMetadata(String kind)
{
EntityMetadata<T> metadata = this.registrar.getMetadata(kind);
if (metadata == null)
throw new IllegalArgumentException("No class with kind '" + kind + "' was registered");
else
return metadata;
}
@SuppressWarnings("unchecked")
public <T> EntityMetadata<T> getMetadataForEntity(T obj)
{
// Type erasure sucks ass
return (EntityMetadata<T>)this.getMetadata(obj.getClass());
}
@SuppressWarnings("unchecked")
public <T> Key<T> getKey(Object keyOrEntity)
{
if (keyOrEntity instanceof Key<?>)
return (Key<T>)keyOrEntity;
else if (keyOrEntity instanceof com.google.appengine.api.datastore.Key)
return new Key<T>((com.google.appengine.api.datastore.Key)keyOrEntity);
else
return new Key<T>(this.getMetadataForEntity(keyOrEntity).getRawKey(keyOrEntity));
}
public com.google.appengine.api.datastore.Key getRawKey(Object keyOrEntity)
{
if (keyOrEntity instanceof com.google.appengine.api.datastore.Key)
return (com.google.appengine.api.datastore.Key)keyOrEntity;
else if (keyOrEntity instanceof Key<?>)
return ((Key<?>)keyOrEntity).getRaw();
else
return this.getMetadataForEntity(keyOrEntity).getRawKey(keyOrEntity);
}
/** This is used just for makeFilterable() */
private static final ConverterSaveContext NO_CONTEXT = new ConverterSaveContext() {
@Override public boolean inEmbeddedCollection() { return false; }
@Override public Field getField() { return null; }
};
/**
* Translate Key<?> or Entity objects into something that can be used in a filter clause.
* Anything unknown (including null) is simply returned as-is and we hope that the filter works.
*
* @return whatever can be put into a filter clause.
*/
public Object makeFilterable(Object keyOrEntityOrOther)
{
if (keyOrEntityOrOther == null)
return null;
// Very important that we use the class rather than the Kind; many unregistered
// classes would otherwise collide with real kinds eg User vs User.
EntityMetadata<?> meta = this.registrar.getMetadata(keyOrEntityOrOther.getClass());
if (meta == null)
return this.getConversions().forDatastore(keyOrEntityOrOther, NO_CONTEXT);
else
return meta.getRawKey(keyOrEntityOrOther);
}
/**
* <p>Converts a Key<?> into a web-safe string suitable for http parameters
* in URLs. Note that you can convert back and forth with the {@code keyToString()}
* and {@code stringToKey()} methods.</p>
*
* <p>The String is actually generated by using the KeyFactory {@code keyToString()}
* method on a raw version of the datastore key. You can, if you wanted, use
* these web safe strings interchangeably.</p>
*
* @param key is any Objectify key
* @return a simple String which does not need urlencoding
*/
public String keyToString(Key<?> key)
{
return KeyFactory.keyToString(key.getRaw());
}
/**
* Converts a String generated with {@code keyToString()} back into an Objectify
* Key. The String could also have been generated by the GAE {@code KeyFactory}.
*
* @param stringifiedKey is generated by either {@code ObjectifyFactory.keyToString()} or
* {@code KeyFactory.keyToString()}.
* @return a Key<?>
*/
public <T> Key<T> stringToKey(String stringifiedKey)
{
return new Key<T>(KeyFactory.stringToKey(stringifiedKey));
}
/**
* Allocates a single id from the allocator for the specified kind. Safe to use in concert
* with the automatic generator. This is just a convenience method for allocateIds().
*
* @param clazz must be a registered entity class with a Long or long id field.
*/
public <T> long allocateId(Class<T> clazz)
{
return allocateIds(clazz, 1).iterator().next().getId();
}
/**
* Allocates a single id from the allocator for the specified kind. Safe to use in concert
* with the automatic generator. This is just a convenience method for allocateIds().
*
* Note that the id is only unique within the parent, not across the entire kind.
*
* @param parentKeyOrEntity must be a legitimate parent for the class type. It need not
* point to an existent entity, but it must be the correct type for clazz.
* @param clazz must be a registered entity class with a Long or long id field, and
* a parent key of the correct type.
*/
public <T> long allocateId(Object parentKeyOrEntity, Class<T> clazz)
{
return allocateIds(parentKeyOrEntity, clazz, 1).iterator().next().getId();
}
/**
* Preallocate a contiguous range of unique ids within the namespace of the
* specified entity class. These ids can be used in concert with the normal
* automatic allocation of ids when put()ing entities with null Long id fields.
*
* @param clazz must be a registered entity class with a Long or long id field.
* @param num must be >= 1 and <= 1 billion
*/
public <T> KeyRange<T> allocateIds(Class<T> clazz, long num)
{
// Feels a little weird going directly to the DatastoreServiceFactory but the
// allocateIds() method really is optionless.
String kind = Key.getKind(clazz);
return new KeyRange<T>(DatastoreServiceFactory.getDatastoreService().allocateIds(kind, num));
}
/**
* Preallocate a contiguous range of unique ids within the namespace of the
* specified entity class and the parent key. These ids can be used in concert with the normal
* automatic allocation of ids when put()ing entities with null Long id fields.
*
* @param parentKeyOrEntity must be a legitimate parent for the class type. It need not
* point to an existent entity, but it must be the correct type for clazz.
* @param clazz must be a registered entity class with a Long or long id field, and
* a parent key of the correct type.
* @param num must be >= 1 and <= 1 billion
*/
public <T> KeyRange<T> allocateIds(Object parentKeyOrEntity, Class<T> clazz, long num)
{
Key<?> parent = this.getKey(parentKeyOrEntity);
String kind = Key.getKind(clazz);
// Feels a little weird going directly to the DatastoreServiceFactory but the
// allocateIds() method really is optionless.
return new KeyRange<T>(DatastoreServiceFactory.getDatastoreService().allocateIds(parent.getRaw(), kind, num));
}
/**
* Allocates a user-specified contiguous range of unique IDs, preventing the allocator from
* giving them out to entities (with autogeneration) or other calls to allocate methods.
* This lets you specify a specific range to block out (for example, you are bulk-loading a
* collection of pre-existing entities). If you don't care about what id is allocated, use
* one of the other allocate methods.
*/
public <T> KeyRangeState allocateIdRange(KeyRange<T> range)
{
return DatastoreServiceFactory.getDatastoreService().allocateIdRange(range.getRaw());
}
/**
* @return the repository of Converter objects
*/
public Conversions getConversions()
{
return this.conversions;
}
} |
package com.thales.window.deckView;
import com.thales.model.Manifest;
import com.thales.window.deckView.CargoView.CargoView;
import com.thales.window.deckView.CargoView.ItemView;
import com.thales.window.deckView.color.DestinationColorFactory;
import com.thales.window.deckView.color.IColorFactory;
import javafx.scene.DepthTest;
import javafx.scene.Group;
import javafx.scene.PerspectiveCamera;
import javafx.scene.SubScene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.paint.PhongMaterial;
import javafx.scene.shape.Box;
import java.util.ArrayList;
import java.util.List;
public class DeckView extends Pane
{
private static final double CAMERA_INITIAL_DISTANCE = -10000;
private static final double CAMERA_INITIAL_X_ANGLE = 0;
private static final double CAMERA_INITIAL_Y_ANGLE = 0;
private static final double CAMERA_INITIAL_Z_ANGLE = 90;
private static final double CAMERA_NEAR_CLIP = 0.1;
private static final double CAMERA_FAR_CLIP = 10000.0;
final PerspectiveCamera camera = new PerspectiveCamera(true);
final Xform cameraXform = new Xform();
final Xform cameraXform2 = new Xform();
final Xform cameraXform3 = new Xform();
final Xform axisGroup = new Xform();
final Xform world = new Xform();
final Group root = new Group();
final Xform axis = new Axis(10000);
final VesselView vesselView = new VesselView();
final Delta dragDelta = new Delta();
final Xform grid = new Grid(14000, 10000, 100, 100);
private Manifest lastUpdated = null;
CargoView cargoView;
private IColorFactory<?> colorFactory = new DestinationColorFactory();
private boolean setNewDelta = true;
final Arrow arrow = new Arrow();
public DeckView()
{
setMaxWidth(1600);
cargoView = new CargoView();
world.getChildren().addAll(axis, grid, vesselView, cargoView, arrow);
// vesselView.setVisible(false);
grid.setVisible(false);
axis.setVisible(false);
buildCamera();
arrow.setTranslateZ(40);
vesselView.setTranslateZ(40);
grid.setTranslateZ(20);
double vesselWidth = vesselView.getLayoutBounds().getWidth();
double vesselHeight = vesselView.getLayoutBounds().getHeight();
double arrowHeight = arrow.getLayoutBounds().getHeight();
arrow.setTranslateY(-vesselHeight / 2 - 30 - arrowHeight/2);
// vesselView.setTranslate(vesselWidth / 2 + 50, -vesselHeight / 2 - 50);
cargoView.setTranslate(-vesselWidth / 2 + 50, (vesselHeight / 2) - 50);
root.getChildren().add(world);
root.setDepthTest(DepthTest.ENABLE);
SubScene subScene = new SubScene(root, 1400, 1200);
subScene.setCamera(camera);
getChildren().add(subScene);
setSceneEvents();
}
public void setColourFactory(IColorFactory<?> colourFactory){
this.colorFactory = colourFactory;
if (lastUpdated != null) {
updateDeck(lastUpdated);
}
}
private void buildAxes() {
System.out.println("buildAxes()");
final PhongMaterial redMaterial = new PhongMaterial();
redMaterial.setDiffuseColor(Color.DARKRED);
redMaterial.setSpecularColor(Color.RED);
final PhongMaterial greenMaterial = new PhongMaterial();
greenMaterial.setDiffuseColor(Color.DARKGREEN);
greenMaterial.setSpecularColor(Color.GREEN);
final PhongMaterial blueMaterial = new PhongMaterial();
blueMaterial.setDiffuseColor(Color.DARKBLUE);
blueMaterial.setSpecularColor(Color.BLUE);
final Box xAxis = new Box(250, 1, 1);
final Box yAxis = new Box(1, 250, 1);
final Box zAxis = new Box(1, 1, 250);
xAxis.setMaterial(redMaterial);
yAxis.setMaterial(greenMaterial);
zAxis.setMaterial(blueMaterial);
axisGroup.getChildren().addAll(xAxis, yAxis, zAxis);
axisGroup.setVisible(true);
world.getChildren().addAll(axisGroup);
}
private void buildCamera() {
root.getChildren().add(cameraXform);
cameraXform.getChildren().add(cameraXform2);
cameraXform2.getChildren().add(cameraXform3);
cameraXform3.getChildren().add(camera);
cameraXform3.setRotateZ(180.0);
camera.setNearClip(CAMERA_NEAR_CLIP);
camera.setFarClip(CAMERA_FAR_CLIP);
camera.setTranslateZ(CAMERA_INITIAL_DISTANCE);
cameraXform.ry.setAngle(CAMERA_INITIAL_Y_ANGLE);
cameraXform.rx.setAngle(CAMERA_INITIAL_X_ANGLE);
cameraXform.rz.setAngle(CAMERA_INITIAL_Z_ANGLE);
}
private void setSceneEvents() {
//handles mouse scrolling
this.setOnScroll(
event -> {
double zoomValue = camera.getTranslateZ() + event.getDeltaY() * 5;
if (zoomValue > -200) {
zoomValue = -200;
} else if (zoomValue < -10000) {
zoomValue = -10000;
}
camera.setTranslateZ(zoomValue);
event.consume();
});
this.setOnMousePressed((dragover) ->
{
setNewDelta = true;
dragover.consume();
});
this.setOnMouseDragged(dragEvent ->
{
if (setNewDelta) {
dragDelta.x = camera.getLayoutX() - dragEvent.getSceneX();
dragDelta.y = camera.getLayoutY() - dragEvent.getSceneY();
setNewDelta = false;
}
camera.setLayoutX(dragEvent.getSceneX() + dragDelta.x);
camera.setLayoutY(dragEvent.getSceneY() + dragDelta.y);
dragEvent.consume();
});
}
class Delta {
double x, y; }
public void updateDeck(Manifest m)
{
lastUpdated = m;
int maxWidth = m.getVessel().getDimension().width;
int maxHeight = m.getVessel().getDimension().height;
List<List<ItemView>> list = new ArrayList<>();
for(int i = 0; i < maxWidth; i++)
{
List<ItemView> row = new ArrayList<>();
for(int j = 0; j < maxHeight; j++)
{
ItemView itemView = new ItemView(m.getPosition(i, j));
itemView.setMaterial(new PhongMaterial(colorFactory.getColor(itemView)));
row.add(itemView);
}
list.add(row);
}
cargoView.update(list);
}
} |
package com.wandrell.velocity.tool;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.velocity.tools.config.DefaultKey;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Tag;
import com.google.common.collect.Iterables;
@DefaultKey("htmlTool")
public final class HTMLUtil {
/**
* Returns the result from recursively splitting an {@code Element} based in
* the specified separators.
* <p>
* The recursion will be used for hunting down the separators. If a child
* {@code Element} is one of the separators, the root will be split there
* and then the next of the roots children will be checked. Otherwise the
* child's children will be checked in search of the separators.
* <p>
* Note that the way the separator is handled is marked by the
* {@code separatorStrategy} argument. If it is {@code AFTER}, then the
* separator will be added to the partition after the separator, if it is
* {@code BEFORE} it will be added to the partition before the separator,
* and if it is {@code NONE} it won't be added to the partitions.
*
* @param root
* {@code Element} to split
* @param separators
* separators used for the splitting
* @param separatorStrategy
* indicates the position where the split element will be added
* @return the root divided into several partitions
*/
private static final Collection<Collection<Element>> split(
final Element root, final Collection<Element> separators,
final Position separatorStrategy) {
final Collection<Collection<Element>> partitions; // Root partitions
Collection<Collection<Element>> childPartitions; // Child partitions
Collection<Element> firstPartition; // First partition of a child
Collection<Element> newPartition; // Newly created partition
Collection<Element> grandchildren; // All of a child children
partitions = new LinkedList<Collection<Element>>();
partitions.add(new LinkedList<Element>());
for (final Element child : root.children()) {
if (separators.contains(child)) {
// The child is a separator
// This point will be used for a split, and this recursion
// branch ends
if (separatorStrategy == Position.BEFORE) {
// Add child to the last partition
Iterables.getLast(partitions).add(child);
}
// Add an empty new partition
newPartition = new LinkedList<Element>();
partitions.add(newPartition);
if (separatorStrategy == Position.AFTER) {
// Add child to the new partition
newPartition.add(child);
}
} else {
// The child is not a separator
// The child's children will be checked in search of a
// separator, starting the recursion
childPartitions = split(child, separators, separatorStrategy);
// Add child to the last partition
Iterables.getLast(partitions).add(child);
if (childPartitions.size() > 1) {
// The child has been split into several partitions
grandchildren = child.children();
firstPartition = Iterables.getFirst(childPartitions,
new LinkedList<Element>());
// Removes all the elements which are not in the first
// partition
grandchildren.removeAll(firstPartition);
for (final Element removeChild : grandchildren) {
removeChild.remove();
}
// Add the remaining partitions
for (final Collection<Element> nextPartition : new LinkedList<Collection<Element>>(
childPartitions).subList(1,
childPartitions.size())) {
partitions.add(nextPartition);
}
}
}
}
return partitions;
}
/**
* Transforms a collection of {@code Element} entities to HTML.
*
* @param elements
* the elements from which the HTML code will be created
* @return HTML code created from the elements
*/
private static final String toHtml(final Collection<Element> elements) {
final Element root; // Root for aggregating the elements
final String html; // Returned HTML
switch (elements.size()) {
case 0:
html = "";
break;
case 1:
html = elements.iterator().next().outerHtml();
break;
default:
// The elements are aggregated into a <div> which will be
// removed afterwards
root = new Element(Tag.valueOf("div"), "");
for (final Element elem : elements) {
root.appendChild(elem);
}
// Returns the HTML code inside the div
html = root.html();
break;
}
return html;
}
/**
* Constructs an instance of the {@code HtmlTool}.
*/
public HTMLUtil() {
super();
}
/**
* Modifies HTML code, adding the specified classes to the selected
* elements.
* <p>
* The selector is a CSS selector code, such as {@code table.bodyTable},
* which identifies the elements to edit. These will be modified, adding all
* the classes on classNames to their classes.
* <p>
* The modified HTML code will be returned by the method, which won't change
* the received content.
*
* @param content
* HTML content to modify
* @param selector
* CSS selector for elements to add classes to
* @param classNames
* Names of classes to add to the selected elements
* @return HTML content with the modified elements. If no elements are
* found, the original content is returned.
*/
public final String addClass(final String content, final String selector,
final Collection<String> classNames) {
final Collection<Element> elements; // All elements selected
final Element body; // Element parsed from the content
final String html; // Modified HTML code
checkNotNull(content, "Received a null pointer as content");
checkNotNull(selector, "Received a null pointer as selector");
checkNotNull(classNames, "Received a null pointer as class names");
body = getBodyContents(content);
elements = body.select(selector);
if (elements.isEmpty()) {
// Nothing to update
html = content;
} else {
for (final Element element : elements) {
for (final String className : classNames) {
element.addClass(className);
}
}
html = body.html();
}
return html;
}
/**
* Modifies HTML code, adding the specified class to the selected elements.
* <p>
* The selector is a CSS selector code, such as {@code table.bodyTable},
* which identifies the elements to edit. These will be modified, adding the
* class on className to their classes.
* <p>
* The modified HTML code will be returned by the method, which won't change
* the received content.
*
* @param content
* HTML content to modify
* @param selector
* CSS selector for elements to add the class to
* @param className
* Name of class to add to the selected elements
* @return HTML content with the modified elements.
*/
public final String addClass(final String content, final String selector,
final String className) {
return addClass(content, selector,
Collections.singletonList(className));
}
/**
* Corrects code divisions, by both correction the elements order, and by
* swapping code classes for the {@code <code>} block.
* <p>
* Maven sites handle code blocks in an outdated fashion, and look like
* this:
*
* <pre>
* {@code <div class="source">
* <pre>Some code
</pre>
* </div>}
* </pre>
* This method fixes them, transforming them into:
*
* <pre>
* {@code <pre>
* <source>Some code</source>
*
</pre>
}
* </pre>
*
* @param content
* HTML content to fix
* @return HTML content, with the source blocks updated
*/
public final String fixCodeBlock(final String content) {
final Collection<Element> codeDivs; // Code divisions
final Element body; // Element parsed from the content
String html; // Fixed html
Element pre; // <pre> element
Element code; // <code> element
body = getBodyContents(content);
codeDivs = body.select(".source:has(pre)");
if (codeDivs.isEmpty()) {
html = content;
} else {
for (final Element div : codeDivs) {
pre = div.getElementsByTag("pre").get(0);
code = new Element(Tag.valueOf("code"), "");
code.text(div.text());
pre.text("");
pre.appendChild(code);
div.replaceWith(pre);
}
html = body.html();
}
return html;
}
/**
* Corrects source divisions by removing redundant apparitions of it.
* <p>
* It is a problem with Maven sites that code divisions get wrapped by
* another code division, so they appear like this:
*
* <pre>
* {@code <div class="source">
* <div class="source">
* <pre>Some code
</pre>
* </div>
* </div>}
* </pre>
* This method fixes that, by removing the outer division.
*
* @param content
* HTML content to fix
* @return HTML content, with the redundant source classes removed
*/
public final String fixRepeatedSourceDiv(final String content) {
final Collection<Element> codeDivs; // Repeated code divs
final Element body; // Element parsed from the content
final String html; // Fixed html
Element validDiv; // Fixed code block
body = getBodyContents(content);
codeDivs = body.select(".source:has(.source)");
if (codeDivs.isEmpty()) {
html = content;
} else {
for (final Element div : codeDivs) {
if (!div.children().isEmpty()) {
validDiv = div.child(0);
validDiv.remove();
div.replaceWith(validDiv);
}
}
html = body.html();
}
return html;
}
public final String fixTableHeads(final String content) {
final Collection<Element> tableHeadRows; // Heads to fix
final Element body; // Element parsed from the content
final String html; // Fixed html
Element table; // HTML table
Element thead; // Table's head for wrapping
checkNotNull(content, "Received a null pointer as content");
body = getBodyContents(content);
// Selects rows with <th> tags within a <tr> in a <tbody>
tableHeadRows = body.select("table > tbody > tr:has(th)");
if (tableHeadRows.isEmpty()) {
// No table heads to fix
html = content;
} else {
for (final Element row : tableHeadRows) {
// Gets the row's table
table = row.parent().parent();
// Removes the row from its original position
row.remove();
// Creates a table header element with the row
thead = new Element(Tag.valueOf("thead"), "");
thead.appendChild(row);
// Adds the head at the beginning of the table
table.prependChild(thead);
}
html = body.html();
}
return html;
}
/**
* Returns the values for an attribute on a selected element.
* <p>
* The element is selected by using a CSS selector.
*
* @param content
* HTML where the element will be searched
* @param selector
* CSS selector for the elements to query
* @param attributeKey
* Attribute name
* @return Attribute values for all the matching elements. If no elements
* are found, an empty list is returned.
*/
public final Collection<String> getAttr(final String content,
final String selector, final String attributeKey) {
final Collection<Element> elements; // Selected elements
final Collection<String> attrs; // Queried attributes
final Element body; // Element parsed from the content
checkNotNull(content, "Received a null pointer as content");
checkNotNull(selector, "Received a null pointer as selector");
checkNotNull(attributeKey, "Received a null pointer as attribute key");
body = getBodyContents(content);
elements = body.select(selector);
attrs = new ArrayList<String>();
for (final Element element : elements) {
attrs.add(element.attr(attributeKey));
}
return attrs;
}
/**
* Removes selected elements from the HTML content.
* <p>
* The elements are selected through the use of a CSS selector.
*
* @param content
* HTML content to modify
* @param selector
* CSS selector for elements to remove
* @return HTML content without the removed elements. If no elements are
* found, the original content is returned.
*/
public final String remove(final String content, final String selector) {
final Collection<Element> elements; // Elements to remove
final Element body; // Element parsed from the content
final String html; // Resulting HTML
checkNotNull(content, "Received a null pointer as content");
checkNotNull(selector, "Received a null pointer as selector");
body = getBodyContents(content);
elements = body.select(selector);
if (elements.isEmpty()) {
// Nothing changed
html = content;
} else {
for (final Element element : elements) {
element.remove();
}
html = body.html();
}
return html;
}
/**
* Replaces a collection of HTML elements.
* <p>
* These elements are received as a {@code Map}, made up of pairs where the
* key is a CSS selector, and the value is the replacement for the selected
* element.
*
* @param content
* HTML content to modify
* @param replacements
* {@code Map} where the key is a CSS selector and the value the
* element's replacement
* @return HTML content with replaced elements. If no elements are found,
* the original content is returned.
*/
public final String replaceAll(final String content,
final Map<String, String> replacements) {
final Element body; // Element parsed from the content
final String html; // Resulting HTML
Boolean modified; // Flag indicating if the HTML has been modified
String selector; // Iterated selector
String replacement; // Iterated HTML replacement
Element replacementElem; // Iterated replacement
Collection<Element> elements; // Selected elements
checkNotNull(content, "Received a null pointer as content");
checkNotNull(replacements, "Received a null pointer as replacements");
body = getBodyContents(content);
modified = false;
for (final Entry<String, String> replacementEntry : replacements
.entrySet()) {
selector = replacementEntry.getKey();
replacement = replacementEntry.getValue();
elements = body.select(selector);
if (!elements.isEmpty()) {
// Take the first child
replacementElem = getBodyContents(replacement).child(0);
if (replacementElem != null) {
for (final Element element : elements) {
element.replaceWith(replacementElem.clone());
}
modified = true;
}
}
}
if (modified) {
html = body.html();
} else {
// Nothing changed
html = content;
}
return html;
}
/**
* Sets the attribute on a selected element to the specified value.
*
* @param content
* HTML content to set attributes on
* @param selector
* CSS selector for elements to modify
* @param attributeKey
* Attribute name
* @param value
* Attribute value
* @return HTML content with the modified elements. If no elements are
* found, the original content is returned.
*/
public final String setAttr(final String content, final String selector,
final String attributeKey, final String value) {
final Collection<Element> elements; // Selected elements
final Element body; // Element parsed from the content
final String html; // Resulting HTML
checkNotNull(content, "Received a null pointer as content");
checkNotNull(selector, "Received a null pointer as selector");
checkNotNull(attributeKey, "Received a null pointer as attribute key");
checkNotNull(value, "Received a null pointer as value");
body = getBodyContents(content);
elements = body.select(selector);
if (elements.isEmpty()) {
// Nothing to update
html = content;
} else {
for (final Element element : elements) {
element.attr(attributeKey, value);
}
html = body.html();
}
return html;
}
/**
* Returns the received HTML split into partitions, based on the given
* separator selector. The separators themselves are dropped from the
* results.
* <p>
* If splitting an element breaks it, it will be fixed by taking all the
* children elements out of if.
* <p>
* For example, if the following is split at the {@code
*
<hr>
* }:
*
* <pre>
* {@code <div>
* <p>First paragraph</p>
* <hr>
* <p>Second paragraph</p>
*</div>}
* </pre>
*
* Then the result will be two groups, one will be:
*
* <pre>
* {@code <div>
* <p>First paragraph</p>
*</div>}
* </pre>
*
* While the other will be:
*
* <pre>
* {@code <p>Second paragraph</p>}
* </pre>
*
* @param content
* HTML content to split
* @param selector
* CSS selector for the separators.
* @return the HTML split into section, and without the separators
*/
public final Collection<String> split(final String content,
final String selector) {
return split(content, selector, Position.NONE);
}
/**
* Splits the given HTML content into partitions, each starting with the
* given separator selector. The separators are kept as the first element of
* each partition.
* <p>
* Note that if the split is successful the first part will be removed, as
* it will be before the first selector.
*
* @param content
* HTML content to split
* @param selector
* CSS selector for separators
* @return the HTML split into sections, each beginning with a separator
*/
public final Collection<String> splitOnStart(final String content,
final String selector) {
final Collection<String> split; // HTML after being split
final Collection<String> result; // The final sections
checkNotNull(content, "Received a null pointer as content");
checkNotNull(selector,
"Received a null pointer as separator CSS selector");
// Splitting. The result will have to be checked.
split = split(content, selector, Position.AFTER);
if (split.size() <= 1) {
// No result or just one part. Return what we have.
result = split;
} else {
// The first section will have to be removed, as it is before the
// first section.
// For example, if the HTML was split based on headings, then the
// first section will contain the code before the first heading.
result = new LinkedList<String>(split).subList(1, split.size());
}
return result;
}
/**
* Transforms images on the body to figures.
* <p>
* This will wrap {@code <image>} elements with a {@code <figure>} element,
* and add a {@code <figcaption>} with the contents of the image's
* {@code alt} attribute, if it has said attribute.
*
* @param content
* HTML content to transform
* @return HTML content, with the body image wrapped in figures.
*/
public final String transformImagesToFigures(final String content) {
final Collection<Element> images; // Image elements from the <body>
final Element body; // Element parsed from the content
String html; // Fixed html
Element figure; // <figure> element
Element caption; // <figcaption> element
body = getBodyContents(content);
images = body.select("img");
if (images.isEmpty()) {
html = content;
} else {
for (final Element img : images) {
figure = new Element(Tag.valueOf("figure"), "");
caption = new Element(Tag.valueOf("figcaption"), "");
img.replaceWith(figure);
figure.appendChild(img);
if (img.hasAttr("alt")) {
caption.text(img.attr("alt"));
figure.appendChild(caption);
}
}
html = body.html();
}
return html;
}
/**
* Returns the HTML code with the elements marked by the selector wrapped on
* the received element.
* <p>
* The method will find all the elements fitting into the selector, and then
* wrap them with the wrapper element. The HTML code will then be adapted to
* this change and returned.
*
* @param content
* HTML content to modify
* @param selector
* CSS selector for elements to wrap
* @param wrapper
* HTML to use for wrapping the selected elements
* @return HTML with the selected elements wrapped with the wrapper element
*/
public final String wrap(final String content, final String selector,
final String wrapper) {
final Collection<Element> elements; // Selected elements
final Element body; // Element parsed from the content
final String html; // Modified HTML
checkNotNull(content, "Received a null pointer as content");
checkNotNull(selector, "Received a null pointer as selector");
checkNotNull(wrapper, "Received a null pointer as HTML wrap");
body = getBodyContents(content);
elements = body.select(selector);
if (elements.isEmpty()) {
// Nothing to update
html = content;
} else {
for (final Element element : elements) {
element.wrap(wrapper);
}
html = body.html();
}
return html;
}
/**
* Parses the HTML into a jsoup {@code Element}, which will contain only the
* data on the {@code <body>} section.
*
* @param html
* the html code of which to get the {@code <body>} contents
* @return the content of the {@code <body>} element of the HTML code
*/
private final Element getBodyContents(final String html) {
return Jsoup.parseBodyFragment(html).body();
}
/**
* Returns the result from splitting the received HTML into partitions,
* based on the received CSS selector.
* <p>
* The separator strategy works as in
* {@link #split(Element, Collection, Position)}.
*
* @param content
* HTML content to split
* @param selector
* CSS selector for separators
* @param separatorStrategy
* strategy to drop or keep separators
* @return the HTML split based on the selectors
* @see #split(Element, Collection, Position)
*/
private final Collection<String> split(final String content,
final String selector, final Position separatorStrategy) {
final Collection<Collection<Element>> split; // Split HTML before
// adapting
final Collection<String> partitions; // HTML split by the separators
final Collection<Element> separators; // Found separators
final Element body; // Element parsed from the content
body = getBodyContents(content);
separators = body.select(selector);
if (separators.isEmpty()) {
// Nothing to split
partitions = Collections.singletonList(content);
} else {
split = split(body, separators, separatorStrategy);
partitions = new ArrayList<String>();
for (final Collection<Element> partition : split) {
partitions.add(toHtml(partition));
}
}
return partitions;
}
} |
package org.junit.experimental.theories;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotating an field or method with @DataPoint will cause the field value
* or the value returned by the method to be used as a potential parameter for
* theories in that class, when run with the
* {@link org.junit.experimental.theories.Theories Theories} runner.
* <p>
* A DataPoint is only considered as a potential value for parameters for
* which its type is assignable. When multiple {@code DataPoint}s exist
* with overlapping types more control can be obtained by naming each DataPoint
* using the value of this annotation, e.g. with
* <code>@DataPoint({"dataset1", "dataset2"})</code>, and then specifying
* which named set to consider as potential values for each parameter using the
* {@link org.junit.experimental.theories.FromDataPoints @FromDataPoints}
* annotation.
* <p>
* Parameters with no specified source (i.e. without @FromDataPoints or
* other {@link org.junit.experimental.theories.ParametersSuppliedBy
* @ParameterSuppliedBy} annotations) will use all {@code DataPoint}s that are
* assignable to the parameter type as potential values, including named sets of
* {@code DataPoint}s.
*
* <pre>
* @DataPoint
* public static String dataPoint = "value";
*
* @DataPoint("generated")
* public static String generatedDataPoint() {
* return "generated value";
* }
*
* @Theory
* public void theoryMethod(String param) {
* ...
* }
* </pre>
*
* @see org.junit.experimental.theories.Theories
* @see org.junit.experimental.theories.Theory
* @see org.junit.experimental.theories.DataPoint
* @see org.junit.experimental.theories.FromDataPoints
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({FIELD, METHOD})
public @interface DataPoint {
String[] value() default {};
} |
package com.ids1024.whitakerswords;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuInflater;
import android.view.inputmethod.EditorInfo;
import android.view.KeyEvent;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.EditText;
import android.widget.ToggleButton;
import android.os.Bundle;
import android.content.Intent;
public class WhitakersWords extends Activity
implements OnEditorActionListener {
/** Called when the activity is first created. */
public void copyFiles() throws IOException {
String[] filenames = {"ADDONS.LAT", "DICTFILE.GEN", "EWDSFILE.GEN",
"INDXFILE.GEN", "INFLECTS.SEC", "STEMFILE.GEN",
"UNIQUES.LAT", "words"};
for (String filename: filenames) {
// Note: Android does not accept upper case in resource names, so it is converted
// And file extensions are stripped, so remove that
String resourcename = filename.toLowerCase();
if (resourcename.contains(".")) {
resourcename = resourcename.substring(0, filename.lastIndexOf('.'));
}
int identifier = getResources().getIdentifier(resourcename, "raw", getPackageName());
InputStream ins = getResources().openRawResource(identifier);
byte[] buffer = new byte[ins.available()];
ins.read(buffer);
ins.close();
FileOutputStream fos = openFileOutput(filename, MODE_PRIVATE);
fos.write(buffer);
fos.close();
}
File wordsbin = getFileStreamPath("words");
wordsbin.setExecutable(true);
}
public String executeWords(String text, boolean fromenglish) {
String wordspath = getFilesDir().getPath() + "/words";
Process process;
try {
if (fromenglish) {
String[] command = {wordspath, "~E", text};
process = Runtime.getRuntime().exec(command, null, getFilesDir());
} else {
String[] command = {wordspath, text};
process = Runtime.getRuntime().exec(command, null, getFilesDir());
}
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
int read;
char[] buffer = new char[4096];
StringBuffer output = new StringBuffer();
while ((read = reader.read(buffer)) > 0) {
output.append(buffer, 0, read);
}
reader.close();
process.waitFor();
return output.toString();
} catch(IOException e) {
throw new RuntimeException(e.getMessage());
} catch(InterruptedException e) {
throw new RuntimeException(e.getMessage());
}
}
public void searchWord(View view) {
TextView result_text = (TextView)findViewById(R.id.result_text);
EditText search_term = (EditText)findViewById(R.id.search_term);
ToggleButton english_to_latin = (ToggleButton)findViewById(R.id.english_to_latin);
String term = search_term.getText().toString();
result_text.setText((CharSequence)executeWords(term, english_to_latin.isChecked()));
}
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
searchWord((View)v);
handled = true;
}
return handled;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
copyFiles();
} catch(IOException e) {
throw new RuntimeException(e.getMessage());
}
setContentView(R.layout.main);
EditText search_term = (EditText)findViewById(R.id.search_term);
search_term.setOnEditorActionListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_settings:
Intent intent = new Intent(this, WhitakersSettings.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
} |
package com.woawi.wx.message;
import com.woawi.wx.Environment;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpMessageHandler;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.WxMpXmlOutTextMessage;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.springframework.context.MessageSource;
import java.util.Locale;
import java.util.Map;
/**
* @author ylxia
* @version 1.0
* @package com.woawi.wx.message
* @date 15/11/25
*/
@Slf4j
public class FocusMeMessage implements WxMpMessageHandler {
@Override
public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService, WxSessionManager sessionManager) throws WxErrorException {
MessageSource source = Environment.getI18n();
String msg = source.getMessage("message.welcome", null, Locale.getDefault());
String event = StringUtils.isBlank(wxMessage.getEvent()) ? StringUtils.EMPTY : wxMessage.getEvent();
WxMpXmlOutTextMessage m = null;
if (WxConsts.EVT_SUBSCRIBE.equals(event)) {
m
= WxMpXmlOutMessage
.TEXT()
.content(msg)
.fromUser(wxMessage.getToUserName())
.toUser(wxMessage.getFromUserName())
.build();
} else if (WxConsts.EVT_UNSUBSCRIBE.equals(event)) {
}
log.info("{} ---> {}", event, ToStringBuilder.reflectionToString(wxMessage));
return m;
}
} |
package com.xqbase.apool.impl;
import com.xqbase.apool.AsyncPool;
import com.xqbase.apool.CreateLatch;
import com.xqbase.apool.LifeCycle;
import com.xqbase.apool.callback.Callback;
import com.xqbase.apool.callback.SimpleCallback;
import com.xqbase.apool.exceptions.SizeLimitExceededException;
import com.xqbase.apool.stats.PoolStats;
import com.xqbase.apool.util.Cancellable;
import com.xqbase.apool.util.LinkedDeque;
import com.xqbase.apool.util.None;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
/**
* The Async Pool Implementation.
*
* @author Tony He
*/
public class AsyncPoolImpl<T> implements AsyncPool<T> {
private static final Logger LOGGER = LoggerFactory.getLogger(AsyncPoolImpl.class);
private final String poolName;
private final int maxSize;
private final int minSize;
private final int maxWaiters;
private final long idleTimeout;
private final ScheduledExecutorService timeoutExecutor;
private volatile ScheduledFuture<?> objectTimeoutFuture;
private final LifeCycle<T> lifeCycle;
private final CreateLatch createLatch;
private final Strategy strategy;
private enum State { NOT_YET_STARTED, RUNNING, SHUTTING_DOWN, STOPPED }
public enum Strategy { LRU, MRU }
private int poolSize = 0;
private final Object lock = new Object();
private final Deque<TimedObject<T>> idle = new LinkedList<>();
private final LinkedDeque<Callback<T>> waiters = new LinkedDeque<>();
private State state = State.NOT_YET_STARTED;
private Callback<None> shutdownCallback = null;
private int totalCreated = 0;
private int totalDestroyed = 0;
private int totalCreateErrors = 0;
private int totalDestroyErrors = 0;
private int totalBadDestroyed = 0;
private int totalTimeout = 0;
private int checkedOut = 0;
public AsyncPoolImpl(String poolName, int maxSize,
int minSize, int maxWaiters,
long idleTimeout,
ScheduledExecutorService timeoutExecutor,
LifeCycle<T> lifeCycle,
CreateLatch createLatch,
Strategy strategy) {
this.poolName = poolName;
this.maxSize = maxSize;
this.minSize = minSize;
this.maxWaiters = maxWaiters;
this.idleTimeout = idleTimeout;
this.timeoutExecutor = timeoutExecutor;
this.lifeCycle = lifeCycle;
this.createLatch = createLatch;
this.strategy = strategy;
}
@Override
public String getName() {
return poolName;
}
@Override
public void start() {
synchronized (lock) {
if (state != State.NOT_YET_STARTED) {
throw new IllegalStateException(poolName + " is " + state);
}
state = State.RUNNING;
if (idleTimeout > 0) {
long freq = Math.min(idleTimeout, 1000);
objectTimeoutFuture = timeoutExecutor.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
timeoutObjects();
}
}, freq, freq, TimeUnit.MILLISECONDS);
}
}
// make the minimum required number of objects now
for (int i = 0; i < minSize; i++) {
if (shouldCreate()) {
create();
}
}
}
@Override
public Cancellable get(Callback<T> callback) {
boolean create = false;
boolean reject = false;
final LinkedDeque.Node<Callback<T>> node;
TimeTrackingCallback<T> timeTrackingCallback = new TimeTrackingCallback<>(callback);
for (;;) {
TimedObject<T> obj = null;
final State innerState;
synchronized (lock) {
innerState = state;
if (innerState == State.RUNNING) {
if (strategy == Strategy.LRU) {
obj = idle.pollFirst();
} else {
obj = idle.pollLast();
}
if (obj == null) {
if (waiters.size() < maxWaiters) {
// the object is null and the waiters queue is not full
node = waiters.addLastNode(timeTrackingCallback);
create = shouldCreate();
} else {
reject = true;
node = null;
}
break;
}
}
}
if (innerState != State.RUNNING) {
timeTrackingCallback.onError(new IllegalStateException(poolName + " is " + innerState));
return null;
}
T rawObj = obj.getObj();
if (lifeCycle.validateGet(rawObj)) {
synchronized (lock) {
checkedOut ++;
}
timeTrackingCallback.onSuccess(rawObj);
return null;
}
// The raw object is invalidate
destroy(rawObj, true);
}
if (reject) {
timeTrackingCallback.onError(new SizeLimitExceededException("APool " + poolSize + " exceeded max waiter size: " + maxWaiters));
}
if (create) {
create();
}
return new Cancellable() {
@Override
public boolean cancel() {
return waiters.removeNode(node) != null;
}
};
}
@Override
public void put(T obj) {
synchronized (lock) {
checkedOut
}
if (!lifeCycle.validatePut(obj)) {
destroy(obj, true);
return;
}
createLatch.setPeriod(0);
add(obj);
}
@Override
public void dispose(T obj) {
synchronized (lock) {
checkedOut
}
destroy(obj, true);
}
@Override
public void shutdown(Callback<None> callback) {
final State innerState;
synchronized (lock) {
innerState = state;
if (innerState == State.RUNNING) {
state = State.SHUTTING_DOWN;
shutdownCallback = callback;
}
}
if (innerState != State.RUNNING) {
callback.onError(new IllegalStateException(poolName + " is in State: " + innerState));
return;
}
shutdownIfNeeded();
}
private void shutdownIfNeeded() {
Callback<None> done = checkShutdownComplete();
if (done != null) {
finishShutdown(done);
}
}
/**
* Check whether the shutdown process is complete.
*
* @return null if incomplete.
*/
private Callback<None> checkShutdownComplete() {
Callback<None> done = null;
final State innerState;
final int waitersSize;
final int idleSize;
final int innerPoolSize;
synchronized (lock) {
innerState = state;
waitersSize = waiters.size();
idleSize = idle.size();
innerPoolSize = poolSize;
if (innerState == State.SHUTTING_DOWN && waitersSize == 0 && idleSize == innerPoolSize) {
state = State.STOPPED;
done = shutdownCallback;
shutdownCallback = null;
}
}
return done;
}
private void finishShutdown(Callback<None> finish) {
Future<?> future = objectTimeoutFuture;
if (future != null) {
future.cancel(false);
}
finish.onSuccess(None.none());
}
@Override
public PoolStats getStats() {
return null;
}
/**
* Whether another object creation should be initiated.
*
* @return true if another object create should be initiated.
*/
public boolean shouldCreate() {
boolean result = false;
synchronized (lock) {
if (state == State.RUNNING) {
if (poolSize > maxSize) {
} else if (waiters.size() > 0 || poolSize < minSize) {
poolSize ++;
result = true;
}
}
}
return result;
}
/**
* The real object creation method.
* PLEASE do not call this method while hold lock.
*/
public void create() {
createLatch.submit(new CreateLatch.Task() {
@Override
public void run(final SimpleCallback callback) {
lifeCycle.create(new Callback<T>() {
@Override
public void onError(Throwable e) {
}
@Override
public void onSuccess(T result) {
synchronized (lock) {
totalCreated ++;
}
add(result);
callback.onDone();
}
});
}
});
}
/**
* Destroy the pool object.
*
* @param obj the pool object to be destroyed.
* @param bad whether the being destroyed pool object is bad or not.
*/
private void destroy(T obj, boolean bad) {
if (bad) {
createLatch.incrementPeriod();
synchronized (lock) {
totalBadDestroyed ++;
}
}
lifeCycle.destroy(obj, bad, new Callback<T>() {
@Override
public void onError(Throwable e) {
boolean create;
synchronized (lock) {
totalDestroyErrors++;
create = objectDestroyed();
}
if (create) {
create();
}
}
@Override
public void onSuccess(T result) {
boolean create;
synchronized (lock) {
totalDestroyed++;
create = objectDestroyed();
}
if (create) {
create();
}
}
});
}
private boolean objectDestroyed() {
return objectDestroyed(1);
}
/**
* This method is safe to call while holding the lock.
*
* @param num number of objects have been destroyed.
* @return true if another pool object creation should be initiated.
*/
private boolean objectDestroyed(int num) {
boolean create;
synchronized (lock) {
if (poolSize - num > 0) {
poolSize -= num;
} else {
poolSize = 0;
}
create = shouldCreate();
}
return create;
}
/**
* Add the newly created object to the idle pool
* or directly transfer to the waiter.
*
* @param obj the newly created pool object.
*/
private void add(T obj) {
Callback<T> waiter;
synchronized (lock) {
// If we have waiters, the idle list must be empty.
waiter = waiters.poll();
if (waiter == null) {
idle.offerLast(new TimedObject<T>(obj));
} else {
checkedOut ++;
}
}
if (waiter != null) {
waiter.onSuccess(obj);
}
}
private void timeoutObjects() {
Collection<T> timeoutIdle = reap(idle, idleTimeout);
if (timeoutIdle.size() > 0) {
LOGGER.debug(poolName + " disposing " + timeoutIdle.size() + " objects due to timeout");
for (T t : timeoutIdle) {
destroy(t, false);
}
}
}
/**
* Get the queue of timeout objects.
*
* @param queue the original queue.
* @param timeout the timeout.
* @return queue of timeout objects.
*/
private <U> Collection<U> reap(Queue<TimedObject<U>> queue, long timeout) {
List<U> timeoutQueue = new ArrayList<>();
long now = System.currentTimeMillis();
long target = now - timeout;
synchronized (lock) {
int exceed = poolSize - minSize;
for (TimedObject<U> p; (p = queue.peek()) != null && p.getTime() < target && exceed > 0; exceed
timeoutQueue.add(queue.poll().getObj());
totalTimeout ++;
}
}
return timeoutQueue;
}
private static class TimedObject<T> {
private final T obj;
private final long time;
private TimedObject(T obj) {
this.obj = obj;
this.time = System.currentTimeMillis();
}
public T getObj() {
return obj;
}
public long getTime() {
return time;
}
}
private class TimeTrackingCallback<T> implements Callback<T> {
private final long startTime;
private final Callback<T> callback;
private TimeTrackingCallback(Callback<T> callback) {
this.startTime = System.currentTimeMillis();
this.callback = callback;
}
@Override
public void onError(Throwable e) {
}
@Override
public void onSuccess(T result) {
}
}
} |
package com.moeyinc.formulamorph;
import java.util.*;
import java.io.*;
import java.net.*;
import java.util.concurrent.LinkedBlockingDeque;
import javax.swing.SwingUtilities;
public class PhidgetInterface implements Parameter.ActivationStateListener
{
String host;
int port;
Socket socket;
LinkedBlockingDeque< String > outDeque = new LinkedBlockingDeque< String >();
PhidgetReaderClient phidgetReaderClient;
PhidgetWriterClient phidgetWriterClient;
private boolean shutdown = false;
static int heartbeat_ms = 1000;
public PhidgetInterface( String host, int port )
{
this.host = host;
this.port = port;
this.socket = new Socket();
try { reconnect(); } catch( IOException ioe ) { /* do nothing since PhidgetWriter will try to reconnect broken connections anyway */ }
phidgetReaderClient = new PhidgetReaderClient();
phidgetWriterClient = new PhidgetWriterClient();
for( Parameter p : Parameter.values() )
p.addActivationStateListener( this );
new Thread( new HeartBeat(), "PhidgetHeartBeat" ).start();
new Thread( phidgetReaderClient, "PhidgetReaderClient" ).start();
new Thread( phidgetWriterClient, "PhidgetWriterClient" ).start();
}
private synchronized void reconnect()
throws IOException, UnknownHostException
{
if( ! shutdown )
{
try
{
socket.close();
socket = new Socket( host, port );
socket.setKeepAlive( true );
socket.setSoTimeout( heartbeat_ms * 5 );
if( !socket.isConnected() || socket.isClosed() )
throw new IOException( "PhidgetInterface: no connection to " + host + ":" + port );
}
catch( IOException e )
{
// block for 1s to avoid calling this method
try { Thread.sleep( 1000 ); } catch( InterruptedException ie ) {}
throw e;
}
}
}
public void shutdown() throws IOException
{
shutdown = true;
try { socket.close(); } catch( IOException ioe ) {}
}
public void stateChanged( Parameter p )
{
setLEDEnabled( p, p.isActive() );
}
public void setLEDEnabled( Parameter p, boolean enabled )
{
int LED_id = -1;
switch( p )
{
case F_a: LED_id = 1; break;
case F_b: LED_id = 2; break;
case F_c: LED_id = 3; break;
case F_d: LED_id = 4; break;
case F_e: LED_id = 5; break;
case F_f: LED_id = 6; break;
case M_t: return; // do nothing
case G_a: LED_id = 7; break;
case G_b: LED_id = 8; break;
case G_c: LED_id = 9; break;
case G_d: LED_id = 10; break;
case G_e: LED_id = 11; break;
case G_f: LED_id = 12; break;
}
String cmd = "LD," + LED_id + "," + ( enabled ? '1' : '0' );
boolean done = false;
do
{
try
{
outDeque.put( cmd );
done = true;
}
catch( Exception e )
{
// retry
}
}
while( !done );
}
class PhidgetReaderClient implements Runnable
{
public void run()
{
Integer[] easterEggSequence_tmp = { 1, -1, 1, 1, -1, -1, -1, 1, 1, 1, 1, 1 }; // alternating Fibonacci sequence code (1, -1, 2, -3, 5)
List< Integer > easterEggSequencePos = new ArrayList< Integer >( Arrays.asList( easterEggSequence_tmp ) );
// second sequence is the negative version of the first one
for( int i = 0; i < easterEggSequence_tmp.length; ++i )
easterEggSequence_tmp[ i ] = -easterEggSequence_tmp[ i ];
List< Integer > easterEggSequenceNeg = new ArrayList< Integer >( Arrays.asList( easterEggSequence_tmp ) );
final EnumMap< Surface, LinkedList< Integer > > currentEasterEggSequences = new EnumMap< Surface, LinkedList< Integer > >( Surface.class );
currentEasterEggSequences.put( Surface.F, new LinkedList< Integer >( Arrays.asList( easterEggSequence_tmp ) ) );
currentEasterEggSequences.put( Surface.G, new LinkedList< Integer >( Arrays.asList( easterEggSequence_tmp ) ) );
// receive input
while( !PhidgetInterface.this.shutdown )
{
try
{
BufferedReader in = new BufferedReader( new InputStreamReader( PhidgetInterface.this.socket.getInputStream() ) );
String cmd;
while( ( cmd = in.readLine() ) != null )
{
cmd = cmd.replaceAll( "#.*$", "" ); // strip comments (everything from # to the end of the command)
cmd = cmd.replaceAll( "\\s", "" ); // strip whitespace
if( cmd.isEmpty() )
continue; // heart beat
boolean unknown_command = false;
try
{
String[] parts = cmd.split(",");
String dev = parts[ 0 ];
final int id = Integer.parseInt( parts[ 1 ] );
String[] values = Arrays.copyOfRange( parts, 2, parts.length );
if( dev.equals( "FS" ) )
{ // formula selector
if( id == 1 || id == 2 )
{
final int offset = Integer.parseInt( values[ 0 ] );
final Surface surface = id == 1 ? Surface.F : Surface.G;
// insert offset into easter egg sequence
for( int i = 0; i < Math.abs( offset ); ++i )
{
currentEasterEggSequences.get( surface ).poll();
currentEasterEggSequences.get( surface ).offer( offset > 0 ? +1 : -1 );
//System.out.println(currentEasterEggSequences.toString());
}
// test if easter egg sequences is complete
if( currentEasterEggSequences.get( surface ).equals( easterEggSequencePos ) || currentEasterEggSequences.get( surface ).equals( easterEggSequenceNeg ) )
{
// launch easter egg
SwingUtilities.invokeLater( new Runnable()
{
public void run()
{
System.out.println( "Easter egg found on " + new Date() );
Main.gui().selectEasterEggSurface( surface );
}
} );
}
else
{
SwingUtilities.invokeLater( new Runnable()
{
public void run()
{
Main.gui().nextSurface( surface, offset );
}
} );
}
}
else
{
unknown_command = true;
}
}
else if( dev.equals( "RE" ) )
{ // rotary encoder
final int relative_angle = Integer.parseInt( values[ 0 ] );
if( id > 0 && id <= 12 )
{
final Parameter[] params = {
Parameter.F_a, Parameter.F_b, Parameter.F_c, Parameter.F_d, Parameter.F_e, Parameter.F_f,
Parameter.G_a, Parameter.G_b, Parameter.G_c, Parameter.G_d, Parameter.G_e, Parameter.G_f };
final Parameter param = params[ id - 1 ];
if( param.isActive() )
{
SwingUtilities.invokeLater( new Runnable()
{
public void run()
{
param.setValue( param.getValue() + ( relative_angle / param.getSpeed() ) * param.getRange() );
}
} );
}
}
else
{
unknown_command = true;
}
}
else if( dev.equals( "JW" ) )
{ // jog wheel
final int relative_angle = Integer.parseInt( values[ 0 ] );
if( id > 0 && id <= 1 )
{
SwingUtilities.invokeLater( new Runnable()
{
public void run()
{
Main.gui().stepPath( relative_angle );
}
} );
}
else
{
unknown_command = true;
}
}
else if( dev.equals( "JS" ) )
{ // joystick
if( id == 1 )
{
final double js_value = Double.parseDouble( values[ 0 ] );
SwingUtilities.invokeLater( new Runnable() { public void run() { Parameter.M_t.setValue( js_value ); } } );
}
else
{
unknown_command = true;
}
}
else if( dev.equals( "SW" ) )
{ // digital switch
if( id == 1 || id == 2 )
{
boolean on = Integer.parseInt( values[ 0 ] ) == 1;
if( on )
{
System.out.println( "SW in" );
SwingUtilities.invokeLater( new Runnable()
{
public void run()
{
if( id == 1 )
Main.gui().saveScreenShot( Surface.F );
else if( id == 2 )
Main.gui().saveScreenShot( Surface.G );
}
} );
System.out.println( "SW out" );
}
}
else
{
unknown_command = true;
}
}
else
{
unknown_command = true;
}
}
catch( ArrayIndexOutOfBoundsException aioobe ) { unknown_command = true; }
catch( NullPointerException npe ) { unknown_command = true; }
catch( NumberFormatException nfe ) { unknown_command = true; }
if( unknown_command )
;//System.err.println( "PhidgetReader: Unknown command \"" + cmd + "\"" );
else
Main.robot().holdBack();
}
}
catch( IOException ioe )
{
System.err.println( "PhidgetReader: no I/O connection to " + PhidgetInterface.this.host + ":" + PhidgetInterface.this.port );
try { Thread.sleep( 1000 ); } catch( InterruptedException ie ) {}
}
}
}
}
class PhidgetWriterClient implements Runnable
{
public void run()
{
boolean reconnect = false;
while( !PhidgetInterface.this.shutdown )
{
try
{
if( !PhidgetInterface.this.socket.isConnected() || PhidgetInterface.this.socket.isClosed() || reconnect )
{
PhidgetInterface.this.reconnect();
reconnect = false;
}
OutputStreamWriter out = new OutputStreamWriter( PhidgetInterface.this.socket.getOutputStream() );
String cmd = null;
while( true )
{
try
{
if( cmd == null )
cmd = outDeque.take();
try
{
out.write( cmd );
out.write( "#FM\n" );
out.flush();
cmd = null;
}
catch( IOException ioe )
{
// put cmd back into queue and retry
outDeque.putFirst( cmd );
throw ioe;
}
}
catch( InterruptedException ie )
{
// retry
}
}
}
catch( IOException ioe )
{
System.err.println( "PhidgetWriter: no I/O connection to " + PhidgetInterface.this.host + ":" + PhidgetInterface.this.port );
reconnect = true;
}
}
}
}
class HeartBeat implements Runnable
{
public void run()
{
while( !PhidgetInterface.this.shutdown )
{
try
{
Thread.sleep( heartbeat_ms );
if( outDeque.size() < 10 ) // don't send anything if there is still something in the buffer
outDeque.put( "" ); // use empty command as heart beat
}
catch( Exception ie )
{
// just repeat
}
}
}
}
} |
package courgette.runtime;
import courgette.integration.reportportal.ReportPortalProperties;
import courgette.runtime.utils.FileUtils;
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;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CopyOnWriteArrayList;
class CourgetteReporter {
private final Map<String, CopyOnWriteArrayList<String>> reports;
private String reportFile;
private CourgetteProperties courgetteProperties;
CourgetteReporter(String reportFile, Map<String, CopyOnWriteArrayList<String>> reports, CourgetteProperties courgetteProperties) {
this.reportFile = reportFile;
this.reports = reports;
this.courgetteProperties = courgetteProperties;
}
CourgetteReporter(Map<String, CopyOnWriteArrayList<String>> reports, CourgetteProperties courgetteProperties) {
this.reports = reports;
this.courgetteProperties = courgetteProperties;
}
void createReport(boolean mergeTestCaseName) {
if (reportFile != null && !reports.isEmpty()) {
final List<String> reportData = getReportData();
final boolean isHtml = reportFile.endsWith(".html");
final boolean isJson = reportFile.endsWith(".json");
final boolean isNdJson = reportFile.endsWith(".ndjson");
final boolean isXml = reportFile.endsWith(".xml");
if (isHtml) {
Optional<String> htmlReport = reportData.stream().filter(report -> report.startsWith("<!DOCTYPE html>")).findFirst();
if (htmlReport.isPresent()) {
String report = htmlReport.get();
reportData.removeIf(r -> !r.startsWith("<!DOCTYPE html>"));
CucumberMessageUpdater messageUpdater = new CucumberMessageUpdater();
reportData.forEach(messageUpdater::filterMessages);
report = messageUpdater.updateMessages(report);
FileUtils.writeFile(reportFile, report);
}
}
if (isJson) {
reportData.removeIf(report -> !report.startsWith("["));
FileUtils.writeFile(reportFile, formatJsonReport(reportData));
}
if (isNdJson) {
List<String> cucumberMessages = filterCucumberMessages(new ArrayList<>(reportData));
FileUtils.writeFile(reportFile, formatNdJsonReport(cucumberMessages));
}
if (isXml) {
reportData.removeIf(report -> !report.startsWith("<?xml"));
FileUtils.writeFile(reportFile, formatXmlReport(reportData, mergeTestCaseName));
}
}
}
void publishCucumberReport() {
if (!reports.isEmpty()) {
List<String> cucumberMessages = filterCucumberMessages(new ArrayList<>(getReportData()));
CucumberReportPublisher reportPublisher = new CucumberReportPublisher(cucumberMessages);
Optional<String> reportUrl = reportPublisher.publish();
StringBuilder out = new StringBuilder();
if (reportUrl.isPresent()) {
out.append("\n
out.append("Report published at: ").append(Instant.now()).append("\n");
out.append("\nCourgette published your Cucumber Report to:\n");
out.append(reportUrl.get());
out.append("\n
System.out.println(out.toString());
String reportLinkFilename = courgetteProperties.getCourgetteOptions().reportTargetDir() + File.separator + "cucumber-report-link.txt";
FileUtils.writeFile(reportLinkFilename, out.toString());
}
}
}
private String formatJsonReport(List<String> reports) {
StringBuilder jsonBuilder = new StringBuilder("[");
reports.forEach(data -> jsonBuilder.append(data, 1, data.length() - 1).append(","));
jsonBuilder.deleteCharAt(jsonBuilder.lastIndexOf(","));
jsonBuilder.append("]");
return jsonBuilder.toString();
}
private String formatNdJsonReport(List<String> reports) {
StringBuilder ndJsonBuilder = new StringBuilder();
reports.forEach(data -> ndJsonBuilder.append(data).append("\n"));
return ndJsonBuilder.toString();
}
private String formatXmlReport(List<String> reports, boolean mergeTestCaseName) {
int failures = 0;
int skipped = 0;
int tests = 0;
double time = 0.0;
String testSuite = "Test Suite";
final StringBuilder xmlBuilder = new StringBuilder();
xmlBuilder.append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n");
xmlBuilder.append("<testsuite failures=\"id:failures\" name=\"id:testSuite\" skipped=\"id:skipped\" tests=\"id:tests\" time=\"id:time\">\n\n");
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
for (String report : reports) {
Document document = builder.parse(new InputSource(new StringReader(report)));
if (document != null) {
Element node = document.getDocumentElement();
failures = failures + Integer.parseInt(node.getAttribute("failures"));
skipped = skipped + Integer.parseInt(node.getAttribute("skipped"));
tests = tests + Integer.parseInt(node.getAttribute("tests"));
time = time + Double.parseDouble(node.getAttribute("time"));
NodeList testCases = document.getElementsByTagName("testcase");
if (testCases != null) {
for (int i = 0; i < testCases.getLength(); i++) {
Node testcase = testCases.item(i);
if (mergeTestCaseName) {
Node testClassName = testcase.getAttributes().getNamedItem("classname");
Node testName = testcase.getAttributes().getNamedItem("name");
String classNameValue = testClassName.getNodeValue();
String testNameValue = testName.getNodeValue();
testName.setNodeValue(classNameValue + ": " + testNameValue);
}
StringWriter sw = new StringWriter();
try {
Transformer t = TransformerFactory.newInstance().newTransformer();
t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
t.setOutputProperty(OutputKeys.INDENT, "yes");
t.transform(new DOMSource(testcase), new StreamResult(sw));
xmlBuilder.append(sw.toString()).append("\n");
} catch (TransformerException te) {
te.printStackTrace();
}
}
}
}
}
} catch (SAXException | IOException | ParserConfigurationException e) {
e.printStackTrace();
}
xmlBuilder.append("</testsuite>");
if (courgetteProperties.isReportPortalPluginEnabled()) {
testSuite = ReportPortalProperties.getInstance().getTestSuite();
}
return xmlBuilder.toString()
.replace("id:failures", String.valueOf(failures))
.replace("id:skipped", String.valueOf(skipped))
.replace("id:tests", String.valueOf(tests))
.replace("id:time", String.valueOf(time))
.replace("id:testSuite", testSuite);
}
private List<String> filterCucumberMessages(List<String> reportData) {
final CucumberMessageUpdater messageUpdater = new CucumberMessageUpdater();
reportData.removeIf(report -> !report.startsWith("{\"meta\":"));
reportData.forEach(messageUpdater::addMessage);
return messageUpdater.updateAndGetMessages();
}
private List<String> getReportData() {
final List<String> reportData = new ArrayList<>();
final Map<String, CopyOnWriteArrayList<String>> reportMap = new LinkedHashMap<>();
this.reports.values().removeIf(t -> t.contains(null) || t.contains("null") || t.contains("[]") || t.contains(""));
this.reports.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.forEachOrdered(x -> reportMap.put(x.getKey(), x.getValue()));
reportMap.values().forEach(report -> {
try {
reportData.add(report.get(0));
} catch (Exception e) {
e.printStackTrace();
}
});
return reportData;
}
} |
package org.minimalj.repository;
import java.sql.SQLException;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import org.apache.derby.jdbc.EmbeddedDataSource;
import org.h2.jdbcx.JdbcDataSource;
import org.mariadb.jdbc.MariaDbDataSource;
import org.minimalj.application.Configuration;
import org.minimalj.util.LoggingRuntimeException;
import org.minimalj.util.StringUtils;
import org.postgresql.ds.PGSimpleDataSource;
import com.microsoft.sqlserver.jdbc.SQLServerDataSource;
public class DataSourceFactory {
public static final Logger logger = Logger.getLogger(DataSourceFactory.class.getName());
public static DataSource create() {
DataSource jndiDataSource = DataSourceFactory.getJndiDataSource();
if (jndiDataSource != null) {
return jndiDataSource;
}
String database = Configuration.get("MjSqlDatabase");
String user = Configuration.get("MjSqlDatabaseUser", "APP");
String password = Configuration.get("MjSqlDatabasePassword", "APP");
if (!StringUtils.isBlank(database)) {
return DataSourceFactory.dataSource(database, user, password);
} else {
String databaseFile = Configuration.get("MjSqlDatabaseFile", null);
return DataSourceFactory.embeddedDataSource(databaseFile);
}
}
public static DataSource getJndiDataSource() {
try {
Context initContext = new InitialContext();
return (DataSource) initContext.lookup("java:/comp/env/jdbc");
} catch (NamingException e) {
logger.fine("Exception while retrieving JNDI datasource (" + e.getMessage() + ")");
return null;
}
}
// every JUnit test must have a fresh memory db
private static int memoryDbCount = 1;
/**
* Convenience method for prototyping and testing. The tables will be
* created automatically.
*
* @return a DataSource representing a in memory database
*/
public static DataSource embeddedDataSource() {
return embeddedDataSource(null);
}
public static DataSource embeddedDataSource(String file) {
JdbcDataSource dataSource;
try {
dataSource = new JdbcDataSource();
} catch (NoClassDefFoundError e) {
logger.severe("Missing JdbcDataSource. Please ensure to have h2 in the classpath");
throw new IllegalStateException("Configuration error: Missing JdbcDataSource");
}
dataSource.setUrl(file != null ? "jdbc:h2:" + file : "jdbc:h2:mem:TempDB" + (memoryDbCount++));
return dataSource;
}
public static DataSource embeddedDerbyDataSource(String file) {
EmbeddedDataSource dataSource;
try {
dataSource = new EmbeddedDataSource();
} catch (NoClassDefFoundError e) {
logger.severe("Missing EmbeddedDataSource. Please ensure to have derby in the classpath");
throw new IllegalStateException("Configuration error: Missing EmbeddedDataSource");
}
dataSource.setDatabaseName(file != null ? file : "memory:TempDB" + (memoryDbCount++));
dataSource.setCreateDatabase("create");
return dataSource;
}
public static DataSource dataSource(String url, String user, String password) {
if (url.startsWith("jdbc:oracle")) {
return oracleDbDataSource(url, user, password);
} else if (url.startsWith("jdbc:mariadb")) {
return mariaDbDataSource(url, user, password);
} else if (url.startsWith("jdbc:postgresql")) {
return postgresqlDataSource(url, user, password);
} else if (url.startsWith("jdbc:sqlserver")) {
return mssqlDataSource(url, user, password);
} else {
throw new RuntimeException("Unknown jdbc URL: " + url);
}
}
public static DataSource mariaDbDataSource(String url, String user, String password) {
try {
MariaDbDataSource dataSource = new MariaDbDataSource();
dataSource.setUrl(url);
dataSource.setUser(user);
dataSource.setPassword(password);
return dataSource;
} catch (SQLException e) {
throw new RuntimeException(e);
} catch (NoClassDefFoundError e) {
logger.severe("Missing MariaDbDataSource. Please ensure to have mariadb-java-client in the classpath");
throw new IllegalStateException("Configuration error: Missing MariaDbDataSource");
}
}
public static DataSource postgresqlDataSource(String url, String user, String password) {
try {
PGSimpleDataSource dataSource = new PGSimpleDataSource();
dataSource.setUrl(url);
dataSource.setUser(user);
dataSource.setPassword(password);
return dataSource;
} catch (NoClassDefFoundError e) {
logger.severe("Missing PGSimpleDataSource. Please ensure to have postgresql driver in the classpath");
throw new IllegalStateException("Configuration error: Missing PGSimpleDataSource");
}
}
public static DataSource mssqlDataSource(String url, String user, String password) {
try {
SQLServerDataSource dataSource = new SQLServerDataSource();
dataSource.setURL(url);
dataSource.setUser(user);
dataSource.setPassword(password);
return dataSource;
} catch (NoClassDefFoundError e) {
logger.severe("Missing SQLServerDataSource. Please ensure to have mssql-jdbc in the classpath");
throw new IllegalStateException("Configuration error: Missing SQLServerDataSource");
}
}
/**
* Don't forget to add the dependency to ojdbc like this in your pom.xml
* <pre>
* <dependency>
* <groupId>com.oracle</groupId>
* <artifactId>ojdbc7</artifactId>
* <version>12.1.0.2</version>
* <scope>provided</scope>
* </dependency>
* </pre>
*
* You need to register at the oracle maven repository to actually get the driver.
*
* @param url for example "jdbc:oracle:thin:@localhost:1521:orcl"
* @param user User
* @param password Password
* @return DataSource
*/
public static DataSource oracleDbDataSource(String url, String user, String password) {
try {
@SuppressWarnings("unchecked")
Class<? extends DataSource> dataSourceClass = (Class<? extends DataSource>) Class.forName("oracle.jdbc.pool.OracleDataSource");
DataSource dataSource = dataSourceClass.newInstance();
dataSourceClass.getMethod("setURL", String.class).invoke(dataSource, url);
dataSourceClass.getMethod("setUser", String.class).invoke(dataSource, user);
dataSourceClass.getMethod("setPassword", String.class).invoke(dataSource, password);
// OracleDataSource dataSource = new OracleDataSource();
// dataSource.setURL(url);
// dataSource.setUser(user);
// dataSource.setPassword(password);
return dataSource;
} catch (Exception e) {
throw new LoggingRuntimeException(e, logger, "Cannot connect to oracle db");
}
}
} |
package crazypants.enderio.item;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraftforge.oredict.ShapedOreRecipe;
import cpw.mods.fml.common.registry.GameRegistry;
import crazypants.enderio.EnderIO;
import crazypants.enderio.material.Alloy;
import crazypants.enderio.material.MachinePart;
import crazypants.enderio.material.Material;
public class ItemRecipes {
public static void addRecipes() {
ItemStack basicGear = new ItemStack(EnderIO.itemMachinePart, 1, MachinePart.BASIC_GEAR.ordinal());
ItemStack electricalSteel = new ItemStack(EnderIO.itemAlloy, 1, Alloy.ELECTRICAL_STEEL.ordinal());
ItemStack conductiveIron = new ItemStack(EnderIO.itemAlloy, 1, Alloy.CONDUCTIVE_IRON.ordinal());
ItemStack vibCry = new ItemStack(EnderIO.itemMaterial, 1, Material.VIBRANT_CYSTAL.ordinal());
ItemStack darkSteel = new ItemStack(EnderIO.itemAlloy, 1, Alloy.DARK_STEEL.ordinal());
ItemStack soularium = new ItemStack(EnderIO.itemAlloy, 1, Alloy.SOULARIUM.ordinal());
// Wrench
ItemStack wrench = new ItemStack(EnderIO.itemYetaWench, 1, 0);
GameRegistry.addShapedRecipe(wrench, "s s", " b ", " s ", 's', electricalSteel, 'b', basicGear);
ItemStack magnet = new ItemStack(EnderIO.itemMagnet, 1, 0);
EnderIO.itemMagnet.setEnergy(magnet, 0);
GameRegistry.addShapedRecipe(magnet, "scc", " v", "scc", 's', electricalSteel, 'c', conductiveIron, 'v', vibCry);
//Dark Steel
GameRegistry.addShapedRecipe(EnderIO.itemDarkSteelHelmet.createItemStack(), "sss", "s s", " ", 's', darkSteel);
GameRegistry.addShapedRecipe(EnderIO.itemDarkSteelChestplate.createItemStack(), "s s", "sss", "sss", 's', darkSteel);
GameRegistry.addShapedRecipe(EnderIO.itemDarkSteelLeggings.createItemStack(), "sss", "s s", "s s", 's', darkSteel);
GameRegistry.addShapedRecipe(EnderIO.itemDarkSteelBoots.createItemStack(), "s s", "s s", " ", 's', darkSteel);
GameRegistry.addShapedRecipe(EnderIO.itemDarkSteelBoots.createItemStack(), " ", "s s", "s s", 's', darkSteel);
ItemStack wing = new ItemStack(EnderIO.itemGliderWing,1,0);
GameRegistry.addShapedRecipe(wing, " s", " sl", "sll", 's', darkSteel, 'l', Items.leather);
GameRegistry.addShapedRecipe(new ItemStack(EnderIO.itemGliderWing,1,1), " s ", "wsw", " ", 's', darkSteel, 'w', wing);
ItemStack dspp = new ItemStack(EnderIO.blockDarkSteelPressurePlate);
GameRegistry.addShapedRecipe(dspp, "ss ", " ", " ", 's', darkSteel);
GameRegistry.addShapedRecipe(new ItemStack(EnderIO.itemSoulVessel), " s ", "q q", " q ", 's', soularium, 'q', new ItemStack(EnderIO.blockFusedQuartz,1,0));
}
public static void addOreDictionaryRecipes() {
ItemStack darkSteel = new ItemStack(EnderIO.itemAlloy, 1, Alloy.DARK_STEEL.ordinal());
GameRegistry.addRecipe(new ShapedOreRecipe(EnderIO.itemDarkSteelSword.createItemStack(), " s ", " s ", " w ", 's', darkSteel, 'w', "stickWood"));
GameRegistry.addRecipe(new ShapedOreRecipe(EnderIO.itemDarkSteelSword.createItemStack(), " s ", " s ", " w ", 's', darkSteel, 'w', "woodStick"));
GameRegistry.addRecipe(new ShapedOreRecipe(EnderIO.itemDarkSteelPickaxe.createItemStack(), "sss", " w ", " w ", 's', darkSteel, 'w', "stickWood"));
GameRegistry.addRecipe(new ShapedOreRecipe(EnderIO.itemDarkSteelPickaxe.createItemStack(), "sss", " w ", " w ", 's', darkSteel, 'w', "woodStick"));
GameRegistry.addRecipe(new ShapedOreRecipe(EnderIO.itemDarkSteelAxe.createItemStack(), "ss ", "sw ", " w ", 's', darkSteel, 'w', "woodStick"));
}
} |
package com.opera.core.systems;
//import java.util.HashMap;
//import java.util.ArrayList;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import com.opera.core.systems.runner.launcher.OperaLauncherRunner;
import com.opera.core.systems.scope.exceptions.CommunicationException;
import com.opera.core.systems.scope.internal.OperaIntervals;
import com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetSearch.QuickWidgetSearchType;
import com.opera.core.systems.scope.protos.SystemInputProtos.ModifierPressed;
import com.opera.core.systems.scope.services.IDesktopWindowManager;
import com.opera.core.systems.scope.services.IDesktopUtils;
import com.opera.core.systems.scope.services.ums.SystemInputManager;
import com.opera.core.systems.settings.OperaDriverSettings;
public class OperaDesktopDriver extends OperaDriver {
private IDesktopWindowManager desktopWindowManager;
private SystemInputManager systemInputManager;
private IDesktopUtils desktopUtils;
public OperaDesktopDriver(OperaDriverSettings settings){
super(settings);
}
/**
* For testing override this method.
*/
protected void init() {
super.init();
desktopWindowManager = services.getDesktopWindowManager();
systemInputManager = services.getSystemInputManager();
desktopUtils = services.getDesktopUtils();
// If the Opera Binary isn't set we are assuming Opera is up and we
// can ask it for the location of itself
if (this.settings != null && this.settings.getOperaBinaryLocation() == null) {
String opera_path = desktopUtils.getOperaPath();
logger.info("OperaBinaryLocation retrieved from Opera: " + opera_path);
if (!opera_path.isEmpty()) {
this.settings.setOperaBinaryLocation(opera_path);
// Get pid of Opera, needed to wait for it to quit after calling quit_opera
int pid = desktopUtils.getOperaPid();
// Now create the OperaLauncherRunner that we have the binary path
this.operaRunner = new OperaLauncherRunner(this.settings);
// Quit and wait for opera to quit properly
this.services.quit(this.operaRunner, pid);
// Work around stop and restart Opera so the Launcher has control of it now
// Initialising the services will start Opera if the OperaLauncherRunner is
// setup correctly
this.init();
}
}
}
// TODO: FIXME
protected Map<String, String> getServicesList() {
Map<String, String> versions = super.getServicesList();
// This is the minimum versions of the services this version
// of the web-driver require work
versions.put("desktop-window-manager", "2.0");
versions.put("system-input", "1.0");
versions.put("desktop-utils", "2.0");
return versions;
}
protected IDesktopWindowManager getDesktopWindowManager() {
return desktopWindowManager;
}
protected SystemInputManager getSystemInputManager() {
return systemInputManager;
}
/**
* Quit Opera
*/
public void quit_opera() {
if (this.operaRunner != null){
if (this.operaRunner.isOperaRunning()) {
this.operaRunner.stopOpera();
}
else{
// Quit with action as opera wasn't started with the launcher
services.quit();
}
}
}
/**
* @return active window id
*/
public int getActiveWindowID() {
return desktopWindowManager.getActiveWindowId();
}
/**
* @param win_name
* @return list of widgets in the window with name win_name
* If no winName is empty, it gets the widgets in the active window
*/
public List<QuickWidget> getQuickWidgetList(String winName) {
int id = getWindowID(winName);
if (id >= 0 || winName.length() == 0) {
return getQuickWidgetList(id);
}
// Couldn't find window with winName
return null;
}
public List<QuickWidget> getQuickWidgetList(int id) {
return desktopWindowManager.getQuickWidgetList(id);
}
public List<QuickWindow> getWindowList() {
return desktopWindowManager.getQuickWindowList();
}
/**
* @param name
* @return window id of window with window_name
*/
public int getWindowID(String windowName) {
return desktopWindowManager.getWindowID(windowName);
}
/**
* @param name
* @return QuickWindow with the given name
*/
public QuickWindow getWindow(String windowName) {
return desktopWindowManager.getWindow(windowName);
}
/**
* @param windowId
* @param widgetName
* @return QuickWidget with the given name in the window with id windowId
*/
public QuickWidget findWidgetByName(int windowId, String widgetName){
return desktopWindowManager.getQuickWidget(windowId, QuickWidgetSearchType.NAME, widgetName);
}
public QuickWidget findWidgetByName(int windowId, String widgetName, String parentName){
return desktopWindowManager.getQuickWidget(windowId, QuickWidgetSearchType.NAME, widgetName, parentName);
}
public QuickWidget findWidgetByText(int windowId, String text){
return desktopWindowManager.getQuickWidget(windowId, QuickWidgetSearchType.TEXT, text);
}
public QuickWidget findWidgetByText(int windowId, String text, String parentName){
return desktopWindowManager.getQuickWidget(windowId, QuickWidgetSearchType.TEXT, text, parentName);
}
public QuickWidget findWidgetByStringId(int windowId, String stringId){
String text = desktopUtils.getString(stringId);
return findWidgetByText(windowId, text);
}
public QuickWidget findWidgetByStringId(int windowId, String stringId, String parentName){
String text = desktopUtils.getString(stringId);
return findWidgetByText(windowId, text, parentName);
}
public QuickWidget findWidgetByPosition(int windowId, int row, int column){
return desktopWindowManager.getQuickWidgetByPos(windowId, row, column);
}
public QuickWidget findWidgetByPosition(int windowId, int row, int column, String parentName){
return desktopWindowManager.getQuickWidgetByPos(windowId, row, column, parentName);
}
public QuickWindow findWindowByName(String windowName){
return desktopWindowManager.getQuickWindow(QuickWidgetSearchType.NAME, windowName);
}
public QuickWindow findWindowById(int windowId){
return desktopWindowManager.getQuickWindowById(windowId);
}
/**
* @param windowId
* @return String: name of the window
*/
public String getWindowName(int windowId) {
return desktopWindowManager.getWindowName(windowId);
}
/**
*
* @param enum_text
* @return the string specified by the id @param enum_text
*/
public String getString(String enum_text){
return desktopUtils.getString(enum_text);
}
public String getOperaPath() {
return desktopUtils.getOperaPath();
}
public String getLargePreferencesPath() {
return desktopUtils.getLargePreferencesPath();
}
public String getSmallPreferencesPath() {
return desktopUtils.getSmallPreferencesPath();
}
public String getCachePreferencesPath() {
return desktopUtils.getCachePreferencesPath();
}
/**
*
* @param key
* @param modifier
* @return the string specified by the id @param enum_text
*/
public void keyPress(String key, List<ModifierPressed> modifiers) {
/*for (ModifierPressed mod : modifiers) {
if (mod != null)
System.out.print(mod.toString() + "(" + i + ",");
}
System.out.println(")");*/
systemInputManager.keyPress(key, modifiers);
}
public void keyUp(String key, List<ModifierPressed> modifiers) {
systemInputManager.keyUp(key, modifiers);
}
public void keyDown(String key, List<ModifierPressed> modifiers) {
systemInputManager.keyDown(key, modifiers);
}
/*public void keyPress(String key, ModifierPressed modifier) {
ArrayList<ModifierPressed> mods = new ArrayList<ModifierPressed>();
mods.add(modifier);
systemInputManager.keyPress(key, mods);
}*/
public int getWindowCount() {
//TODO FIXME
//return desktopWindowManager.getOpenWindowCount();
return 0;
}
/**
* Execute opera action
* @param using - action_name
* @param data - data parameter
* @param dataString - data string parameter
* @param dataStringParam - parameter to data string
*/
public void operaDesktopAction(String using, int data, String dataString, String dataStringParam) {
exec.action(using, data, dataString, dataStringParam);
}
/*
* Starts a process of waiting for a window to show
* After this call, messages to the driver about window events are not thrown away,
* so that the notification about window shown is not lost because of other events or messages
*/
public void waitStart() {
if (services.getConnection() == null)
throw new CommunicationException("waiting for a window failed because Opera is not connected.");
services.waitStart();
}
/**
* Wait for any window update event
*/
public void waitForWindowUpdated() {
waitForWindowUpdated("");
}
/**
* Wait for any window activated event
*/
public void waitForWindowActivated() {
waitForWindowActivated("");
}
/**
* Wait for any window close event
*/
public void waitForWindowClose() {
waitForWindowClose("");
}
/**
* Wait until the window given by the @param win_name is shown, and then returns the
* window id of this window
*
* @param win_name - window to wait for shown event on
* @return id of window
* @throws CommuncationException if no connection
*/
public int waitForWindowShown(String win_name) {
if (services.getConnection() == null)
throw new CommunicationException("waiting for a window failed because Opera is not connected.");
return services.waitForDesktopWindowShown(win_name, OperaIntervals.PAGE_LOAD_TIMEOUT.getValue());
}
/**
* Wait until the window given by the @param win_name is updated, and then returns the
* window id of this window
*
* @param win_name - window to wait for shown event on
* @return id of window
* @throws CommuncationException if no connection
*/
public int waitForWindowUpdated(String win_name) {
if (services.getConnection() == null)
throw new CommunicationException("waiting for a window failed because Opera is not connected.");
return services.waitForDesktopWindowUpdated(win_name, OperaIntervals.PAGE_LOAD_TIMEOUT.getValue());
}
/**
* Wait until the window given by the @param win_name is activated, and then returns the
* window id of this window
*
* @param win_name - window to wait for shown event on
* @return id of window
* @throws CommuncationException if no connection
*/
public int waitForWindowActivated(String win_name) {
if (services.getConnection() == null)
throw new CommunicationException("waiting for a window failed because Opera is not connected.");
return services.waitForDesktopWindowActivated(win_name, OperaIntervals.PAGE_LOAD_TIMEOUT.getValue());
}
/**
* Wait until the window given by the @param win_name is closed, and then returns the
* window id of this window
*
* @param win_name - window to wait for shown event on
* @return id of window
* @throws CommuncationException if no connection
*/
public int waitForWindowClose(String win_name) {
if (services.getConnection() == null)
throw new CommunicationException("waiting for a window failed because Opera is not connected.");
return services.waitForDesktopWindowClosed(win_name, OperaIntervals.PAGE_LOAD_TIMEOUT.getValue());
}
public int waitForWindowLoaded(String win_name) {
if (services.getConnection() == null)
throw new CommunicationException("waiting for a window failed because Opera is not connected.");
return services.waitForDesktopWindowLoaded(win_name, OperaIntervals.PAGE_LOAD_TIMEOUT.getValue());
}
public void resetOperaPrefs(String newPrefs) {
resetOperaPrefs(this.getLargePreferencesPath(), newPrefs);
}
public void resetOperaPrefs(String prefsPath, String newPrefs) {
quit_opera();
deleteFolder(prefsPath);
copyFolder(newPrefs, prefsPath);
start_opera();
}
private void start_opera() {
init();
}
private boolean deleteFolder(String folderpath) {
File dir = new File(folderpath);
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i=0; i<children.length; i++) {
boolean success = deleteFolder(children[i]);
if (!success) {
//return false;
}
}
}
// The directory/file is now empty so delete it
return dir.delete();
}
private void copyFolder(String from, String to) {
try {
copyFolder(new File(from), new File(to));
} catch (IOException ex) {
}
}
private void copyFolder(File srcPath, File dstPath) throws IOException {
if (srcPath.isDirectory()){
// Create destination folder if needed
if (!dstPath.exists()){
dstPath.mkdir();
}
String files[] = srcPath.list();
for(int i = 0; i < files.length; i++){
copyFolder(new File(srcPath, files[i]), new File(dstPath, files[i]));
}
}
else {
if(!srcPath.exists()){
System.out.println("File or directory does not exist.");
}
else
{
InputStream in = new FileInputStream(srcPath);
OutputStream out = new FileOutputStream(dstPath);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
}
}
} |
package org.minimalj.repository.sql;
import java.io.InputStream;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.Temporal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;
import java.util.function.BiFunction;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sql.DataSource;
import org.apache.derby.jdbc.EmbeddedDataSource;
import org.h2.jdbcx.JdbcDataSource;
import org.minimalj.application.Configuration;
import org.minimalj.model.Code;
import org.minimalj.model.EnumUtils;
import org.minimalj.model.Keys;
import org.minimalj.model.Keys.MethodProperty;
import org.minimalj.model.Model;
import org.minimalj.model.View;
import org.minimalj.model.ViewUtil;
import org.minimalj.model.annotation.Materialized;
import org.minimalj.model.annotation.Searched;
import org.minimalj.model.properties.ChainedProperty;
import org.minimalj.model.properties.FieldProperty;
import org.minimalj.model.properties.FlatProperties;
import org.minimalj.model.properties.PropertyInterface;
import org.minimalj.model.test.ModelTest;
import org.minimalj.repository.DataSourceFactory;
import org.minimalj.repository.Repository;
import org.minimalj.repository.TransactionalRepository;
import org.minimalj.repository.list.QueryResultList;
import org.minimalj.repository.list.SortableList;
import org.minimalj.repository.query.AllCriteria;
import org.minimalj.repository.query.By;
import org.minimalj.repository.query.Criteria;
import org.minimalj.repository.query.Limit;
import org.minimalj.repository.query.Query;
import org.minimalj.util.CloneHelper;
import org.minimalj.util.Codes;
import org.minimalj.util.Codes.CodeCacheItem;
import org.minimalj.util.CsvReader;
import org.minimalj.util.FieldUtils;
import org.minimalj.util.IdUtils;
import org.minimalj.util.LoggingRuntimeException;
import org.minimalj.util.StringUtils;
/**
* The Mapper to a relational Database
*
*/
public class SqlRepository implements TransactionalRepository {
private static final Logger logger = Logger.getLogger(SqlRepository.class.getName());
protected final SqlDialect sqlDialect;
protected final SqlIdentifier sqlIdentifier;
private final Map<Class<?>, AbstractTable<?>> tables = new LinkedHashMap<>();
private final Map<String, AbstractTable<?>> tableByName = new HashMap<>();
private final Map<Class<?>, LinkedHashMap<String, PropertyInterface>> columnsForClass = new HashMap<>(200);
private final Map<Class<?>, HashMap<String, PropertyInterface>> columnsForClassUpperCase = new HashMap<>(200);
private final DataSource dataSource;
private Connection autoCommitConnection;
private final BlockingDeque<Connection> connectionDeque = new LinkedBlockingDeque<>();
private final ThreadLocal<Connection> threadLocalTransactionConnection = new ThreadLocal<>();
private final HashMap<Class<? extends Code>, CodeCacheItem<? extends Code>> codeCache = new HashMap<>();
public SqlRepository(Model model) {
this(DataSourceFactory.create(), model.getEntityClasses());
}
public SqlRepository(DataSource dataSource, Class<?>... classes) {
this.dataSource = dataSource;
Connection connection = getAutoCommitConnection();
try {
sqlDialect = findDialect(connection);
sqlIdentifier = createSqlIdentifier();
for (Class<?> clazz : classes) {
addClass(clazz);
}
new ModelTest(classes).assertValid();
if (createTablesOnInitialize(dataSource)) {
createTables();
createCodes();
}
} catch (SQLException x) {
throw new LoggingRuntimeException(x, logger, "Could not determine product name of database");
}
}
private SqlDialect findDialect(Connection connection) throws SQLException {
if (Configuration.available("MjSqlDialect")) {
return Configuration.getClazz("MjSqlDialect", SqlDialect.class);
}
String databaseProductName = connection.getMetaData().getDatabaseProductName();
if (StringUtils.equals(databaseProductName, "MySQL")) {
return new SqlDialect.MariaSqlDialect();
} else if (StringUtils.equals(databaseProductName, "PostgreSQL")) {
return new SqlDialect.PostgresqlDialect();
} else if (StringUtils.equals(databaseProductName, "Apache Derby")) {
return new SqlDialect.DerbySqlDialect();
} else if (StringUtils.equals(databaseProductName, "H2")) {
return new SqlDialect.H2SqlDialect();
} else if (StringUtils.equals(databaseProductName, "Oracle")) {
return new SqlDialect.OracleSqlDialect();
} else if (StringUtils.equals(databaseProductName, "Microsoft SQL Server")) {
return new SqlDialect.MsSqlDialect();
} else {
return new SqlDialect.H2SqlDialect();
// throw new RuntimeException("Only Oracle, H2, MySQL/MariaDB, SQL Server and Derby DB supported at the moment. ProductName: " + databaseProductName);
}
}
protected SqlIdentifier createSqlIdentifier() {
if (sqlDialect instanceof SqlDialect.PostgresqlDialect) {
return new SqlIdentifier(sqlDialect.getMaxIdentifierLength()) {
protected String identifier(String identifier, Set<String> alreadyUsedIdentifiers) {
identifier = super.identifier(identifier, alreadyUsedIdentifiers);
return identifier.toLowerCase();
}
};
} else {
return new SqlIdentifier(sqlDialect.getMaxIdentifierLength());
}
}
private Connection getAutoCommitConnection() {
try {
if (autoCommitConnection == null || !sqlDialect.isValid(autoCommitConnection)) {
autoCommitConnection = dataSource.getConnection();
autoCommitConnection.setAutoCommit(true);
}
return autoCommitConnection;
} catch (Exception e) {
throw new LoggingRuntimeException(e, logger, "Not possible to create autocommit connection");
}
}
public SqlDialect getSqlDialect() {
return sqlDialect;
}
@Override
public void startTransaction(int transactionIsolationLevel) {
if (isTransactionActive()) return;
Connection transactionConnection = allocateConnection(transactionIsolationLevel);
threadLocalTransactionConnection.set(transactionConnection);
}
@Override
public void endTransaction(boolean commit) {
Connection transactionConnection = threadLocalTransactionConnection.get();
if (transactionConnection == null) return;
try {
if (commit) {
transactionConnection.commit();
} else {
transactionConnection.rollback();
}
} catch (SQLException x) {
throw new LoggingRuntimeException(x, logger, "Transaction failed");
}
releaseConnection(transactionConnection);
threadLocalTransactionConnection.set(null);
}
private Connection allocateConnection(int transactionIsolationLevel) {
Connection connection = connectionDeque.poll();
while (true) {
boolean valid = false;
try {
valid = connection != null && connection.isValid(0);
} catch (SQLException x) {
// ignore
}
if (valid) {
return connection;
}
try {
connection = dataSource.getConnection();
connection.setTransactionIsolation(transactionIsolationLevel);
connection.setAutoCommit(false);
return connection;
} catch (Exception e) {
// this could happen if there are already too many connections
e.printStackTrace();
logger.log(Level.FINE, "Not possible to create additional connection", e);
}
// so no connection available and not possible to create one
// block and wait till a connection is in deque
try {
connectionDeque.poll(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
logger.log(Level.FINEST, "poll for connection interrupted", e);
}
}
}
private void releaseConnection(Connection connection) {
// last in first out in the hope that recent accessed objects are the fastest
connectionDeque.push(connection);
}
/**
* Use with care. Removes all content of all tables. Should only
* be used for JUnit tests.
*/
public void clear() {
List<AbstractTable<?>> tableList = new ArrayList<>(tables.values());
for (AbstractTable<?> table : tableList) {
table.clear();
}
}
public boolean isTransactionActive() {
Connection connection = threadLocalTransactionConnection.get();
return connection != null;
}
public Connection getConnection() {
Connection connection = threadLocalTransactionConnection.get();
if (connection != null) {
return connection;
} else {
connection = getAutoCommitConnection();
return connection;
}
}
private boolean createTablesOnInitialize(DataSource dataSource) throws SQLException {
// If the classes are not in the classpath a 'instanceof' would throw ClassNotFoundError
if (StringUtils.equals(dataSource.getClass().getName(), "org.apache.derby.jdbc.EmbeddedDataSource")) {
return "create".equals(((EmbeddedDataSource) dataSource).getCreateDatabase());
} else if (StringUtils.equals(dataSource.getClass().getName(), "org.h2.jdbcx.JdbcDataSource")) {
String url = ((JdbcDataSource) dataSource).getUrl();
if (url.startsWith("jdbc:h2:mem")) {
return true;
}
try (ResultSet tableDescriptions = getConnection().getMetaData().getTables(null, null, null, new String[] {"TABLE"})) {
return !tableDescriptions.next();
}
}
return false;
}
@Override
public <T> T read(Class<T> clazz, Object id) {
if (View.class.isAssignableFrom(clazz)) {
@SuppressWarnings("unchecked")
Table<T> table = (Table<T>) getTable(ViewUtil.getViewedClass(clazz));
return table.readView(clazz, id, new HashMap<>());
} else {
return getTable(clazz).read(id);
}
}
@Override
public <T> List<T> find(Class<T> resultClass, Query query) {
if (query instanceof Limit || query instanceof AllCriteria) {
@SuppressWarnings("unchecked")
Table<T> table = (Table<T>) getTable(ViewUtil.resolve(resultClass));
List<T> list = table.find(query, resultClass);
return (query instanceof AllCriteria) ? new SortableList<>(list) : list;
} else {
return new SqlQueryResultList<>(this, resultClass, query);
}
}
private static class SqlQueryResultList<T> extends QueryResultList<T> {
private static final long serialVersionUID = 1L;
public SqlQueryResultList(Repository repository, Class<T> clazz, Query query) {
super(repository, clazz, query);
}
@Override
public boolean canSortBy(Object sortKey) {
PropertyInterface property = Keys.getProperty(sortKey);
if (property.getClass() != FieldProperty.class) {
return false;
}
return property.getClazz() == String.class || Number.class.isAssignableFrom(property.getClazz())
|| Temporal.class.isAssignableFrom(property.getClazz());
}
}
@SuppressWarnings("unchecked")
@Override
public <T> long count(Class<T> clazz, Criteria criteria) {
if (View.class.isAssignableFrom(clazz)) {
clazz = (Class<T>) ViewUtil.getViewedClass(clazz);
}
Table<?> table = getTable(clazz);
return table.count(criteria);
}
@Override
public <T> Object insert(T object) {
if (object == null) throw new NullPointerException();
Object originalId = IdUtils.getId(object);
@SuppressWarnings("unchecked")
Table<T> table = getTable((Class<T>) object.getClass());
try {
return table.insert(object);
} finally {
// all repositories should behave to same and not set the new id in the
// original object.
IdUtils.setId(object, originalId);
}
}
@Override
public <T> void update(T object) {
if (object == null) throw new NullPointerException();
@SuppressWarnings("unchecked")
Table<T> table = getTable((Class<T>) object.getClass());
table.update(object);
}
@Override
public <T> void delete(T object) {
@SuppressWarnings("unchecked")
Table<T> table = getTable((Class<T>) object.getClass());
table.delete(object);
}
@Override
public <T> int delete(Class<T> clazz, Criteria criteria) {
Table<T> table = getTable(clazz);
return table.delete(clazz, criteria);
}
public <T> void deleteAll(Class<T> clazz) {
Table<T> table = getTable(clazz);
table.clear();
}
private PreparedStatement createStatement(Connection connection, String query, Object[] parameters) throws SQLException {
PreparedStatement preparedStatement = AbstractTable.createStatement(getConnection(), query, false);
int param = 1;
for (Object parameter : parameters) {
setParameter(preparedStatement, param++, parameter);
}
return preparedStatement;
}
public LinkedHashMap<String, PropertyInterface> findColumns(Class<?> clazz) {
if (columnsForClass.containsKey(clazz)) {
return columnsForClass.get(clazz);
}
LinkedHashMap<String, PropertyInterface> columns = new LinkedHashMap<>();
for (Field field : clazz.getFields()) {
if (!FieldUtils.isPublic(field) || FieldUtils.isStatic(field) || FieldUtils.isTransient(field)) continue;
String fieldName = field.getName();
if (StringUtils.equals(fieldName, "id", "version", "historized")) continue;
if (FieldUtils.isList(field)) continue;
if (FieldUtils.isFinal(field) && !FieldUtils.isSet(field) && !Codes.isCode(field.getType())) {
Map<String, PropertyInterface> inlinePropertys = findColumns(field.getType());
boolean hasClassName = FieldUtils.hasClassName(field) && !FlatProperties.hasCollidingFields(clazz, field.getType(), field.getName());
for (String inlineKey : inlinePropertys.keySet()) {
String key = inlineKey;
if (!hasClassName) {
key = fieldName + "_" + inlineKey;
}
key = sqlIdentifier.column(key, columns.keySet(), field.getType());
columns.put(key, new ChainedProperty(new FieldProperty(field), inlinePropertys.get(inlineKey)));
}
} else {
fieldName = sqlIdentifier.column(fieldName, columns.keySet(), field.getType());
columns.put(fieldName, new FieldProperty(field));
}
}
for (Method method: clazz.getMethods()) {
if (!Keys.isPublic(method) || Keys.isStatic(method)) continue;
if (method.getAnnotation(Searched.class) == null && method.getAnnotation(Materialized.class) == null) continue;
String methodName = method.getName();
if (!methodName.startsWith("get") || methodName.length() < 4) continue;
String fieldName = StringUtils.lowerFirstChar(methodName.substring(3));
String columnName = sqlIdentifier.column(fieldName, columns.keySet(), method.getReturnType());
columns.put(columnName, new Keys.MethodProperty(method.getReturnType(), fieldName, method, null));
}
columnsForClass.put(clazz, columns);
return columns;
}
protected HashMap<String, PropertyInterface> findColumnsUpperCase(Class<?> clazz) {
if (columnsForClassUpperCase.containsKey(clazz)) {
return columnsForClassUpperCase.get(clazz);
}
LinkedHashMap<String, PropertyInterface> columns = findColumns(clazz);
HashMap<String, PropertyInterface> columnsUpperCase = new HashMap<>(columns.size() * 3);
columns.forEach((key, value) -> columnsUpperCase.put(key.toUpperCase(), value));
columnsForClassUpperCase.put(clazz, columnsUpperCase);
return columnsUpperCase;
}
/*
* TODO: should be merged with the setParameter in AbstractTable.
*/
private void setParameter(PreparedStatement preparedStatement, int param, Object value) throws SQLException {
if (value instanceof Enum<?>) {
Enum<?> e = (Enum<?>) value;
value = e.ordinal();
} else if (value instanceof LocalDate) {
value = java.sql.Date.valueOf((LocalDate) value);
} else if (value instanceof LocalTime) {
value = java.sql.Time.valueOf((LocalTime) value);
} else if (value instanceof LocalDateTime) {
value = java.sql.Timestamp.valueOf((LocalDateTime) value);
}
preparedStatement.setObject(param, value);
}
public <T> List<T> find(Class<T> clazz, String query, int maxResults, Object... parameters) {
try (PreparedStatement preparedStatement = createStatement(getConnection(), query, parameters)) {
try (ResultSet resultSet = preparedStatement.executeQuery()) {
List<T> result = new ArrayList<>();
Map<Class<?>, Map<Object, Object>> loadedReferences = new HashMap<>();
while (resultSet.next() && result.size() < maxResults) {
result.add(readResultSetRow(clazz, resultSet, loadedReferences));
}
return result;
}
} catch (SQLException x) {
throw new LoggingRuntimeException(x, logger, "Couldn't execute query");
}
}
public void execute(String query, Serializable... parameters) {
try (PreparedStatement preparedStatement = createStatement(getConnection(), query, parameters)) {
preparedStatement.executeQuery();
} catch (SQLException x) {
throw new LoggingRuntimeException(x, logger, "Couldn't execute query");
}
}
public <T> T execute(Class<T> resultClass, String query, Serializable... parameters) {
try (PreparedStatement preparedStatement = createStatement(getConnection(), query, parameters)) {
try (ResultSet resultSet = preparedStatement.executeQuery()) {
T result = null;
if (resultSet.next()) {
result = readResultSetRow(resultClass, resultSet);
}
return result;
}
} catch (SQLException x) {
throw new LoggingRuntimeException(x, logger, "Couldn't execute query");
}
}
public <R> R readResultSetRow(Class<R> clazz, ResultSet resultSet) throws SQLException {
Map<Class<?>, Map<Object, Object>> loadedReferences = new HashMap<>();
return readResultSetRow(clazz, resultSet, loadedReferences);
}
@SuppressWarnings("unchecked")
public <R> R readResultSetRow(Class<R> clazz, ResultSet resultSet, Map<Class<?>, Map<Object, Object>> loadedReferences) throws SQLException {
if (clazz == Integer.class) {
return (R) Integer.valueOf(resultSet.getInt(1));
} else if (clazz == Long.class) {
return (R) Long.valueOf(resultSet.getLong(1));
} else if (clazz == BigDecimal.class) {
return (R) resultSet.getBigDecimal(1);
} else if (clazz == String.class) {
return (R) resultSet.getString(1);
}
Object id = null;
Integer position = 0;
R result = CloneHelper.newInstance(clazz);
HashMap<String, PropertyInterface> columns = findColumnsUpperCase(clazz);
// first read the resultSet completely then resolve references
// derby db mixes closing of resultSets.
Map<PropertyInterface, Object> values = new HashMap<>(resultSet.getMetaData().getColumnCount() * 3);
for (int columnIndex = 1; columnIndex <= resultSet.getMetaData().getColumnCount(); columnIndex++) {
String columnName = resultSet.getMetaData().getColumnName(columnIndex).toUpperCase();
if ("ID".equals(columnName)) {
id = resultSet.getObject(columnIndex);
IdUtils.setId(result, id);
continue;
} else if ("VERSION".equals(columnName)) {
IdUtils.setVersion(result, resultSet.getInt(columnIndex));
continue;
} else if ("POSITION".equals(columnName)) {
position = resultSet.getInt(columnIndex);
continue;
}
PropertyInterface property = columns.get(columnName);
if (property == null) continue;
Class<?> fieldClass = property.getClazz();
boolean isByteArray = fieldClass.isArray() && fieldClass.getComponentType() == Byte.TYPE;
Object value;
if (isByteArray) {
value = resultSet.getBytes(columnIndex);
} else if (fieldClass == BigDecimal.class) {
// MS Sql getObject returns float
value = resultSet.getBigDecimal(columnIndex);
} else {
value = resultSet.getObject(columnIndex);
}
if (value == null) continue;
values.put(property, value);
}
if (id != null) {
if (!loadedReferences.containsKey(clazz)) {
loadedReferences.put(clazz, new HashMap<>());
}
Object key = position == null ? id : id + "-" + position;
if (loadedReferences.get(clazz).containsKey(key)) {
return (R) loadedReferences.get(clazz).get(key);
} else {
loadedReferences.get(clazz).put(key, result);
}
}
for (Map.Entry<PropertyInterface, Object> entry : values.entrySet()) {
Object value = entry.getValue();
PropertyInterface property = entry.getKey();
if (value != null && !(property instanceof MethodProperty)) {
Class<?> fieldClass = property.getClazz();
if (Code.class.isAssignableFrom(fieldClass)) {
Class<? extends Code> codeClass = (Class<? extends Code>) fieldClass;
value = getCode(codeClass, value);
} else if (IdUtils.hasId(fieldClass)) {
Map<Object, Object> loadedReferencesOfClass = loadedReferences.computeIfAbsent(fieldClass, c -> new HashMap<>());
if (loadedReferencesOfClass.containsKey(value)) {
value = loadedReferencesOfClass.get(value);
} else {
Object referencedValue;
if (View.class.isAssignableFrom(fieldClass)) {
Class<?> viewedClass = ViewUtil.getViewedClass(fieldClass);
if (Code.class.isAssignableFrom(viewedClass)) {
Class<? extends Code> codeClass = (Class<? extends Code>) viewedClass;
referencedValue = ViewUtil.view(getCode(codeClass, value), CloneHelper.newInstance(fieldClass));
} else {
Table<?> referenceTable = getTable(viewedClass);
referencedValue = referenceTable.readView(fieldClass, value, loadedReferences);
}
} else {
Table<?> referenceTable = getTable(fieldClass);
referencedValue = referenceTable.read(value, loadedReferences);
}
loadedReferencesOfClass.put(value, referencedValue);
value = referencedValue;
}
} else if (AbstractTable.isDependable(property)) {
value = getTable(fieldClass).read(value);
} else if (fieldClass == Set.class) {
Set<?> set = (Set<?>) property.getValue(result);
Class<?> enumClass = property.getGenericClass();
EnumUtils.fillSet((int) value, enumClass, set);
continue; // skip setValue, it's final
} else {
value = sqlDialect.convertToFieldClass(fieldClass, value);
}
property.setValue(result, value);
}
}
return result;
}
@SuppressWarnings("unchecked")
public <R> R readResultSetRowPrimitive(Class<R> clazz, ResultSet resultSet) throws SQLException {
Object value = resultSet.getObject(1);
return (R) sqlDialect.convertToFieldClass(clazz, value);
}
<U> void addClass(Class<U> clazz) {
if (!tables.containsKey(clazz)) {
tables.put(clazz, null); // break recursion. at some point it is checked if a clazz is already in the tables map.
Table<U> table = createTable(clazz);
tables.put(table.getClazz(), table);
}
}
protected <U> Table<U> createTable(Class<U> clazz) {
return new Table<>(this, clazz);
}
void createTables() {
List<AbstractTable<?>> tableList = new ArrayList<>(tables.values());
for (AbstractTable<?> table : tableList) {
table.createTable(sqlDialect);
}
for (AbstractTable<?> table : tableList) {
table.createIndexes(sqlDialect);
}
for (AbstractTable<?> table : tableList) {
table.createConstraints(sqlDialect);
}
}
void dropTables() {
List<AbstractTable<?>> tableList = new ArrayList<>(tables.values());
for (AbstractTable<?> table : tableList) {
table.dropConstraints(sqlDialect);
}
for (AbstractTable<?> table : tableList) {
table.dropTable(sqlDialect);
}
}
// TODO move someplace where it's available for all kind of repositories (Memory DB for example)
void createCodes() {
startTransaction(Connection.TRANSACTION_READ_UNCOMMITTED);
createConstantCodes();
createCsvCodes();
endTransaction(true);
}
@SuppressWarnings("unchecked")
private void createConstantCodes() {
for (AbstractTable<?> table : tables.values()) {
if (Code.class.isAssignableFrom(table.getClazz())) {
Class<? extends Code> codeClass = (Class<? extends Code>) table.getClazz();
List<? extends Code> constants = Codes.getConstants(codeClass);
for (Code code : constants) {
((Table<Code>) table).insert(code);
}
}
}
}
@SuppressWarnings("unchecked")
private void createCsvCodes() {
List<AbstractTable<?>> tableList = new ArrayList<>(tables.values());
for (AbstractTable<?> table : tableList) {
if (Code.class.isAssignableFrom(table.getClazz())) {
Class<? extends Code> clazz = (Class<? extends Code>) table.getClazz();
InputStream is = clazz.getResourceAsStream(clazz.getSimpleName() + ".csv");
if (is != null) {
CsvReader reader = new CsvReader(is, getObjectProvider());
List<? extends Code> values = reader.readValues(clazz);
values.forEach(value -> ((Table<Code>) table).insert(value));
}
}
}
}
private BiFunction<Class<?>, Object, Object> getObjectProvider() {
return new BiFunction<Class<?>, Object, Object>() {
@Override
public Object apply(Class<?> clazz, Object id) {
return read(clazz, id);
}
};
}
@SuppressWarnings("unchecked")
public <U> AbstractTable<U> getAbstractTable(Class<U> clazz) {
if (!tables.containsKey(clazz)) {
throw new IllegalArgumentException(clazz.getName());
}
return (AbstractTable<U>) tables.get(clazz);
}
public <U> Table<U> getTable(Class<U> clazz) {
AbstractTable<U> table = getAbstractTable(clazz);
if (!(table instanceof Table)) throw new IllegalArgumentException(clazz.getName());
return (Table<U>) table;
}
@SuppressWarnings("unchecked")
public <U> Table<U> getTable(String className) {
for (Entry<Class<?>, AbstractTable<?>> entry : tables.entrySet()) {
if (entry.getKey().getName().equals(className)) {
return (Table<U>) entry.getValue();
}
}
return null;
}
public String name(Object classOrKey) {
if (classOrKey instanceof Class) {
// TODO
return tableByName.entrySet().stream().filter(e -> e.getValue().getClazz() == classOrKey).findAny().get().getKey();
} else {
return column(classOrKey);
}
}
public String table(Class<?> clazz) {
AbstractTable<?> table = getAbstractTable(clazz);
return table.getTableName();
}
public String column(Object key) {
PropertyInterface property = Keys.getProperty(key);
Class<?> declaringClass = property.getDeclaringClass();
if (tables.containsKey(declaringClass)) {
AbstractTable<?> table = getAbstractTable(declaringClass);
return table.column(property);
} else {
LinkedHashMap<String, PropertyInterface> columns = findColumns(declaringClass);
for (Map.Entry<String, PropertyInterface> entry : columns.entrySet()) {
if (StringUtils.equals(entry.getValue().getPath(), property.getPath())) {
return entry.getKey();
}
}
return null;
}
}
public boolean tableExists(Class<?> clazz) {
return tables.containsKey(clazz);
}
public <T extends Code> T getCode(Class<T> clazz, Object codeId) {
if (isLoading(clazz)) {
// this special case is needed to break a possible reference cycle
return getTable(clazz).read(codeId);
}
List<T> codes = getCodes(clazz);
return Codes.findCode(codes, codeId);
}
@SuppressWarnings("unchecked")
private <T extends Code> boolean isLoading(Class<T> clazz) {
CodeCacheItem<T> cacheItem = (CodeCacheItem<T>) codeCache.get(clazz);
return cacheItem != null && cacheItem.isLoading();
}
@SuppressWarnings("unchecked")
<T extends Code> List<T> getCodes(Class<T> clazz) {
synchronized (clazz) {
CodeCacheItem<T> cacheItem = (CodeCacheItem<T>) codeCache.get(clazz);
if (cacheItem == null || !cacheItem.isValid()) {
updateCode(clazz);
}
cacheItem = (CodeCacheItem<T>) codeCache.get(clazz);
List<T> codes = cacheItem.getCodes();
return codes;
}
}
private <T extends Code> void updateCode(Class<T> clazz) {
CodeCacheItem<T> codeCacheItem = new CodeCacheItem<>();
codeCache.put(clazz, codeCacheItem);
List<T> codes = find(clazz, By.all());
codeCacheItem.setCodes(codes);
}
public void invalidateCodeCache(Class<?> clazz) {
codeCache.remove(clazz);
}
public int getMaxIdentifierLength() {
return sqlDialect.getMaxIdentifierLength();
}
public Map<String, AbstractTable<?>> getTableByName() {
return tableByName;
}
} |
package de.dakror.arise.layer;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Polygon;
import java.awt.Stroke;
import java.awt.event.MouseEvent;
import java.awt.geom.AffineTransform;
import java.io.IOException;
import de.dakror.arise.game.Game;
import de.dakror.arise.game.world.City;
import de.dakror.arise.game.world.Transfer;
import de.dakror.arise.layer.dialog.AttackCityDialog;
import de.dakror.arise.net.packet.Packet;
import de.dakror.arise.net.packet.Packet.PacketTypes;
import de.dakror.arise.net.packet.Packet05Resources;
import de.dakror.arise.settings.TransferType;
import de.dakror.gamesetup.ui.Component;
/**
* @author Dakror
*/
public class WorldHUDLayer extends MPLayer
{
public static City selectedCity;
public static City hoveredCity;
boolean showArrow;
Point drag;
City draggedOnto;
TransferType dragType;
int hovId, draggedOntoId;
boolean waitingForResources;
@Override
public void init()
{
dragType = TransferType.TROOPS_ATTACK;
}
@Override
public void draw(Graphics2D g)
{
// if (selectedCity != null)
// int width = 300, height = 200;
// Helper.drawContainer(Game.getWidth() - width, Game.getHeight() - height, width, height, true, false, g);
try
{
if (showArrow && drag != null && hoveredCity != null)
{
Stroke s = g.getStroke();
Color c = g.getColor();
g.setStroke(new BasicStroke(12, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_ROUND));
g.setColor(Color.black);
int x1 = hoveredCity.getX() + Game.world.x + City.SIZE / 2, y1 = hoveredCity.getY() + Game.world.y + City.SIZE / 2;
// g.drawLine(x1, y1, drag.x, drag.y);
// g.setStroke(new BasicStroke(10, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_ROUND));
// g.setColor(dragType.getColor());
// g.drawLine(x1, y1, drag.x, drag.y);
g.setStroke(s);
double angle = Math.atan2(drag.y - y1, drag.x - x1);
int length = (int) (Math.sqrt(Math.pow((drag.x - x1), 2) + Math.pow((drag.y - y1), 2))) - 24;
AffineTransform old = g.getTransform();
AffineTransform at = g.getTransform();
at.rotate(angle, x1, y1);
at.translate(x1, y1);
g.setTransform(at);
Polygon arrow = new Polygon();
if (length >= 0)
{
arrow.addPoint(0, -6);
arrow.addPoint(0, 6);
arrow.addPoint(length, 6);
}
arrow.addPoint(length, 18);
arrow.addPoint(length + 24, 0);
arrow.addPoint(length, -18);
if (length >= 0) arrow.addPoint(length, -6);
g.setStroke(new BasicStroke(2, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_ROUND));
g.setColor(Color.black);
g.draw(arrow);
g.setStroke(s);
g.setColor(dragType.getColor());
g.fill(arrow);
g.setColor(c);
g.setTransform(old);
}
}
catch (NullPointerException e)
{}
}
@Override
public void update(int tick)
{
if (!Game.world.anyCityActive) selectedCity = null;
}
@Override
public void mouseDragged(MouseEvent e)
{
super.mouseDragged(e);
selectedCity = null;
showArrow = hoveredCity != null && hoveredCity.getUserId() == Game.userID && e.getModifiers() == 16; // LMB
if (showArrow)
{
drag = e.getPoint();
boolean ontoAny = false;
for (Component c : Game.world.components)
{
if (c instanceof City)
{
if (!c.equals(hoveredCity) && !c.equals(selectedCity)) c.state = 0;
if (c.contains(drag.x - Game.world.x, drag.y - Game.world.y) && !c.equals(hoveredCity))
{
boolean canTarget = true;
for (Component c1 : Game.world.components)
{
if (c1 instanceof Transfer && ((Transfer) c1).getCityFrom().equals(hoveredCity) && ((Transfer) c1).getCityTo().equals(c))
{
canTarget = false;
break;
}
}
if (!canTarget) continue;
drag = new Point(c.getX() + Game.world.x + City.SIZE / 2, c.getY() + Game.world.y + City.SIZE / 2);
draggedOnto = (City) c;
draggedOnto.state = 2;
ontoAny = true;
}
}
}
if (!ontoAny) draggedOnto = null;
}
}
@Override
public void mouseReleased(MouseEvent e)
{
super.mouseReleased(e);
if (draggedOnto != null)
{
try
{
waitingForResources = true;
hovId = hoveredCity.getId();
draggedOntoId = draggedOnto.getId();
Game.client.sendPacket(new Packet05Resources(hoveredCity.getId()));
}
catch (IOException e1)
{
e1.printStackTrace();
}
Game.currentGame.addLayer(new LoadingLayer());
}
drag = null;
showArrow = false;
draggedOnto = null;
}
@Override
public void onReceivePacket(Packet p)
{
super.onReceivePacket(p);
if (p.getType() == PacketTypes.RESOURCES && waitingForResources)
{
Packet05Resources packet = (Packet05Resources) p;
if (packet.getCityId() == hovId)
{
Game.currentGame.removeLoadingLayer();
Game.currentGame.addLayer(new AttackCityDialog(hovId, draggedOntoId, packet.getResources()));
hovId = 0;
draggedOntoId = 0;
}
waitingForResources = false;
}
}
} |
package com.reason.lang.ocaml;
import com.intellij.lang.ASTNode;
import com.intellij.lang.ParserDefinition;
import com.intellij.lang.PsiParser;
import com.intellij.lexer.Lexer;
import com.intellij.openapi.project.Project;
import com.intellij.psi.FileViewProvider;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.TokenType;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.IFileElementType;
import com.intellij.psi.tree.TokenSet;
import com.reason.ide.files.OclFile;
import com.reason.ide.files.OclInterfaceFile;
import com.reason.ide.files.OclInterfaceFileType;
import com.reason.lang.core.stub.type.ORStubElementType;
import com.reason.lang.core.stub.type.OclFileStubElementType;
import org.jetbrains.annotations.NotNull;
public class OclParserDefinition implements ParserDefinition {
private static final TokenSet WHITE_SPACES = TokenSet.create(TokenType.WHITE_SPACE);
private static final TokenSet COMMENTS = TokenSet.create(OclTypes.INSTANCE.MULTI_COMMENT);
private static final TokenSet STRINGS = TokenSet.create(OclTypes.INSTANCE.STRING_VALUE);
@NotNull
@Override
public Lexer createLexer(Project project) {
return new OclLexer();
}
@NotNull
public TokenSet getWhitespaceTokens() {
return WHITE_SPACES;
}
@NotNull
public TokenSet getCommentTokens() {
return COMMENTS;
}
@NotNull
public TokenSet getStringLiteralElements() {
return STRINGS;
}
@NotNull
public PsiParser createParser(final Project project) {
return new OclParser();
}
@NotNull
@Override
public IFileElementType getFileNodeType() {
return OclFileStubElementType.INSTANCE;
}
@NotNull
public PsiFile createFile(@NotNull FileViewProvider viewProvider) {
return viewProvider.getFileType() instanceof OclInterfaceFileType
? new OclInterfaceFile(viewProvider)
: new OclFile(viewProvider);
}
@NotNull
public SpaceRequirements spaceExistenceTypeBetweenTokens(ASTNode left, ASTNode right) {
return SpaceRequirements.MAY;
}
@NotNull
public PsiElement createElement(@NotNull ASTNode node) {
IElementType type = node.getElementType();
if (type instanceof ORStubElementType) {
//noinspection rawtypes
return ((ORStubElementType) node.getElementType()).createPsi(node);
}
throw new IllegalArgumentException(
"Not an OCaml node: " + node + " (" + type + ", " + type.getLanguage() + "): " + node.getText());
}
} |
package de.dwslab.risk.gui;
import static java.awt.Dialog.ModalityType.APPLICATION_MODAL;
import static java.lang.Boolean.FALSE;
import static java.lang.Boolean.TRUE;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.EventObject;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import com.mxgraph.model.mxCell;
import com.mxgraph.swing.mxGraphComponent;
import com.mxgraph.swing.view.mxCellEditor;
import com.mxgraph.view.mxCellState;
import de.dwslab.risk.gui.exception.RoCAException;
import de.dwslab.risk.gui.model.Entity;
import de.dwslab.risk.gui.model.Grounding;
public class CustomCellEditor extends mxCellEditor {
public CustomCellEditor(mxGraphComponent graphComponent) {
super(graphComponent);
}
@Override
public void startEditing(Object cell, EventObject event) {
editingCell = cell;
UserObjectEditDialog dialog = new UserObjectEditDialog((mxCell) cell, event, graphComponent);
dialog.pack();
dialog.setModalityType(APPLICATION_MODAL);
dialog.setLocationRelativeTo(graphComponent);
dialog.setVisible(true);
editingCell = null;
}
@Override
public void stopEditing(boolean cancel) {
// calling super causes false labels
// super.stopEditing(cancel);
}
private static class UserObjectEditDialog extends JDialog {
private final JPanel panel;
private final mxGraphComponent graphComponent;
private final mxCell cell;
private EventObject event;
public UserObjectEditDialog(mxCell cell, EventObject event, mxGraphComponent graphComponent) {
super(SwingUtilities.getWindowAncestor(graphComponent), "Eigenschaften");
this.cell = cell;
this.event = event;
this.graphComponent = graphComponent;
panel = new JPanel(new GridBagLayout());
if (cell.getValue() instanceof Entity) {
Entity entity = (Entity) cell.getValue();
if (entity.getType().getName().equals("infra")) {
createDialogInfra(entity);
} else {
createDialogRisk(entity);
}
} else if (cell.getValue() instanceof Grounding) {
Grounding grounding = (Grounding) cell.getValue();
if (grounding.getPredicate().getName().equals("hasRiskDegree")) {
createDialogHasRiskDegree(grounding);
} else {
createDialogDependsOn(grounding);
}
} else {
throw new RoCAException("Unknown graph UserObject: " + cell.getValue() + " "
+ cell.getValue().getClass());
}
add(panel);
}
private void createDialogInfra(Entity entity) {
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(10, 10, 0, 10);
c.gridx = 0;
c.gridy = 0;
panel.add(new JLabel("Name"), c);
c.gridx = 1;
JTextField textFieldName = new JTextField(15);
textFieldName.setText(entity.getName());
panel.add(textFieldName, c);
c.gridx = 0;
c.gridy = 1;
panel.add(new JLabel("Status"), c);
c.gridx = 1;
String[] values = { "online", "unbekannt", "offline" };
JComboBox<String> comboOffline = new JComboBox<>(values);
if (TRUE.equals(entity.getOffline())) {
comboOffline.setSelectedIndex(2);
} else if (FALSE.equals(entity.getOffline())) {
comboOffline.setSelectedIndex(0);
} else {
comboOffline.setSelectedIndex(1);
}
panel.add(comboOffline, c);
c.insets = new Insets(30, 10, 10, 10);
c.gridx = 0;
c.gridy = 2;
JButton buttonOk = new JButton("OK");
buttonOk.addActionListener(l -> {
setVisible(false);
entity.setName(textFieldName.getText());
mxCellState state = graphComponent.getGraph().getView().getState(cell, true);
String style = cell.getStyle();
int fillIndex = -1;
if (style != null) {
fillIndex = style.indexOf("fillColor");
}
switch (comboOffline.getSelectedIndex()) {
case 0:
entity.setOffline(FALSE);
if (fillIndex < 0) {
cell.setStyle((style == null ? "" : style + ";") + "fillColor=#22ff22");
} else {
StringBuilder str = new StringBuilder(style);
str.replace(fillIndex + 11, fillIndex + 17, "22ff22");
cell.setStyle(str.toString());
}
break;
case 1:
entity.setOffline(null);
if (fillIndex < 0) {
cell.setStyle((style == null ? "" : style + ";") + "fillColor=#adc5ff");
} else {
StringBuilder str = new StringBuilder(style);
str.replace(fillIndex + 11, fillIndex + 17, "adc5ff");
cell.setStyle(str.toString());
}
break;
case 2:
entity.setOffline(TRUE);
if (fillIndex < 0) {
cell.setStyle((style == null ? "" : style + ";") + "fillColor=#ff2222");
} else {
StringBuilder str = new StringBuilder(style);
str.replace(fillIndex + 11, fillIndex + 17, "ff2222");
cell.setStyle(str.toString());
}
break;
default:
throw new RoCAException("Unknown ComboBox index");
}
graphComponent.redraw(state);
graphComponent.labelChanged(cell, cell.getValue(), event);
});
getRootPane().setDefaultButton(buttonOk);
panel.add(buttonOk, c);
c.gridx = 1;
JButton buttonCancel = new JButton("Abbrechen");
buttonCancel.addActionListener(l -> {
setVisible(false);
});
panel.add(buttonCancel, c);
}
private void createDialogRisk(Entity entity) {
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(10, 10, 0, 10);
c.gridx = 0;
c.gridy = 0;
panel.add(new JLabel("Name"), c);
c.gridx = 1;
JTextField textFieldName = new JTextField(15);
textFieldName.setText(entity.getName());
panel.add(textFieldName, c);
c.insets = new Insets(30, 10, 10, 10);
c.gridx = 0;
c.gridy = 1;
JButton buttonOk = new JButton("OK");
buttonOk.addActionListener(l -> {
setVisible(false);
entity.setName(textFieldName.getText());
mxCellState state = graphComponent.getGraph().getView().getState(cell, true);
graphComponent.redraw(state);
graphComponent.labelChanged(cell, cell.getValue(), event);
});
getRootPane().setDefaultButton(buttonOk);
panel.add(buttonOk, c);
c.gridx = 1;
JButton buttonCancel = new JButton("Abbrechen");
buttonCancel.addActionListener(l -> {
setVisible(false);
});
panel.add(buttonCancel, c);
}
private void createDialogDependsOn(Grounding grounding) {
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(10, 10, 0, 10);
c.gridx = 0;
c.gridy = 0;
panel.add(new JLabel("Relation:"), c);
c.gridx = 1;
JLabel labelName = new JLabel(grounding.toString());
panel.add(labelName, c);
c.insets = new Insets(30, 10, 10, 10);
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 2;
JButton buttonOk = new JButton("OK");
buttonOk.addActionListener(l -> {
setVisible(false);
});
getRootPane().setDefaultButton(buttonOk);
panel.add(buttonOk, c);
}
private void createDialogHasRiskDegree(Grounding grounding) {
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(10, 10, 0, 10);
c.gridx = 0;
c.gridy = 0;
panel.add(new JLabel("Gewicht"), c);
c.gridx = 1;
JTextField textFieldWeight = new JTextField(15);
textFieldWeight.setText(grounding.getValues().get(2));
panel.add(textFieldWeight, c);
c.insets = new Insets(30, 10, 10, 10);
c.gridx = 0;
c.gridy = 1;
JButton buttonOk = new JButton("OK");
buttonOk.addActionListener(l -> {
setVisible(false);
grounding.getValues().set(2, textFieldWeight.getText());
mxCellState state = graphComponent.getGraph().getView().getState(cell);
graphComponent.redraw(state);
graphComponent.labelChanged(cell, cell.getValue(), event);
});
getRootPane().setDefaultButton(buttonOk);
panel.add(buttonOk, c);
c.gridx = 1;
JButton buttonCancel = new JButton("Abbrechen");
buttonCancel.addActionListener(l -> {
setVisible(false);
});
panel.add(buttonCancel, c);
}
}
} |
package org.owasp.esapi.reference;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Level;
import org.owasp.esapi.ESAPI;
import org.owasp.esapi.LogFactory;
import org.owasp.esapi.Logger;
import org.owasp.esapi.User;
public class Log4JLogFactory implements LogFactory {
private HashMap loggersMap = new HashMap();
/**
* Null argument constructor for this implementation of the LogFactory interface
* needed for dynamic configuration.
*/
public Log4JLogFactory() {}
/**
* {@inheritDoc}
*/
public Logger getLogger(Class clazz) {
// If a logger for this class already exists, we return the same one, otherwise we create a new one.
Logger classLogger = (Logger) loggersMap.get(clazz);
if (classLogger == null) {
classLogger = new Log4JLogger(clazz.getName());
loggersMap.put(clazz, classLogger);
}
return classLogger;
}
/**
* {@inheritDoc}
*/
public Logger getLogger(String moduleName) {
// If a logger for this module already exists, we return the same one, otherwise we create a new one.
Logger moduleLogger = (Logger) loggersMap.get(moduleName);
if (moduleLogger == null) {
moduleLogger = new Log4JLogger(moduleName);
loggersMap.put(moduleName, moduleLogger);
}
return moduleLogger;
}
private static class Log4JLogger implements org.owasp.esapi.Logger {
/** The jlogger object used by this class to log everything. */
private org.apache.log4j.Logger jlogger = null;
/** The module name using this log. */
private String moduleName = null;
/** The application name defined in ESAPI.properties */
private String applicationName=ESAPI.securityConfiguration().getApplicationName();
/** Log the application name? */
private static boolean logAppName = ESAPI.securityConfiguration().getLogApplicationName();
/** Log the server ip? */
private static boolean logServerIP = ESAPI.securityConfiguration().getLogServerIP();
/**
* Public constructor should only ever be called via the appropriate LogFactory
*
* @param moduleName the module name
*/
private Log4JLogger(String moduleName) {
this.moduleName = moduleName;
this.jlogger = org.apache.log4j.Logger.getLogger(applicationName + ":" + moduleName);
}
/**
* {@inheritDoc}
* Note: In this implementation, this change is not persistent,
* meaning that if the application is restarted, the log level will revert to the level defined in the
* ESAPI SecurityConfiguration properties file.
*/
public void setLevel(int level)
{
try {
jlogger.setLevel(convertESAPILeveltoLoggerLevel( level ));
}
catch (IllegalArgumentException e) {
this.error(Logger.SECURITY_FAILURE, "", e);
}
}
private static Level convertESAPILeveltoLoggerLevel(int level)
{
switch (level) {
case Logger.OFF: return Level.OFF;
case Logger.FATAL: return Level.FATAL;
case Logger.ERROR: return Level.ERROR;
case Logger.WARNING: return Level.WARN;
case Logger.INFO: return Level.INFO;
case Logger.DEBUG: return Level.DEBUG; //fine
case Logger.TRACE: return Level.TRACE; //finest
case Logger.ALL: return Level.ALL;
default: {
throw new IllegalArgumentException("Invalid logging level. Value was: " + level);
}
}
}
/**
* {@inheritDoc}
*/
public void trace(EventType type, String message, Throwable throwable) {
log(Level.TRACE, type, message, throwable);
}
/**
* {@inheritDoc}
*/
public void trace(EventType type, String message) {
log(Level.TRACE, type, message, null);
}
/**
* {@inheritDoc}
*/
public void debug(EventType type, String message, Throwable throwable) {
log(Level.DEBUG, type, message, throwable);
}
/**
* {@inheritDoc}
*/
public void debug(EventType type, String message) {
log(Level.DEBUG, type, message, null);
}
/**
* {@inheritDoc}
*/
public void info(EventType type, String message) {
log(Level.INFO, type, message, null);
}
/**
* {@inheritDoc}
*/
public void info(EventType type, String message, Throwable throwable) {
log(Level.INFO, type, message, throwable);
}
/**
* {@inheritDoc}
*/
public void warning(EventType type, String message, Throwable throwable) {
log(Level.WARN, type, message, throwable);
}
/**
* {@inheritDoc}
*/
public void warning(EventType type, String message) {
log(Level.WARN, type, message, null);
}
/**
* {@inheritDoc}
*/
public void error(EventType type, String message, Throwable throwable) {
log(Level.ERROR, type, message, throwable);
}
/**
* {@inheritDoc}
*/
public void error(EventType type, String message) {
log(Level.ERROR, type, message, null);
}
/**
* {@inheritDoc}
*/
public void fatal(EventType type, String message, Throwable throwable) {
log(Level.FATAL, type, message, throwable);
}
/**
* {@inheritDoc}
*/
public void fatal(EventType type, String message) {
log(Level.FATAL, type, message, null);
}
/**
* Log the message after optionally encoding any special characters that might be dangerous when viewed
* by an HTML based log viewer. Also encode any carriage returns and line feeds to prevent log
* injection attacks. This logs all the supplied parameters plus the user ID, user's source IP, a logging
* specific session ID, and the current date/time.
*
* It will only log the message if the current logging level is enabled, otherwise it will
* discard the message.
*
* @param level the severity level of the security event
* @param type the type of the event (SECURITY, FUNCTIONALITY, etc.)
* @param success whether this was a failed or successful event
* @param message the message
* @param throwable the throwable
*/
private void log(Level level, EventType type, String message, Throwable throwable) {
// Check to see if we need to log
if (!jlogger.isEnabledFor( level )) return;
// create a random session number for the user to represent the user's 'session', if it doesn't exist already
String sid = null;
HttpServletRequest request = ESAPI.httpUtilities().getCurrentRequest();
if ( request != null ) {
HttpSession session = request.getSession( false );
if ( session != null ) {
sid = (String)session.getAttribute("ESAPI_SESSION");
// if there is no session ID for the user yet, we create one and store it in the user's session
if ( sid == null ) {
sid = ""+ ESAPI.randomizer().getRandomInteger(0, 1000000);
session.setAttribute("ESAPI_SESSION", sid);
}
}
}
// ensure there's something to log
if ( message == null ) {
message = "";
}
// ensure no CRLF injection into logs for forging records
String clean = message.replace( '\n', '_' ).replace( '\r', '_' );
if ( ((DefaultSecurityConfiguration)ESAPI.securityConfiguration()).getLogEncodingRequired() ) {
clean = ESAPI.encoder().encodeForHTML(message);
if (!message.equals(clean)) {
clean += " (Encoded)";
}
}
// log user information - username:session@ipaddr
User user = ESAPI.authenticator().getCurrentUser();
String userInfo = "";
if ( user != null && type != null) {
userInfo = user.getAccountName()+ ":" + sid + "@"+ user.getLastHostAddress();
}
// log server, port, app name, module name -- server:80/app/module
StringBuilder appInfo = new StringBuilder();
if ( ESAPI.currentRequest() != null && logServerIP ) {
appInfo.append( ESAPI.currentRequest().getLocalAddr() + ":" + ESAPI.currentRequest().getLocalPort() );
}
if ( logAppName ) {
appInfo.append( "/" + applicationName );
}
appInfo.append( "/" + moduleName );
// log the message
jlogger.log(level, "[" + userInfo + " -> " + appInfo + "] " + clean, throwable);
}
/**
* {@inheritDoc}
*/
public boolean isDebugEnabled() {
return jlogger.isEnabledFor(Level.DEBUG);
}
/**
* {@inheritDoc}
*/
public boolean isErrorEnabled() {
return jlogger.isEnabledFor(Level.ERROR);
}
/**
* {@inheritDoc}
*/
public boolean isFatalEnabled() {
return jlogger.isEnabledFor(Level.FATAL);
}
/**
* {@inheritDoc}
*/
public boolean isInfoEnabled() {
return jlogger.isEnabledFor(Level.INFO);
}
/**
* {@inheritDoc}
*/
public boolean isTraceEnabled() {
return jlogger.isEnabledFor(Level.TRACE);
}
/**
* {@inheritDoc}
*/
public boolean isWarningEnabled() {
return jlogger.isEnabledFor(Level.WARN);
}
}
} |
package org.procrastinationpatients.tts.core;
/**
* @Author Decker & his father -- Jeffrey
*/
public class Lane {
Vehicle[] vehicles;
Lane input;
Lane output;
Container container ;
public Lane()
{
}
public Lane(Container container, Lane input , Lane output)
{
this.container = container ;
this.input = input ;
this.output = output ;
}
public Lane getInput(){
return this.input ;
}
public Lane getOutput(){
return this.output ;
}
public Container getContainer(){
return this.container ;
}
public void setInput(Lane input){ this.input = input ;}
public void setOutput(Lane output){ this.output = output ;}
} |
package org.taktik.mpegts.sources;
import java.nio.ByteBuffer;
import java.util.Map;
import com.google.common.collect.Maps;
import org.taktik.mpegts.MTSPacket;
/**
* This class will attempt to fix timestamp discontinuities
* when switching from one source to another.
* This should allow for smoother transitions between videos.<br>
* This class does 3 things:
* <ol>
* <li> Rewrite the PCR to be continuous with the previous source</li>
* <li> Rewrite the PTS of the PES to be continuous with the previous source</li>
* <li> Rewrite the continuity counter to be continuous with the previous source</li>
* </ol>
*
* Code using this class should call {@link #fixContinuity(org.taktik.mpegts.MTSPacket)} for each source packet,
* then {@link #nextSource()} after the last packet of the current source and before the first packet of the next source.
*/
public class ContinuityFixer {
private Map<Integer, MTSPacket> pcrPackets;
private Map<Integer, MTSPacket> allPackets;
private Map<Integer, Long> ptss;
private Map<Integer, Long> lastPTSsOfPreviousSource;
private Map<Integer, Long> lastPCRsOfPreviousSource;
private Map<Integer, Long> firstPCRsOfCurrentSource;
private Map<Integer, Long> firstPTSsOfCurrentSource;
private Map<Integer, MTSPacket> lastPacketsOfPreviousSource = Maps.newHashMap();
private Map<Integer, MTSPacket> firstPacketsOfCurrentSource = Maps.newHashMap();
private Map<Integer, Integer> continuityFixes = Maps.newHashMap();
private boolean firstSource;
public ContinuityFixer() {
pcrPackets = Maps.newHashMap();
allPackets = Maps.newHashMap();
ptss = Maps.newHashMap();
lastPTSsOfPreviousSource = Maps.newHashMap();
lastPCRsOfPreviousSource = Maps.newHashMap();
firstPCRsOfCurrentSource = Maps.newHashMap();
firstPTSsOfCurrentSource = Maps.newHashMap();
lastPacketsOfPreviousSource = Maps.newHashMap();
firstPacketsOfCurrentSource = Maps.newHashMap();
continuityFixes = Maps.newHashMap();
firstSource = true;
}
/**
* Signals the {@link org.taktik.mpegts.sources.ContinuityFixer} that the following
* packet will be from another source.
*
* Call this method after the last packet of the current source and before the first packet of the next source.
*/
public void nextSource() {
firstPCRsOfCurrentSource.clear();
lastPCRsOfPreviousSource.clear();
firstPTSsOfCurrentSource.clear();
lastPTSsOfPreviousSource.clear();
firstPacketsOfCurrentSource.clear();
lastPacketsOfPreviousSource.clear();
for (MTSPacket mtsPacket : pcrPackets.values()) {
lastPCRsOfPreviousSource.put(mtsPacket.getPid(), mtsPacket.getAdaptationField().getPcr().getValue());
}
lastPTSsOfPreviousSource.putAll(ptss);
lastPacketsOfPreviousSource.putAll(allPackets);
pcrPackets.clear();
ptss.clear();
allPackets.clear();
firstSource = false;
}
/**
* Fix the continuity of the packet.
*
* Call this method for each source packet, in order.
*
* @param tsPacket The packet to fix.
*/
public void fixContinuity(MTSPacket tsPacket) {
int pid = tsPacket.getPid();
allPackets.put(pid, tsPacket);
if (!firstPacketsOfCurrentSource.containsKey(pid)) {
firstPacketsOfCurrentSource.put(pid, tsPacket);
if (!firstSource) {
MTSPacket lastPacketOfPreviousSource = lastPacketsOfPreviousSource.get(pid);
int continuityFix = lastPacketOfPreviousSource == null ? 0 : lastPacketOfPreviousSource.getContinuityCounter() - tsPacket.getContinuityCounter();
if (tsPacket.isContainsPayload()) {
continuityFix++;
}
continuityFixes.put(pid, continuityFix);
}
}
if (!firstSource) {
tsPacket.setContinuityCounter((tsPacket.getContinuityCounter() + continuityFixes.get(pid)) % 16);
}
fixPTS(tsPacket, pid);
fixPCR(tsPacket, pid);
}
private void fixPCR(MTSPacket tsPacket, int pid) {
if (tsPacket.isAdaptationFieldExist() && tsPacket.getAdaptationField() != null) {
if (tsPacket.getAdaptationField().isPcrFlag()) {
if (!firstPCRsOfCurrentSource.containsKey(pid)) {
firstPCRsOfCurrentSource.put(pid, tsPacket.getAdaptationField().getPcr().getValue());
}
rewritePCR(tsPacket);
pcrPackets.put(pid, tsPacket);
}
}
}
private void fixPTS(MTSPacket tsPacket, int pid) {
if (tsPacket.isContainsPayload()) {
ByteBuffer payload = tsPacket.getPayload();
if (((payload.get(0) & 0xff) == 0) && ((payload.get(1) & 0xff) == 0) && ((payload.get(2) & 0xff) == 1)) {
int extension = payload.getShort(6) & 0xffff;
if ((extension & 0x80) != 0) {
// PTS is present
// TODO add payload size check to avoid indexoutofboundexception
long pts = (((payload.get(9) & 0xE)) << 29) | (((payload.getShort(10) & 0xFFFE)) << 14) | ((payload.getShort(12) & 0xFFFE) >> 1);
if (!firstPTSsOfCurrentSource.containsKey(pid)) {
firstPTSsOfCurrentSource.put(pid, pts);
}
if (!firstSource) {
long newPts = Math.round(pts + (getTimeGap(pid) / 300.0) + 100 * ((27_000_000 / 300.0) / 1_000));
payload.put(9, (byte) (0x20 | ((newPts & 0x1C0000000l) >> 29) | 0x1));
payload.putShort(10, (short) (0x1 | ((newPts & 0x3FFF8000) >> 14)));
payload.putShort(12, (short) (0x1 | ((newPts & 0x7FFF) << 1)));
payload.rewind();
pts = newPts;
}
ptss.put(pid, pts);
}
}
}
}
private long getTimeGap(int pid) {
// Try with PCR of the same PID
Long lastPCROfPreviousSource = lastPCRsOfPreviousSource.get(pid);
if (lastPCROfPreviousSource == null) {
lastPCROfPreviousSource = 0l;
}
Long firstPCROfCurrentSource = firstPCRsOfCurrentSource.get(pid);
if (firstPCROfCurrentSource != null) {
return lastPCROfPreviousSource - firstPCROfCurrentSource;
}
// Try with any PCR
if (!lastPCRsOfPreviousSource.isEmpty()) {
int pcrPid = lastPCRsOfPreviousSource.keySet().iterator().next();
lastPCROfPreviousSource = lastPCRsOfPreviousSource.get(pcrPid);
if (lastPCROfPreviousSource == null) {
lastPCROfPreviousSource = 0l;
}
firstPCROfCurrentSource = firstPCRsOfCurrentSource.get(pcrPid);
if (firstPCROfCurrentSource != null) {
return lastPCROfPreviousSource - firstPCROfCurrentSource;
}
}
// Try with PTS of the same PID
Long lastPTSOfPreviousSource = lastPTSsOfPreviousSource.get(pid);
if (lastPTSOfPreviousSource == null) {
lastPTSOfPreviousSource = 0l;
}
Long firstPTSofCurrentSource = firstPTSsOfCurrentSource.get(pid);
if (firstPTSofCurrentSource != null) {
return (lastPTSOfPreviousSource - firstPTSofCurrentSource) * 300;
}
// Try with any PTS
if (!lastPTSsOfPreviousSource.isEmpty()) {
int randomPid = lastPTSsOfPreviousSource.keySet().iterator().next();
lastPTSOfPreviousSource = lastPTSsOfPreviousSource.get(randomPid);
if (lastPTSOfPreviousSource == null) {
lastPTSOfPreviousSource = 0l;
}
firstPTSofCurrentSource = firstPTSsOfCurrentSource.get(randomPid);
if (firstPTSofCurrentSource != null) {
return (lastPTSOfPreviousSource - firstPTSofCurrentSource) * 300;
}
}
return 0;
}
private void rewritePCR(MTSPacket tsPacket) {
if (firstSource) {
return;
}
long timeGap = getTimeGap(tsPacket.getPid());
long pcr = tsPacket.getAdaptationField().getPcr().getValue();
long newPcr = pcr + timeGap + 100 * ((27_000_000) / 1_000);
tsPacket.getAdaptationField().getPcr().setValue(newPcr);
}
} |
package foodtruck.schedule;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
import com.google.common.collect.ImmutableList;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.Duration;
import org.joda.time.LocalDate;
import org.joda.time.LocalTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import foodtruck.email.EmailNotifier;
import foodtruck.geolocation.GeoLocator;
import foodtruck.geolocation.GeolocationGranularity;
import foodtruck.model.DayOfWeek;
import foodtruck.model.Location;
import foodtruck.model.StopOrigin;
import foodtruck.model.Story;
import foodtruck.model.Truck;
import foodtruck.model.TruckStop;
import foodtruck.util.Clock;
/**
* Matches a tweet to a location, truck and time.
* @author aviolette@gmail.com
* @since 9/22/11
*/
public class TruckStopMatcher {
private static final Logger log = Logger.getLogger(TruckStopMatcher.class.getName());
public static final int DEFAULT_STOP_LENGTH_IN_HOURS = 2;
public static final String TIME_PATTERN = "(\\d+(:\\d+)*\\s*(p|pm|a|am|a\\.m\\.|p\\.m\\.)?)|noon";
static final String TIME_PATTERN_STRICT =
"(\\d+:\\d+\\s*(p|pm|a|am|a\\.m\\.|p\\.m\\.)?)|noon|(\\d+\\s*(p|pm|a|am|a\\.m\\.|p\\.m\\.)|((11|12|1|2|3|4|5|6)\\b))";
private static final String TIME_RANGE_PATTERN =
"(" + TIME_PATTERN + ")\\s*-\\s*(" + TIME_PATTERN + ")[\\s|\\$|\\n|,|\\.&&[^\\-]]";
private static final String TOMORROW = "2morrow|tmw|tmrw|tomorrow|maana|mañana";
private final AddressExtractor addressExtractor;
private final GeoLocator geoLocator;
private final DateTimeFormatter formatter;
private final Clock clock;
private final EmailNotifier notifier;
private final Location center;
private final LocalTime defaultLunchTime;
private final Pattern endTimePattern = Pattern.compile("\\b(close at|leaving at|until|til|till) (" + TIME_PATTERN + ")"),
timeRangePattern = Pattern.compile(TIME_RANGE_PATTERN, Pattern.CASE_INSENSITIVE),
atTimePattern = Pattern.compile("\\b(be at|ETA|open at|opening at|opens at|arrive at|there at) (" + TIME_PATTERN_STRICT + ")"),
schedulePattern = Pattern.compile(".*M:.+(\\b|\\n)T:.+(\\b|\\n)W:.+"),
simpleDateParser = Pattern.compile("(\\d{1,2})/(\\d{1,2})");
@Inject
public TruckStopMatcher(AddressExtractor extractor, GeoLocator geoLocator, DateTimeZone defaultZone, Clock clock,
EmailNotifier notifier, @Named("center") Location center, @DefaultStartTime LocalTime startTime) {
this.addressExtractor = extractor;
this.geoLocator = geoLocator;
this.center = center;
this.defaultLunchTime = startTime;
formatter = DateTimeFormat.forPattern("hhmma").withZone(defaultZone);
this.clock = clock;
this.notifier = notifier;
}
/**
* Matches a truck to a location via a story.
* @param truck a truck
* @param story a story
* @return a TruckStopMatch if the match can be made, otherwise {@code null}
*/
public @Nullable TruckStopMatch match(Truck truck, Story story) {
TruckStop.Builder truckStopBuilder = TruckStop.builder()
.origin(StopOrigin.TWITTER)
.truck(truck);
try {
// Ignore story if it's a retweet of another story
checkIfShared(story);
// Some trucks will only count if they contain a certain regular expression; conversely, we want to filter
// out tweets where regular expressions don't match
final String lowerCaseTweet = story.getText().toLowerCase();
verifyMatchOnlyExpression(truck, story, lowerCaseTweet);
// Some tweets indicate a daily schedule or a set of stops...skip those
verifySchedule(story);
// Some tweets are talking about happenings on other days...skip those too
verifyOtherDay(story);
// Get the location out of the story
Location location = extractLocation(story, truck);
verifyLocation(location);
truckStopBuilder.location(location);
// Get the time out of the story
boolean softEnding = extractDateTime(truck, story, truckStopBuilder);
return TruckStopMatch.builder()
.stop(truckStopBuilder
.notes(ImmutableList.of(String.format("Tweet received for location: '%s'", story.getText())))
.build())
.text(story.getText())
.softEnding(softEnding)
.tweetId(story.getId())
.build();
} catch (UnmatchedException e) {
log.info(e.getMessage());
return null;
}
}
private void verifyOtherDay(Story tweet) throws UnmatchedException {
if (matchesOtherDay(tweet.getText())) {
throw new UnmatchedException(String.format("Didn't match '%s' because it contained a day of the week", tweet));
}
}
private void verifySchedule(Story tweet) throws UnmatchedException {
String lowerCaseTweet = tweet.getText().toLowerCase();
final boolean morning = isMorning(tweet.getTime());
if (lowerCaseTweet.contains("stops") ||
(morning && (lowerCaseTweet.contains("schedule"))) || containsAbbreviatedSchedule(tweet.getText())) {
throw new UnmatchedException(String.format("Ignoring '%s' because the word 'schedule' is there", tweet.getText()));
}
}
private boolean extractDateTime(Truck truck, Story tweet, TruckStop.Builder tsBuilder) throws UnmatchedException {
// Handling time ranges (e.g. 11am-2pm)
handleTimeRange(tweet, tsBuilder);
// Handling start-time only
handleStartTime(truck, tweet, tsBuilder);
// If there's no start time, just start it now or (if certain rules apply) at lunch hour
handleImmediateStart(truck, tweet, tsBuilder);
// See if we can parse the end time out if it wasn't specified as a range earlier
handleSeparateEndTime(tweet, tsBuilder);
// If there is no end time, just guess
return handleSoftEnding(truck, tsBuilder);
}
private boolean handleSoftEnding(Truck truck, TruckStop.Builder tsBuilder) {
if (tsBuilder.endTime() != null) {
return false;
}
// If it's a lunch truck, extend its time to a min of 1pm.
if (tsBuilder.startTime().getHourOfDay() == 10 && tsBuilder.startTime().getMinuteOfHour() >= 30
&& truck.getCategoryList().contains("Lunch")) {
tsBuilder.endTime(tsBuilder.startTime().withTime(14, 0, 0, 0));
} else {
tsBuilder.endTime(tsBuilder.startTime().plusHours(stopTime(truck, tsBuilder.startTime())));
}
return true;
}
private void handleSeparateEndTime(Story tweet, TruckStop.Builder tsBuilder) {
if (tsBuilder.endTime() == null) {
final DateTime endTime = parseEndTime(tweet.getText(), tsBuilder.startTime());
tsBuilder.endTime(endTime);
if (tsBuilder.hasTimes() &&
(tsBuilder.startTime().isAfter(endTime) && endTime.isAfter(tweet.getTime()))) {
tsBuilder.startTime(tweet.getTime());
}
}
}
private void handleImmediateStart(Truck truck, Story tweet, TruckStop.Builder tsBuilder) {
if (tsBuilder.startTime() != null) {
return;
}
// Cupcake trucks and such should not be matched at all by this rule since they make many frequent stops
if (canStartNow(truck, isMorning(tweet.getTime()), tweet.getText())) {
tsBuilder.startTime(tweet.getTime());
} else {
tsBuilder.startTime(tweet.getTime().withTime(defaultLunchTime));
tsBuilder.endTime(null);
}
}
private void handleStartTime(Truck truck, Story tweet, TruckStop.Builder tsBuilder) {
Matcher m;
// This is detecting something in the format: We will be at Merchandise mart at 11:00.
if (tsBuilder.startTime() == null) {
m = atTimePattern.matcher(tweet.getText());
if (m.find()) {
final LocalDate date = tweet.getTime().toLocalDate();
tsBuilder.startTime(parseTime(m.group(2), date, null));
if (tsBuilder.startTime() != null) {
if (tsBuilder.startTime().getHourOfDay() == 0) {
tsBuilder.startTime(tsBuilder.startTime().withHourOfDay(12));
}
tsBuilder.endTime(tsBuilder.startTime().plusHours(stopTime(truck, tsBuilder.startTime())));
}
// This is a special case, since matching ranges like that will produce a lot of
// false positives, but 11-1 is commonly used for lunch hour
} else if (tweet.getText().contains("11-1")) {
tsBuilder.startTime(clock.currentDay().toDateTime(new LocalTime(11, 0), clock.zone()));
tsBuilder.endTime(clock.currentDay().toDateTime(new LocalTime(13, 0), clock.zone()));
} else if (tweet.getText().contains("11-2")) {
tsBuilder.startTime(clock.currentDay().toDateTime(new LocalTime(11, 0), clock.zone()));
tsBuilder.endTime(clock.currentDay().toDateTime(new LocalTime(14, 0), clock.zone()));
} else if (tweet.getText().contains("11a") && truck.getCategories().contains("Lunch")) {
tsBuilder.startTime(clock.currentDay().toDateTime(new LocalTime(11, 0), clock.zone()));
tsBuilder.endTime(clock.currentDay().toDateTime(new LocalTime(13, 0), clock.zone()));
} else if (tweet.getTime().getHourOfDay() > 12 && tweet.getTime().getHourOfDay() < 17 &&
(tweet.getText().contains("tonight") || tweet.getText().contains("tonite"))) {
tsBuilder.startTime(clock.currentDay().toDateTime(new LocalTime(17, 30), clock.zone()));
}
}
}
private void handleTimeRange(Story tweet, TruckStop.Builder tsBuilder) {
Matcher m = timeRangePattern.matcher(tweet.getText() + " ");
if (m.find()) {
final LocalDate date = tweet.getTime().toLocalDate();
tsBuilder.startTime(parseTime(m.group(1), date, null));
tsBuilder.endTime(parseTime(m.group(5), date, tsBuilder.startTime()));
if (tsBuilder.hasTimes() && tsBuilder.startTime().getHourOfDay() > 12 &&
tsBuilder.startTime().isAfter(tsBuilder.endTime())) {
tsBuilder.startTime(tsBuilder.startTime().minusHours(12));
} else if (tsBuilder.hasTimes() && tsBuilder.endTime().isBefore(tweet.getTime())) {
Duration duration = new Duration(tsBuilder.startTime().toInstant(),
tsBuilder.endTime().toInstant());
tsBuilder.startTime(tsBuilder.startTime().plusHours(12));
tsBuilder.endTime(tsBuilder.startTime().plus(duration));
}
}
}
private void verifyLocation(Location location) throws UnmatchedException {
if (location == null) {
throw new UnmatchedException("Location is not specified");
}
if (location.distanceFrom(center) > 50.0d) {
throw new UnmatchedException("Center greater than 50 miles");
}
}
private void checkIfShared(Story tweet) throws UnmatchedException {
if (tweet.isManualRetweet()) {
throw new UnmatchedException("Retweeted: " + tweet.getText());
}
}
private boolean isMorning(DateTime time) {
LocalTime lt = time.toLocalTime();
// anything before 4 counts as the previous night
return lt.isAfter(new LocalTime(4, 0)) && lt.isBefore(new LocalTime(10, 30));
}
/**
* Tests for tweets like this: <code></code>THE TRUCK: M: 600 W Chicago T: NBC Tower W: Clark & Monroe
* TH: Madison & Wacker + Montrose & Ravenswood (5pm) F: Lake & Wabash</code>
*/
private boolean containsAbbreviatedSchedule(String tweetText) {
return schedulePattern.matcher(tweetText).find();
}
private int stopTime(Truck truck, DateTime startTime) {
if (startTime.getHourOfDay() < 11 && truck.getCategories().contains("MorningSquatter")) {
return Math.max(13 - startTime.getHourOfDay(), DEFAULT_STOP_LENGTH_IN_HOURS);
}
return truck.getCategories().contains("1HRStops") ? 1 : DEFAULT_STOP_LENGTH_IN_HOURS;
}
private boolean canStartNow(Truck truck, boolean morning, String tweetText) {
if (!morning) {
return true;
}
Set<String> categories = truck.getCategories();
boolean breakfast = categories.contains("Breakfast");
if (breakfast && categories.contains("Lunch")) {
String lower = tweetText.toLowerCase();
return lower.matches(".*b(\\w*|')fast.*") || lower.contains("open for b") || lower.contains("brunch")
|| lower.contains("mornin") || lower.contains("biscuit") || lower.matches(".*rise\\s*(&|and)\\s*shine.*");
} else if (breakfast) {
return true;
}
return false;
}
private void verifyMatchOnlyExpression(Truck truck, Story tweet, String lower) throws UnmatchedException {
Pattern p = truck.getMatchOnlyIf();
if (p != null) {
Matcher m = p.matcher(lower);
if (!m.find()) {
throw new UnmatchedException(String.format("Match-only-if expression '%s' not found for tweet '%s'",
truck.getMatchOnlyIfString(), tweet.getText()));
}
}
p = truck.getDonotMatchIf();
if (p != null) {
Matcher m = p.matcher(lower);
if ( m.find()) {
throw new UnmatchedException(String.format("Do-not-match-if expression '%s' found in tweet '%s'", truck.getDonotMatchIfString(), tweet.getText()));
}
}
}
private boolean matchesOtherDay(String tweetText) {
Matcher matcher = simpleDateParser.matcher(tweetText);
// matches date pattern
if (matcher.find()) {
LocalDate date = clock.currentDay();
String first = matcher.group(1);
String second = matcher.group(2);
if (Integer.parseInt(first) != date.getMonthOfYear() || Integer.parseInt(second) != date.getDayOfMonth()) {
return true;
}
}
// check to see if it has a day-of-the-week in the tweet (or 'tomorrow') that's not today
StringBuilder pattern = new StringBuilder();
pattern.append("\\b(");
DayOfWeek now = clock.dayOfWeek();
for (DayOfWeek dayOfWeek : DayOfWeek.values()) {
if (dayOfWeek != now) {
pattern.append(dayOfWeek.getMatchPattern()).append("|");
}
}
pattern.append(TOMORROW).append(")\\b");
return Pattern.compile(pattern.toString(), Pattern.CASE_INSENSITIVE).matcher(tweetText).find();
}
private @Nullable Location extractLocation(Story tweet, Truck truck) {
List<String> addresses = addressExtractor.parse(tweet.getText(), truck);
Location tweetLocation = tweet.getLocation();
if (tweetLocation != null) {
log.info("Location data enabled for tweet from " + truck.getId());
// Currently not using this function...remove next line to re-enabled
}
log.log(Level.INFO, "Extracted these addresses: {0} from tweet: {1}", new Object[] {addresses, tweet.getText()});
for (String address : addresses) {
Location loc = geoLocator.locate(address, GeolocationGranularity.NARROW);
if (loc != null && loc.isResolved()) {
if (loc.isJustResolved()) {
this.notifier.systemNotifyLocationAdded(loc, tweet, truck);
}
return loc;
}
}
return null;
}
private @Nullable DateTime parseTime(String timeText, LocalDate date, @Nullable DateTime after) {
int plusDay = 0;
if (timeText.toLowerCase().equals("noon")) {
timeText = "12:00p.m.";
}
timeText = timeText.replace(".", "");
if (timeText.endsWith("p") || timeText.endsWith("a")) {
timeText = timeText + "m";
}
timeText = timeText.replace(":", "");
timeText = timeText.replace(" ", "");
timeText = timeText.toLowerCase();
timeText = timeText.trim();
String tmpTime = timeText;
String suffix = null;
if (timeText.endsWith("pm") || timeText.endsWith("am")) {
tmpTime = timeText.substring(0, timeText.length() - 2);
suffix = timeText.substring(timeText.length() - 2);
}
switch (tmpTime.length()) {
case 1:
tmpTime = "0" + tmpTime + "00";
break;
case 2:
tmpTime = tmpTime + "00";
break;
case 3:
tmpTime = "0" + tmpTime;
break;
}
if (suffix != null) {
} else if (after != null) {
// TODO: handle military time
tmpTime = tmpTime.trim();
if (tmpTime.length() == 3) {
tmpTime = "0" + tmpTime;
}
int hour = Integer.parseInt(tmpTime.substring(0, 2).trim());
int min = Integer.parseInt(tmpTime.substring(2, 4).trim());
if (after.isAfter(date.toDateTime(new LocalTime(hour, min), clock.zone()))) {
suffix = "pm";
} else if (hour == 12) {
if (after.getHourOfDay() < 13) {
suffix = "pm";
} else {
suffix = "am";
plusDay++;
}
} else {
suffix = "am";
}
} else {
int hour = Integer.parseInt(tmpTime.substring(0, 2));
suffix = (hour > 8 && hour < 12) ? "am" : "pm";
}
timeText = tmpTime + suffix;
try {
return formatter.parseDateTime(timeText).withDate(date.getYear(), date.getMonthOfYear(),
date.getDayOfMonth()).plusDays(plusDay);
} catch (IllegalArgumentException iae) {
log.log(Level.WARNING, iae.getMessage(), iae);
return null;
}
}
private @Nullable DateTime parseEndTime(String tweetText, DateTime startTime) {
Matcher matcher = endTimePattern.matcher(tweetText.toLowerCase());
if (matcher.find()) {
DateTime dt = parseTime(matcher.group(2), startTime.toLocalDate(), startTime);
if (dt == null) {
return null;
}
if (startTime.isAfter(dt)) {
return dt.plusHours(12);
}
return dt;
}
return null;
}
static class UnmatchedException extends Exception {
public UnmatchedException(String msg) {
super(msg);
}
}
} |
package io;
import java.util.Collection;
import gui.ConsolePane;
import vk.core.api.CompilationUnit;
import vk.core.api.CompileError;
import vk.core.api.CompilerResult;
import vk.core.api.JavaStringCompiler;
import vk.core.api.TestFailure;
import vk.core.api.TestResult;
import vk.core.internal.InternalCompiler;
public class Testing {
private static ConsolePane console;
public static void setConsole(ConsolePane console1){//TODO: schoener machen
console = console1;
}
public static void compile(CompilationUnit[] comp_uns){ //gibt fehlermeldungen, wenn vorhanden auf die console aus
JavaStringCompiler comp = getJSC(comp_uns);
CompilerResult comp_res = comp.getCompilerResult();
if(comp_res.hasCompileErrors()){
for(CompilationUnit cu: comp_uns){
Collection<CompileError> errors = comp_res.getCompilerErrorsForCompilationUnit(cu);
print_errors_to_console(errors);
}
}
}
private static void print_errors_to_console(Collection<CompileError> errors){ //gibt compileerrors auf console aus
console.set_textln("Compilation-Errors:");
for(CompileError error: errors){
console.set_text(error.getCodeLineContainingTheError());
console.set_textln(": "+error.getMessage());
}
console.set_textln("");
}
public static boolean hasCompileErrors(CompilationUnit[] comp_uns){ //fuer next-button
JavaStringCompiler comp = getJSC(comp_uns);
CompilerResult comp_res = comp.getCompilerResult();
compile(comp_uns);
return comp_res.hasCompileErrors();
}
public static boolean tests_passed(CompilationUnit[] comp_uns){ //fuer next-button
if(!hasCompileErrors(comp_uns)){
JavaStringCompiler comp = getJSC(comp_uns);
TestResult test_res = comp.getTestResult();
test(comp_uns);
return(test_res.getNumberOfFailedTests() == 0);
} else return false;
}
public static void test(CompilationUnit[] comp_uns){ //gibt testergebnisse auf console aus
JavaStringCompiler comp = getJSC(comp_uns);
TestResult test_res = comp.getTestResult();
int tests_ok = test_res.getNumberOfSuccessfulTests();
int tests_fail = test_res.getNumberOfFailedTests();
console.set_textln("Testresult:");
Collection<TestFailure> fails = test_res.getTestFailures();
console.set_textln("OK: "+tests_ok+" FAIL: "+tests_fail);
for(TestFailure fail: fails){ //TODO: gucken was da ausgegeben wird und dann anpassen (von der formatierung her)
console.set_textln("Testname: "+fail.getTestClassName());
console.set_textln("Methodname: "+fail.getMethodName());
console.set_textln(fail.getMessage());
console.set_textln("");
}
console.set_textln("");
}
private static JavaStringCompiler getJSC(CompilationUnit[] comp_uns){ //erzeugt JSC und ruftcompileAndRunTests() auf
JavaStringCompiler comp = new InternalCompiler(comp_uns);
comp.compileAndRunTests();
return comp;
}
} |
package io.bastillion.common.util;
import io.bastillion.manage.util.EncryptionUtil;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import java.io.File;
import java.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Utility to look up configurable commands and resources
*/
public class AppConfig {
private static Logger log = LoggerFactory.getLogger(AppConfig.class);
private static PropertiesConfiguration prop;
public static final String CONFIG_DIR = StringUtils.isNotEmpty(System.getProperty("CONFIG_DIR")) ? System.getProperty("CONFIG_DIR").trim() : AppConfig.class.getClassLoader().getResource(".").getPath();
static {
try {
//move configuration to specified dir
if (StringUtils.isNotEmpty(System.getProperty("CONFIG_DIR"))) {
File configFile = new File(CONFIG_DIR + "BastillionConfig.properties");
if (!configFile.exists()) {
File oldConfig = new File(AppConfig.class.getClassLoader().getResource(".").getPath() + "BastillionConfig.properties");
FileUtils.moveFile(oldConfig, configFile);
}
configFile = new File(CONFIG_DIR + "jaas.conf");
if (!configFile.exists()) {
File oldConfig = new File(AppConfig.class.getClassLoader().getResource(".").getPath() + "jaas.conf");
FileUtils.moveFile(oldConfig, configFile);
}
}
prop = new PropertiesConfiguration(CONFIG_DIR + "BastillionConfig.properties");
} catch (Exception ex) {
log.error(ex.toString(), ex);
}
}
private AppConfig() {
}
/**
* gets the property from config
*
* @param name property name
* @return configuration property
*/
public static String getProperty(String name) {
String property = null;
if (StringUtils.isNotEmpty(name)) {
if (StringUtils.isNotEmpty(System.getenv(name))) {
property = System.getenv(name);
} else if (StringUtils.isNotEmpty(System.getenv(name.toUpperCase()))) {
property = System.getenv(name.toUpperCase());
} else {
property = prop.getString(name);
}
}
return property;
}
/**
* gets the property from config
*
* @param name property name
* @param defaultValue default value if property is empty
* @return configuration property
*/
public static String getProperty(String name, String defaultValue) {
String value = getProperty(name);
if (StringUtils.isEmpty(value)) {
value = defaultValue;
}
return value;
}
/**
* gets the property from config and replaces placeholders
*
* @param name property name
* @param replacementMap name value pairs of place holders to replace
* @return configuration property
*/
public static String getProperty(String name, Map<String, String> replacementMap) {
String value = getProperty(name);
if (StringUtils.isNotEmpty(value)) {
//iterate through map to replace text
Set<String> keySet = replacementMap.keySet();
for (String key : keySet) {
//replace values in string
String rVal = replacementMap.get(key);
value = value.replace("${" + key + "}", rVal);
}
}
return value;
}
/**
* removes property from the config
*
* @param name property name
*/
public static void removeProperty(String name) {
//remove property
try {
prop.clearProperty(name);
prop.save();
} catch (Exception ex) {
log.error(ex.toString(), ex);
}
}
/**
* updates the property in the config
*
* @param name property name
* @param value property value
*/
public static void updateProperty(String name, String value) {
//remove property
if (StringUtils.isNotEmpty(value)) {
try {
prop.setProperty(name, value);
prop.save();
} catch (Exception ex) {
log.error(ex.toString(), ex);
}
}
}
/**
* checks if property is encrypted
*
* @param name property name
* @return true if property is encrypted
*/
public static boolean isPropertyEncrypted(String name) {
String property = prop.getString(name);
if (StringUtils.isNotEmpty(property)) {
return property.matches("^" + EncryptionUtil.CRYPT_ALGORITHM + "\\{.*\\}$");
} else {
return false;
}
}
/**
* decrypts and returns the property from config
*
* @param name property name
* @return configuration property
*/
public static String decryptProperty(String name) {
String retVal = prop.getString(name);
if (StringUtils.isNotEmpty(retVal)) {
retVal = retVal.replaceAll("^" + EncryptionUtil.CRYPT_ALGORITHM + "\\{", "").replaceAll("\\}$", "");
retVal = EncryptionUtil.decrypt(retVal);
}
return retVal;
}
/**
* encrypts and updates the property in the config
*
* @param name property name
* @param value property value
*/
public static void encryptProperty(String name, String value) {
//remove property
if (StringUtils.isNotEmpty(value)) {
try {
prop.setProperty(name, EncryptionUtil.CRYPT_ALGORITHM + "{" + EncryptionUtil.encrypt(value) + "}");
prop.save();
} catch (Exception ex) {
log.error(ex.toString(), ex);
}
}
}
} |
package gov.nih.nci.calab.service.login;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.log4j.Logger;
import gov.nih.nci.security.AuthenticationManager;
import gov.nih.nci.security.authorization.domainobjects.ProtectionElement;
import gov.nih.nci.security.authorization.domainobjects.ProtectionElementPrivilegeContext;
import gov.nih.nci.security.authorization.domainobjects.User;
import gov.nih.nci.security.dao.ProtectionElementSearchCriteria;
import gov.nih.nci.security.dao.UserSearchCriteria;
import gov.nih.nci.security.exceptions.CSException;
import gov.nih.nci.security.exceptions.CSObjectNotFoundException;
import gov.nih.nci.security.exceptions.CSTransactionException;
import gov.nih.nci.security.SecurityServiceProvider;
import gov.nih.nci.security.authorization.domainobjects.Role;
import gov.nih.nci.security.authorization.domainobjects.ProtectionGroup;
import gov.nih.nci.security.dao.RoleSearchCriteria;
import gov.nih.nci.security.dao.ProtectionGroupSearchCriteria;
import gov.nih.nci.calab.dto.security.SecurityBean;
/**
* The LoginService authenticates users into the calab system.
*
* @author doswellj
* @param applicationName sets the application name for use by CSM
* @param am Authentication Manager for CSM.
*/
public class LoginService
{
String applicationName = null;
AuthenticationManager am = null;
// TODO Make a singleton
/**
* LoginService Constructor
* @param strname name of the application
*/
public LoginService(String strname) throws Exception
{
this.applicationName = strname;
am = SecurityServiceProvider.getAuthenticationManager(this.applicationName);
//TODO Add Role implementation
}
/**
* The login method uses CSM to authenticated the user with LoginId and Password credentials
* @param strusername LoginId of the user
* @param strpassword Encrypted password of the user
* @return boolean identicating whether the user successfully authenticated
*/
public boolean login(String strUsername, String strPassword ) throws CSException
{
return am.login( strUsername,strPassword);
}
/**
* The userInfo method sets and authenticated user's information
* @param strLoginId LoginId of the authenticated user
* @return SecurityBean containing an authenticated user's information
*/
public SecurityBean setUserInfo(String strLoginId)
{
//TODO Implement method to query CSM_USER table and get logged in user's recordset
SecurityBean securityBean = new SecurityBean();
securityBean.setLoginId(strLoginId);
//set remaining info
return securityBean;
}
} |
package de.fosd.jdime.strategy;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import org.apache.log4j.Logger;
import de.fosd.jdime.common.ASTNodeArtifact;
import de.fosd.jdime.common.FileArtifact;
import de.fosd.jdime.common.Level;
import de.fosd.jdime.common.MergeContext;
import de.fosd.jdime.common.MergeTriple;
import de.fosd.jdime.common.NotYetImplementedException;
import de.fosd.jdime.common.operations.MergeOperation;
import de.fosd.jdime.stats.ASTStats;
import de.fosd.jdime.stats.MergeTripleStats;
import de.fosd.jdime.stats.Stats;
import de.fosd.jdime.stats.StatsElement;
/**
* Performs a structured merge.
*
* @author Olaf Lessenich
*
*/
public class StructuredStrategy extends MergeStrategy<FileArtifact> {
/**
* Logger.
*/
private static final Logger LOG = Logger
.getLogger(StructuredStrategy.class);
/*
* (non-Javadoc)
*
* @see de.fosd.jdime.strategy.MergeStrategy#merge(
* de.fosd.jdime.common.operations.MergeOperation,
* de.fosd.jdime.common.MergeContext)
*/
@Override
public final void merge(final MergeOperation<FileArtifact> operation,
final MergeContext context) throws IOException,
InterruptedException {
assert (operation != null);
assert (context != null);
MergeTriple<FileArtifact> triple = operation.getMergeTriple();
assert (triple != null);
assert (triple.isValid()) : "The merge triple is not valid!";
assert (triple.getLeft() instanceof FileArtifact);
assert (triple.getBase() instanceof FileArtifact);
assert (triple.getRight() instanceof FileArtifact);
assert (triple.getLeft().exists() && !triple.getLeft().isDirectory());
assert ((triple.getBase().exists() && !triple.getBase().isDirectory()) || triple
.getBase().isEmptyDummy());
assert (triple.getRight().exists() && !triple.getRight().isDirectory());
context.resetStreams();
FileArtifact target = null;
if (operation.getTarget() != null) {
assert (operation.getTarget() instanceof FileArtifact);
target = operation.getTarget();
assert (!target.exists() || target.isEmpty()) : "Would be overwritten: "
+ target;
}
// ASTNodeArtifacts are created from the input files.
// Then, a ASTNodeStrategy can be applied.
// The Result is pretty printed and can be written into the output file.
ASTNodeArtifact left, base, right;
ArrayList<Long> runtimes = new ArrayList<>();
MergeContext mergeContext;
int conflicts = 0;
int loc = 0;
int cloc = 0;
ASTStats astStats = null;
if (LOG.isDebugEnabled()) {
LOG.debug("Merging: " + triple.getLeft().getPath() + " "
+ triple.getBase().getPath() + " "
+ triple.getRight().getPath());
}
try {
for (int i = 0; i < context.getBenchmarkRuns() + 1
&& (i == 0 || context.isBenchmark()); i++) {
if (i == 0 && (!context.isBenchmark() || context.hasStats())) {
mergeContext = context;
} else {
mergeContext = (MergeContext) context.clone();
mergeContext.setSaveStats(false);
mergeContext.setOutputFile(null);
}
long cmdStart = System.currentTimeMillis();
left = new ASTNodeArtifact(triple.getLeft());
base = new ASTNodeArtifact(triple.getBase());
right = new ASTNodeArtifact(triple.getRight());
// Output tree
// Program program = new Program();
// program.state().reset();
// ASTNodeArtifact targetNode = new ASTNodeArtifact(program);
ASTNodeArtifact targetNode = ASTNodeArtifact
.createProgram(left);
targetNode.setRevision(left.getRevision());
targetNode.forceRenumbering();
if (LOG.isTraceEnabled()) {
LOG.trace("target.dumpTree(:");
System.out.println(targetNode.dumpTree());
}
MergeTriple<ASTNodeArtifact> nodeTriple = new MergeTriple<>(
triple.getMergeType(), left, base, right);
MergeOperation<ASTNodeArtifact> astMergeOp = new MergeOperation<>(
nodeTriple, targetNode);
if (LOG.isTraceEnabled()) {
LOG.trace("ASTMOperation.apply(context)");
}
astMergeOp.apply(mergeContext);
if (i == 0 && (!context.isBenchmark() || context.hasStats())) {
if (LOG.isTraceEnabled()) {
LOG.trace("Structured merge finished.");
if (!context.isDiffOnly()) {
LOG.trace("target.dumpTree():");
System.out.println(targetNode.dumpTree());
}
LOG.trace("Pretty-printing left:");
System.out.println(left.prettyPrint());
LOG.trace("Pretty-printing right:");
System.out.println(right.prettyPrint());
if (!context.isDiffOnly()) {
LOG.trace("Pretty-printing merge:");
if (mergeContext.isQuiet()) {
System.out.println(targetNode.prettyPrint());
}
}
}
if (!context.isDiffOnly()) {
try (
// process input stream
BufferedReader buf = new BufferedReader(
new StringReader(targetNode.prettyPrint()))) {
boolean conflict = false;
boolean afterconflict = false;
boolean inleft = false;
boolean inright = false;
int tmp = 0;
String line;
StringBuffer leftlines = null;
StringBuffer rightlines = null;
while ((line = buf.readLine()) != null) {
if (line.matches("^$")
|| line.matches("^\\s*$")) {
// skip empty lines
if (!conflict && !afterconflict) {
mergeContext.appendLine(line);
}
continue;
}
if (line.matches("^\\s*<<<<<<<.*")) {
conflict = true;
tmp = cloc;
conflicts++;
inleft = true;
if (!afterconflict) {
// new conflict or new chain of
// conflicts
leftlines = new StringBuffer();
rightlines = new StringBuffer();
} else {
// is directly after a previous conflict
// lets merge them
conflicts
}
} else if (line.matches("^\\s*=======.*")) {
inleft = false;
inright = true;
} else if (line.matches("^\\s*>>>>>>>.*")) {
conflict = false;
afterconflict = true;
if (tmp == cloc) {
// only empty lines
conflicts
}
inright = false;
} else {
loc++;
if (conflict) {
cloc++;
if (inleft) {
assert (leftlines != null);
leftlines.append(line).append(
System.lineSeparator());
} else if (inright) {
assert (rightlines != null);
rightlines.append(line).append(
System.lineSeparator());
}
} else {
if (afterconflict) {
assert (leftlines != null);
assert (rightlines != null);
// need to print the previous
// conflict(s)
mergeContext.appendLine("<<<<<<< ");
mergeContext.append(leftlines
.toString());
mergeContext.appendLine("======= ");
mergeContext.append(rightlines
.toString());
mergeContext.appendLine(">>>>>>> ");
}
afterconflict = false;
mergeContext.appendLine(line);
}
}
}
}
}
}
long runtime = System.currentTimeMillis() - cmdStart;
runtimes.add(runtime);
// collect stats
ASTStats leftStats = left.getStats(right.getRevision(),
Level.TOP);
ASTStats rightStats = right.getStats(left.getRevision(),
Level.TOP);
ASTStats targetStats = targetNode.getStats(null, Level.TOP);
assert (leftStats.getDiffStats(Level.ALL.toString())
.getMatches() == rightStats.getDiffStats(
Level.ALL.toString()).getMatches()) : "Number of matches should be equal in left and "
+ "right revision.";
astStats = ASTStats.add(leftStats, rightStats);
astStats.setConflicts(targetStats);
if (LOG.isInfoEnabled()) {
String sep = " / ";
int nodes = astStats.getDiffStats(Level.ALL.toString())
.getElements();
int matches = astStats.getDiffStats(Level.ALL.toString())
.getMatches();
int changes = astStats.getDiffStats(Level.ALL.toString())
.getAdded();
int removals = astStats.getDiffStats(Level.ALL.toString())
.getDeleted();
int conflictnodes = astStats.getDiffStats(
Level.ALL.toString()).getConflicting();
LOG.info("Change awareness (nodes" + sep + "matches" + sep
+ "changes" + sep + "removals" + sep
+ "conflicts): ");
LOG.info(nodes + sep + matches + sep + changes + sep
+ removals + sep + conflictnodes);
if (nodes > 0) {
LOG.info("Change awareness % (nodes" + sep + "matches"
+ sep + "changes" + sep + "removals" + sep
+ "conflicts): ");
LOG.info(100.0 + sep + 100.0 * matches / nodes + sep
+ 100.0 * changes / nodes + sep + 100.0
* removals / nodes + sep + 100.0
* conflictnodes / nodes);
}
}
if (context.hasStats()) {
Stats stats = context.getStats();
stats.addASTStats(astStats);
}
if (LOG.isInfoEnabled() && context.isBenchmark()
&& context.hasStats()) {
if (i == 0) {
LOG.info("Initial run: " + runtime + " ms");
} else {
LOG.info("Run " + i + " of "
+ context.getBenchmarkRuns() + ": " + runtime
+ " ms");
}
}
}
if (context.isBenchmark() && runtimes.size() > 1) {
// remove first run as it took way longer due to all the
// counting
runtimes.remove(0);
}
Long runtime = MergeContext.median(runtimes);
LOG.debug("Structured merge time was " + runtime + " ms.");
if (context.hasErrors()) {
System.err.println(context.getStdErr());
}
// write output
if (target != null) {
assert (target.exists());
target.write(context.getStdIn());
}
// add statistical data to context
if (context.hasStats()) {
assert (cloc <= loc);
Stats stats = context.getStats();
StatsElement linesElement = stats.getElement("lines");
assert (linesElement != null);
StatsElement newElement = new StatsElement();
newElement.setMerged(loc);
newElement.setConflicting(cloc);
linesElement.addStatsElement(newElement);
if (conflicts > 0) {
assert (cloc > 0);
stats.addConflicts(conflicts);
StatsElement filesElement = stats.getElement("files");
assert (filesElement != null);
filesElement.incrementConflicting();
} else {
assert (cloc == 0);
}
stats.increaseRuntime(runtime);
MergeTripleStats scenariostats = new MergeTripleStats(triple,
conflicts, cloc, loc, runtime, astStats);
stats.addScenarioStats(scenariostats);
}
} catch (Throwable t) {
LOG.fatal(t + " while merging " + triple.getLeft().getPath() + " "
+ triple.getBase().getPath() + " "
+ triple.getRight().getPath());
if (!context.isKeepGoing()) {
throw new Error(t);
} else {
if (context.hasStats()) {
MergeTripleStats scenariostats = new MergeTripleStats(
triple, t.toString());
context.getStats().addScenarioStats(scenariostats);
}
}
}
System.gc();
return;
}
/*
* (non-Javadoc)
*
* @see de.fosd.jdime.strategy.MergeStrategy#toString()
*/
@Override
public final String toString() {
return "structured";
}
/*
* (non-Javadoc)
*
* @see de.fosd.jdime.strategy.StatsInterface#createStats()
*/
@Override
public final Stats createStats() {
return new Stats(new String[] { "directories", "files", "lines",
"nodes" });
}
@Override
public final String getStatsKey(final FileArtifact artifact) {
// FIXME: remove me when implementation is complete!
throw new NotYetImplementedException(
"StructuredStrategy: Implement me!");
}
@Override
public final void dump(final FileArtifact artifact, final boolean graphical)
throws IOException {
new ASTNodeStrategy().dump(new ASTNodeArtifact(artifact), graphical);
}
} |
package reborncore.common.blocks;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.Material;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.state.StateFactory;
import net.minecraft.state.property.BooleanProperty;
import net.minecraft.state.property.DirectionProperty;
import net.minecraft.util.Hand;
import net.minecraft.util.hit.BlockHitResult;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction;
import net.minecraft.world.BlockView;
import net.minecraft.world.World;
import reborncore.api.ToolManager;
import reborncore.api.blockentity.IMachineGuiHandler;
import reborncore.api.blockentity.IUpgrade;
import reborncore.api.blockentity.IUpgradeable;
import reborncore.api.items.InventoryUtils;
import reborncore.common.BaseBlockEntityProvider;
import reborncore.common.blockentity.MachineBaseBlockEntity;
import reborncore.common.fluid.FluidUtil;
import reborncore.common.util.ItemHandlerUtils;
import reborncore.common.util.Tank;
import reborncore.common.util.WrenchUtils;
public abstract class BlockMachineBase extends BaseBlockEntityProvider {
public static DirectionProperty FACING = DirectionProperty.of("facing", Direction.Type.HORIZONTAL);
public static BooleanProperty ACTIVE = BooleanProperty.of("active");
boolean hasCustomStaes;
public BlockMachineBase() {
this(Block.Settings.of(Material.METAL));
}
public BlockMachineBase(Block.Settings builder) {
this(builder, false);
}
public BlockMachineBase(Block.Settings builder, boolean hasCustomStates) {
super(builder);
this.hasCustomStaes = hasCustomStates;
if (!hasCustomStates) {
this.setDefaultState(
this.stateFactory.getDefaultState().with(FACING, Direction.NORTH).with(ACTIVE, false));
}
BlockWrenchEventHandler.wrenableBlocks.add(this);
}
@Override
protected void appendProperties(StateFactory.Builder<Block, BlockState> builder) {
FACING = DirectionProperty.of("facing", Direction.Type.HORIZONTAL);
ACTIVE = BooleanProperty.of("active");
builder.add(FACING, ACTIVE);
}
@Override
public BlockEntity createBlockEntity(BlockView worldIn) {
return null;
}
@Override
public void onPlaced(World worldIn, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack) {
super.onPlaced(worldIn, pos, state, placer, stack);
setFacing(placer.getHorizontalFacing().getOpposite(), worldIn, pos);
}
@Override
public boolean allowsSpawning(BlockState state, BlockView world, BlockPos pos, EntityType<?> entityType_1) {
return false;
}
@Override
public void onBlockRemoved(BlockState state, World worldIn, BlockPos pos, BlockState newState, boolean isMoving) {
if (state.getBlock() != newState.getBlock()) {
ItemHandlerUtils.dropContainedItems(worldIn, pos);
super.onBlockRemoved(state, worldIn, pos, newState, isMoving);
}
}
public boolean isAdvanced() {
return false;
}
/*
* Right-click should open GUI for all non-wrench items
* Shift-Right-click should apply special action, like fill\drain bucket, install behavior, etc.
*/
@Override
public boolean activate(BlockState state, World worldIn, BlockPos pos, PlayerEntity playerIn, Hand hand, BlockHitResult hitResult) {
ItemStack stack = playerIn.getStackInHand(hand);
BlockEntity blockEntity = worldIn.getBlockEntity(pos);
// We extended BlockTileBase. Thus we should always have blockEntity entity. I hope.
if (blockEntity == null) {
return false;
}
if (blockEntity instanceof MachineBaseBlockEntity) {
Tank tank = ((MachineBaseBlockEntity) blockEntity).getTank();
if (tank != null && FluidUtil.interactWithFluidHandler(playerIn, hand, tank)) {
return true;
}
}
if (!stack.isEmpty()) {
if (ToolManager.INSTANCE.canHandleTool(stack)) {
if (WrenchUtils.handleWrench(stack, worldIn, pos, playerIn, hitResult.getSide())) {
return true;
}
} else if (stack.getItem() instanceof IUpgrade && blockEntity instanceof IUpgradeable) {
IUpgradeable upgradeableEntity = (IUpgradeable) blockEntity;
if (upgradeableEntity.canBeUpgraded()) {
if (InventoryUtils.insertItemStacked(upgradeableEntity.getUpgradeInvetory(), stack,
true).getCount() > 0) {
stack = InventoryUtils.insertItemStacked(upgradeableEntity.getUpgradeInvetory(), stack, false);
playerIn.setStackInHand(Hand.MAIN_HAND, stack);
return true;
}
}
}
}
if (getGui() != null && !playerIn.isSneaking()) {
getGui().open(playerIn, pos, worldIn);
return true;
}
return super.activate(state, worldIn, pos, playerIn, hand, hitResult);
}
public boolean isActive(BlockState state) {
return state.get(ACTIVE);
}
public Direction getFacing(BlockState state) {
return state.get(FACING);
}
public void setFacing(Direction facing, World world, BlockPos pos) {
if (hasCustomStaes) {
return;
}
world.setBlockState(pos, world.getBlockState(pos).with(FACING, facing));
}
public void setActive(Boolean active, World world, BlockPos pos) {
if (hasCustomStaes) {
return;
}
Direction facing = world.getBlockState(pos).get(FACING);
BlockState state = world.getBlockState(pos).with(ACTIVE, active).with(FACING, facing);
world.setBlockState(pos, state, 3);
}
public Direction getSideFromint(int i) {
if (i == 0) {
return Direction.NORTH;
} else if (i == 1) {
return Direction.SOUTH;
} else if (i == 2) {
return Direction.EAST;
} else if (i == 3) {
return Direction.WEST;
}
return Direction.NORTH;
}
public int getSideFromEnum(Direction facing) {
if (facing == Direction.NORTH) {
return 0;
} else if (facing == Direction.SOUTH) {
return 1;
} else if (facing == Direction.EAST) {
return 2;
} else if (facing == Direction.WEST) {
return 3;
}
return 0;
}
public abstract IMachineGuiHandler getGui();
} |
package it.matjaz.numerus.core;
import java.io.Serializable;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RomanNumeral implements Serializable, Cloneable, CharSequence {
/**
* The passed string representing the roman numeral.
*
* It is a serializable field.
*/
private String numeral;
public final String CORRECT_ROMAN_SYNTAX_REGEX = "^(M{0,3})(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$";
public final String NON_ROMAN_CHARS_REGEX = "[^MDCLXVI]";
/**
* Regex matching four consecutive characters M or C or X or I.
*/
private final String FOUR_CONSECUTIVE_TEN_LIKE_CHARS_REGEX = "(MMMM|CCCC|XXXX|IIII)";
/**
* Regex matching two characters D or L or V in the same string.
*/
private final String TWO_SAME_FIVE_LIKE_CHARS_REGEX = "(D.*D|L.*L|V.*V)";
private static final long serialVersionUID = 20150422L;
/**
* Constructs an empty RomanNumeral.
* <p>
* Contains no value so {@link #setNumeral(java.lang.String) the setter}
* needs to be used before using the RomanNumeral. Calling this method and
* then the setter leads to the same result.
*/
public RomanNumeral() {
this.numeral = "";
}
public RomanNumeral(String symbols) {
this.numeral = cleanUpcaseAndSyntaxCheckString(symbols);
}
/**
* Getter of the roman numerals String.
* <p>
* If RomanNumeral is not initialized, the returned String is <b>empty</b>.
*
* @return a String containing the roman numeral.
*/
public String getNumeral() {
return numeral;
}
/**
* Checks if this RomanNumeral contains a numeral or not.
* <p>
* Returns <code>true</code> if this RomanNumeal has a roman numeral stored
* in it, else <code>false</code> if contains just an empty string. The
* verification is done by confronting an empty String with the result of
* the {@link #getNumeral() getter}. The only way it can contain an empty
* string is to be initialized with the
* {@link #RomanNumeral() default constructor} (the one without parameters)
* without setting the value after that with the
* {@link #setNumeral(java.lang.String) setter}.
*
* @return <code>true</code> has a roman numeral stored in it, else
* <code>false</code> if it's empty.
*/
public boolean isInitialized() {
return !"".equals(getNumeral());
}
public void setNumeral(String numeral) {
this.numeral = cleanUpcaseAndSyntaxCheckString(numeral);
}
/**
* Performs a check of the syntax of the given roman numeral without storing
* it in a RomanNumeral.
* <p>
* Returns <code>true</code> if the passed String matches the syntax of
* roman numerals; else <code>false</code>. Useful to just quickly check if
* a String is a roman numeral when an instance of it is not needed. If the
* result is <code>true</code>, then the passed String can be successfully
* stored in a RomanNumeral by
* {@link #RomanNumeral(java.lang.String) constructor} or
* {@link #setNumeral(java.lang.String) setter}.
*
* @param numeralsToCheck the String to check the roman syntax on.
* @return <code>true</code> if the passed String is a roman numeral; else
* <code>false</code>.
*/
public static boolean isCorrectRomanSyntax(String numeralsToCheck) {
try {
new RomanNumeral().cleanUpcaseAndSyntaxCheckString(numeralsToCheck);
return true;
} catch (NumberFormatException ex) {
return false;
}
}
/**
* Removes all whitespace characters, upcases the String and verifies the
* roman syntax.
* <p>
* If the syntax does not match, an exception is thrown.
*
* @param symbols string to be cleaned, upcased and checked.
* @return given string without whitespaces and upcased.
*/
private String cleanUpcaseAndSyntaxCheckString(String symbols) {
String cleanSymbols = symbols.replaceAll("\\s+", "").toUpperCase();
throwExceptionIfIllegalRomanSyntax(cleanSymbols);
return cleanSymbols;
}
private static String findAllRegexMatchingSubstrings(String textToParse, String regex) {
StringBuilder matches = new StringBuilder();
Matcher matcher = Pattern.compile(regex).matcher(textToParse);
while (matcher.find()) {
matches.append(matcher.group());
}
return matches.toString();
}
private void throwExceptionIfIllegalRomanSyntax(String symbols) {
if (symbols.isEmpty()) {
throw new NumberFormatException("Empty roman numeral.");
}
if (symbols.length() >= 20) {
throw new NumberFormatException("Impossibly long roman numeral.");
}
if (!symbols.matches(CORRECT_ROMAN_SYNTAX_REGEX)) {
String illegalChars;
illegalChars = findAllRegexMatchingSubstrings(symbols, NON_ROMAN_CHARS_REGEX);
if (!illegalChars.isEmpty()) {
throw new NumberFormatException("Non roman characters: " + illegalChars);
}
illegalChars = findAllRegexMatchingSubstrings(symbols, FOUR_CONSECUTIVE_TEN_LIKE_CHARS_REGEX);
if (!illegalChars.isEmpty()) {
throw new NumberFormatException("Four consecutive: " + illegalChars);
}
illegalChars = findAllRegexMatchingSubstrings(symbols, TWO_SAME_FIVE_LIKE_CHARS_REGEX);
if (!illegalChars.isEmpty()) {
throw new NumberFormatException("Two D, L or V same characters: " + illegalChars);
}
throw new NumberFormatException("Generic roman numeral syntax error.");
}
}
/**
* Returns the hash of this RomanNumeral.
* <p>
* The hashcode is created using only the roman numeral String in this
* RomanNumeral. Uses {@link Objects#hashCode(java.lang.Object)} and
* overrides {@link Object#hashCode()}.
*
* @return the hash of this RomanNumeral.
* @see Object#hashCode()
*/
@Override
public int hashCode() {
int hash = 7;
hash = 71 * hash + Objects.hashCode(this.numeral);
return hash;
}
/**
* Verifies if the passed Object is equal to this.
* <p>
* Returns <code>true</code> if the passed Object is a RomanNumeral and
* contains the same roman numeral as this one, else <code>false</code>.
*
* @param otherRomanNumeral to compare with this.
* @return a boolean telling if the two RomanNumerals are equal.
* @see Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object otherRomanNumeral) {
if (otherRomanNumeral == null) {
return false;
}
if (getClass() != otherRomanNumeral.getClass()) {
return false;
}
final RomanNumeral other = (RomanNumeral) otherRomanNumeral;
return Objects.equals(this.numeral, other.getNumeral());
}
/**
* Returns a String representation of this RomanNumeral, which is the roman
* numeral String stored in it.
* <p>
* This method is a delegate method and just calls {@link #getNumeral()} so
* the returned string is exactly the same for both. This method is here for
* compatibility reasons.
*
* @return a String containing the roman numeral.
* @see #getNumeral()
* @see Object#toString()
*/
@Override
public String toString() {
return getNumeral();
}
/**
* Returns a {@link Object#clone() clone} of this object with the same
* numeral.
* <p>
* The original and the RomanNumeral store an equal roman numeral and
* applying an {@link #equals(java.lang.Object) equals() } method to them,
* will result <code>true</code>.
* <p>
* Since the only field of RomanNumeral is a String, the
* CloneNotSupportedException should never raise.
* <p>
* Delegates {@link Object#clone()}.
*
* @return a RomanNumeral with the same numeral.
* @throws CloneNotSupportedException when super object is not cloneable.
* @see Object#clone()
*/
@Override
public RomanNumeral clone() throws CloneNotSupportedException {
return (RomanNumeral) super.clone();
}
/**
* Returns the lenght of the roman numeral contained in this RomanNumeral
* expressed as number of characters.
* <p>
* Delegates {@link String#length()}.
*
* @return number of characters in the roman numeral.
* @see String#length()
*/
@Override
public int length() {
return numeral.length();
}
/**
* Returns the character of the roman numeral at the given index.
* <p>
* Delegates {@link String#charAt(int)}.
*
* @param index of the wanted character in the roman numeral.
* @return the character at the given index.
* @see String#charAt(int)
*/
@Override
public char charAt(int index) {
return numeral.charAt(index);
}
/**
* Returns a CharSequence containing a part of this RomanNumeral.
* <p>
* The returned CharSequence contains the characters of the roman numeral
* from the start index (included) to the end index (exluded).
* <p>
* Delegates {@link String#subSequence(int, int)}.
*
* @param startIncluded index of the first character to be included.
* @param endNotIncluded index of the first character after the end of the
* wanted part.
* @return a part of the roman numeral as CharSequence.
* @see String#subSequence(int, int)
*/
@Override
public CharSequence subSequence(int startIncluded, int endNotIncluded) {
return numeral.subSequence(startIncluded, endNotIncluded);
}
} |
package gov.nih.nci.calab.service.remote;
import gov.nih.nci.cagrid.cananolab.service.globus.resource.ResourceConstants;
import gov.nih.nci.cagrid.common.Utils;
import gov.nih.nci.cagrid.discovery.client.DiscoveryClient;
import gov.nih.nci.cagrid.metadata.MetadataUtils;
import gov.nih.nci.cagrid.metadata.ResourcePropertyHelper;
import gov.nih.nci.cagrid.metadata.ServiceMetadata;
import gov.nih.nci.calab.dto.remote.GridNodeBean;
import java.io.Reader;
import java.io.StringReader;
import java.util.Collection;
import java.util.Map;
import java.util.TreeMap;
import org.apache.axis.message.addressing.EndpointReferenceType;
import org.globus.wsrf.utils.XmlUtils;
import org.w3c.dom.Element;
/**
* Grid service utils for grid node discovery and grid node URL lookup.
*
* @author pansu
*
*/
public class GridService {
/**
* Temp code to be replaced
*
* @param indexServiceURL
* @param domainModelName
* @return
* @throws Exception
*/
public static Map<String, GridNodeBean> discoverServicesTmp(
String indexServiceURL, String domainModelName) throws Exception {
Map<String, GridNodeBean> gridNodeMap = new TreeMap<String, GridNodeBean>();
GridNodeBean qaNode = new GridNodeBean(
"caNanoLab-QA",
"http://cananolab-qa.nci.nih.gov:8080/wsrf/services/cagrid/CaNanoLabSvc",
"http://cananolab-qa.nci.nih.gov/caNanoLabSDK/http/remoteService");
GridNodeBean devNode = new GridNodeBean(
"caNanoLab-DEV",
"http://cananolab-dev.nci.nih.gov:8080/wsrf/services/cagrid/CaNanoLabSvc",
"http://cananolab-dev.nci.nih.gov/caNanoLabSDK/http/remoteService");
gridNodeMap.put("caNanoLab-QA", qaNode);
gridNodeMap.put("caNanoLab-DEV", devNode);
return gridNodeMap;
}
/**
* Query the grid index service by domain model name and return a map of
* GridNodeBeans with keys being the hostnames.
*
* @param indexServiceURL
* @param domainModelName
* @return
* @throws Exception
*/
public static Map<String, GridNodeBean> discoverServices(
String indexServiceURL, String domainModelName) throws Exception {
Map<String, GridNodeBean> gridNodeMap = new TreeMap<String, GridNodeBean>();
DiscoveryClient discoveryClient = new DiscoveryClient(indexServiceURL);
EndpointReferenceType[] services = discoveryClient
.discoverDataServicesByDomainModel(domainModelName);
if (services != null) {
for (EndpointReferenceType service : services) {
String address = service.getAddress().toString();
String hostName = "", appServiceURL = "";
ServiceMetadata serviceMetaData = MetadataUtils
.getServiceMetadata(service);
if (serviceMetaData != null) {
if (serviceMetaData.getHostingResearchCenter() != null) {
if (serviceMetaData.getHostingResearchCenter()
.getResearchCenter() != null) {
hostName = serviceMetaData
.getHostingResearchCenter()
.getResearchCenter().getDisplayName();
}
}
}
// retrieve customized metadata
Element resourceProp = ResourcePropertyHelper
.getResourceProperty(service,
ResourceConstants.APPLICATIONSERVICEURL_MD_RP);
Reader xmlReader = new StringReader(XmlUtils
.toString(resourceProp));
appServiceURL = (String) Utils.deserializeObject(xmlReader,
String.class);
GridNodeBean gridNode = new GridNodeBean(hostName, address,
appServiceURL);
gridNodeMap.put(hostName, gridNode);
}
return gridNodeMap;
} else {
return null;
}
}
/**
* Return an array of GridNodeBean based on grid host names
*
* @param gridNodeMap
* @param gridNodeHosts
* @return
*/
public static GridNodeBean[] getGridNodesFromHostNames(
Map<String, GridNodeBean> gridNodeMap, String[] gridNodeHosts) {
GridNodeBean[] gridNodes = null;
if (gridNodeHosts.length == 0) {
Collection<GridNodeBean> selectedGrids = gridNodeMap.values();
gridNodes = new GridNodeBean[selectedGrids.size()];
selectedGrids.toArray(gridNodes);
} else {
gridNodes = new GridNodeBean[gridNodeHosts.length];
int i = 0;
for (String host : gridNodeHosts) {
gridNodes[i] = gridNodeMap.get(host);
i++;
}
}
return gridNodes;
}
} |
package de.jungblut.classification.eval;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.google.common.base.Preconditions;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import de.jungblut.classification.Classifier;
import de.jungblut.classification.ClassifierFactory;
import de.jungblut.classification.Predictor;
import de.jungblut.datastructure.ArrayUtils;
import de.jungblut.math.DoubleVector;
import de.jungblut.math.MathUtils;
import de.jungblut.math.MathUtils.PredictionOutcomePair;
import de.jungblut.partition.BlockPartitioner;
import de.jungblut.partition.Boundaries.Range;
/**
* Binary-/Multi-class classification evaluator utility that takes care of
* test/train splitting and its evaluation with various metrics.
*
* @author thomas.jungblut
*
*/
public final class Evaluator {
private static final Logger LOG = LogManager.getLogger(Evaluator.class);
private Evaluator() {
throw new IllegalAccessError();
}
public static class EvaluationResult {
int numLabels, correct, testSize, truePositive, falsePositive,
trueNegative, falseNegative;
int[][] confusionMatrix;
double auc, logLoss;
public double getAUC() {
return auc;
}
public double getLogLoss() {
return -logLoss / testSize;
}
public double getPrecision() {
return ((double) truePositive) / (truePositive + falsePositive);
}
public double getRecall() {
return ((double) truePositive) / (truePositive + falseNegative);
}
// fall-out
public double getFalsePositiveRate() {
return ((double) falsePositive) / (falsePositive + trueNegative);
}
public double getAccuracy() {
if (isBinary()) {
return ((double) truePositive + trueNegative)
/ (truePositive + trueNegative + falsePositive + falseNegative);
} else {
return correct / (double) testSize;
}
}
public double getF1Score() {
return 2d * (getPrecision() * getRecall())
/ (getPrecision() + getRecall());
}
public int getCorrect() {
if (!isBinary()) {
return correct;
} else {
return truePositive + trueNegative;
}
}
public int getNumLabels() {
return numLabels;
}
public int getTestSize() {
return testSize;
}
public int[][] getConfusionMatrix() {
return this.confusionMatrix;
}
public boolean isBinary() {
return numLabels == 2;
}
public void add(EvaluationResult res) {
correct += res.correct;
testSize += res.testSize;
truePositive += res.truePositive;
falsePositive += res.falsePositive;
trueNegative += res.trueNegative;
falseNegative += res.falseNegative;
auc += res.auc;
logLoss += res.logLoss;
if (this.confusionMatrix == null && res.confusionMatrix != null) {
this.confusionMatrix = res.confusionMatrix;
} else if (this.confusionMatrix != null && res.confusionMatrix != null) {
for (int i = 0; i < numLabels; i++) {
for (int j = 0; j < numLabels; j++) {
this.confusionMatrix[i][j] += res.confusionMatrix[i][j];
}
}
}
}
public void average(int n) {
correct /= n;
testSize /= n;
truePositive /= n;
falsePositive /= n;
trueNegative /= n;
falseNegative /= n;
auc /= n;
logLoss /= n;
if (this.confusionMatrix != null) {
for (int i = 0; i < numLabels; i++) {
for (int j = 0; j < numLabels; j++) {
this.confusionMatrix[i][j] /= n;
}
}
}
}
public int getTruePositive() {
return this.truePositive;
}
public int getFalsePositive() {
return this.falsePositive;
}
public int getTrueNegative() {
return this.trueNegative;
}
public int getFalseNegative() {
return this.falseNegative;
}
public void print() {
print(LOG);
}
public void print(Logger log) {
log.info("Number of labels: " + getNumLabels());
log.info("Testset size: " + getTestSize());
log.info("Correctly classified: " + getCorrect());
log.info("Accuracy: " + getAccuracy());
log.info("Log loss: " + getLogLoss());
if (isBinary()) {
log.info("TP: " + truePositive);
log.info("FP: " + falsePositive);
log.info("TN: " + trueNegative);
log.info("FN: " + falseNegative);
log.info("Precision: " + getPrecision());
log.info("Recall: " + getRecall());
log.info("F1 Score: " + getF1Score());
log.info("AUC: " + getAUC());
} else {
printConfusionMatrix();
}
}
public void printConfusionMatrix() {
printConfusionMatrix(null);
}
public void printConfusionMatrix(String[] classNames) {
Preconditions.checkNotNull(this.confusionMatrix,
"No confusion matrix found.");
if (classNames != null) {
Preconditions.checkArgument(classNames.length == getNumLabels(),
"Passed class names doesn't match with number of labels! Expected "
+ getNumLabels() + " but was " + classNames.length);
}
System.out
.println("\nConfusion matrix (real outcome on rows, prediction in columns)\n");
for (int i = 0; i < getNumLabels(); i++) {
System.out.format("%5d", i);
}
System.out.format(" <- %5s %5s\t%s\n", "sum", "perc", "class");
for (int i = 0; i < getNumLabels(); i++) {
int sum = 0;
for (int j = 0; j < getNumLabels(); j++) {
if (i != j) {
sum += confusionMatrix[i][j];
}
System.out.format("%5d", confusionMatrix[i][j]);
}
float falsePercentage = sum / (float) (sum + confusionMatrix[i][i]);
String clz = classNames != null ? " " + i + " (" + classNames[i] + ")"
: " " + i;
System.out.format(" <- %5s %5s\t%s\n", sum, NumberFormat
.getPercentInstance().format(falsePercentage), clz);
}
}
}
/**
* Trains and evaluates the given classifier with a test split.
*
* @param classifier the classifier to train and evaluate.
* @param features the features to split.
* @param outcome the outcome to split.
* @param splitFraction a value between 0f and 1f that sets the size of the
* trainingset. With 1k items, a splitFraction of 0.9f will result in
* 900 items to train and 100 to evaluate.
* @param random true if you want to perform shuffling on the data beforehand.
* @return a new {@link EvaluationResult}.
*/
public static EvaluationResult evaluateClassifier(Classifier classifier,
DoubleVector[] features, DoubleVector[] outcome, float splitFraction,
boolean random) {
return evaluateClassifier(classifier, features, outcome, splitFraction,
random, null);
}
/**
* Trains and evaluates the given classifier with a test split.
*
* @param classifier the classifier to train and evaluate.
* @param features the features to split.
* @param outcome the outcome to split.
* @param numLabels the number of labels that are used. (e.G. 2 in binary
* classification).
* @param splitFraction a value between 0f and 1f that sets the size of the
* trainingset. With 1k items, a splitFraction of 0.9f will result in
* 900 items to train and 100 to evaluate.
* @param random true if you want to perform shuffling on the data beforehand.
* @param threshold in case of binary predictions, threshold is used to call
* in {@link Classifier#predictedClass(DoubleVector, double)}. Can be
* null, then no thresholding will be used.
* @return a new {@link EvaluationResult}.
*/
public static EvaluationResult evaluateClassifier(Classifier classifier,
DoubleVector[] features, DoubleVector[] outcome, float splitFraction,
boolean random, Double threshold) {
EvaluationSplit split = EvaluationSplit.create(features, outcome,
splitFraction, random);
return evaluateSplit(classifier, split, threshold);
}
/**
* Evaluates a given train/test split with the given classifier.
*
* @param classifier the classifier to train on the train split.
* @param split the {@link EvaluationSplit} that contains the test and train
* data.
* @return a fresh evalation result filled with the evaluated metrics.
*/
public static EvaluationResult evaluateSplit(Classifier classifier,
EvaluationSplit split) {
return evaluateSplit(classifier, split.getTrainFeatures(),
split.getTrainOutcome(), split.getTestFeatures(),
split.getTestOutcome(), null);
}
/**
* Evaluates a given train/test split with the given classifier.
*
* @param classifier the classifier to train on the train split.
* @param split the {@link EvaluationSplit} that contains the test and train
* data.
* @param threshold the threshold for predicting a specific class by
* probability (if not provided = null).
* @return a fresh evalation result filled with the evaluated metrics.
*/
public static EvaluationResult evaluateSplit(Classifier classifier,
EvaluationSplit split, Double threshold) {
return evaluateSplit(classifier, split.getTrainFeatures(),
split.getTrainOutcome(), split.getTestFeatures(),
split.getTestOutcome(), threshold);
}
/**
* Evaluates a given train/test split with the given classifier.
*
* @param classifier the classifier to train on the train split.
* @param trainFeatures the features to train with.
* @param trainOutcome the outcomes to train with.
* @param testFeatures the features to test with.
* @param testOutcome the outcome to test with.
* @param threshold the threshold for predicting a specific class by
* probability (if not provided = null).
* @return a fresh evalation result filled with the evaluated metrics.
*/
public static EvaluationResult evaluateSplit(Classifier classifier,
DoubleVector[] trainFeatures, DoubleVector[] trainOutcome,
DoubleVector[] testFeatures, DoubleVector[] testOutcome, Double threshold) {
classifier.train(trainFeatures, trainOutcome);
return testClassifier(classifier, testFeatures, testOutcome, threshold);
}
/**
* Tests the given classifier without actually training it.
*
* @param classifier the classifier to evaluate on the test split.
* @param testFeatures the features to test with.
* @param testOutcome the outcome to test with.
* @return a fresh evalation result filled with the evaluated metrics.
*/
public static EvaluationResult testClassifier(Predictor classifier,
DoubleVector[] testFeatures, DoubleVector[] testOutcome) {
return testClassifier(classifier, testFeatures, testOutcome, null);
}
/**
* Tests the given classifier without actually training it.
*
* @param classifier the classifier to evaluate on the test split.
* @param testFeatures the features to test with.
* @param testOutcome the outcome to test with.
* @param threshold the threshold for predicting a specific class by
* probability (if not provided = null).
* @return a fresh evalation result filled with the evaluated metrics.
*/
public static EvaluationResult testClassifier(Predictor classifier,
DoubleVector[] testFeatures, DoubleVector[] testOutcome, Double threshold) {
EvaluationResult result = new EvaluationResult();
result.numLabels = Math.max(2, testOutcome[0].getDimension());
result.testSize = testOutcome.length;
// check the binary case to calculate special metrics
if (result.isBinary()) {
List<PredictionOutcomePair> outcomePredictedPairs = new ArrayList<>();
for (int i = 0; i < testFeatures.length; i++) {
DoubleVector outcomeVector = testOutcome[i];
DoubleVector predictedVector = classifier.predict(testFeatures[i]);
int outcomeClass = observeBinaryClassificationElement(classifier,
threshold, result, outcomeVector, predictedVector);
outcomePredictedPairs.add(PredictionOutcomePair.from(outcomeClass,
predictedVector.get(0)));
}
// we can compute the AUC from the outcomePredictedPairs we gathered
result.auc = MathUtils.computeAUC(outcomePredictedPairs);
} else {
int[][] confusionMatrix = new int[result.numLabels][result.numLabels];
for (int i = 0; i < testFeatures.length; i++) {
DoubleVector predicted = classifier.predict(testFeatures[i]);
DoubleVector outcomeVector = testOutcome[i];
result.logLoss += outcomeVector
.multiply(MathUtils.logVector(predicted)).sum();
int outcomeClass = outcomeVector.maxIndex();
int prediction = classifier.extractPredictedClass(predicted);
confusionMatrix[outcomeClass][prediction]++;
if (outcomeClass == prediction) {
result.correct++;
}
}
result.confusionMatrix = confusionMatrix;
}
return result;
}
public static int observeBinaryClassificationElement(Predictor predictor,
Double threshold, EvaluationResult result, DoubleVector outcomeVector,
DoubleVector predictedVector) {
int outcomeClass = ((int) outcomeVector.get(0));
result.logLoss += outcomeVector.multiply(
MathUtils.logVector(predictedVector)).sum();
int prediction = 0;
if (threshold == null) {
prediction = predictor.extractPredictedClass(predictedVector);
} else {
prediction = predictor.extractPredictedClass(predictedVector, threshold);
}
if (outcomeClass == 1) {
if (prediction == 1) {
result.truePositive++; // "Correct result"
} else {
result.falseNegative++; // "Missing the correct result"
}
} else if (outcomeClass == 0) {
if (prediction == 0) {
result.trueNegative++; // "Correct absence of result"
} else {
result.falsePositive++; // "Unexpected result"
}
} else {
throw new IllegalArgumentException(
"Outcome class was neither 0 or 1. Was: " + outcomeClass
+ "; the supplied outcome value was: " + outcomeVector.get(0));
}
return outcomeClass;
}
/**
* Does a k-fold crossvalidation on the given classifiers with features and
* outcomes. The folds will be calculated on a new thread.
*
* @param classifierFactory the classifiers to train and test.
* @param features the features to train/test with.
* @param outcome the outcomes to train/test with.
* @param numLabels the total number of labels that are possible. e.G. 2 in
* the binary case.
* @param folds the number of folds to fold, usually 10.
* @param threshold the threshold for predicting a specific class by
* probability (if not provided = null).
* @param verbose true if partial fold results should be printed.
* @return a averaged evaluation result over all k folds.
*/
public static <A extends Classifier> EvaluationResult crossValidateClassifier(
ClassifierFactory<A> classifierFactory, DoubleVector[] features,
DoubleVector[] outcome, int numLabels, int folds, Double threshold,
boolean verbose) {
return crossValidateClassifier(classifierFactory, features, outcome,
numLabels, folds, threshold, 1, verbose);
}
/**
* Does a k-fold crossvalidation on the given classifiers with features and
* outcomes.
*
* @param classifierFactory the classifiers to train and test.
* @param features the features to train/test with.
* @param outcome the outcomes to train/test with.
* @param numLabels the total number of labels that are possible. e.G. 2 in
* the binary case.
* @param folds the number of folds to fold, usually 10.
* @param threshold the threshold for predicting a specific class by
* probability (if not provided = null).
* @param numThreads how many threads to use to evaluate the folds.
* @param verbose true if partial fold results should be printed.
* @return a averaged evaluation result over all k folds.
*/
public static <A extends Classifier> EvaluationResult crossValidateClassifier(
ClassifierFactory<A> classifierFactory, DoubleVector[] features,
DoubleVector[] outcome, int numLabels, int folds, Double threshold,
int numThreads, boolean verbose) {
// train on k-1 folds, test on 1 fold, results are averaged
final int numFolds = folds + 1;
// multi shuffle the arrays first, note that this is not stratified.
ArrayUtils.multiShuffle(features, outcome);
EvaluationResult averagedModel = new EvaluationResult();
averagedModel.numLabels = numLabels;
final int m = features.length;
// compute the split ranges by blocks, so we have range from 0 to the next
// partition index end that will be our testset, and so on.
List<Range> partition = new ArrayList<>(new BlockPartitioner().partition(
numFolds, m).getBoundaries());
int[] splitRanges = new int[numFolds];
for (int i = 1; i < numFolds; i++) {
splitRanges[i] = partition.get(i).getEnd();
}
// because we are dealing with indices, we have to subtract 1 from the end
splitRanges[numFolds - 1] = splitRanges[numFolds - 1] - 1;
if (verbose) {
LOG.info("Computed split ranges: " + Arrays.toString(splitRanges) + "\n");
}
final ExecutorService pool = Executors.newFixedThreadPool(numThreads,
new ThreadFactoryBuilder().setDaemon(true).build());
final ExecutorCompletionService<EvaluationResult> completionService = new ExecutorCompletionService<>(
pool);
// build the models fold for fold
for (int fold = 0; fold < folds; fold++) {
completionService.submit(new CallableEvaluation<>(fold, splitRanges, m,
classifierFactory, features, outcome, folds, threshold));
}
// retrieve the results
for (int fold = 0; fold < folds; fold++) {
Future<EvaluationResult> take;
try {
take = completionService.take();
EvaluationResult foldSplit = take.get();
if (verbose) {
LOG.info("Fold: " + (fold + 1));
foldSplit.print();
LOG.info("");
}
averagedModel.add(foldSplit);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
// average the sums in the model
averagedModel.average(folds);
return averagedModel;
}
/**
* Does a 10 fold crossvalidation.
*
* @param classifierFactory the classifiers to train and test.
* @param features the features to train/test with.
* @param outcome the outcomes to train/test with.
* @param numLabels the total number of labels that are possible. e.G. 2 in
* the binary case.
* @param threshold the threshold for predicting a specific class by
* probability (if not provided = null).
* @param numThreads how many threads to use to evaluate the folds.
* @param verbose true if partial fold results should be printed.
* @return a averaged evaluation result over all 10 folds.
*/
public static <A extends Classifier> EvaluationResult tenFoldCrossValidation(
ClassifierFactory<A> classifierFactory, DoubleVector[] features,
DoubleVector[] outcome, int numLabels, Double threshold, boolean verbose) {
return crossValidateClassifier(classifierFactory, features, outcome,
numLabels, 10, threshold, verbose);
}
/**
* Does a 10 fold crossvalidation.
*
* @param classifierFactory the classifiers to train and test.
* @param features the features to train/test with.
* @param outcome the outcomes to train/test with.
* @param numLabels the total number of labels that are possible. e.G. 2 in
* the binary case.
* @param threshold the threshold for predicting a specific class by
* probability (if not provided = null).
* @param verbose true if partial fold results should be printed.
* @return a averaged evaluation result over all 10 folds.
*/
public static <A extends Classifier> EvaluationResult tenFoldCrossValidation(
ClassifierFactory<A> classifierFactory, DoubleVector[] features,
DoubleVector[] outcome, int numLabels, Double threshold, int numThreads,
boolean verbose) {
return crossValidateClassifier(classifierFactory, features, outcome,
numLabels, 10, threshold, numThreads, verbose);
}
private static class CallableEvaluation<A extends Classifier> implements
Callable<EvaluationResult> {
private final int fold;
private final int[] splitRanges;
private final int m;
private final DoubleVector[] features;
private final DoubleVector[] outcome;
private final ClassifierFactory<A> classifierFactory;
private final Double threshold;
public CallableEvaluation(int fold, int[] splitRanges, int m,
ClassifierFactory<A> classifierFactory, DoubleVector[] features,
DoubleVector[] outcome, int folds, Double threshold) {
this.fold = fold;
this.splitRanges = splitRanges;
this.m = m;
this.classifierFactory = classifierFactory;
this.features = features;
this.outcome = outcome;
this.threshold = threshold;
}
@Override
public EvaluationResult call() throws Exception {
DoubleVector[] featureTest = ArrayUtils.subArray(features,
splitRanges[fold], splitRanges[fold + 1]);
DoubleVector[] outcomeTest = ArrayUtils.subArray(outcome,
splitRanges[fold], splitRanges[fold + 1]);
DoubleVector[] featureTrain = new DoubleVector[m - featureTest.length];
DoubleVector[] outcomeTrain = new DoubleVector[m - featureTest.length];
int index = 0;
for (int i = 0; i < m; i++) {
if (i < splitRanges[fold] || i > splitRanges[fold + 1]) {
featureTrain[index] = features[i];
outcomeTrain[index] = outcome[i];
index++;
}
}
return evaluateSplit(classifierFactory.newInstance(), featureTrain,
outcomeTrain, featureTest, outcomeTest, threshold);
}
}
} |
package it.polimi.hegira.queue;
import it.polimi.hegira.exceptions.QueueException;
import it.polimi.hegira.utils.DefaultSerializer;
import java.io.IOException;
import org.apache.log4j.Logger;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.ConsumerCancelledException;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.ShutdownSignalException;
/**
* Service queue which allows the interaction between the API component and the SRC or TWC
* @author Marco Scavuzzo
*
*/
public class ServiceQueue {
private static Logger log = Logger.getLogger(ServiceQueue.class);
private ConnectionFactory factory;
private Connection connection;
private Channel channelPublish;
private Channel channelConsume;
private static final String EXCHANGE_NAME = "service-queue";
public static final String API_PUBLISH_RK = "toApiServer";
private String LISTEN_RK;
QueueingConsumer consumer;
public ServiceQueue(String componentType, String queueAddress){
LISTEN_RK = componentType;
factory = new ConnectionFactory();
factory.setHost(queueAddress);
try {
connection = factory.newConnection();
//SENDER PART
channelPublish = connection.createChannel();
/**
* direct exchange: a message goes to the queues whose binding key
* exactly matches the routing key of the message.
*/
channelPublish.exchangeDeclare(EXCHANGE_NAME, "direct");
log.debug("Publish channel created. Exchange: "+EXCHANGE_NAME+" type: direct");
//RECEIVER PART
channelConsume = connection.createChannel();
channelConsume.exchangeDeclare(EXCHANGE_NAME, "direct");
log.debug("Consuming channel created. Exchange: "+EXCHANGE_NAME+" type: direct");
//String queueName = channelConsume.queueDeclare().getQueue();
String queueName;
switch(componentType){
case "SRC":
queueName = channelConsume.queueDeclare("Q2", false, false, false, null).getQueue();
break;
case "TWC":
queueName = channelConsume.queueDeclare("Q3", false, false, false, null).getQueue();
break;
default:
queueName = channelConsume.queueDeclare().getQueue();
break;
}
/**
* routing key bindings: relationship between an exchange and a queue.
*/
channelConsume.queueBind(queueName, EXCHANGE_NAME, LISTEN_RK);
log.debug("Binding the consuming channel. ROUTING KEY: "+LISTEN_RK+" QUEUE NAME: "+queueName);
/**
* Telling the server to deliver us the messages from the queue.
* Since it will push us messages asynchronously, we provide a callback
* in the form of an object (QueueingConsumer) that will buffer the messages
* until we're ready to use them.
*/
consumer = new QueueingConsumer(channelConsume);
/**
* basicConsume(java.lang.String queue, boolean autoAck, Consumer callback)
* Starts a non-nolocal, non-exclusive consumer,
* with a server-generated consumerTag.
*/
channelConsume.basicConsume(queueName, true, consumer);
log.debug("Consumer started on queue: "+queueName);
} catch (IOException e) {
log.error(e.toString());
}
}
/**
* Writes a message in the queue with the given routing key.
* @param routingKey
* @param messageBody
* @throws QueueException if an error has occurred.
*/
public void publish(String routingKey, byte[] messageBody) throws QueueException{
/**
* Declaring a queue is idempotent - it will only be created if it doesn't exist already.
* basicPublish(java.lang.String exchange,
* java.lang.String routingKey,
* AMQP.BasicProperties props, byte[] body)
*/
try {
channelPublish.basicPublish(EXCHANGE_NAME, routingKey, null, messageBody);
log.debug("Message published. ROUTING KEY: "+routingKey);
} catch (IOException e) {
throw new QueueException();
}
}
public void announcePresence() throws QueueException{
publish(API_PUBLISH_RK, LISTEN_RK.getBytes());
}
public void receiveCommands() throws QueueException{
while(true){
/**
* QueueingConsumer.nextDelivery() blocks
* until another message has been delivered from the server.
*/
QueueingConsumer.Delivery delivery;
try {
delivery = consumer.nextDelivery();
byte[] message = delivery.getBody();
String routingKey = delivery.getEnvelope().getRoutingKey();
try{
ServiceQueueMessage sqm = (ServiceQueueMessage) DefaultSerializer.deserialize(message);
switch(sqm.getCommand()){
case "switchover":
if(LISTEN_RK.equals("SRC")){
}else if(LISTEN_RK.equals("TWC")){
}
break;
default:
break;
}
} catch (ClassNotFoundException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ShutdownSignalException | ConsumerCancelledException
| InterruptedException e) {
throw new QueueException();
}
}
}
public QueueingConsumer getConsumer(){
return consumer;
}
} |
package me.rkfg.xmpp.bot.plugins.game;
import static me.rkfg.xmpp.bot.plugins.game.misc.Attrs.*;
import static me.rkfg.xmpp.bot.plugins.game.misc.Utils.*;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import me.rkfg.xmpp.bot.message.Message;
import me.rkfg.xmpp.bot.plugins.game.event.RenameEvent;
import me.rkfg.xmpp.bot.plugins.game.event.TickEvent;
import me.rkfg.xmpp.bot.plugins.game.misc.Attrs.GamePlayerState;
import me.rkfg.xmpp.bot.plugins.game.repository.ArmorRepository;
import me.rkfg.xmpp.bot.plugins.game.repository.EffectRepository;
import me.rkfg.xmpp.bot.plugins.game.repository.MessageRepository;
import me.rkfg.xmpp.bot.plugins.game.repository.NameRepository;
import me.rkfg.xmpp.bot.plugins.game.repository.TraitsRepository;
import me.rkfg.xmpp.bot.plugins.game.repository.UsableRepository;
import me.rkfg.xmpp.bot.plugins.game.repository.WeaponRepository;
public class World extends Player {
private static final int TICKRATE = 15;
public static final World THIS = new World();
private Map<String, IPlayer> players = new HashMap<>();
private NameRepository nameRepository;
private List<String> names;
private MessageRepository messageRepository;
private WeaponRepository weaponRepository;
private ArmorRepository armorRepository;
private EffectRepository effectRepository;
private UsableRepository usableRepository;
private TraitsRepository traitsRepository;
private Timer timer;
public World() {
super("ZAWARUDO");
setState(GamePlayerState.GATHER);
}
public void init() {
nameRepository = new NameRepository();
nameRepository.loadContent();
names = nameRepository.getAllContent().stream().map(tm -> tm.get(DESC_CNT)).map(Optional::get).collect(Collectors.toList());
messageRepository = new MessageRepository();
messageRepository.loadContent();
effectRepository = new EffectRepository();
effectRepository.loadContent();
weaponRepository = new WeaponRepository();
weaponRepository.loadContent();
armorRepository = new ArmorRepository();
armorRepository.loadContent();
usableRepository = new UsableRepository();
usableRepository.loadContent();
traitsRepository = new TraitsRepository();
traitsRepository.loadContent();
}
public void startTime() {
timer = new Timer("Game clock", true);
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
synchronized (World.this) {
players.values().forEach(p -> p.enqueueEvent(new TickEvent()));
}
}
}, TimeUnit.SECONDS.toMillis(TICKRATE), TimeUnit.SECONDS.toMillis(TICKRATE));
}
private void stopTime() {
timer.cancel();
}
public Optional<IPlayer> getCurrentPlayer(Message message) {
final Optional<IPlayer> player = Optional.ofNullable(players.computeIfAbsent(message.getFrom(), id -> {
if (getState() == GamePlayerState.PLAYING) {
return null;
}
return new Player(id);
}));
player.flatMap(p -> p.as(MUTABLEPLAYER_OBJ)).ifPresent(p -> {
p.setRoomId(message.getFromRoom());
});
return player;
}
public List<IPlayer> listPlayers() {
return players.values().stream().sorted((p1, p2) -> p1.getName().compareTo(p2.getName())).collect(Collectors.toList());
}
private void generateTraits(IPlayer player) {
player.as(MUTABLEPLAYER_OBJ).ifPresent(IMutablePlayer::reset);
Stream.of("const", "mental", "addict").forEach(s -> {
if (dice("1d6") < 5) {
traitsRepository.getRandomObject(GROUP_IDX, s).ifPresent(player::enqueueAttachEffect);
}
});
}
public void announce(String message) {
players.values().stream().filter(p -> p.getState() != GamePlayerState.NONE)
.forEach(p -> p.log("=== ОБЪЯВЛЕНИЕ: " + message + " ==="));
}
public void checkVictory() {
List<IPlayer> alive = players.values().stream().filter(IPlayer::isAlive).collect(Collectors.toList());
if (alive.isEmpty()) {
announce("Игра завершена, выживших нет.");
setState(GamePlayerState.GATHER);
}
if (alive.size() == 1) {
final IPlayer winner = alive.get(0);
announce("Игра завершена, последний выживший — " + winner.getName() + " aka " + winner.getId());
winner.log("Вы победили!");
setState(GamePlayerState.GATHER);
}
if (getState() == GamePlayerState.GATHER) {
stopTime();
players.values().stream().map(p -> p.as(MUTABLEPLAYER_OBJ)).forEach(p -> p.ifPresent(pp -> pp.setState(GamePlayerState.NONE)));
}
}
public NameRepository getNameRepository() {
return nameRepository;
}
public MessageRepository getMessageRepository() {
return messageRepository;
}
public WeaponRepository getWeaponRepository() {
return weaponRepository;
}
public ArmorRepository getArmorRepository() {
return armorRepository;
}
public EffectRepository getEffectRepository() {
return effectRepository;
}
public UsableRepository getUsableRepository() {
return usableRepository;
}
public void defaultCommand(IPlayer player) {
switch (getState()) {
case GATHER:
switch (player.getState()) {
case NONE:
player.log("Чтобы вступить в игру, напишите %гм участвую");
break;
case READY:
player.log("Вы готовы начать игру.");
break;
case GATHER:
player.log("Чтобы подтвердить свою готовность, напишите %гм готов");
break;
default:
player.log("Неверный статус.");
break;
}
break;
case PLAYING:
player.dumpStats();
break;
default:
break;
}
}
public Optional<String> setPlayerState(IPlayer player, GamePlayerState playerState) {
if (getState() == GamePlayerState.GATHER) {
player.as(MUTABLEPLAYER_OBJ).ifPresent(p -> {
p.setState(playerState);
switch (playerState) {
case NONE:
player.log("Вы не будете участвовать в игре.");
break;
case READY:
announce(String.format("Игрок %s готов начать игру.", p.getId()));
int readyCnt = 0;
int gatherCnt = 0;
for (IPlayer p2 : players.values()) {
if (p2.getState() == GamePlayerState.READY) {
++readyCnt;
}
if (p2.getState() != GamePlayerState.NONE) {
++gatherCnt;
}
}
if (gatherCnt == 0) {
gatherCnt = 1; // should never happen
}
long readyPlayersPct = readyCnt * 100 / gatherCnt;
if (readyPlayersPct >= 75 && gatherCnt > 1) {
startGame();
} else {
player.log("Чтобы отменить свою готовность, напишите %гм готов 0");
}
break;
case GATHER:
player.log("Вы будете участвовать в игре. Чтобы отказаться от участия, напишите %гм участвую 0");
break;
default:
player.log("Неверный статус.");
break;
}
});
} else if (getState() == GamePlayerState.PLAYING) {
if (player.getState() != GamePlayerState.PLAYING) {
return Optional.of("Игра уже идёт, дождитесь следующего раунда.");
} else {
return Optional.of("Игра уже идёт, и вы участвуете.");
}
}
return Optional.empty();
}
private void startGame() {
setState(GamePlayerState.PLAYING);
players.entrySet().removeIf(e -> {
GamePlayerState r = e.getValue().getState();
return r != GamePlayerState.READY && r != GamePlayerState.GATHER;
}); // remove non-participating players
players.values().stream().forEach(p -> p.log("Игра начинается!"));
initPlayers();
startTime();
}
private void initPlayers() {
int pIdx = 0;
for (Entry<String, IPlayer> entry : players.entrySet()) {
if (pIdx % names.size() == 0) {
Collections.shuffle(names);
}
int round = pIdx / names.size() + 1;
String name = names.get(pIdx % names.size());
if (round > 1) {
name += " " + round + "-й";
}
IPlayer player = entry.getValue();
generateTraits(player);
player.enqueueEvent(new RenameEvent(name));
player.getDescription().ifPresent(player::log);
player.dumpStats();
pIdx++;
}
}
@Override
public void flushLogs() {
players.values().stream().forEach(IPlayer::flushLogs);
}
} |
package de.mrapp.android.adapter.logging;
/**
* Defines the interface, a class, which should allow to use logging, must
* implement.
*
* @author Michael Rapp
*
* @since 1.0.0
*/
public interface Loggable {
/**
* Returns the current log level. Only log messages with a rank greater or
* equal than the current rank of the currently applied log level, are
* intended to be written to the output.
*
* @return The current log level as a value of the enum {@link LogLevel}.
* The log level may either be <code>ALL</code>, <code>DEBUG</code>,
* <code>INFO</code>, <code>WARN</code>, <code>ERROR</code> or
* <code>OFF</code>
*/
LogLevel getLogLevel();
/**
* Sets the log level. Only log messages with a rank greater or equal than
* the current rank of the currently applied log level, are intended to be
* written to the output.
*
* @param logLevel
* The log level, which should be set, as a value of the enum
* {@link LogLevel}. The log level may not be null
*/
void setLogLevel(LogLevel logLevel);
} |
package seedu.doit.logic.parser;
import static seedu.doit.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import seedu.doit.logic.commands.Command;
import seedu.doit.logic.commands.IncorrectCommand;
import seedu.doit.logic.commands.SortCommand;
/**
* Parses input arguments and creates a new SortCommand object
*/
public class SortCommandParser {
public static final String SORT_VALIDATION_REGEX = "(priority)|(deadline)|(start time)";
/**
* Parses the given {@code String} of arguments in the context of the FindCommand
* and returns an FindCommand object for execution.
*/
public Command parse(String args) {
if (args.trim().matches(SORT_VALIDATION_REGEX)) {
return new SortCommand(args.trim());
} else {
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, SortCommand.MESSAGE_USAGE));
}
}
} |
package mho.haskellesque.math;
import mho.haskellesque.iterables.Exhaustive;
import mho.haskellesque.iterables.IndexedIterable;
import mho.haskellesque.tuples.Pair;
import mho.haskellesque.tuples.Quadruple;
import mho.haskellesque.tuples.Triple;
import java.math.BigInteger;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import static mho.haskellesque.iterables.IterableUtils.*;
import static mho.haskellesque.ordering.Ordering.*;
public class Combinatorics {
public static BigInteger factorial(int n) {
return productBigInteger(range(BigInteger.ONE, BigInteger.valueOf(n).add(BigInteger.ONE)));
}
public static BigInteger factorial(BigInteger n) {
return productBigInteger(range(BigInteger.ONE, n.add(BigInteger.ONE)));
}
public static BigInteger subfactorial(int n) {
if (n == 0) return BigInteger.ONE;
BigInteger a = BigInteger.ONE;
BigInteger b = BigInteger.ZERO;
BigInteger c = b;
for (int i = 1; i < n; i++) {
c = BigInteger.valueOf(i).multiply(a.add(b));
a = b;
b = c;
}
return c;
}
public static BigInteger subfactorial(BigInteger n) {
if (n.equals(BigInteger.ZERO)) return BigInteger.ONE;
BigInteger a = BigInteger.ONE;
BigInteger b = BigInteger.ZERO;
BigInteger c = b;
for (BigInteger i = BigInteger.ONE; lt(i, n); i = i.add(BigInteger.ONE)) {
c = i.multiply(a.add(b));
a = b;
b = c;
}
return c;
}
public static <S, T> Iterable<Pair<S, T>> cartesianPairs(Iterable<S> fsts, Iterable<T> snds) {
return concatMap(p -> zip(repeat(p.fst), p.snd), zip(fsts, repeat(snds)));
}
public static <A, B, C> Iterable<Triple<A, B, C>> cartesianTriples(
Iterable<A> as,
Iterable<B> bs,
Iterable<C> cs
) {
return map(
p -> new Triple<>(p.fst, p.snd.fst, p.snd.snd),
cartesianPairs(as, (Iterable<Pair<B, C>>) cartesianPairs(bs, cs))
);
}
public static <A, B, C, D> Iterable<Quadruple<A, B, C, D>> cartesianQuadruples(
Iterable<A> as,
Iterable<B> bs,
Iterable<C> cs,
Iterable<D> ds
) {
return map(
p -> new Quadruple<>(p.fst.fst, p.fst.snd, p.snd.fst, p.snd.snd),
cartesianPairs(
(Iterable<Pair<A, B>>)cartesianPairs(as, bs),
(Iterable<Pair<C, D>>) cartesianPairs(cs, ds)
)
);
}
public static <S, T> Iterable<Pair<S, T>> exponentialPairs(Iterable<S> fsts, Iterable<T> snds) {
IndexedIterable<S> fstii = new IndexedIterable<>(fsts);
IndexedIterable<T> sndii = new IndexedIterable<>(snds);
Function<BigInteger, Optional<Pair<S, T>>> f = bi -> {
Pair<BigInteger, BigInteger> p = BasicMath.exponentialDemux(bi);
assert p.fst != null;
Optional<S> optFst = fstii.get(p.fst.intValue());
if (!optFst.isPresent()) return Optional.empty();
assert p.snd != null;
Optional<T> optSnd = sndii.get(p.snd.intValue());
if (!optSnd.isPresent()) return Optional.empty();
return Optional.of(new Pair<S, T>(optFst.get(), optSnd.get()));
};
return map(
Optional::get,
filter(
Optional<Pair<S, T>>::isPresent,
(Iterable<Optional<Pair<S, T>>>) map(bi -> f.apply(bi), Exhaustive.BIG_INTEGERS)
)
);
}
public static <T> Iterable<Pair<T, T>> exponentialPairs(Iterable<T> xs) {
IndexedIterable<T> ii = new IndexedIterable<>(xs);
Function<BigInteger, Optional<Pair<T, T>>> f = bi -> {
Pair<BigInteger, BigInteger> p = BasicMath.exponentialDemux(bi);
assert p.fst != null;
Optional<T> optFst = ii.get(p.fst.intValue());
if (!optFst.isPresent()) return Optional.empty();
assert p.snd != null;
Optional<T> optSnd = ii.get(p.snd.intValue());
if (!optSnd.isPresent()) return Optional.empty();
return Optional.of(new Pair<T, T>(optFst.get(), optSnd.get()));
};
return map(
Optional::get,
filter(
Optional<Pair<T, T>>::isPresent,
(Iterable<Optional<Pair<T, T>>>) map(bi -> f.apply(bi), Exhaustive.NATURAL_BIG_INTEGERS)
)
);
}
public static <S, T> Iterable<Pair<S, T>> pairs(Iterable<S> fsts, Iterable<T> snds) {
IndexedIterable<S> fstii = new IndexedIterable<>(fsts);
IndexedIterable<T> sndii = new IndexedIterable<>(snds);
Function<BigInteger, Optional<Pair<S, T>>> f = bi -> {
List<BigInteger> p = BasicMath.demux(2, bi);
assert p.get(0) != null;
Optional<S> optFst = fstii.get(p.get(0).intValue());
if (!optFst.isPresent()) return Optional.empty();
assert p.get(1) != null;
Optional<T> optSnd = sndii.get(p.get(1).intValue());
if (!optSnd.isPresent()) return Optional.empty();
return Optional.of(new Pair<S, T>(optFst.get(), optSnd.get()));
};
return map(
Optional::get,
filter(
Optional<Pair<S, T>>::isPresent,
(Iterable<Optional<Pair<S, T>>>) map(bi -> f.apply(bi), Exhaustive.NATURAL_BIG_INTEGERS)
)
);
}
public static <A, B, C> Iterable<Triple<A, B, C>> triples(Iterable<A> as, Iterable<B> bs, Iterable<C> cs) {
IndexedIterable<A> aii = new IndexedIterable<>(as);
IndexedIterable<B> bii = new IndexedIterable<>(bs);
IndexedIterable<C> cii = new IndexedIterable<>(cs);
Function<BigInteger, Optional<Triple<A, B, C>>> f = bi -> {
List<BigInteger> p = BasicMath.demux(3, bi);
assert p.get(0) != null;
Optional<A> optA = aii.get(p.get(0).intValue());
if (!optA.isPresent()) return Optional.empty();
assert p.get(1) != null;
Optional<B> optB = bii.get(p.get(1).intValue());
if (!optB.isPresent()) return Optional.empty();
assert p.get(2) != null;
Optional<C> optC = cii.get(p.get(2).intValue());
if (!optC.isPresent()) return Optional.empty();
return Optional.of(new Triple<A, B, C>(optA.get(), optB.get(), optC.get()));
};
return map(
Optional::get,
filter(
Optional<Triple<A, B, C>>::isPresent,
(Iterable<Optional<Triple<A, B, C>>>) map(bi -> f.apply(bi), Exhaustive.NATURAL_BIG_INTEGERS)
)
);
}
public static <A, B, C, D> Iterable<Quadruple<A, B, C, D>> quadruples(
Iterable<A> as,
Iterable<B> bs,
Iterable<C> cs,
Iterable<D> ds
) {
IndexedIterable<A> aii = new IndexedIterable<>(as);
IndexedIterable<B> bii = new IndexedIterable<>(bs);
IndexedIterable<C> cii = new IndexedIterable<>(cs);
IndexedIterable<D> dii = new IndexedIterable<>(ds);
Function<BigInteger, Optional<Quadruple<A, B, C, D>>> f = bi -> {
List<BigInteger> p = BasicMath.demux(4, bi);
assert p.get(0) != null;
Optional<A> optA = aii.get(p.get(0).intValue());
if (!optA.isPresent()) return Optional.empty();
assert p.get(1) != null;
Optional<B> optB = bii.get(p.get(1).intValue());
if (!optB.isPresent()) return Optional.empty();
assert p.get(2) != null;
Optional<C> optC = cii.get(p.get(2).intValue());
if (!optC.isPresent()) return Optional.empty();
assert p.get(3) != null;
Optional<D> optD = dii.get(p.get(3).intValue());
if (!optD.isPresent()) return Optional.empty();
return Optional.of(new Quadruple<A, B, C, D>(optA.get(), optB.get(), optC.get(), optD.get()));
};
return map(
Optional::get,
filter(
Optional<Quadruple<A, B, C, D>>::isPresent,
(Iterable<Optional<Quadruple<A, B, C, D>>>)
map(bi -> f.apply(bi), Exhaustive.NATURAL_BIG_INTEGERS)
)
);
}
} |
package seedu.task.logic.parser;
import static seedu.task.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.task.logic.parser.CliSyntax.PREFIX_TAG;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import seedu.task.commons.exceptions.IllegalValueException;
import seedu.task.logic.commands.Command;
import seedu.task.logic.commands.EditCommand;
import seedu.task.logic.commands.IncorrectCommand;
import seedu.task.logic.commands.EditCommand.EditTaskDescriptor;
import seedu.task.model.tag.UniqueTagList;
/**
* Parses input arguments and creates a new EditCommand object
*/
public class EditCommandParser {
/**
* Parses the given {@code String} of arguments in the context of the EditCommand
* and returns an EditCommand object for execution.
*/
public Command parse(String args) {
assert args != null;
ArgumentTokenizer argsTokenizer =
new ArgumentTokenizer(PREFIX_TAG);
argsTokenizer.tokenize(args);
List<Optional<String>> preambleFields = ParserUtil.splitPreamble(argsTokenizer.getPreamble().orElse(""), 2);
Optional<Integer> index = preambleFields.get(0).flatMap(ParserUtil::parseIndex);
if (!index.isPresent()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE));
}
EditTaskDescriptor editTaskDescriptor = new EditTaskDescriptor();
try {
editTaskDescriptor.setName(ParserUtil.parseName(preambleFields.get(1)));
editTaskDescriptor.setTags(parseTagsForEdit(ParserUtil.toSet(argsTokenizer.getAllValues(PREFIX_TAG))));
} catch (IllegalValueException ive) {
return new IncorrectCommand(ive.getMessage());
}
if (!editTaskDescriptor.isAnyFieldEdited()) {
return new IncorrectCommand(EditCommand.MESSAGE_NOT_EDITED);
}
return new EditCommand(index.get(), editTaskDescriptor);
}
/**
* Parses {@code Collection<String> tags} into an {@code Optional<UniqueTagList>} if {@code tags} is non-empty.
* If {@code tags} contain only one element which is an empty string, it will be parsed into a
* {@code Optional<UniqueTagList>} containing zero tags.
*/
private Optional<UniqueTagList> parseTagsForEdit(Collection<String> tags) throws IllegalValueException {
assert tags != null;
if (tags.isEmpty()) {
return Optional.empty();
}
Collection<String> tagSet = tags.size() == 1 && tags.contains("") ? Collections.emptySet() : tags;
return Optional.of(ParserUtil.parseTags(tagSet));
}
} |
package org.xins.server;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.NDC;
import org.apache.oro.text.regex.MalformedPatternException;
import org.apache.oro.text.regex.Pattern;
import org.apache.oro.text.regex.Perl5Compiler;
import org.apache.oro.text.regex.Perl5Matcher;
import org.xins.common.MandatoryArgumentChecker;
import org.xins.common.Utils;
import org.xins.common.collections.InvalidPropertyValueException;
import org.xins.common.collections.MissingRequiredPropertyException;
import org.xins.common.collections.PropertyReader;
import org.xins.common.manageable.InitializationException;
import org.xins.common.servlet.ServletConfigPropertyReader;
import org.xins.common.text.TextUtils;
import org.xins.logdoc.ExceptionUtils;
/**
* XINS server engine. An <code>Engine</code> is a delegate of the
* {@link APIServlet} that is responsible for initialization and request
* handling.
*
* <p>When an <code>Engine</code> instance is constructed, it gathers
* initialization information from different sources:
*
* <dl>
* <dt><strong>1. Build-time settings</strong></dt>
* <dd>The application package contains a <code>web.xml</code> file with
* build-time settings. Some of these settings are required in order for
* the XINS/Java Server Framework to start up, while others are optional.
* These build-time settings are passed to the servlet by the application
* server as a {@link ServletConfig} object. See
* {@link APIServlet#init(ServletConfig)}.
* <br>The servlet configuration is the responsibility of the
* <em>assembler</em>.</dd>
*
* <dt><strong>2. System properties</strong></dt>
* <dd>The location of the configuration file must be passed to the Java VM
* at startup, as a system property.
* <br>System properties are the responsibility of the
* <em>system administrator</em>.
* <br>Example:
* <br><code>java -Dorg.xins.server.config=`pwd`/config/xins.properties
* -jar orion.jar</code></dd>
*
* <dt><strong>3. Configuration file</strong></dt>
* <dd>The configuration file should contain runtime configuration
* settings, like the settings for the logging subsystem.
* <br>Runtime properties are the responsibility of the
* <em>system administrator</em>.
* <br>Example contents for a configuration file:
* <blockquote><code>log4j.rootLogger=DEBUG, console
* <br>log4j.appender.console=org.apache.log4j.ConsoleAppender
* <br>log4j.appender.console.layout=org.apache.log4j.PatternLayout
* <br>log4j.appender.console.layout.ConversionPattern=%d %-5p [%c]
* %m%n</code></blockquote>
* </dl>
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:ernst.dehaan@nl.wanadoo.com">ernst.dehaan@nl.wanadoo.com</a>)
* @author Anthony Goubard (<a href="mailto:anthony.goubard@nl.wanadoo.com">anthony.goubard@nl.wanadoo.com</a>)
* @author Mees Witteman (<a href="mailto:mees.witteman@nl.wanadoo.com">mees.witteman@nl.wanadoo.com</a>)
*/
final class Engine extends Object {
// Class fields
/**
* Perl 5 pattern compiler.
*/
private static final Perl5Compiler PATTERN_COMPILER = new Perl5Compiler();
// Class functions
// Constructors
Engine(final ServletConfig config)
throws IllegalArgumentException, ServletException {
// Check preconditions
MandatoryArgumentChecker.check("config", config);
// Construct the EngineStarter
_starter = new EngineStarter(config);
// Construct a configuration manager and store the servlet configuration
_configManager = new ConfigManager(this, config);
_servletConfig = config;
// Proceed to first actual stage
_state.setState(EngineState.BOOTSTRAPPING_FRAMEWORK);
// Read configuration details
_configManager.determineConfigFile();
_configManager.readRuntimeProperties();
// Construct and bootstrap the API
_state.setState(EngineState.CONSTRUCTING_API);
try {
_api = _starter.constructAPI();
} catch (ServletException se) {
_state.setState(EngineState.API_CONSTRUCTION_FAILED);
throw se;
}
bootstrapAPI();
// Done bootstrapping the framework
Log.log_3225(Library.getVersion());
// Initialize the configuration manager
_configManager.init();
// Check post-conditions
if (_api == null) {
throw Utils.logProgrammingError("_api == null");
} else if (_apiName == null) {
throw Utils.logProgrammingError("_apiName == null");
}
}
// Fields
/**
* The state machine for this engine. Never <code>null</code>.
*/
private final EngineStateMachine _state = new EngineStateMachine();
/**
* The starter of this engine. Never <code>null</code>.
*/
private final EngineStarter _starter;
/**
* The stored servlet configuration object. Never <code>null</code>.
*/
private final ServletConfig _servletConfig;
/**
* The API that this engine forwards requests to. Never <code>null</code>.
*/
private final API _api;
/**
* Diagnostic context ID generator. Never <code>null</code>.
*/
private ContextIDGenerator _contextIDGenerator;
/**
* The name of the API. Never <code>null</code>.
*/
private String _apiName;
/**
* The manager for the runtime configuration file. Never <code>null</code>.
*/
private final ConfigManager _configManager;
/**
* The manager for the calling conventions. Initially this
* field is indeed <code>null</code>.
*/
private CallingConventionManager _conventionManager;
/**
* Pattern which incoming diagnostic context identifiers must match. Can be
* <code>null</code> in case no pattern has been specified. Initially this
* field is indeed <code>null</code>.
*/
private Pattern _contextIDPattern;
// Methods
private Pattern determineContextIDPattern(PropertyReader properties)
throws IllegalArgumentException, InvalidPropertyValueException {
// Check preconditions
MandatoryArgumentChecker.check("properties", properties);
// Determine pattern string
// XXX: Store "org.xins.server.contextID.filter" in a constant
String propName = "org.xins.server.contextID.filter";
String propValue = properties.get(propName);
// If the property value is empty, then there is no pattern
Pattern pattern;
if (TextUtils.isEmpty(propValue)) {
pattern = null;
Log.log_3431();
// Otherwise we must provide a Pattern instance
} else {
// Convert the string to a Pattern
try {
int mask = Perl5Compiler.READ_ONLY_MASK
| Perl5Compiler.CASE_INSENSITIVE_MASK;
pattern = PATTERN_COMPILER.compile(propValue, mask);
Log.log_3432(propValue);
// Malformed pattern indicates an invalid value
} catch (MalformedPatternException exception) {
Log.log_3433(propValue);
InvalidPropertyValueException ipve;
ipve = new InvalidPropertyValueException(propName, propValue);
ExceptionUtils.setCause(ipve, exception);
throw ipve;
}
}
return pattern;
}
/**
* Bootstraps the API. The following steps will be performed:
*
* <ul>
* <li>determine the API name;
* <li>load the Logdoc, if available;
* <li>bootstrap the API;
* <li>construct and bootstrap the calling conventions;
* <li>link the engine to the API;
* <li>construct and bootstrap a context ID generator;
* </ul>
*
* @throws ServletException
* if bootstrap fails.
*/
private void bootstrapAPI() throws ServletException {
// XXX: This method should not throw ServletException
// Proceed to next stage
_state.setState(EngineState.BOOTSTRAPPING_API);
PropertyReader bootProps;
try {
// Determine the name of the API
_apiName = _starter.determineAPIName();
// Load the Logdoc if available
_starter.loadLogdoc();
// Actually bootstrap the API
bootProps = _starter.bootstrap(_api);
// Handle any failures
} catch (ServletException se) {
_state.setState(EngineState.API_BOOTSTRAP_FAILED);
throw se;
}
// Create the calling convention manager
_conventionManager = new CallingConventionManager(_api);
// Bootstrap the calling convention manager
try {
_conventionManager.bootstrap(bootProps);
} catch (Throwable cause) {
ServletException exception = new ServletException();
ExceptionUtils.setCause(exception, cause);
throw exception;
}
// Make the API have a link to this Engine
_api.setEngine(this);
// Construct a generator for diagnostic context IDs
_contextIDGenerator = new ContextIDGenerator(_api.getName());
try {
_contextIDGenerator.bootstrap(bootProps);
} catch (Exception exception) {
throw EngineStarter.servletExceptionFor(exception);
}
}
/**
* Initializes the API using the current runtime settings. This method
* should be called whenever the runtime properties changed.
*
* @return
* <code>true</code> if the initialization succeeded, otherwise
* <code>false</code>.
*/
boolean initAPI() {
_state.setState(EngineState.INITIALIZING_API);
// Determine the current runtime properties
PropertyReader properties = _configManager.getRuntimeProperties();
boolean succeeded = false;
boolean localeInitialized = _configManager.determineLogLocale();
if (! localeInitialized) {
_state.setState(EngineState.API_INITIALIZATION_FAILED);
return false;
}
try {
// Determine filter for incoming diagnostic context IDs
_contextIDPattern = determineContextIDPattern(properties);
// Initialize the diagnostic context ID generator
_contextIDGenerator.init(properties);
// Initialize the API
_api.init(properties);
// Initialize the default calling convention for this API
_conventionManager.init(properties);
succeeded = true;
// Missing required property
} catch (MissingRequiredPropertyException exception) {
Log.log_3411(exception.getPropertyName());
// Invalid property value
} catch (InvalidPropertyValueException exception) {
Log.log_3412(exception.getPropertyName(),
exception.getPropertyValue(),
exception.getReason());
// Initialization of API failed for some other reason
} catch (InitializationException exception) {
Log.log_3413(exception);
// Unexpected error
// XXX: According to the documentation of the Manageable class, this
// cannot happen.
} catch (Throwable exception) {
Log.log_3414(exception);
// Always leave the object in a well-known state
} finally {
if (succeeded) {
_state.setState(EngineState.READY);
} else {
_state.setState(EngineState.API_INITIALIZATION_FAILED);
}
}
return succeeded;
}
/**
* Handles a request to this servlet (wrapper method). If any of the
* arguments is <code>null</code>, then the behaviour of this method is
* undefined.
*
* @param request
* the servlet request, should not be <code>null</code>.
*
* @param response
* the servlet response, should not be <code>null</code>.
*
* @throws IOException
* if there is an error error writing to the response output stream.
*/
void service(final HttpServletRequest request,
final HttpServletResponse response)
throws IOException {
// Associate the current diagnostic context identifier with this thread
String contextID = determineContextID(request);
NDC.push(contextID);
// Handle the request
try {
doService(request, response);
// Catch and log all exceptions
} catch (Throwable exception) {
Log.log_3003(exception);
// Finally always disassociate the diagnostic context identifier from
// this thread
} finally {
NDC.pop();
NDC.remove();
}
}
/**
* Returns an applicable diagnostic context identifier. If the request
* already specifies a diagnostic context identifier, then that will be
* used. Otherwise a new one will be generated.
*
* @param request
* the HTTP servlet request, should not be <code>null</code>.
*
* @return
* the diagnostic context identifier, never <code>null</code> and never
* an empty string.
*/
private String determineContextID(final HttpServletRequest request) {
// See if the request already specifies a diagnostic context identifier
// XXX: Store "_context" in a constant
String contextID = request.getParameter("_context");
if (TextUtils.isEmpty(contextID)) {
Log.log_3580();
contextID = null;
// Indeed there is a context ID in the request, make sure it's valid
} else {
// Valid context ID
if (isValidContextID(contextID)) {
Log.log_3581(contextID);
// Invalid context ID
} else {
Log.log_3582(contextID);
contextID = null;
}
}
// If we have no (acceptable) context ID yet, then generate one now
if (contextID == null) {
contextID = _contextIDGenerator.generate();
Log.log_3583(contextID);
}
return contextID;
}
/**
* Determines if the specified incoming context identifier is considered
* valid.
*
* @param contextID
* the incoming diagnostic context identifier, should not be
* <code>null</code>.
*
* @return
* <code>true</code> if <code>contextID</code> is considered acceptable,
* <code>false</code> if it is considered unacceptable.
*/
private boolean isValidContextID(String contextID) {
// If a filter is specified, validate that the ID matches it
if (_contextIDPattern != null) {
Perl5Matcher matcher = new Perl5Matcher();
return matcher.matches(contextID, _contextIDPattern);
// No filter is specified, everything is allowed
} else {
return true;
}
}
/**
* Handles a request to this servlet (implementation method). If any of the
* arguments is <code>null</code>, then the behaviour of this method is
* undefined.
*
* <p>This method is called from the corresponding wrapper method,
* {@link #service(HttpServletRequest,HttpServletResponse)}.
*
* @param request
* the servlet request, should not be <code>null</code>.
*
* @param response
* the servlet response, should not be <code>null</code>.
*
* @throws IOException
* if there is an error error writing to the response output stream.
*/
private void doService(final HttpServletRequest request,
final HttpServletResponse response)
throws IOException {
// Determine current time
long start = System.currentTimeMillis();
// Determine the remote IP address and the query string
String remoteIP = request.getRemoteAddr();
String queryString = request.getQueryString();
// Check the HTTP request method
String method = request.getMethod();
boolean sendOutput;
// Support HTTP GET
if ("GET".equals(method)) {
sendOutput = true;
// Support HTTP POST
} else if ("POST".equals(method)) {
sendOutput = true;
// Support HTTP HEAD (returns no output)
} else if ("HEAD".equals(method)) {
sendOutput = false;
response.setContentLength(0);
// Support HTTP OPTIONS
} else if ("OPTIONS".equals(method)) {
Log.log_3521(remoteIP, method, request.getRequestURI(), queryString);
response.setContentLength(0);
response.setHeader("Accept", "GET, HEAD, POST");
response.setStatus(HttpServletResponse.SC_OK);
return;
// Otherwise the HTTP method is unrecognized, so return
// '405 Method Not Allowed'
} else {
Log.log_3520(remoteIP, method, queryString);
response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
return;
}
// Log that we have received an HTTP request
Log.log_3521(remoteIP, method, request.getRequestURI(), queryString);
// Determine the calling convention; if an existing calling convention
// is specified in the request, then use that, otherwise use the default
// calling convention for this engine
String ccParam = request.getParameter(APIServlet.CALLING_CONVENTION_PARAMETER);
CallingConvention cc = null;
FunctionRequest xinsRequest = null;
FunctionResult result = null;
// Call the API if the state is READY
EngineState state = _state.getState();
if (state == EngineState.READY) {
try {
cc = _conventionManager.getCallingConvention(ccParam);
// Convert the HTTP request to a XINS request
xinsRequest = cc.convertRequest(request);
// Call the function
result = _api.handleCall(start, xinsRequest, remoteIP);
} catch (Throwable exception) {
String subjectClass = null;
String subjectMethod = null;
if (cc == null) {
subjectClass = _conventionManager.getClass().getName();
subjectMethod = "getCallingConvention(String)";
} else if (xinsRequest == null) {
subjectClass = cc.getClass().getName();
subjectMethod = "convertRequest(javax.servlet.http.HttpServletRequest)";
} else if (result == null) {
subjectClass = _api.getClass().getName();
subjectMethod = "handleCall(long,"
+ FunctionRequest.class.getName()
+ ",java.lang.String)";
}
int error;
// If the function is not specified, then return '404 Not Found'
if (exception instanceof FunctionNotSpecifiedException) {
error = HttpServletResponse.SC_NOT_FOUND;
// If the request is invalid, then return '400 Bad Request'
} else if (exception instanceof InvalidRequestException) {
error = HttpServletResponse.SC_BAD_REQUEST;
// If access is denied, return '403 Forbidden'
} else if (exception instanceof AccessDeniedException) {
error = HttpServletResponse.SC_FORBIDDEN;
// If no matching function is found, return '404 Not Found'
} else if (exception instanceof NoSuchFunctionException) {
error = HttpServletResponse.SC_NOT_FOUND;
// Otherwise an unexpected exception is thrown, return
// '500 Internal Server Error'
} else {
error = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
Utils.logProgrammingError(
Engine.class.getName(),
"doService(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)",
subjectClass,
subjectMethod,
null,
exception);
}
Log.log_3522(exception, error);
// XXX: We could pass the result of HttpStatus.getStatusText(int)
// to log message 3522, but this would introduce a dependency
// from the XINS/Java Server Framework on the HttpClient
// library.
response.sendError(error);
return;
}
// Otherwise return an appropriate 50x HTTP response code
} else if (state == EngineState.INITIAL
|| state == EngineState.BOOTSTRAPPING_FRAMEWORK
|| state == EngineState.CONSTRUCTING_API
|| state == EngineState.BOOTSTRAPPING_API
|| state == EngineState.INITIALIZING_API) {
response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
return;
} else {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
// Send the output only if GET or POST; convert it from a XINS function
// result to an HTTP response
if (sendOutput) {
try {
cc.convertResult(result, response, request);
} catch (Throwable exception) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
}
}
/**
* Destroys this servlet. A best attempt will be made to release all
* resources.
*
* <p>After this method has finished, it will set the state to
* <em>disposed</em>. In that state no more requests will be handled.
*/
void destroy() {
// Log: Shutting down XINS/Java Server Framework
Log.log_3600();
// Set the state temporarily to DISPOSING
_state.setState(EngineState.DISPOSING);
// Destroy the configuration manager
if (_configManager != null) {
try {
_configManager.destroy();
} catch (Throwable exception) {
Utils.logIgnoredException(
Engine.class.getName(), "destroy()",
_configManager.getClass().getName(), "destroy()",
exception);
}
}
// Destroy the API
if (_api != null) {
try {
_api.deinit();
} catch (Throwable exception) {
Utils.logIgnoredException(
Engine.class.getName(), "destroy()",
_api.getClass().getName(), "deinit()",
exception);
}
}
// Set the state to DISPOSED
_state.setState(EngineState.DISPOSED);
// Log: Shutdown completed
Log.log_3602();
}
/**
* Re-initializes the configuration file listener if there is no file
* watcher; otherwise interrupts the file watcher.
*/
void reloadPropertiesIfChanged() {
_configManager.reloadPropertiesIfChanged();
}
/**
* Returns the <code>ServletConfig</code> object which contains the
* build properties for this servlet. The returned {@link ServletConfig}
* object is the one passed to the constructor.
*
* @return
* the {@link ServletConfig} object that was used to initialize this
* servlet, never <code>null</code>.
*/
ServletConfig getServletConfig() {
return _servletConfig;
}
} |
package dr.evomodel.antigenic;
import dr.evolution.util.*;
import dr.inference.model.*;
import dr.math.MathUtils;
import dr.math.distributions.NormalDistribution;
import dr.util.*;
import dr.xml.*;
import java.io.*;
import java.util.*;
import java.util.logging.Logger;
/**
* @author Andrew Rambaut
* @author Trevor Bedford
* @author Marc Suchard
* @version $Id$
*/
public class AntigenicLikelihood extends AbstractModelLikelihood implements Citable {
public final static String ANTIGENIC_LIKELIHOOD = "antigenicLikelihood";
// column indices in table
private static final int COLUMN_LABEL = 0;
private static final int SERUM_STRAIN = 2;
private static final int ROW_LABEL = 1;
private static final int VIRUS_STRAIN = 3;
private static final int SERUM_DATE = 4;
private static final int VIRUS_DATE = 5;
private static final int RAW_TITRE = 6;
private static final int MIN_TITRE = 7;
private static final int MAX_TITRE = 8;
public enum MeasurementType {
INTERVAL,
POINT,
UPPER_BOUND,
LOWER_BOUND,
MISSING
}
public AntigenicLikelihood(
int mdsDimension,
Parameter mdsPrecisionParameter,
TaxonList strainTaxa,
MatrixParameter locationsParameter,
Parameter datesParameter,
Parameter columnParameter,
Parameter rowParameter,
DataTable<String[]> dataTable,
List<String> virusLocationStatisticList) {
super(ANTIGENIC_LIKELIHOOD);
List<String> strainNames = new ArrayList<String>();
Map<String, Double> strainDateMap = new HashMap<String, Double>();
for (int i = 0; i < dataTable.getRowCount(); i++) {
String[] values = dataTable.getRow(i);
int column = columnLabels.indexOf(values[COLUMN_LABEL]);
if (column == -1) {
columnLabels.add(values[0]);
column = columnLabels.size() - 1;
}
int columnStrain = -1;
if (strainTaxa != null) {
columnStrain = strainTaxa.getTaxonIndex(values[SERUM_STRAIN]);
} else {
columnStrain = strainNames.indexOf(values[SERUM_STRAIN]);
if (columnStrain == -1) {
strainNames.add(values[SERUM_STRAIN]);
Double date = Double.parseDouble(values[VIRUS_DATE]);
strainDateMap.put(values[SERUM_STRAIN], date);
columnStrain = strainNames.size() - 1;
}
}
if (columnStrain == -1) {
throw new IllegalArgumentException("Error reading data table: Unrecognized serum strain name, " + values[SERUM_STRAIN] + ", in row " + (i+1));
}
int row = rowLabels.indexOf(values[ROW_LABEL]);
if (row == -1) {
rowLabels.add(values[ROW_LABEL]);
row = rowLabels.size() - 1;
}
int rowStrain = -1;
if (strainTaxa != null) {
rowStrain = strainTaxa.getTaxonIndex(values[VIRUS_STRAIN]);
} else {
rowStrain = strainNames.indexOf(values[VIRUS_STRAIN]);
if (rowStrain == -1) {
strainNames.add(values[VIRUS_STRAIN]);
Double date = Double.parseDouble(values[VIRUS_DATE]);
strainDateMap.put(values[VIRUS_STRAIN], date);
rowStrain = strainNames.size() - 1;
}
}
if (rowStrain == -1) {
throw new IllegalArgumentException("Error reading data table: Unrecognized virus strain name, " + values[VIRUS_STRAIN] + ", in row " + (i+1));
}
double minTitre = Double.NaN;
if (values[MIN_TITRE].length() > 0) {
try {
minTitre = Double.parseDouble(values[MIN_TITRE]);
} catch (NumberFormatException nfe) {
// do nothing
}
}
double maxTitre = Double.NaN;
if (values[MAX_TITRE].length() > 0) {
try {
maxTitre = Double.parseDouble(values[MAX_TITRE]);
} catch (NumberFormatException nfe) {
// do nothing
}
}
MeasurementType type = MeasurementType.INTERVAL;
if (minTitre == maxTitre) {
type = MeasurementType.POINT;
}
if (Double.isNaN(minTitre) || minTitre == 0.0) {
if (Double.isNaN(maxTitre)) {
throw new IllegalArgumentException("Error in measurement: both min and max titre are at bounds in row " + (i+1));
}
type = MeasurementType.UPPER_BOUND;
} else if (Double.isNaN(maxTitre)) {
type = MeasurementType.LOWER_BOUND;
}
Measurement measurement = new Measurement(column, columnStrain, row, rowStrain, type, minTitre, maxTitre);
measurements.add(measurement);
}
double[] maxColumnTitre = new double[columnLabels.size()];
double[] maxRowTitre = new double[rowLabels.size()];
for (Measurement measurement : measurements) {
double titre = measurement.maxTitre;
if (Double.isNaN(titre)) {
titre = measurement.minTitre;
}
if (titre > maxColumnTitre[measurement.column]) {
maxColumnTitre[measurement.column] = titre;
}
if (titre > maxRowTitre[measurement.row]) {
maxRowTitre[measurement.row] = titre;
}
}
if (strainTaxa != null) {
this.strains = strainTaxa;
// fill in the strain name array for local use
for (int i = 0; i < strains.getTaxonCount(); i++) {
strainNames.add(strains.getTaxon(i).getId());
}
} else {
Taxa taxa = new Taxa();
for (String strain : strainNames) {
taxa.addTaxon(new Taxon(strain));
}
this.strains = taxa;
}
this.mdsDimension = mdsDimension;
this.mdsPrecisionParameter = mdsPrecisionParameter;
addVariable(mdsPrecisionParameter);
this.locationsParameter = locationsParameter;
setupLocationsParameter(this.locationsParameter, strainNames);
addVariable(this.locationsParameter);
if (datesParameter != null) {
// this parameter is not used in this class but is setup to be used in other classes
datesParameter.setDimension(strainNames.size());
String[] labelArray = new String[strainNames.size()];
strainNames.toArray(labelArray);
datesParameter.setDimensionNames(labelArray);
for (int i = 0; i < strainNames.size(); i++) {
Double date = strainDateMap.get(strainNames.get(i));
if (date == null) {
throw new IllegalArgumentException("Date missing for strain: " + strainNames.get(i));
}
datesParameter.setParameterValue(i, date);
}
}
if (columnParameter == null) {
this.columnEffectsParameter = new Parameter.Default("columnEffects");
} else {
this.columnEffectsParameter = columnParameter;
}
this.columnEffectsParameter.setDimension(columnLabels.size());
addVariable(this.columnEffectsParameter);
String[] labelArray = new String[columnLabels.size()];
columnLabels.toArray(labelArray);
this.columnEffectsParameter.setDimensionNames(labelArray);
for (int i = 0; i < maxColumnTitre.length; i++) {
this.columnEffectsParameter.setParameterValueQuietly(i, maxColumnTitre[i]);
}
if (rowParameter == null) {
this.rowEffectsParameter = new Parameter.Default("rowEffects");
} else {
this.rowEffectsParameter = rowParameter;
}
this.rowEffectsParameter.setDimension(rowLabels.size());
addVariable(this.rowEffectsParameter);
labelArray = new String[rowLabels.size()];
rowLabels.toArray(labelArray);
this.rowEffectsParameter.setDimensionNames(labelArray);
for (int i = 0; i < maxRowTitre.length; i++) {
this.rowEffectsParameter.setParameterValueQuietly(i, maxRowTitre[i]);
}
StringBuilder sb = new StringBuilder();
sb.append("\tAntigenicLikelihood:\n");
sb.append("\t\t" + this.strains.getTaxonCount() + " strains\n");
sb.append("\t\t" + columnLabels.size() + " unique columns\n");
sb.append("\t\t" + rowLabels.size() + " unique rows\n");
sb.append("\t\t" + measurements.size() + " assay measurements\n");
Logger.getLogger("dr.evomodel").info(sb.toString());
// initial locations
double earliestDate = datesParameter.getParameterValue(0);
for (int i=0; i<datesParameter.getDimension(); i++) {
double date = datesParameter.getParameterValue(i);
if (earliestDate > date) {
earliestDate = date;
}
}
for (int i = 0; i < locationsParameter.getParameterCount(); i++) {
String name = strainNames.get(i);
double date = (double) strainDateMap.get(strainNames.get(i));
double diff = (date-earliestDate);
locationsParameter.getParameter(i).setParameterValueQuietly(0, diff + MathUtils.nextGaussian());
for (int j = 1; j < mdsDimension; j++) {
double r = MathUtils.nextGaussian();
locationsParameter.getParameter(i).setParameterValueQuietly(j, r);
}
}
locationChanged = new boolean[this.locationsParameter.getRowDimension()];
logLikelihoods = new double[measurements.size()];
storedLogLikelihoods = new double[measurements.size()];
makeDirty();
}
protected void setupLocationsParameter(MatrixParameter locationsParameter, List<String> strains) {
locationsParameter.setColumnDimension(mdsDimension);
locationsParameter.setRowDimension(strains.size());
for (int i = 0; i < strains.size(); i++) {
locationsParameter.getParameter(i).setId(strains.get(i));
}
}
@Override
protected void handleModelChangedEvent(Model model, Object object, int index) {
}
@Override
protected void handleVariableChangedEvent(Variable variable, int index, Variable.ChangeType type) {
if (variable == locationsParameter) {
locationChanged[index / mdsDimension] = true;
} else if (variable == mdsPrecisionParameter) {
setLocationChangedFlags(true);
} else if (variable == columnEffectsParameter) {
setLocationChangedFlags(true);
} else if (variable == rowEffectsParameter) {
setLocationChangedFlags(true);
} else {
// could be a derived class's parameter
}
likelihoodKnown = false;
}
@Override
protected void storeState() {
System.arraycopy(logLikelihoods, 0, storedLogLikelihoods, 0, logLikelihoods.length);
}
@Override
protected void restoreState() {
double[] tmp = logLikelihoods;
logLikelihoods = storedLogLikelihoods;
storedLogLikelihoods = tmp;
likelihoodKnown = false;
}
@Override
protected void acceptState() {
}
@Override
public Model getModel() {
return this;
}
@Override
public double getLogLikelihood() {
if (!likelihoodKnown) {
logLikelihood = computeLogLikelihood();
}
return logLikelihood;
}
// This function can be overwritten to implement other sampling densities, i.e. discrete ranks
private double computeLogLikelihood() {
double precision = mdsPrecisionParameter.getParameterValue(0);
double sd = 1.0 / Math.sqrt(precision);
logLikelihood = 0.0;
int i = 0;
for (Measurement measurement : measurements) {
if (locationChanged[measurement.rowStrain] || locationChanged[measurement.columnStrain]) {
double distance = computeDistance(measurement.rowStrain, measurement.columnStrain);
double logNormalization = calculateTruncationNormalization(distance, sd);
switch (measurement.type) {
case INTERVAL: {
double minTitre = transformTitre(measurement.minTitre, measurement.column, measurement.row, distance, sd);
double maxTitre = transformTitre(measurement.maxTitre, measurement.column, measurement.row, distance, sd);
logLikelihoods[i] = computeMeasurementIntervalLikelihood(minTitre, maxTitre) - logNormalization;
} break;
case POINT: {
double titre = transformTitre(measurement.minTitre, measurement.column, measurement.row, distance, sd);
logLikelihoods[i] = computeMeasurementLikelihood(titre) - logNormalization;
} break;
case LOWER_BOUND: {
double minTitre = transformTitre(measurement.minTitre, measurement.column, measurement.row, distance, sd);
logLikelihoods[i] = computeMeasurementLowerBoundLikelihood(minTitre) - logNormalization;
} break;
case UPPER_BOUND: {
double maxTitre = transformTitre(measurement.maxTitre, measurement.column, measurement.row, distance, sd);
logLikelihoods[i] = computeMeasurementUpperBoundLikelihood(maxTitre) - logNormalization;
} break;
case MISSING:
break;
}
}
logLikelihood += logLikelihoods[i];
i++;
}
likelihoodKnown = true;
setLocationChangedFlags(false);
return logLikelihood;
}
private void setLocationChangedFlags(boolean flag) {
for (int i = 0; i < locationChanged.length; i++) {
locationChanged[i] = flag;
}
}
protected double computeDistance(int rowStrain, int columnStrain) {
if (rowStrain == columnStrain) {
return 0.0;
}
Parameter X = locationsParameter.getParameter(rowStrain);
Parameter Y = locationsParameter.getParameter(columnStrain);
double sum = 0.0;
for (int i = 0; i < mdsDimension; i++) {
double difference = X.getParameterValue(i) - Y.getParameterValue(i);
sum += difference * difference;
}
return Math.sqrt(sum);
}
/**
* Transforms a titre into log2 space and normalizes it with respect to a unit normal
* @param titre
* @param column
* @param row
* @param mean
* @param sd
* @return
*/
private double transformTitre(double titre, int column, int row, double mean, double sd) {
double rowEffect = rowEffectsParameter.getParameterValue(row);
double columnEffect = columnEffectsParameter.getParameterValue(column);
double t = ((rowEffect + columnEffect) * 0.5) - titre;
return (t - mean) / sd;
}
private double computeMeasurementIntervalLikelihood(double minTitre, double maxTitre) {
double cdf1 = NormalDistribution.standardCDF(minTitre, false);
double cdf2 = NormalDistribution.standardCDF(maxTitre, false);
double lnL = Math.log(cdf1 - cdf2);
if (cdf1 == cdf2) {
lnL = Math.log(cdf1);
}
if (Double.isNaN(lnL) || Double.isInfinite(lnL)) {
throw new RuntimeException("infinite");
}
return lnL;
}
private double computeMeasurementLikelihood(double titre) {
double lnL = Math.log(NormalDistribution.pdf(titre, 0.0, 1.0));
if (Double.isNaN(lnL) || Double.isInfinite(lnL)) {
throw new RuntimeException("infinite");
}
return lnL;
}
private double computeMeasurementLowerBoundLikelihood(double transformedMinTitre) {
// a lower bound in non-transformed titre so the bottom tail of the distribution
double cdf = NormalDistribution.standardTail(transformedMinTitre, true);
double lnL = Math.log(cdf);
if (Double.isNaN(lnL) || Double.isInfinite(lnL)) {
throw new RuntimeException("infinite");
}
return lnL;
}
private double computeMeasurementUpperBoundLikelihood(double transformedMaxTitre) {
// a upper bound in non-transformed titre so the upper tail of the distribution
// using special tail function of NormalDistribution (see main() in NormalDistribution for test)
double tail = NormalDistribution.standardTail(transformedMaxTitre, false);
double lnL = Math.log(tail);
if (Double.isNaN(lnL) || Double.isInfinite(lnL)) {
throw new RuntimeException("infinite");
}
return lnL;
}
private double calculateTruncationNormalization(double distance, double sd) {
return NormalDistribution.cdf(distance, 0.0, sd, true);
}
@Override
public void makeDirty() {
likelihoodKnown = false;
setLocationChangedFlags(true);
}
private class Measurement {
private Measurement(final int column, final int columnStrain, final int row, final int rowStrain, final MeasurementType type, final double minTitre, final double maxTitre) {
this.column = column;
this.columnStrain = columnStrain;
this.row = row;
this.rowStrain = rowStrain;
this.type = type;
this.minTitre = Math.log(minTitre) / Math.log(2);
this.maxTitre = Math.log(maxTitre) / Math.log(2);
}
final int column;
final int row;
final int columnStrain;
final int rowStrain;
final MeasurementType type;
final double minTitre;
final double maxTitre;
};
private final List<Measurement> measurements = new ArrayList<Measurement>();
private final List<String> columnLabels = new ArrayList<String>();
private final List<String> rowLabels = new ArrayList<String>();
private final int mdsDimension;
private final Parameter mdsPrecisionParameter;
private final MatrixParameter locationsParameter;
private final TaxonList strains;
// private final CompoundParameter tipTraitParameter;
private final Parameter columnEffectsParameter;
private final Parameter rowEffectsParameter;
private double logLikelihood = 0.0;
private boolean likelihoodKnown = false;
private final boolean[] locationChanged;
private double[] logLikelihoods;
private double[] storedLogLikelihoods;
// XMLObjectParser
public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
public final static String FILE_NAME = "fileName";
public final static String TIP_TRAIT = "tipTrait";
public final static String LOCATIONS = "locations";
public final static String DATES = "dates";
public static final String MDS_DIMENSION = "mdsDimension";
public static final String MDS_PRECISION = "mdsPrecision";
public static final String COLUMN_EFFECTS = "columnEffects";
public static final String ROW_EFFECTS = "rowEffects";
public static final String STRAINS = "strains";
public String getParserName() {
return ANTIGENIC_LIKELIHOOD;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
String fileName = xo.getStringAttribute(FILE_NAME);
DataTable<String[]> assayTable;
try {
assayTable = DataTable.Text.parse(new FileReader(fileName), true, false);
} catch (IOException e) {
throw new XMLParseException("Unable to read assay data from file: " + e.getMessage());
}
int mdsDimension = xo.getIntegerAttribute(MDS_DIMENSION);
// CompoundParameter tipTraitParameter = null;
// if (xo.hasChildNamed(TIP_TRAIT)) {
// tipTraitParameter = (CompoundParameter) xo.getElementFirstChild(TIP_TRAIT);
TaxonList strains = null;
if (xo.hasChildNamed(STRAINS)) {
strains = (TaxonList) xo.getElementFirstChild(STRAINS);
}
MatrixParameter locationsParameter = (MatrixParameter) xo.getElementFirstChild(LOCATIONS);
Parameter datesParameter = null;
if (xo.hasChildNamed(DATES)) {
datesParameter = (Parameter) xo.getElementFirstChild(DATES);
}
Parameter mdsPrecision = (Parameter) xo.getElementFirstChild(MDS_PRECISION);
Parameter columnEffectsParameter = (Parameter) xo.getElementFirstChild(COLUMN_EFFECTS);
Parameter rowEffectsParameter = (Parameter) xo.getElementFirstChild(ROW_EFFECTS);
AntigenicLikelihood AGL = new AntigenicLikelihood(
mdsDimension,
mdsPrecision,
strains,
locationsParameter,
datesParameter,
columnEffectsParameter,
rowEffectsParameter,
assayTable,
null);
Logger.getLogger("dr.evomodel").info("Using EvolutionaryCartography model. Please cite:\n" + Utils.getCitationString(AGL));
return AGL;
} |
package mho.haskellesque.math;
import mho.haskellesque.iterables.CachedIterable;
import mho.haskellesque.iterables.Exhaustive;
import mho.haskellesque.ordering.Ordering;
import mho.haskellesque.structures.*;
import org.jetbrains.annotations.NotNull;
import java.math.BigInteger;
import java.util.*;
import java.util.function.Function;
import java.util.function.Predicate;
import static mho.haskellesque.iterables.IterableUtils.*;
import static mho.haskellesque.iterables.IterableUtils.isEmpty;
import static mho.haskellesque.iterables.IterableUtils.map;
import static mho.haskellesque.ordering.Ordering.*;
/**
* Various combinatorial functions and <tt>Iterable</tt>s.
*/
public class Combinatorics {
/**
* The factorial function <tt>n</tt>!
*
* <ul>
* <li><tt>n</tt> must be non-negative.</li>
* <li>The result is a factorial.</li>
* </ul>
*
* @param n the argument
* @return <tt>n</tt>!
*/
public static @NotNull BigInteger factorial(int n) {
if (n < 0)
throw new ArithmeticException("cannot take factorial of " + n);
return productBigInteger(range(BigInteger.ONE, BigInteger.valueOf(n)));
}
/**
* The factorial function <tt>n</tt>!
*
* <ul>
* <li><tt>n</tt> must be non-negative.</li>
* <li>The result is a factorial.</li>
* </ul>
*
* @param n the argument
* @return <tt>n</tt>!
*/
public static @NotNull BigInteger factorial(@NotNull BigInteger n) {
if (n.signum() == -1)
throw new ArithmeticException("cannot take factorial of " + n);
return productBigInteger(range(BigInteger.ONE, n));
}
/**
* The subfactorial function !<tt>n</tt>
*
* <ul>
* <li><tt>n</tt> must be non-negative.</li>
* <li>The result is a subfactorial (rencontres number).</li>
* </ul>
*
* @param n the argument
* @return !<tt>n</tt>
*/
public static @NotNull BigInteger subfactorial(int n) {
if (n < 0)
throw new ArithmeticException("cannot take subfactorial of " + n);
BigInteger sf = BigInteger.ONE;
for (int i = 1; i <= n; i++) {
sf = sf.multiply(BigInteger.valueOf(i));
if ((i & 1) == 0) {
sf = sf.add(BigInteger.ONE);
} else {
sf = sf.subtract(BigInteger.ONE);
}
}
return sf;
}
/**
* The subfactorial function !<tt>n</tt>
*
* <ul>
* <li><tt>n</tt> must be non-negative.</li>
* <li>The result is a subfactorial (rencontres number).</li>
* </ul>
*
* @param n the argument
* @return !<tt>n</tt>
*/
public static @NotNull BigInteger subfactorial(@NotNull BigInteger n) {
if (n.signum() == -1)
throw new ArithmeticException("cannot take subfactorial of " + n);
BigInteger sf = BigInteger.ONE;
for (BigInteger i = BigInteger.ONE; le(i, n); i = i.add(BigInteger.ONE)) {
sf = sf.multiply(i);
if (i.getLowestSetBit() != 0) {
sf = sf.add(BigInteger.ONE);
} else {
sf = sf.subtract(BigInteger.ONE);
}
}
return sf;
}
/**
* Given two <tt>Iterable</tt>s, returns all ordered pairs of elements from these <tt>Iterable</tt>s in ascending
* order. The second <tt>Iterable</tt> must be finite; using a long second <tt>Iterable</tt> is possible but
* discouraged.
*
* <ul>
* <li><tt>as</tt> must be non-null.</li>
* <li><tt>bs</tt> must be finite.</li>
* <li>The result is the Cartesian product of two finite <tt>Iterable</tt>s.</li>
* </ul>
*
* Result length is |<tt>as</tt>||<tt>bs</tt>|
*
* @param as the first <tt>Iterable</tt>
* @param bs the second <tt>Iterable</tt>
* @param <A> the type of the first <tt>Iterable</tt>'s elements
* @param <B> the type of the second <tt>Iterable</tt>'s elements
* @return all ordered pairs of elements from <tt>as</tt> and <tt>bs</tt>
*/
public static @NotNull <A, B> Iterable<Pair<A, B>> pairsAscending(
@NotNull Iterable<A> as,
@NotNull Iterable<B> bs
) {
return concatMap(p -> zip(repeat(p.a), p.b), zip(as, repeat(bs)));
}
/**
* Given three <tt>Iterable</tt>s, returns all ordered triples of elements from these <tt>Iterable</tt>s in
* ascending order. All <tt>Iterable</tt>s but the first must be finite; using long <tt>Iterable</tt>s in any
* position but the first is possible but discouraged.
*
* <ul>
* <li><tt>as</tt> must be non-null.</li>
* <li><tt>bs</tt> must be finite.</li>
* <li><tt>cs</tt> must be finite.</li>
* <li>The result is the Cartesian product of three finite <tt>Iterable</tt>s.</li>
* </ul>
*
* Result length is |<tt>as</tt>||<tt>bs</tt>||<tt>cs</tt>|
*
* @param as the first <tt>Iterable</tt>
* @param bs the second <tt>Iterable</tt>
* @param cs the third <tt>Iterable</tt>
* @param <A> the type of the first <tt>Iterable</tt>'s elements
* @param <B> the type of the second <tt>Iterable</tt>'s elements
* @param <C> the type of the third <tt>Iterable</tt>'s elements
* @return all ordered triples of elements from <tt>as</tt>, <tt>bs</tt>, and <tt>cs</tt>
*/
public static @NotNull <A, B, C> Iterable<Triple<A, B, C>> triplesAscending(
@NotNull Iterable<A> as,
@NotNull Iterable<B> bs,
@NotNull Iterable<C> cs
) {
return map(
p -> new Triple<>(p.a, p.b.a, p.b.b),
pairsAscending(as, (Iterable<Pair<B, C>>) pairsAscending(bs, cs))
);
}
/**
* Given four <tt>Iterable</tt>s, returns all ordered quadruples of elements from these <tt>Iterable</tt>s in
* ascending order. All <tt>Iterable</tt>s but the first must be finite; using long <tt>Iterable</tt>s in any
* position but the first is possible but discouraged.
*
* <ul>
* <li><tt>as</tt> must be non-null.</li>
* <li><tt>bs</tt> must be finite.</li>
* <li><tt>cs</tt> must be finite.</li>
* <li><tt>ds</tt> must be finite.</li>
* <li>The result is the Cartesian product of four finite <tt>Iterable</tt>s.</li>
* </ul>
*
* Result length is |<tt>as</tt>||<tt>bs</tt>||<tt>cs</tt>||<tt>ds</tt>|
*
* @param as the first <tt>Iterable</tt>
* @param bs the second <tt>Iterable</tt>
* @param cs the third <tt>Iterable</tt>
* @param ds the fourth <tt>Iterable</tt>
* @param <A> the type of the first <tt>Iterable</tt>'s elements
* @param <B> the type of the second <tt>Iterable</tt>'s elements
* @param <C> the type of the third <tt>Iterable</tt>'s elements
* @param <D> the type of the fourth <tt>Iterable</tt>'s elements
* @return all ordered quadruples of elements from <tt>as</tt>, <tt>bs</tt>, <tt>cs</tt>, and <tt>ds</tt>
*/
public static @NotNull <A, B, C, D> Iterable<Quadruple<A, B, C, D>> quadruplesAscending(
@NotNull Iterable<A> as,
@NotNull Iterable<B> bs,
@NotNull Iterable<C> cs,
@NotNull Iterable<D> ds
) {
return map(
p -> new Quadruple<>(p.a.a, p.a.b, p.b.a, p.b.b),
pairsAscending(
(Iterable<Pair<A, B>>) pairsAscending(as, bs),
(Iterable<Pair<C, D>>) pairsAscending(cs, ds)
)
);
}
/**
* Given five <tt>Iterable</tt>s, returns all ordered quintuples of elements from these <tt>Iterable</tt>s in
* ascending order. All <tt>Iterable</tt>s but the first must be finite; using long <tt>Iterable</tt>s in any
* position but the first is possible but discouraged.
*
* <ul>
* <li><tt>as</tt> must be non-null.</li>
* <li><tt>bs</tt> must be finite.</li>
* <li><tt>cs</tt> must be finite.</li>
* <li><tt>ds</tt> must be finite.</li>
* <li><tt>es</tt> must be finite.</li>
* <li>The result is the Cartesian product of five finite <tt>Iterable</tt>s.</li>
* </ul>
*
* Result length is |<tt>as</tt>||<tt>bs</tt>||<tt>cs</tt>||<tt>ds</tt>||<tt>es</tt>|
*
* @param as the first <tt>Iterable</tt>
* @param bs the second <tt>Iterable</tt>
* @param cs the third <tt>Iterable</tt>
* @param ds the fourth <tt>Iterable</tt>
* @param es the fifth <tt>Iterable</tt>
* @param <A> the type of the first <tt>Iterable</tt>'s elements
* @param <B> the type of the second <tt>Iterable</tt>'s elements
* @param <C> the type of the third <tt>Iterable</tt>'s elements
* @param <D> the type of the fourth <tt>Iterable</tt>'s elements
* @param <E> the type of the fifth <tt>Iterable</tt>'s elements
* @return all ordered quintuples of elements from <tt>as</tt>, <tt>bs</tt>, <tt>cs</tt>, <tt>ds</tt>, and
* <tt>es</tt>
*/
public static @NotNull <A, B, C, D, E> Iterable<Quintuple<A, B, C, D, E>> quintuplesAscending(
@NotNull Iterable<A> as,
@NotNull Iterable<B> bs,
@NotNull Iterable<C> cs,
@NotNull Iterable<D> ds,
@NotNull Iterable<E> es
) {
return map(
p -> new Quintuple<>(p.a.a, p.a.b, p.b.a, p.b.b, p.b.c),
pairsAscending(
(Iterable<Pair<A, B>>) pairsAscending(as, bs),
(Iterable<Triple<C, D, E>>) triplesAscending(cs, ds, es)
)
);
}
/**
* Given six <tt>Iterable</tt>s, returns all ordered sextuples of elements from these <tt>Iterable</tt>s in
* ascending order. All <tt>Iterable</tt>s but the first must be finite; using long <tt>Iterable</tt>s in any
* position but the first is possible but discouraged.
*
* <ul>
* <li><tt>as</tt> must be non-null.</li>
* <li><tt>bs</tt> must be finite.</li>
* <li><tt>cs</tt> must be finite.</li>
* <li><tt>ds</tt> must be finite.</li>
* <li><tt>es</tt> must be finite.</li>
* <li><tt>fs</tt> must be finite.</li>
* <li>The result is the Cartesian product of six finite <tt>Iterable</tt>s.</li>
* </ul>
*
* Result length is |<tt>as</tt>||<tt>bs</tt>||<tt>cs</tt>||<tt>ds</tt>||<tt>es</tt>||<tt>fs</tt>|
*
* @param as the first <tt>Iterable</tt>
* @param bs the second <tt>Iterable</tt>
* @param cs the third <tt>Iterable</tt>
* @param ds the fourth <tt>Iterable</tt>
* @param es the fifth <tt>Iterable</tt>
* @param fs the sixth <tt>Iterable</tt>
* @param <A> the type of the first <tt>Iterable</tt>'s elements
* @param <B> the type of the second <tt>Iterable</tt>'s elements
* @param <C> the type of the third <tt>Iterable</tt>'s elements
* @param <D> the type of the fourth <tt>Iterable</tt>'s elements
* @param <E> the type of the fifth <tt>Iterable</tt>'s elements
* @param <F> the type of the sixth <tt>Iterable</tt>'s elements
* @return all ordered sextuples of elements from <tt>as</tt>, <tt>bs</tt>, <tt>cs</tt>, <tt>ds</tt>, <tt>es</tt>,
* and <tt>fs</tt>
*/
public static @NotNull <A, B, C, D, E, F> Iterable<Sextuple<A, B, C, D, E, F>> sextuplesAscending(
@NotNull Iterable<A> as,
@NotNull Iterable<B> bs,
@NotNull Iterable<C> cs,
@NotNull Iterable<D> ds,
@NotNull Iterable<E> es,
@NotNull Iterable<F> fs
) {
return map(
p -> new Sextuple<>(p.a.a, p.a.b, p.a.c, p.b.a, p.b.b, p.b.c),
pairsAscending(
(Iterable<Triple<A, B, C>>) triplesAscending(as, bs, cs),
(Iterable<Triple<D, E, F>>) triplesAscending(ds, es, fs)
)
);
}
/**
* Given seven <tt>Iterable</tt>s, returns all ordered septuples of elements from these <tt>Iterable</tt>s in
* ascending order. All <tt>Iterable</tt>s but the first must be finite; using long <tt>Iterable</tt>s in any
* position but the first is possible but discouraged.
*
* <ul>
* <li><tt>as</tt> must be non-null.</li>
* <li><tt>bs</tt> must be finite.</li>
* <li><tt>cs</tt> must be finite.</li>
* <li><tt>ds</tt> must be finite.</li>
* <li><tt>es</tt> must be finite.</li>
* <li><tt>fs</tt> must be finite.</li>
* <li><tt>gs</tt> must be finite.</li>
* <li>The result is the Cartesian product of seven finite <tt>Iterable</tt>s.</li>
* </ul>
*
* Result length is |<tt>as</tt>||<tt>bs</tt>||<tt>cs</tt>||<tt>ds</tt>||<tt>es</tt>||<tt>fs</tt>||<tt>gs</tt>
*
* @param as the first <tt>Iterable</tt>
* @param bs the second <tt>Iterable</tt>
* @param cs the third <tt>Iterable</tt>
* @param ds the fourth <tt>Iterable</tt>
* @param es the fifth <tt>Iterable</tt>
* @param fs the sixth <tt>Iterable</tt>
* @param gs the seventh <tt>Iterable</tt>
* @param <A> the type of the first <tt>Iterable</tt>'s elements
* @param <B> the type of the second <tt>Iterable</tt>'s elements
* @param <C> the type of the third <tt>Iterable</tt>'s elements
* @param <D> the type of the fourth <tt>Iterable</tt>'s elements
* @param <E> the type of the fifth <tt>Iterable</tt>'s elements
* @param <F> the type of the sixth <tt>Iterable</tt>'s elements
* @param <G> the type of the seventh <tt>Iterable</tt>'s elements
* @return all ordered septuples of elements from <tt>as</tt>, <tt>bs</tt>, <tt>cs</tt>, <tt>ds</tt>, <tt>es</tt>,
* <tt>fs</tt>, and <tt>gs</tt>
*/
public static @NotNull <A, B, C, D, E, F, G> Iterable<Septuple<A, B, C, D, E, F, G>> septuplesAscending(
@NotNull Iterable<A> as,
@NotNull Iterable<B> bs,
@NotNull Iterable<C> cs,
@NotNull Iterable<D> ds,
@NotNull Iterable<E> es,
@NotNull Iterable<F> fs,
@NotNull Iterable<G> gs
) {
return map(
p -> new Septuple<>(p.a.a, p.a.b, p.a.c, p.b.a, p.b.b, p.b.c, p.b.d),
pairsAscending(
(Iterable<Triple<A, B, C>>) triplesAscending(as, bs, cs),
(Iterable<Quadruple<D, E, F, G>>) quadruplesAscending(ds, es, fs, gs)
)
);
}
/**
* Returns an <tt>Iterable</tt> containing all lists of a given length with elements from a given
* <tt>Iterable</tt>. The lists are ordered lexicographically, matching the order given by the original
* <tt>Iterable</tt>. The <tt>Iterable</tt> must be finite; using a long <tt>Iterable</tt> is possible but
* discouraged.
*
* <ul>
* <li><tt>length</tt> must be non-negative.</li>
* <li><tt>xs</tt> must be finite.</li>
* <li>The result is finite. All of its elements have the same length. None are empty, unless the result consists
* entirely of one empty element.</li>
* </ul>
*
* Result length is |<tt>xs</tt>|<sup><tt>length</tt></sup>
*
* @param length the length of the result lists
* @param xs the <tt>Iterable</tt> from which elements are selected
* @param <T> the type of the given <tt>Iterable</tt>'s elements
* @return all lists of a given length created from <tt>xs</tt>
*/
public static @NotNull <T> Iterable<List<T>> listsAscending(int length, @NotNull Iterable<T> xs) {
if (length < 0)
throw new IllegalArgumentException("lists must have a non-negative length");
if (length == 0) {
return Arrays.asList(new ArrayList<T>());
}
Function<T, List<T>> makeSingleton = x -> {
List<T> list = new ArrayList<>();
list.add(x);
return list;
};
List<Iterable<List<T>>> intermediates = new ArrayList<>();
intermediates.add(map(makeSingleton, xs));
for (int i = 1; i < length; i++) {
Iterable<List<T>> lists = last(intermediates);
intermediates.add(concatMap(x -> map(list -> toList(cons(x, list)), lists), xs));
}
return last(intermediates);
}
/**
* Returns an <tt>Iterable</tt> containing all lists of a given length with elements from a given
* <tt>Iterable</tt>. The lists are ordered lexicographically, matching the order given by the original
* <tt>Iterable</tt>. The <tt>Iterable</tt> must be finite; using a long <tt>Iterable</tt> is possible but
* discouraged.
*
* <ul>
* <li><tt>length</tt> must be non-negative.</li>
* <li><tt>xs</tt> must be finite.</li>
* <li>The result is finite. All of its elements have the same length. None are empty, unless the result consists
* entirely of one empty element.</li>
* </ul>
*
* Result length is |<tt>xs</tt>|<sup><tt>length</tt></sup>
*
* @param length the length of the result lists
* @param xs the <tt>Iterable</tt> from which elements are selected
* @param <T> the type of the given <tt>Iterable</tt>'s elements
* @return all lists of a given length created from <tt>xs</tt>
*/
public static @NotNull <T> Iterable<List<T>> listsAscending(@NotNull BigInteger length, @NotNull Iterable<T> xs) {
if (lt(length, BigInteger.ZERO))
throw new IllegalArgumentException("lists must have a non-negative length");
if (eq(length, BigInteger.ZERO)) {
return Arrays.asList(new ArrayList<T>());
}
Function<T, List<T>> makeSingleton = x -> {
List<T> list = new ArrayList<>();
list.add(x);
return list;
};
List<Iterable<List<T>>> intermediates = new ArrayList<>();
intermediates.add(map(makeSingleton, xs));
for (BigInteger i = BigInteger.ONE; lt(i, length); i = i.add(BigInteger.ONE)) {
Iterable<List<T>> lists = last(intermediates);
intermediates.add(concatMap(x -> map(list -> toList((Iterable<T>) cons(x, list)), lists), xs));
}
return last(intermediates);
}
/**
* Returns an <tt>Iterable</tt> containing all <tt>String</tt>s of a given length with characters from a given
* <tt>Iterable</tt>. The <tt>String</tt>s are ordered lexicographically, matching the order given by the original
* <tt>Iterable</tt>. Using long <tt>String</tt> is possible but discouraged.
*
* <ul>
* <li><tt>length</tt> must be non-negative.</li>
* <li><tt>s</tt> is non-null.</li>
* <li>The result is finite. All of its <tt>String</tt>s have the same length. None are empty, unless the result
* consists entirely of one empty <tt>String</tt>.</li>
* </ul>
*
* Result length is |<tt>s</tt>|<sup><tt>length</tt></sup>
*
* @param length the length of the result <tt>String</tt>
* @param s the <tt>String</tt> from which characters are selected
* @return all Strings of a given length created from <tt>s</tt>
*/
public static @NotNull Iterable<String> stringsAscending(int length, @NotNull String s) {
if (length < 0)
throw new IllegalArgumentException("strings must have a non-negative length");
BigInteger totalLength = BigInteger.valueOf(s.length()).pow(length);
Function<BigInteger, String> f = bi -> charsToString(
map(
i -> s.charAt(i.intValue()),
BasicMath.bigEndianDigitsPadded(BigInteger.valueOf(length), BigInteger.valueOf(s.length()), bi)
)
);
return map(f, range(BigInteger.ZERO, totalLength.subtract(BigInteger.ONE)));
}
/**
* Returns an <tt>Iterable</tt> containing all <tt>String</tt>s of a given length with characters from a given
* <tt>Iterable</tt>. The <tt>String</tt>s are ordered lexicographically, matching the order given by the original
* <tt>Iterable</tt>. Using long <tt>String</tt> is possible but discouraged.
*
* <ul>
* <li><tt>length</tt> must be non-negative.</li>
* <li><tt>s</tt> is non-null.</li>
* <li>The result is finite. All of its <tt>String</tt>s have the same length. None are empty, unless the result
* consists entirely of one empty <tt>String</tt>.</li>
* </ul>
*
* Result length is |<tt>s</tt>|<sup><tt>length</tt></sup>
*
* @param length the length of the result <tt>String</tt>
* @param s the <tt>String</tt> from which characters are selected
* @return all Strings of a given length created from <tt>s</tt>
*/
public static @NotNull Iterable<String> stringsAscending(@NotNull BigInteger length, @NotNull String s) {
if (lt(length, BigInteger.ZERO))
throw new IllegalArgumentException("strings must have a non-negative length");
BigInteger totalLength = BigInteger.valueOf(s.length()).pow(length.intValue());
Function<BigInteger, String> f = bi -> charsToString(
map(
i -> s.charAt(i.intValue()),
BasicMath.bigEndianDigitsPadded(
BigInteger.valueOf(length.intValue()),
BigInteger.valueOf(s.length()),
bi
)
)
);
return map(f, range(BigInteger.ZERO, totalLength.subtract(BigInteger.ONE)));
}
/**
* Returns an <tt>Iterable</tt> containing all lists with elements from a given <tt>Iterable</tt>. The lists are in
* shortlex order; that is, shorter lists precede longer lists, and lists of the same length are ordered
* lexicographically, matching the order given by the original <tt>Iterable</tt>. The <tt>Iterable</tt> must be
* finite; using a long <tt>Iterable</tt> is possible but discouraged.
*
* <ul>
* <li><tt>xs</tt> must be finite.</li>
* <li>The result either consists of a single empty list, or is infinite. It is in shortlex order (according to
* some ordering of its elements) and contains every list of elements drawn from some sequence.</li>
* </ul>
*
* Result length is 1 if <tt>xs</tt> is empty, infinite otherwise
*
* @param xs the <tt>Iterable</tt> from which elements are selected
* @param <T> the type of the given <tt>Iterable</tt>'s elements
* @return all lists created from <tt>xs</tt>
*/
public static @NotNull <T> Iterable<List<T>> listsShortlex(@NotNull Iterable<T> xs) {
if (isEmpty(xs)) return Arrays.asList(new ArrayList<T>());
return concatMap(i -> listsAscending(i, xs), Exhaustive.NATURAL_BIG_INTEGERS);
}
/**
* Returns an <tt>Iterable</tt> containing all <tt>String</tt>s with characters from a given <tt>String</tt>. The
* <tt>String</tt>s are in shortlex order; that is, shorter <tt>String</tt>s precede longer <tt>String</tt>s, and
* <tt>String</tt>s of the same length are ordered lexicographically, matching the order given by the original
* <tt>String</tt>. Using a long <tt>String</tt> is possible but discouraged.
*
* <ul>
* <li><tt>s</tt> must be non-null.</li>
* <li>The result either consists of a single empty <tt>String</tt>, or is infinite. It is in shortlex order
* (according to some ordering of its characters) and contains every <tt>String</tt> with characters drawn from
* some sequence.</li>
* </ul>
*
* Result length is 1 if <tt>s</tt> is empty, infinite otherwise
*
* @param s the <tt>String</tt> from which characters are selected
* @return all <tt>String</tt>s created from <tt>s</tt>
*/
public static @NotNull Iterable<String> stringsShortlex(@NotNull String s) {
if (isEmpty(s)) return Arrays.asList("");
return concatMap(i -> stringsAscending(i, s), Exhaustive.NATURAL_BIG_INTEGERS);
}
/**
* Returns all pairs of elements taken from two <tt>Iterable</tt>s in such a way that the first component grows
* linearly but the second grows logarithmically (hence the name).
*
* <ul>
* <li><tt>xs</tt> is non-null.</li>
* <li>The result is an <tt>Iterable</tt> containing all pairs of elements taken from some <tt>Iterable</tt>.
* The ordering of these elements is determined by mapping the sequence 0, 1, 2, ... by
* <tt>BasicMath.logarithmicDemux</tt> and interpreting the resulting pairs as indices into the original
* <tt>Iterable</tt>.</li>
* </ul>
*
* Result length is |<tt>xs</tt>|<sup>2</sup>
*
* @param xs the <tt>Iterable</tt> from which elements are selected
* @param <T> the type of the given <tt>Iterable</tt>'s elements
* @return all pairs of elements from <tt>xs</tt> in logarithmic order
*/
public static @NotNull <T> Iterable<Pair<T, T>> pairsLogarithmicOrder(@NotNull Iterable<T> xs) {
if (isEmpty(xs)) return new ArrayList<>();
CachedIterable<T> ii = new CachedIterable<>(xs);
Function<BigInteger, Optional<Pair<T, T>>> f = bi -> {
Pair<BigInteger, BigInteger> p = BasicMath.logarithmicDemux(bi);
assert p.a != null;
NullableOptional<T> optA = ii.get(p.a.intValue());
if (!optA.isPresent()) return Optional.empty();
assert p.b != null;
NullableOptional<T> optB = ii.get(p.b.intValue());
if (!optB.isPresent()) return Optional.empty();
return Optional.of(new Pair<T, T>(optA.get(), optB.get()));
};
Predicate<Optional<Pair<T, T>>> lastPair = o -> {
if (!o.isPresent()) return false;
Pair<T, T> p = o.get();
Optional<Boolean> lastA = ii.isLast(p.a);
Optional<Boolean> lastB = ii.isLast(p.b);
return lastA.isPresent() && lastB.isPresent() && lastA.get() && lastB.get();
};
return map(
Optional::get,
filter(
Optional<Pair<T, T>>::isPresent,
stopAt(
lastPair,
(Iterable<Optional<Pair<T, T>>>)
map(bi -> f.apply(bi), Exhaustive.NATURAL_BIG_INTEGERS)
)
)
);
}
//todo
private static @NotNull <A, B> Iterable<Pair<A, B>> pairsByFunction(
@NotNull Function<BigInteger, Pair<BigInteger, BigInteger>> unpairingFunction,
@NotNull Iterable<A> as,
@NotNull Iterable<B> bs
) {
if (isEmpty(as) || isEmpty(bs)) return new ArrayList<>();
CachedIterable<A> aii = new CachedIterable<>(as);
CachedIterable<B> bii = new CachedIterable<>(bs);
Function<BigInteger, Optional<Pair<A, B>>> f = bi -> {
Pair<BigInteger, BigInteger> p = unpairingFunction.apply(bi);
assert p.a != null;
NullableOptional<A> optA = aii.get(p.a.intValue());
if (!optA.isPresent()) return Optional.empty();
assert p.b != null;
NullableOptional<B> optB = bii.get(p.b.intValue());
if (!optB.isPresent()) return Optional.empty();
return Optional.of(new Pair<A, B>(optA.get(), optB.get()));
};
Predicate<Optional<Pair<A, B>>> lastPair = o -> {
if (!o.isPresent()) return false;
Pair<A, B> p = o.get();
Optional<Boolean> lastA = aii.isLast(p.a);
Optional<Boolean> lastB = bii.isLast(p.b);
return lastA.isPresent() && lastB.isPresent() && lastA.get() && lastB.get();
};
return map(
Optional::get,
filter(
Optional<Pair<A, B>>::isPresent,
stopAt(
lastPair,
(Iterable<Optional<Pair<A, B>>>)
map(bi -> f.apply(bi), Exhaustive.NATURAL_BIG_INTEGERS)
)
)
);
}
/**
* Returns all pairs of elements taken from two <tt>Iterable</tt>s in such a way that the first component grows
* linearly but the second grows logarithmically.
*
* <ul>
* <li><tt>as</tt> is non-null.</li>
* <li><tt>bs</tt> is non-null.</li>
* <li>The result is an <tt>Iterable</tt> containing all pairs of elements taken from two <tt>Iterable</tt>s.
* The ordering of these elements is determined by mapping the sequence 0, 1, 2, ... by
* <tt>BasicMath.logarithmicDemux</tt> and interpreting the resulting pairs as indices into the original
* <tt>Iterable</tt>s.</li>
* </ul>
*
* Result length is |<tt>as</tt>||<tt>bs</tt>|
*
* @param as the <tt>Iterable</tt> from which the first components of the pairs are selected
* @param bs the <tt>Iterable</tt> from which the second components of the pairs are selected
* @param <A> the type of the first <tt>Iterable</tt>'s elements
* @param <B> the type of the second <tt>Iterable</tt>'s elements
* @return all pairs of elements from <tt>as</tt> and <tt>bs</tt> in logarithmic order
*/
public static @NotNull <A, B> Iterable<Pair<A, B>> pairsLogarithmicOrder(
@NotNull Iterable<A> as,
@NotNull Iterable<B> bs
) {
return pairsByFunction(BasicMath::logarithmicDemux, as, bs);
}
/**
* Returns all pairs of elements taken from two <tt>Iterable</tt>s in such a way that both components grow as the
* square root of the number of pairs iterated.
*
* <ul>
* <li><tt>as</tt> is non-null.</li>
* <li><tt>bs</tt> is non-null.</li>
* <li>The result is an <tt>Iterable</tt> containing all pairs of elements taken from two <tt>Iterable</tt>s.
* The elements are ordered by following a Z-curve through the pair space. The curve is computed by
* un-interleaving bits of successive integers.</li>
* </ul>
*
* Result length is |<tt>as</tt>||<tt>bs</tt>|
*
* @param as the <tt>Iterable</tt> from which the first components of the pairs are selected
* @param bs the <tt>Iterable</tt> from which the second components of the pairs are selected
* @param <A> the type of the first <tt>Iterable</tt>'s elements
* @param <B> the type of the second <tt>Iterable</tt>'s elements
* @return all pairs of elements from <tt>as</tt> and <tt>bs</tt>
*/
public static @NotNull <A, B> Iterable<Pair<A, B>> pairs(@NotNull Iterable<A> as, @NotNull Iterable<B> bs) {
return pairsByFunction(
bi -> {
List<BigInteger> list = BasicMath.demux(2, bi);
return new Pair<>(list.get(0), list.get(1));
},
as,
bs
);
}
/**
* Returns all triples of elements taken from three <tt>Iterable</tt>s in such a way that all components grow as
* the cube root of the number of triples iterated.
*
* <ul>
* <li><tt>as</tt> is non-null.</li>
* <li><tt>bs</tt> is non-null.</li>
* <li><tt>cs</tt> is non-null.</li>
* <li>The result is an <tt>Iterable</tt> containing all triples of elements taken from three <tt>Iterable</tt>s.
* The elements are ordered by following a Z-curve through the triple space. The curve is computed by
* un-interleaving bits of successive integers.</li>
* </ul>
*
* Result length is |<tt>as</tt>||<tt>bs</tt>||<tt>cs</tt>|
*
* @param as the <tt>Iterable</tt> from which the first components of the triples are selected
* @param bs the <tt>Iterable</tt> from which the second components of the triples are selected
* @param cs the <tt>Iterable</tt> from which the third components of the triples are selected
* @param <A> the type of the first <tt>Iterable</tt>'s elements
* @param <B> the type of the second <tt>Iterable</tt>'s elements
* @param <C> the type of the third <tt>Iterable</tt>'s elements
* @return all triples of elements from <tt>as</tt>, <tt>bs</tt>, and <tt>cs</tt>
*/
public static @NotNull <A, B, C> Iterable<Triple<A, B, C>> triples(
@NotNull Iterable<A> as,
@NotNull Iterable<B> bs,
@NotNull Iterable<C> cs
) {
if (isEmpty(as) || isEmpty(bs) || isEmpty(cs)) return new ArrayList<>();
CachedIterable<A> aii = new CachedIterable<>(as);
CachedIterable<B> bii = new CachedIterable<>(bs);
CachedIterable<C> cii = new CachedIterable<>(cs);
Function<BigInteger, Optional<Triple<A, B, C>>> f = bi -> {
List<BigInteger> p = BasicMath.demux(3, bi);
assert p.get(0) != null;
NullableOptional<A> optA = aii.get(p.get(0).intValue());
if (!optA.isPresent()) return Optional.empty();
assert p.get(1) != null;
NullableOptional<B> optB = bii.get(p.get(1).intValue());
if (!optB.isPresent()) return Optional.empty();
assert p.get(2) != null;
NullableOptional<C> optC = cii.get(p.get(2).intValue());
if (!optC.isPresent()) return Optional.empty();
return Optional.of(new Triple<A, B, C>(optA.get(), optB.get(), optC.get()));
};
Predicate<Optional<Triple<A, B, C>>> lastTriple = o -> {
if (!o.isPresent()) return false;
Triple<A, B, C> p = o.get();
Optional<Boolean> lastA = aii.isLast(p.a);
Optional<Boolean> lastB = bii.isLast(p.b);
Optional<Boolean> lastC = cii.isLast(p.c);
return lastA.isPresent() &&
lastB.isPresent() &&
lastC.isPresent() &&
lastA.get() &&
lastB.get() &&
lastC.get();
};
return map(
Optional::get,
filter(
Optional<Triple<A, B, C>>::isPresent,
stopAt(
lastTriple,
(Iterable<Optional<Triple<A, B, C>>>)
map(bi -> f.apply(bi), Exhaustive.NATURAL_BIG_INTEGERS)
)
)
);
}
/**
* Returns all quadruples of elements taken from four <tt>Iterable</tt>s in such a way that all components grow as
* the fourth root of the number of quadruples iterated.
*
* <ul>
* <li><tt>as</tt> is non-null.</li>
* <li><tt>bs</tt> is non-null.</li>
* <li><tt>cs</tt> is non-null.</li>
* <li><tt>ds</tt> is non-null.</li>
* <li>The result is an <tt>Iterable</tt> containing all quadruples of elements taken from four
* <tt>Iterable</tt>s. The elements are ordered by following a Z-curve through the quadruple space. The curve is
* computed by un-interleaving bits of successive integers.</li>
* </ul>
*
* Result length is |<tt>as</tt>||<tt>bs</tt>||<tt>cs</tt>||<tt>ds</tt>|
*
* @param as the <tt>Iterable</tt> from which the first components of the quadruples are selected
* @param bs the <tt>Iterable</tt> from which the second components of the quadruples are selected
* @param cs the <tt>Iterable</tt> from which the third components of the quadruples are selected
* @param ds the <tt>Iterable</tt> from which the fourth components of the quadruples are selected
* @param <A> the type of the first <tt>Iterable</tt>'s elements
* @param <B> the type of the second <tt>Iterable</tt>'s elements
* @param <C> the type of the third <tt>Iterable</tt>'s elements
* @param <D> the type of the fourth <tt>Iterable</tt>'s elements
* @return all quadruples of elements from <tt>as</tt>, <tt>bs</tt>, <tt>cs</tt>, and <tt>ds</tt>
*/
public static @NotNull <A, B, C, D> Iterable<Quadruple<A, B, C, D>> quadruples(
@NotNull Iterable<A> as,
@NotNull Iterable<B> bs,
@NotNull Iterable<C> cs,
@NotNull Iterable<D> ds
) {
if (isEmpty(as) || isEmpty(bs) || isEmpty(cs) || isEmpty(ds)) return new ArrayList<>();
CachedIterable<A> aii = new CachedIterable<>(as);
CachedIterable<B> bii = new CachedIterable<>(bs);
CachedIterable<C> cii = new CachedIterable<>(cs);
CachedIterable<D> dii = new CachedIterable<>(ds);
Function<BigInteger, Optional<Quadruple<A, B, C, D>>> f = bi -> {
List<BigInteger> p = BasicMath.demux(4, bi);
assert p.get(0) != null;
NullableOptional<A> optA = aii.get(p.get(0).intValue());
if (!optA.isPresent()) return Optional.empty();
assert p.get(1) != null;
NullableOptional<B> optB = bii.get(p.get(1).intValue());
if (!optB.isPresent()) return Optional.empty();
assert p.get(2) != null;
NullableOptional<C> optC = cii.get(p.get(2).intValue());
if (!optC.isPresent()) return Optional.empty();
assert p.get(3) != null;
NullableOptional<D> optD = dii.get(p.get(3).intValue());
if (!optD.isPresent()) return Optional.empty();
return Optional.of(new Quadruple<A, B, C, D>(optA.get(), optB.get(), optC.get(), optD.get()));
};
Predicate<Optional<Quadruple<A, B, C, D>>> lastQuadruple = o -> {
if (!o.isPresent()) return false;
Quadruple<A, B, C, D> p = o.get();
Optional<Boolean> lastA = aii.isLast(p.a);
Optional<Boolean> lastB = bii.isLast(p.b);
Optional<Boolean> lastC = cii.isLast(p.c);
Optional<Boolean> lastD = dii.isLast(p.d);
return lastA.isPresent() &&
lastB.isPresent() &&
lastC.isPresent() &&
lastD.isPresent() &&
lastA.get() &&
lastB.get() &&
lastC.get() &&
lastD.get();
};
return map(
Optional::get,
filter(
Optional<Quadruple<A, B, C, D>>::isPresent,
stopAt(
lastQuadruple,
(Iterable<Optional<Quadruple<A, B, C, D>>>)
map(bi -> f.apply(bi), Exhaustive.NATURAL_BIG_INTEGERS)
)
)
);
}
/**
* Returns all quintuples of elements taken from five <tt>Iterable</tt>s in such a way that all components grow as
* the fifth root of the number of quintuples iterated.
*
* <ul>
* <li><tt>as</tt> is non-null.</li>
* <li><tt>bs</tt> is non-null.</li>
* <li><tt>cs</tt> is non-null.</li>
* <li><tt>ds</tt> is non-null.</li>
* <li><tt>es</tt> is non-null.</li>
* <li>The result is an <tt>Iterable</tt> containing all quintuples of elements taken from five
* <tt>Iterable</tt>s. The elements are ordered by following a Z-curve through the quintuple space. The curve is
* computed by un-interleaving bits of successive integers.</li>
* </ul>
*
* Result length is |<tt>as</tt>||<tt>bs</tt>||<tt>cs</tt>||<tt>ds</tt>||<tt>es</tt>|
*
* @param as the <tt>Iterable</tt> from which the first components of the quintuples are selected
* @param bs the <tt>Iterable</tt> from which the second components of the quintuples are selected
* @param cs the <tt>Iterable</tt> from which the third components of the quintuples are selected
* @param ds the <tt>Iterable</tt> from which the fourth components of the quintuples are selected
* @param es the <tt>Iterable</tt> from which the fifth components of the quintuples are selected
* @param <A> the type of the first <tt>Iterable</tt>'s elements
* @param <B> the type of the second <tt>Iterable</tt>'s elements
* @param <C> the type of the third <tt>Iterable</tt>'s elements
* @param <D> the type of the fourth <tt>Iterable</tt>'s elements
* @param <E> the type of the fifth <tt>Iterable</tt>'s elements
* @return all quintuples of elements from <tt>as</tt>, <tt>bs</tt>, <tt>cs</tt>, <tt>ds</tt>, and <tt>es</tt>
*/
public static @NotNull <A, B, C, D, E> Iterable<Quintuple<A, B, C, D, E>> quintuples(
@NotNull Iterable<A> as,
@NotNull Iterable<B> bs,
@NotNull Iterable<C> cs,
@NotNull Iterable<D> ds,
@NotNull Iterable<E> es
) {
if (isEmpty(as) || isEmpty(bs) || isEmpty(cs) || isEmpty(ds) || isEmpty(es)) return new ArrayList<>();
CachedIterable<A> aii = new CachedIterable<>(as);
CachedIterable<B> bii = new CachedIterable<>(bs);
CachedIterable<C> cii = new CachedIterable<>(cs);
CachedIterable<D> dii = new CachedIterable<>(ds);
CachedIterable<E> eii = new CachedIterable<>(es);
Function<BigInteger, Optional<Quintuple<A, B, C, D, E>>> f = bi -> {
List<BigInteger> p = BasicMath.demux(5, bi);
assert p.get(0) != null;
NullableOptional<A> optA = aii.get(p.get(0).intValue());
if (!optA.isPresent()) return Optional.empty();
assert p.get(1) != null;
NullableOptional<B> optB = bii.get(p.get(1).intValue());
if (!optB.isPresent()) return Optional.empty();
assert p.get(2) != null;
NullableOptional<C> optC = cii.get(p.get(2).intValue());
if (!optC.isPresent()) return Optional.empty();
assert p.get(3) != null;
NullableOptional<D> optD = dii.get(p.get(3).intValue());
if (!optD.isPresent()) return Optional.empty();
assert p.get(4) != null;
NullableOptional<E> optE = eii.get(p.get(4).intValue());
if (!optE.isPresent()) return Optional.empty();
return Optional.of(new Quintuple<A, B, C, D, E>(
optA.get(),
optB.get(),
optC.get(),
optD.get(),
optE.get()
));
};
Predicate<Optional<Quintuple<A, B, C, D, E>>> lastQuintuple = o -> {
if (!o.isPresent()) return false;
Quintuple<A, B, C, D, E> p = o.get();
Optional<Boolean> lastA = aii.isLast(p.a);
Optional<Boolean> lastB = bii.isLast(p.b);
Optional<Boolean> lastC = cii.isLast(p.c);
Optional<Boolean> lastD = dii.isLast(p.d);
Optional<Boolean> lastE = eii.isLast(p.e);
return lastA.isPresent() &&
lastB.isPresent() &&
lastC.isPresent() &&
lastD.isPresent() &&
lastE.isPresent() &&
lastA.get() &&
lastB.get() &&
lastC.get() &&
lastD.get() &&
lastE.get();
};
return map(
Optional::get,
filter(
Optional<Quintuple<A, B, C, D, E>>::isPresent,
stopAt(
lastQuintuple,
(Iterable<Optional<Quintuple<A, B, C, D, E>>>)
map(bi -> f.apply(bi), Exhaustive.NATURAL_BIG_INTEGERS)
)
)
);
}
/**
* Returns all sextuples of elements taken from six <tt>Iterable</tt>s in such a way that all components grow as
* the sixth root of the number of sextuples iterated.
*
* <ul>
* <li><tt>as</tt> is non-null.</li>
* <li><tt>bs</tt> is non-null.</li>
* <li><tt>cs</tt> is non-null.</li>
* <li><tt>ds</tt> is non-null.</li>
* <li><tt>es</tt> is non-null.</li>
* <li><tt>fs</tt> is non-null.</li>
* <li>The result is an <tt>Iterable</tt> containing all sextuples of elements taken from six <tt>Iterable</tt>s.
* The elements are ordered by following a Z-curve through the sextuple space. The curve is computed by
* un-interleaving bits of successive integers.</li>
* </ul>
*
* Result length is |<tt>as</tt>||<tt>bs</tt>||<tt>cs</tt>||<tt>ds</tt>||<tt>es</tt>||<tt>fs</tt>|
*
* @param as the <tt>Iterable</tt> from which the first components of the sextuples are selected
* @param bs the <tt>Iterable</tt> from which the second components of the sextuples are selected
* @param cs the <tt>Iterable</tt> from which the third components of the sextuples are selected
* @param ds the <tt>Iterable</tt> from which the fourth components of the sextuples are selected
* @param es the <tt>Iterable</tt> from which the fifth components of the sextuples are selected
* @param fs the <tt>Iterable</tt> from which the sixth components of the sextuples are selected
* @param <A> the type of the first <tt>Iterable</tt>'s elements
* @param <B> the type of the second <tt>Iterable</tt>'s elements
* @param <C> the type of the third <tt>Iterable</tt>'s elements
* @param <D> the type of the fourth <tt>Iterable</tt>'s elements
* @param <E> the type of the fifth <tt>Iterable</tt>'s elements
* @param <F> the type of the sixth <tt>Iterable</tt>'s elements
* @return all sextuples of elements from <tt>as</tt>, <tt>bs</tt>, <tt>cs</tt>, <tt>ds</tt>, <tt>es</tt>, and
* <tt>fs</tt>
*/
public static @NotNull <A, B, C, D, E, F> Iterable<Sextuple<A, B, C, D, E, F>> sextuples(
@NotNull Iterable<A> as,
@NotNull Iterable<B> bs,
@NotNull Iterable<C> cs,
@NotNull Iterable<D> ds,
@NotNull Iterable<E> es,
@NotNull Iterable<F> fs
) {
if (
isEmpty(as) ||
isEmpty(bs) ||
isEmpty(cs) ||
isEmpty(ds) ||
isEmpty(es) ||
isEmpty(fs)
) return new ArrayList<>();
CachedIterable<A> aii = new CachedIterable<>(as);
CachedIterable<B> bii = new CachedIterable<>(bs);
CachedIterable<C> cii = new CachedIterable<>(cs);
CachedIterable<D> dii = new CachedIterable<>(ds);
CachedIterable<E> eii = new CachedIterable<>(es);
CachedIterable<F> fii = new CachedIterable<>(fs);
Function<BigInteger, Optional<Sextuple<A, B, C, D, E, F>>> f = bi -> {
List<BigInteger> p = BasicMath.demux(6, bi);
assert p.get(0) != null;
NullableOptional<A> optA = aii.get(p.get(0).intValue());
if (!optA.isPresent()) return Optional.empty();
assert p.get(1) != null;
NullableOptional<B> optB = bii.get(p.get(1).intValue());
if (!optB.isPresent()) return Optional.empty();
assert p.get(2) != null;
NullableOptional<C> optC = cii.get(p.get(2).intValue());
if (!optC.isPresent()) return Optional.empty();
assert p.get(3) != null;
NullableOptional<D> optD = dii.get(p.get(3).intValue());
if (!optD.isPresent()) return Optional.empty();
assert p.get(4) != null;
NullableOptional<E> optE = eii.get(p.get(4).intValue());
if (!optE.isPresent()) return Optional.empty();
assert p.get(5) != null;
NullableOptional<F> optF = fii.get(p.get(5).intValue());
if (!optF.isPresent()) return Optional.empty();
return Optional.of(new Sextuple<A, B, C, D, E, F>(
optA.get(),
optB.get(),
optC.get(),
optD.get(),
optE.get(),
optF.get()
));
};
Predicate<Optional<Sextuple<A, B, C, D, E, F>>> lastSextuple = o -> {
if (!o.isPresent()) return false;
Sextuple<A, B, C, D, E, F> p = o.get();
Optional<Boolean> lastA = aii.isLast(p.a);
Optional<Boolean> lastB = bii.isLast(p.b);
Optional<Boolean> lastC = cii.isLast(p.c);
Optional<Boolean> lastD = dii.isLast(p.d);
Optional<Boolean> lastE = eii.isLast(p.e);
Optional<Boolean> lastF = fii.isLast(p.f);
return lastA.isPresent() &&
lastB.isPresent() &&
lastC.isPresent() &&
lastD.isPresent() &&
lastE.isPresent() &&
lastF.isPresent() &&
lastA.get() &&
lastB.get() &&
lastC.get() &&
lastD.get() &&
lastE.get() &&
lastF.get();
};
return map(
Optional::get,
filter(
Optional<Sextuple<A, B, C, D, E, F>>::isPresent,
stopAt(
lastSextuple,
(Iterable<Optional<Sextuple<A, B, C, D, E, F>>>)
map(bi -> f.apply(bi), Exhaustive.NATURAL_BIG_INTEGERS)
)
)
);
}
/**
* Returns all septuples of elements taken from seven <tt>Iterable</tt>s in such a way that all components grow as
* the seventh root of the number of septuples iterated.
*
* <ul>
* <li><tt>as</tt> is non-null.</li>
* <li><tt>bs</tt> is non-null.</li>
* <li><tt>cs</tt> is non-null.</li>
* <li><tt>ds</tt> is non-null.</li>
* <li><tt>es</tt> is non-null.</li>
* <li><tt>fs</tt> is non-null.</li>
* <li><tt>gs</tt> is non-null.</li>
* <li>The result is an <tt>Iterable</tt> containing all septuples of elements taken from seven
* <tt>Iterable</tt>s. The elements are ordered by following a Z-curve through the septuple space. The curve is
* computed by un-interleaving bits of successive integers.</li>
* </ul>
*
* Result length is |<tt>as</tt>||<tt>bs</tt>||<tt>cs</tt>||<tt>ds</tt>||<tt>es</tt>||<tt>fs</tt>||<tt>gs</tt>|
*
* @param as the <tt>Iterable</tt> from which the first components of the septuples are selected
* @param bs the <tt>Iterable</tt> from which the second components of the septuples are selected
* @param cs the <tt>Iterable</tt> from which the third components of the septuples are selected
* @param ds the <tt>Iterable</tt> from which the fourth components of the septuples are selected
* @param es the <tt>Iterable</tt> from which the fifth components of the septuples are selected
* @param fs the <tt>Iterable</tt> from which the sixth components of the septuples are selected
* @param gs the <tt>Iterable</tt> from which the seventh components of the septuples are selected
* @param <A> the type of the first <tt>Iterable</tt>'s elements
* @param <B> the type of the second <tt>Iterable</tt>'s elements
* @param <C> the type of the third <tt>Iterable</tt>'s elements
* @param <D> the type of the fourth <tt>Iterable</tt>'s elements
* @param <E> the type of the fifth <tt>Iterable</tt>'s elements
* @param <F> the type of the sixth <tt>Iterable</tt>'s elements
* @param <G> the type of the seventh <tt>Iterable</tt>'s elements
* @return all septuples of elements from <tt>as</tt>, <tt>bs</tt>, <tt>cs</tt>, <tt>ds</tt>, <tt>es</tt>,
* <tt>fs</tt>, and <tt>gs</tt>
*/
public static @NotNull <A, B, C, D, E, F, G> Iterable<Septuple<A, B, C, D, E, F, G>> septuples(
@NotNull Iterable<A> as,
@NotNull Iterable<B> bs,
@NotNull Iterable<C> cs,
@NotNull Iterable<D> ds,
@NotNull Iterable<E> es,
@NotNull Iterable<F> fs,
@NotNull Iterable<G> gs
) {
if (
isEmpty(as) ||
isEmpty(bs) ||
isEmpty(cs) ||
isEmpty(ds) ||
isEmpty(es) ||
isEmpty(fs) ||
isEmpty(gs)
) return new ArrayList<>();
CachedIterable<A> aii = new CachedIterable<>(as);
CachedIterable<B> bii = new CachedIterable<>(bs);
CachedIterable<C> cii = new CachedIterable<>(cs);
CachedIterable<D> dii = new CachedIterable<>(ds);
CachedIterable<E> eii = new CachedIterable<>(es);
CachedIterable<F> fii = new CachedIterable<>(fs);
CachedIterable<G> gii = new CachedIterable<>(gs);
Function<BigInteger, Optional<Septuple<A, B, C, D, E, F, G>>> f = bi -> {
List<BigInteger> p = BasicMath.demux(7, bi);
assert p.get(0) != null;
NullableOptional<A> optA = aii.get(p.get(0).intValue());
if (!optA.isPresent()) return Optional.empty();
assert p.get(1) != null;
NullableOptional<B> optB = bii.get(p.get(1).intValue());
if (!optB.isPresent()) return Optional.empty();
assert p.get(2) != null;
NullableOptional<C> optC = cii.get(p.get(2).intValue());
if (!optC.isPresent()) return Optional.empty();
assert p.get(3) != null;
NullableOptional<D> optD = dii.get(p.get(3).intValue());
if (!optD.isPresent()) return Optional.empty();
assert p.get(4) != null;
NullableOptional<E> optE = eii.get(p.get(4).intValue());
if (!optE.isPresent()) return Optional.empty();
assert p.get(5) != null;
NullableOptional<F> optF = fii.get(p.get(5).intValue());
if (!optF.isPresent()) return Optional.empty();
assert p.get(6) != null;
NullableOptional<G> optG = gii.get(p.get(6).intValue());
if (!optG.isPresent()) return Optional.empty();
return Optional.of(new Septuple<A, B, C, D, E, F, G>(
optA.get(),
optB.get(),
optC.get(),
optD.get(),
optE.get(),
optF.get(),
optG.get()
));
};
Predicate<Optional<Septuple<A, B, C, D, E, F, G>>> lastSeptuple = o -> {
if (!o.isPresent()) return false;
Septuple<A, B, C, D, E, F, G> p = o.get();
Optional<Boolean> lastA = aii.isLast(p.a);
Optional<Boolean> lastB = bii.isLast(p.b);
Optional<Boolean> lastC = cii.isLast(p.c);
Optional<Boolean> lastD = dii.isLast(p.d);
Optional<Boolean> lastE = eii.isLast(p.e);
Optional<Boolean> lastF = fii.isLast(p.f);
Optional<Boolean> lastG = gii.isLast(p.g);
return lastA.isPresent() &&
lastB.isPresent() &&
lastC.isPresent() &&
lastD.isPresent() &&
lastE.isPresent() &&
lastF.isPresent() &&
lastG.isPresent() &&
lastA.get() &&
lastB.get() &&
lastC.get() &&
lastD.get() &&
lastE.get() &&
lastF.get() &&
lastG.get();
};
return map(
Optional::get,
filter(
Optional<Septuple<A, B, C, D, E, F, G>>::isPresent,
stopAt(
lastSeptuple,
(Iterable<Optional<Septuple<A, B, C, D, E, F, G>>>)
map(bi -> f.apply(bi), Exhaustive.NATURAL_BIG_INTEGERS)
)
)
);
}
public static <T> Iterable<List<T>> lists(int size, Iterable<T> xs) {
if (size == 0) {
return Arrays.asList(new ArrayList<T>());
}
CachedIterable<T> ii = new CachedIterable<>(xs);
Function<BigInteger, Optional<List<T>>> f = bi -> ii.get(map(BigInteger::intValue, BasicMath.demux(size, bi)));
return map(
Optional::get,
filter(
Optional<List<T>>::isPresent,
(Iterable<Optional<List<T>>>) map(bi -> f.apply(bi), Exhaustive.NATURAL_BIG_INTEGERS)
)
);
}
public static <T> Iterable<List<T>> lists(Iterable<T> xs) {
CachedIterable<T> ii = new CachedIterable<>(xs);
Function<BigInteger, Optional<List<T>>> f = bi -> {
if (bi.equals(BigInteger.ZERO)) {
return Optional.of(new ArrayList<T>());
}
bi = bi.subtract(BigInteger.ONE);
Pair<BigInteger, BigInteger> sizeIndex = BasicMath.logarithmicDemux(bi);
int size = sizeIndex.b.intValue() + 1;
return ii.get(map(BigInteger::intValue, BasicMath.demux(size, sizeIndex.a)));
};
return map(
Optional::get,
filter(
Optional<List<T>>::isPresent,
(Iterable<Optional<List<T>>>) map(bi -> f.apply(bi), Exhaustive.NATURAL_BIG_INTEGERS)
)
);
}
public static <T> Iterable<List<T>> orderedSubsequences(Iterable<T> xs) {
if (isEmpty(xs))
return Arrays.asList(new ArrayList<T>());
final CachedIterable<T> ii = new CachedIterable(xs);
return () -> new Iterator<List<T>>() {
private List<Integer> indices = new ArrayList<>();
@Override
public boolean hasNext() {
return indices != null;
}
@Override
public List<T> next() {
List<T> subsequence = ii.get(indices).get();
if (indices.isEmpty()) {
indices.add(0);
} else {
int lastIndex = last(indices);
if (lastIndex < ii.size() - 1) {
indices.add(lastIndex + 1);
} else if (indices.size() == 1) {
indices = null;
} else {
indices.remove(indices.size() - 1);
indices.set(indices.size() - 1, last(indices) + 1);
}
}
return subsequence;
}
};
}
} |
// $Id: Getdown.java,v 1.15 2004/07/20 01:27:32 mdb Exp $
package com.threerings.getdown.launcher;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
// import org.apache.commons.io.TeeOutputStream;
import com.samskivert.swing.util.SwingUtil;
import com.samskivert.text.MessageUtil;
import com.samskivert.util.StringUtil;
import com.threerings.getdown.Log;
import com.threerings.getdown.data.Application;
import com.threerings.getdown.data.Resource;
import com.threerings.getdown.tools.Patcher;
import com.threerings.getdown.util.ProgressObserver;
/**
* Manages the main control for the Getdown application updater and
* deployment system.
*/
public class Getdown extends Thread
implements Application.StatusDisplay
{
public Getdown (File appDir)
{
super("Getdown");
_app = new Application(appDir);
_msgs = ResourceBundle.getBundle("com.threerings.getdown.messages");
}
public void run ()
{
try {
// first parses our application deployment file
try {
_ifc = _app.init();
} catch (IOException ioe) {
Log.warning("Failed to parse 'getdown.txt': " + ioe);
_app.attemptRecovery();
_ifc = _app.init();
}
for (int ii = 0; ii < MAX_LOOPS; ii++) {
// make sure we have the desired version and that the
// metadata files are valid...
setStatus("m.validating", -1, -1L, false);
if (_app.verifyMetadata(this)) {
Log.info("Application requires update.");
update();
// loop back again and reverify the metadata
continue;
}
// now verify our resources...
setStatus("m.validating", -1, -1L, false);
List failures = _app.verifyResources(_progobs);
if (failures == null) {
Log.info("Resources verified.");
launch();
return;
}
// redownload any that are corrupt or invalid...
Log.info(failures.size() + " rsrcs require update.");
download(failures);
// now we'll loop back and try it all again
}
Log.warning("Pants! We couldn't get the job done.");
throw new IOException("m.unable_to_repair");
} catch (Exception e) {
Log.logStackTrace(e);
String msg = e.getMessage();
if (msg == null) {
msg = "m.unknown_error";
} else if (!msg.startsWith("m.")) {
// try to do something sensible based on the type of error
if (e instanceof FileNotFoundException) {
msg = MessageUtil.tcompose("m.missing_resource", msg);
} else {
msg = MessageUtil.tcompose("m.init_error", msg);
}
}
updateStatus(msg);
}
}
// documentation inherited from interface
public void updateStatus (String message)
{
setStatus(message, -1, -1L, true);
}
/**
* Called if the application is determined to be of an old version.
*/
protected void update ()
throws IOException
{
// first clear all validation markers
_app.clearValidationMarkers();
// attempt to download the patch file
final Resource patch = _app.getPatchResource();
if (patch != null) {
// download the patch file...
ArrayList list = new ArrayList();
list.add(patch);
download(list);
// and apply it...
updateStatus("m.patching");
Patcher patcher = new Patcher();
patcher.patch(patch.getLocal().getParentFile(),
patch.getLocal(), _progobs);
// lastly clean up the patch file
if (!patch.getLocal().delete()) {
Log.warning("Failed to delete '" + patch + "'.");
}
}
// if the patch resource is null, that means something was booched
// in the application, so we skip the patching process but update
// the metadata which will result in a "brute force" upgrade
// finally update our metadata files...
_app.updateMetadata();
// ...and reinitialize the application
_ifc = _app.init();
}
/**
* Called if the application is determined to require resource
* downloads.
*/
protected void download (List resources)
{
final Object lock = new Object();
// create our user interface
createInterface();
// create a downloader to download our resources
Downloader.Observer obs = new Downloader.Observer() {
public void resolvingDownloads () {
updateStatus("m.resolving");
}
public void downloadProgress (int percent, long remaining) {
setStatus("m.downloading", percent, remaining, true);
if (percent == 100) {
synchronized (lock) {
lock.notify();
}
}
}
public void downloadFailed (Resource rsrc, Exception e) {
updateStatus(
MessageUtil.tcompose("m.failure", e.getMessage()));
Log.warning("Download failed [rsrc=" + rsrc + "].");
Log.logStackTrace(e);
synchronized (lock) {
lock.notify();
}
}
};
Downloader dl = new Downloader(resources, obs);
dl.start();
// now wait for it to complete
synchronized (lock) {
try {
lock.wait();
} catch (InterruptedException ie) {
Log.warning("Waitus interruptus " + ie + ".");
}
}
}
/**
* Called to launch the application if everything is determined to be
* ready to go.
*/
protected void launch ()
{
setStatus("m.launching", 100, -1L, false);
try {
Process proc = _app.createProcess();
System.exit(0);
} catch (IOException ioe) {
Log.logStackTrace(ioe);
}
}
/**
* Creates our user interface, which we avoid doing unless we actually
* have to update something.
*/
protected void createInterface ()
{
if (_frame != null) {
return;
}
Rectangle ppos = (_ifc.progress == null) ? DEFAULT_PPOS : _ifc.progress;
Rectangle spos = (_ifc.status == null) ? DEFAULT_STATUS : _ifc.status;
Rectangle bounds = ppos.union(spos);
bounds.grow(5, 5);
// if we have a background image, load it up
BufferedImage bgimg = null;
if (!StringUtil.blank(_ifc.background)) {
File bgpath = _app.getLocalPath(_ifc.background);
try {
bgimg = ImageIO.read(bgpath);
bounds.setRect(0, 0, bgimg.getWidth(), bgimg.getHeight());
} catch (IOException ioe) {
Log.warning("Failed to read UI background [path=" + bgpath +
", error=" + ioe + "].");
}
}
// create our user interface, and display it
_frame = new JFrame(StringUtil.blank(_ifc.name) ? "" : _ifc.name);
_frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
_status = new StatusPanel(_msgs, bounds, bgimg, ppos, spos);
_frame.getContentPane().add(_status, BorderLayout.CENTER);
_frame.pack();
SwingUtil.centerWindow(_frame);
_frame.show();
}
protected void setStatus (final String message, final int percent,
final long remaining, boolean createUI)
{
if (_status == null && createUI) {
createInterface();
}
if (_status != null) {
EventQueue.invokeLater(new Runnable() {
public void run () {
if (message != null) {
_status.setStatus(message);
}
if (percent >= 0) {
_status.setProgress(percent, remaining);
}
}
});
}
}
public static void main (String[] args)
{
// maybe they specified the appdir in a system property
String adarg = System.getProperty("appdir");
// if not, check for a command line argument
if (StringUtil.blank(adarg)) {
if (args.length != 1) {
System.err.println("Usage: java -jar getdown.jar app_dir");
System.exit(-1);
}
adarg = args[0];
}
// ensure a valid directory was supplied
File appDir = new File(adarg);
if (!appDir.exists() || !appDir.isDirectory()) {
Log.warning("Invalid app_dir '" + adarg + "'.");
System.exit(-1);
}
// // tee our output into a file in the application directory
// File log = new File(appDir, "getdown.log");
// try {
// FileOutputStream fout = new FileOutputStream(log);
// System.setOut(new PrintStream(
// new TeeOutputStream(System.out, fout)));
// System.setErr(new PrintStream(
// new TeeOutputStream(System.err, fout)));
// } catch (IOException ioe) {
// Log.warning("Unable to redirect output to '" + log + "': " + ioe);
try {
Getdown app = new Getdown(appDir);
app.start();
} catch (Exception e) {
Log.logStackTrace(e);
}
}
/** Used to pass progress on to our user interface. */
protected ProgressObserver _progobs = new ProgressObserver() {
public void progress (final int percent) {
setStatus(null, percent, -1L, false);
}
};
protected Application _app;
protected Application.UpdateInterface _ifc =
new Application.UpdateInterface();
protected ResourceBundle _msgs;
protected JFrame _frame;
protected StatusPanel _status;
protected static final int MAX_LOOPS = 5;
protected static final Rectangle DEFAULT_PPOS =
new Rectangle(5, 5, 300, 15);
protected static final Rectangle DEFAULT_STATUS =
new Rectangle(5, 25, 300, 100);
} |
package dr.evomodel.antigenic;
import dr.inference.model.*;
import dr.util.Author;
import dr.util.Citable;
import dr.util.Citation;
import dr.xml.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author Andrew Rambaut
* @author Trevor Bedford
* @author Marc Suchard
* @version $Id$
*/
public class AntigenicSplitPrior extends AbstractModelLikelihood implements Citable {
public final static String ANTIGENIC_SPLIT_PRIOR = "antigenicSplitPrior";
public AntigenicSplitPrior(
MatrixParameter locationsParameter,
Parameter datesParameter,
Parameter regressionSlopeParameter,
Parameter regressionPrecisionParameter,
Parameter splitTimeParameter,
Parameter splitAngleParameter,
Parameter splitAssignmentParameter,
List<String> topBranchList,
List<String> bottomBranchList
) {
super(ANTIGENIC_SPLIT_PRIOR);
this.locationsParameter = locationsParameter;
addVariable(this.locationsParameter);
this.datesParameter = datesParameter;
addVariable(this.datesParameter);
dimension = locationsParameter.getParameter(0).getDimension();
count = locationsParameter.getParameterCount();
earliestDate = datesParameter.getParameterValue(0);
double latestDate = datesParameter.getParameterValue(0);
for (int i=0; i<count; i++) {
double date = datesParameter.getParameterValue(i);
if (earliestDate > date) {
earliestDate = date;
}
if (latestDate < date) {
latestDate = date;
}
}
double timeSpan = latestDate - earliestDate;
this.regressionSlopeParameter = regressionSlopeParameter;
addVariable(regressionSlopeParameter);
regressionSlopeParameter.addBounds(new Parameter.DefaultBounds(Double.MAX_VALUE, 0.0, 1));
this.regressionPrecisionParameter = regressionPrecisionParameter;
addVariable(regressionPrecisionParameter);
regressionPrecisionParameter.addBounds(new Parameter.DefaultBounds(Double.MAX_VALUE, 0.0, 1));
this.splitTimeParameter = splitTimeParameter;
addVariable(splitTimeParameter);
splitTimeParameter.addBounds(new Parameter.DefaultBounds(50.0, 20.0, 1));
this.splitAngleParameter = splitAngleParameter;
addVariable(splitAngleParameter);
splitAngleParameter.addBounds(new Parameter.DefaultBounds(0.5*Math.PI, 0.01, 1));
this.splitAssignmentParameter = splitAssignmentParameter;
addVariable(splitAssignmentParameter);
splitAssignmentParameter.addBounds(new Parameter.DefaultBounds(1.0, 0.0, 1));
String[] labelArray = new String[count];
splitAssignmentParameter.setDimension(count);
topBranchIndices = new int[topBranchList.size()];
bottomBranchIndices = new int[bottomBranchList.size()];
for (int i = 0; i < count; i++) {
String iName = datesParameter.getDimensionName(i);
labelArray[i] = iName;
splitAssignmentParameter.setParameterValueQuietly(i, 0.0);
// top branch is 1
for (int j=0; j < topBranchList.size(); j++) {
String jName = topBranchList.get(j);
if (jName.equals(iName)) {
topBranchIndices[j] = i;
splitAssignmentParameter.setParameterValueQuietly(i, 1.0);
}
}
// bottom branch is 0
for (int j=0; j < bottomBranchList.size(); j++) {
String jName = bottomBranchList.get(j);
if (jName.equals(iName)) {
bottomBranchIndices[j] = i;
splitAssignmentParameter.setParameterValueQuietly(i, 0.0);
}
}
}
splitAssignmentParameter.setDimensionNames(labelArray);
likelihoodKnown = false;
}
@Override
protected void handleModelChangedEvent(Model model, Object object, int index) {
}
@Override
protected void handleVariableChangedEvent(Variable variable, int index, Variable.ChangeType type) {
if (variable == locationsParameter || variable == datesParameter
|| variable == regressionSlopeParameter || variable == regressionPrecisionParameter
|| variable == splitTimeParameter || variable == splitAngleParameter
|| variable == splitAssignmentParameter) {
likelihoodKnown = false;
}
}
@Override
protected void storeState() {
storedLogLikelihood = logLikelihood;
}
@Override
protected void restoreState() {
logLikelihood = storedLogLikelihood;
likelihoodKnown = false;
}
@Override
protected void acceptState() {
}
@Override
public Model getModel() {
return this;
}
@Override
public double getLogLikelihood() {
if (!likelihoodKnown) {
logLikelihood = computeLogLikelihood();
}
return logLikelihood;
}
private double computeLogLikelihood() {
double logLikelihood = 0.0;
double precision = regressionPrecisionParameter.getParameterValue(0);
logLikelihood += (0.5 * Math.log(precision) * count) - (0.5 * precision * sumOfSquaredResiduals());
logLikelihood += assignmentLikelihood();
likelihoodKnown = true;
return logLikelihood;
}
// set likelihood to negative infinity is an assignment is broken
protected double assignmentLikelihood() {
double logLikelihood = 0.0;
// these must be 1
for (int index : topBranchIndices) {
int assignment = (int) splitAssignmentParameter.getParameterValue(index);
if (assignment == 0) {
// logLikelihood = Double.NEGATIVE_INFINITY;
logLikelihood -= 1000;
}
}
// these must be 0
for (int index : bottomBranchIndices) {
int assignment = (int) splitAssignmentParameter.getParameterValue(index);
if (assignment == 1) {
// logLikelihood = Double.NEGATIVE_INFINITY;
logLikelihood -= 1000;
}
}
return logLikelihood;
}
// go through each location and compute sum of squared residuals from regression line
protected double sumOfSquaredResiduals() {
double ssr = 0.0;
for (int i=0; i < count; i++) {
Parameter loc = locationsParameter.getParameter(i);
double x = loc.getParameterValue(0);
double y = expectedAG1(i);
ssr += (x - y) * (x - y);
if (dimension > 1) {
x = loc.getParameterValue(1);
y = expectedAG2(i);
ssr += (x - y) * (x - y);
}
for (int j=2; j < dimension; j++) {
x = loc.getParameterValue(j);
ssr += x*x;
}
}
return ssr;
}
// given a location index, calculate the expected AG1 value
protected double expectedAG1(int index) {
double date = datesParameter.getParameterValue(index);
double ag1 = 0;
double time = date - earliestDate;
double splitTime = splitTimeParameter.getParameterValue(0);
double splitAngle = splitAngleParameter.getParameterValue(0);
double beta = regressionSlopeParameter.getParameterValue(0);
if (time <= splitTime) {
ag1 = beta * time;
}
else {
ag1 = (beta * splitTime) + (beta * (time-splitTime) * Math.cos(splitAngle));
}
return ag1;
}
// given a location index, calculate the expected AG2 value of top branch
protected double expectedAG2(int index) {
double date = datesParameter.getParameterValue(index);
int assignment = (int) splitAssignmentParameter.getParameterValue(index);
double ag2 = 0;
double time = date - earliestDate;
double splitTime = splitTimeParameter.getParameterValue(0);
double splitAngle = splitAngleParameter.getParameterValue(0);
double beta = regressionSlopeParameter.getParameterValue(0);
if (time <= splitTime) {
ag2 = 0;
}
else {
ag2 = beta * (time-splitTime) * Math.sin(splitAngle);
}
if (assignment == 1) {
ag2 = -1*ag2;
}
return ag2;
}
@Override
public void makeDirty() {
likelihoodKnown = false;
}
private final int dimension;
private final int count;
private final Parameter datesParameter;
private final MatrixParameter locationsParameter;
private final Parameter regressionSlopeParameter;
private final Parameter regressionPrecisionParameter;
private final Parameter splitTimeParameter;
private final Parameter splitAngleParameter;
private final Parameter splitAssignmentParameter;
private final int[] topBranchIndices;
private final int[] bottomBranchIndices;
private double earliestDate;
private double logLikelihood = 0.0;
private double storedLogLikelihood = 0.0;
private boolean likelihoodKnown = false;
// XMLObjectParser
public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
public final static String LOCATIONS = "locations";
public final static String DATES = "dates";
public final static String REGRESSIONSLOPE = "regressionSlope";
public final static String REGRESSIONPRECISION = "regressionPrecision";
public final static String SPLITTIME = "splitTime";
public final static String SPLITANGLE = "splitAngle";
public final static String SPLITASSIGNMENT = "splitAssignment";
public static final String TOPBRANCH = "topBranch";
public static final String BOTTOMBRANCH = "bottomBranch";
public String getParserName() {
return ANTIGENIC_SPLIT_PRIOR;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
MatrixParameter locationsParameter = (MatrixParameter) xo.getElementFirstChild(LOCATIONS);
Parameter datesParameter = (Parameter) xo.getElementFirstChild(DATES);
Parameter regressionSlopeParameter = (Parameter) xo.getElementFirstChild(REGRESSIONSLOPE);
Parameter regressionPrecisionParameter = (Parameter) xo.getElementFirstChild(REGRESSIONPRECISION);
Parameter splitTimeParameter = (Parameter) xo.getElementFirstChild(SPLITTIME);
Parameter splitAngleParameter = (Parameter) xo.getElementFirstChild(SPLITANGLE);
Parameter splitAssignmentParameter = (Parameter) xo.getElementFirstChild(SPLITASSIGNMENT); List<String> virusLocationStatisticList = null;
List<String> topBranchList = null;
String[] topBranch = xo.getStringArrayAttribute(TOPBRANCH);
if (topBranch != null) {
topBranchList = Arrays.asList(topBranch);
}
List<String> bottomBranchList = null;
String[] bottomBranch = xo.getStringArrayAttribute(BOTTOMBRANCH);
if (bottomBranch != null) {
bottomBranchList = Arrays.asList(bottomBranch);
}
AntigenicSplitPrior AGDP = new AntigenicSplitPrior(
locationsParameter,
datesParameter,
regressionSlopeParameter,
regressionPrecisionParameter,
splitTimeParameter,
splitAngleParameter,
splitAssignmentParameter,
topBranchList,
bottomBranchList);
// Logger.getLogger("dr.evomodel").info("Using EvolutionaryCartography model. Please cite:\n" + Utils.getCitationString(AGL));
return AGDP;
} |
package mho.wheels.iterables;
import mho.wheels.math.MathUtils;
import mho.wheels.ordering.Ordering;
import mho.wheels.random.IsaacPRNG;
import mho.wheels.structures.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.*;
import static mho.wheels.iterables.IterableUtils.*;
import static mho.wheels.ordering.Ordering.lt;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* <p>A {@code RandomProvider} produces {@code Iterable}s that randomly generate some set of values with a specified
* distribution. A {@code RandomProvider} is immutable and deterministic. The source of its randomness is a
* {@code int[]} seed. It contains two scale parameters which some of the distributions depend on; the exact
* relationship between the parameters and the distributions is specified in the distribution's documentation.
*
* <p>{@code RandomProvider} uses the cryptographically-secure ISAAC pseudorandom number generator, implemented in
* {@link mho.wheels.random.IsaacPRNG}.
*
* <p>Note that sometimes the documentation will say things like "returns an {@code Iterable} containing all
* {@code String}s". This cannot strictly be true, since {@link java.util.Random} has a finite period, and will
* therefore produce only a finite number of {@code String}s. So in general, the documentation often pretends that the
* source of randomness is perfect (but still deterministic).
*/
public final class RandomProvider extends IterableProvider {
/**
* The default value of {@code scale}.
*/
private static final int DEFAULT_SCALE = 32;
/**
* The default value of {@code secondaryScale}.
*/
private static final int DEFAULT_SECONDARY_SCALE = 8;
/**
* Sometimes a "special element" (for example, null) is inserted into an {@code Iterable} with some probability.
* That probability is 1/{@code SPECIAL_ELEMENT_RATIO}.
*/
private static final int SPECIAL_ELEMENT_RATIO = 50;
/**
* A list of numbers which determines exactly which values will be deterministically output over the life of
* {@code this}. It must have length {@link mho.wheels.random.IsaacPRNG#SIZE}.
*/
private @NotNull List<Integer> seed;
/**
* A parameter that determines the size of some of the generated objects. Cannot be negative.
*/
private int scale = DEFAULT_SCALE;
/**
* Another parameter that determines the size of some of the generated objects. Cannot be negative.
*/
private int secondaryScale = DEFAULT_SECONDARY_SCALE;
/**
* A {@code RandomProvider} used for testing. This allows for deterministic testing without manually setting up a
* lengthy seed each time.
*/
public static final @NotNull RandomProvider EXAMPLE;
static {
IsaacPRNG prng = IsaacPRNG.example();
List<Integer> seed = new ArrayList<>();
for (int i = 0; i < IsaacPRNG.SIZE; i++) {
seed.add(prng.nextInt());
}
EXAMPLE = new RandomProvider(seed);
}
/**
* Constructs a {@code RandomProvider} with a seed generated from the current system time.
*
* <ul>
* <li>(conjecture) Any {@code RandomProvider} with default {@code scale} and {@code secondaryScale} may be
* constructed with this constructor.</li>
* </ul>
*/
public RandomProvider() {
IsaacPRNG prng = new IsaacPRNG();
seed = new ArrayList<>();
for (int i = 0; i < IsaacPRNG.SIZE; i++) {
seed.add(prng.nextInt());
}
}
/**
* Constructs a {@code RandomProvider} with a given seed.
*
* <ul>
* <li>{@code seed} must have length {@link mho.wheels.random.IsaacPRNG#SIZE}.</li>
* <li>Any {@code RandomProvider} with default {@code scale} and {@code secondaryScale} may be constructed with
* this constructor.</li>
* </ul>
*
* @param seed the source of randomness
*/
public RandomProvider(@NotNull List<Integer> seed) {
if (seed.size() != IsaacPRNG.SIZE) {
throw new IllegalArgumentException("seed must have length mho.wheels.random.IsaacPRNG#SIZE, which is " +
IsaacPRNG.SIZE + ". Length of invalid seed: " + seed.size());
}
this.seed = seed;
}
/**
* Returns {@code this}'s scale parameter.
*
* <ul>
* <li>The result is non-negative.</li>
* </ul>
*
* @return the scale parameter of {@code this}
*/
public int getScale() {
return scale;
}
/**
* Returns {@code this}'s other scale parameter.
*
* <ul>
* <li>The result is non-negative.</li>
* </ul>
*
* @return the other scale parameter of {@code this}
*/
public int getSecondaryScale() {
return secondaryScale;
}
/**
* Returns {@code this}'s seed. Makes a defensive copy.
*
* <ul>
* <li>The result is an array of {@link mho.wheels.random.IsaacPRNG#SIZE} {@code int}s.</li>
* </ul>
*
* @return the seed of {@code this}
*/
public @NotNull List<Integer> getSeed() {
return toList(seed);
}
/**
* A {@code RandomProvider} with the same fields as {@code this}.
*
* <ul>
* <li>The result is not null.</li>
* </ul>
*
* @return A copy of {@code this}.
*/
private @NotNull RandomProvider copy() {
RandomProvider copy = new RandomProvider(seed);
copy.scale = scale;
copy.secondaryScale = secondaryScale;
return copy;
}
@Override
public @NotNull RandomProvider alt() {
RandomProvider alt = copy();
IsaacPRNG prng = new IsaacPRNG(seed);
List<Integer> newSeed = new ArrayList<>();
for (int i = 0; i < IsaacPRNG.SIZE; i++) {
newSeed.add(prng.nextInt());
}
alt.seed = newSeed;
return alt;
}
/**
* A {@code RandomProvider} with the same fields as {@code this} except for a new scale.
*
* <ul>
* <li>{@code scale} cannot be negative.</li>
* <li>The result is not null.</li>
* </ul>
*
* @param scale the new scale
* @return A copy of {@code this} with a new scale
*/
@Override
public @NotNull RandomProvider withScale(int scale) {
if (scale < 0) {
throw new IllegalArgumentException("scale cannot be negative. Invalid scale: " + scale);
}
RandomProvider copy = copy();
copy.scale = scale;
return copy;
}
/**
* A {@code RandomProvider} with the same fields as {@code this} except for a new secondary scale.
*
* <ul>
* <li>{@code secondaryScale} cannot be negative.</li>
* <li>The result is not null.</li>
* </ul>
*
* @param secondaryScale the new secondary scale
* @return A copy of {@code this} with a new secondary scale
*/
@Override
public @NotNull RandomProvider withSecondaryScale(int secondaryScale) {
if (secondaryScale < 0) {
throw new IllegalArgumentException("secondaryScale cannot be negative. Invalid secondaryScale: " +
secondaryScale);
}
RandomProvider copy = copy();
copy.secondaryScale = secondaryScale;
return copy;
}
/**
* An {@code Iterator} that generates both {@code Boolean}s from a uniform distribution. Does not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Boolean> booleans() {
return () -> new NoRemoveIterator<Boolean>() {
private @NotNull IsaacPRNG prng = new IsaacPRNG(seed);
@Override
public boolean hasNext() {
return true;
}
@Override
public Boolean next() {
return (prng.nextInt() & 1) == 1;
}
};
}
/**
* An {@code Iterable} that generates all {@code Integer}s from a uniform distribution. Does not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Integer> integers() {
return () -> new NoRemoveIterator<Integer>() {
private @NotNull IsaacPRNG prng = new IsaacPRNG(seed);
@Override
public boolean hasNext() {
return true;
}
@Override
public Integer next() {
return prng.nextInt();
}
};
}
/**
* An {@code Iterable} that generates all {@code Long}s from a uniform distribution. Does not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Long> longs() {
return () -> new NoRemoveIterator<Long>() {
private @NotNull IsaacPRNG prng = new IsaacPRNG(seed);
@Override
public boolean hasNext() {
return true;
}
@Override
public Long next() {
int a = prng.nextInt();
int b = prng.nextInt();
return (long) a << 32 | b & 0xffffffffL;
}
};
}
/**
* Returns the next non-negative {@code BigInteger} of up to {@code bits} bits generated by {@code prng}.
*
* <ul>
* <li>{@code prng} cannot be null.</li>
* <li>{@code bits} must be positive.</li>
* <li>The result is non-negative.</li>
* </ul>
*
* @param prng the {@code IsaacPRNG} generating a {@code BigInteger}
* @param bits the maximum bitlength of the generated {@code BigInteger}
* @return A random {@code BigInteger}
*/
private static @NotNull BigInteger nextBigInteger(@NotNull IsaacPRNG prng, int bits) {
byte[] bytes = new byte[bits / 8 + 1];
int x = 0;
for (int i = 0; i < bytes.length; i++) {
if (i % 4 == 0) {
x = prng.nextInt();
}
bytes[i] = (byte) x;
x >>= 8;
}
bytes[0] &= (1 << (bits % 8)) - 1;
return new BigInteger(bytes);
}
private @NotNull Iterable<Integer> randomIntsPow2(int bits) {
int mask = (1 << bits) - 1;
return map(i -> i & mask, integers());
}
private @NotNull Iterable<Long> randomLongsPow2(int bits) {
long mask = (1L << bits) - 1;
return map(l -> l & mask, longs());
}
private @NotNull Iterable<BigInteger> randomBigIntegersPow2(int bits) {
return () -> new NoRemoveIterator<BigInteger>() {
private @NotNull IsaacPRNG prng = new IsaacPRNG(seed);
@Override
public boolean hasNext() {
return true;
}
@Override
public BigInteger next() {
return nextBigInteger(prng, bits);
}
};
}
private @NotNull Iterable<Integer> randomInts(int n) {
return filter(
i -> i < n,
randomIntsPow2(MathUtils.ceilingLog(BigInteger.valueOf(2), BigInteger.valueOf(n)).intValueExact())
);
}
private @NotNull Iterable<Long> randomLongs(long n) {
return filter(
l -> l < n,
randomLongsPow2(MathUtils.ceilingLog(BigInteger.valueOf(2), BigInteger.valueOf(n)).intValueExact())
);
}
private @NotNull Iterable<BigInteger> randomBigIntegers(@NotNull BigInteger n) {
return filter(
i -> lt(i, n),
randomBigIntegersPow2(MathUtils.ceilingLog(BigInteger.valueOf(2), n).intValueExact())
);
}
/**
* An {@code Iterable} that uniformly generates {@code Byte}s greater than or equal to {@code a}.
*
* <ul>
* <li>{@code a} may be any {@code byte}.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code Byte}s.</li>
* </ul>
*
* Length is infinite
*
* @param a the inclusive lower bound of the generated elements
* @return uniformly-distributed {@code Byte}s greater than or equal to {@code a}
*/
@Override
public @NotNull Iterable<Byte> rangeUp(byte a) {
return map(i -> (byte) (i + a), randomInts((1 << 7) - a));
}
/**
* An {@code Iterable} that uniformly generates {@code Short}s greater than or equal to {@code a}.
*
* <ul>
* <li>{@code a} may be any {@code short}.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code Short}s.</li>
* </ul>
*
* Length is infinite
*
* @param a the inclusive lower bound of the generated elements
* @return uniformly-distributed {@code Short}s greater than or equal to {@code a}
*/
@Override
public @NotNull Iterable<Short> rangeUp(short a) {
return map(i -> (short) (i + a), randomInts((1 << 15) - a));
}
/**
* An {@code Iterable} that uniformly generates {@code Integer}s greater than or equal to {@code a}.
*
* <ul>
* <li>{@code a} may be any {@code int}.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code Integer}s.</li>
* </ul>
*
* Length is infinite
*
* @param a the inclusive lower bound of the generated elements
* @return uniformly-distributed {@code Integer}s greater than or equal to {@code a}
*/
@Override
public @NotNull Iterable<Integer> rangeUp(int a) {
return map(l -> (int) (l + a), randomLongs((1L << 31) - a));
}
/**
* An {@code Iterable} that uniformly generates {@code Long}s greater than or equal to {@code a}.
*
* <ul>
* <li>{@code a} may be any {@code long}.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code Long}s.</li>
* </ul>
*
* Length is infinite
*
* @param a the inclusive lower bound of the generated elements
* @return uniformly-distributed {@code Long}s greater than or equal to {@code a}
*/
@Override
public @NotNull Iterable<Long> rangeUp(long a) {
return map(
i -> i.add(BigInteger.valueOf(a)).longValueExact(),
randomBigIntegers(BigInteger.ONE.shiftLeft(63).subtract(BigInteger.valueOf(a)))
);
}
//todo docs
@Override
public @NotNull Iterable<BigInteger> rangeUp(@NotNull BigInteger a) {
return map(i -> i.add(a), naturalBigIntegers());
}
/**
* An {@code Iterable} that uniformly generates {@code Characters}s greater than or equal to {@code a}.
*
* <ul>
* <li>{@code a} may be any {@code char}.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code Character}s.</li>
* </ul>
*
* Length is infinite
*
* @param a the inclusive lower bound of the generated elements
* @return uniformly-distributed {@code Character}s greater than or equal to {@code a}
*/
@Override
public @NotNull Iterable<Character> rangeUp(char a) {
return map(i -> (char) (i + a), randomInts((1 << 16) - a));
}
/**
* An {@code Iterable} that uniformly generates {@code Byte}s less than or equal to {@code a}.
*
* <ul>
* <li>{@code a} may be any {@code byte}.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code Byte}s.</li>
* </ul>
*
* Length is infinite
*
* @param a the inclusive upper bound of the generated elements
* @return uniformly-distributed {@code Byte}s less than or equal to {@code a}
*/
@Override
public @NotNull Iterable<Byte> rangeDown(byte a) {
int offset = 1 << 7;
return map(i -> (byte) (i - offset), randomInts(a + offset + 1));
}
/**
* An {@code Iterable} that uniformly generates {@code Short}s less than or equal to {@code a}.
*
* <ul>
* <li>{@code a} may be any {@code short}.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code Short}s.</li>
* </ul>
*
* Length is infinite
*
* @param a the inclusive upper bound of the generated elements
* @return uniformly-distributed {@code Short}s less than or equal to {@code a}
*/
@Override
public @NotNull Iterable<Short> rangeDown(short a) {
int offset = 1 << 15;
return map(i -> (short) (i - offset), randomInts(a + offset + 1));
}
/**
* An {@code Iterable} that uniformly generates {@code Integer}s less than or equal to {@code a}.
*
* <ul>
* <li>{@code a} may be any {@code int}.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code Integer}s.</li>
* </ul>
*
* Length is infinite
*
* @param a the inclusive upper bound of the generated elements
* @return uniformly-distributed {@code Integer}s less than or equal to {@code a}
*/
@Override
public @NotNull Iterable<Integer> rangeDown(int a) {
long offset = 1L << 31;
return map(l -> (int) (l - offset), randomLongs(a + offset + 1));
}
/**
* An {@code Iterable} that uniformly generates {@code Long}s less than or equal to {@code a}.
*
* <ul>
* <li>{@code a} may be any {@code long}.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code Long}s.</li>
* </ul>
*
* Length is infinite
*
* @param a the inclusive upper bound of the generated elements
* @return uniformly-distributed {@code Long}s less than or equal to {@code a}
*/
@Override
public @NotNull Iterable<Long> rangeDown(long a) {
return map(
i -> i.subtract(BigInteger.ONE.shiftLeft(63)).longValueExact(),
randomBigIntegers(BigInteger.valueOf(a).add(BigInteger.ONE).add(BigInteger.ONE.shiftLeft(63)))
);
}
//todo docs
@Override
public @NotNull Iterable<BigInteger> rangeDown(@NotNull BigInteger a) {
return map(i -> i.add(BigInteger.ONE).add(a), negativeBigIntegers());
}
/**
* An {@code Iterable} that uniformly generates {@code Character}s less than or equal to {@code a}.
*
* <ul>
* <li>{@code a} may be any {@code char}.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code Character}s.</li>
* </ul>
*
* Length is infinite
*
* @param a the inclusive upper bound of the generated elements
* @return uniformly-distributed {@code Character}s less than or equal to {@code a}
*/
@Override
public @NotNull Iterable<Character> rangeDown(char a) {
return map(i -> (char) (int) i, randomInts(a + 1));
}
@Override
public @NotNull Iterable<Byte> range(byte a, byte b) {
if (a > b) return Collections.emptyList();
return map(i -> (byte) (i + a), randomInts((int) b - a + 1));
}
@Override
public @NotNull Iterable<Short> range(short a, short b) {
if (a > b) return Collections.emptyList();
return map(i -> (short) (i + a), randomInts((int) b - a + 1));
}
@Override
public @NotNull Iterable<Integer> range(int a, int b) {
if (a > b) return Collections.emptyList();
return map(i -> (int) (i + a), randomLongs((long) b - a + 1));
}
public @NotNull Iterable<Long> range(long a, long b) {
if (a > b) return Collections.emptyList();
return map(
i -> i.add(BigInteger.valueOf(a)).longValueExact(),
randomBigIntegers(BigInteger.valueOf(b).subtract(BigInteger.valueOf(a)).add(BigInteger.ONE))
);
}
@Override
public @NotNull Iterable<BigInteger> range(@NotNull BigInteger a, @NotNull BigInteger b) {
if (Ordering.gt(a, b)) return Collections.emptyList();
return map(i -> i.add(a), randomBigIntegers(b.subtract(a).add(BigInteger.ONE)));
}
@Override
public @NotNull Iterable<Character> range(char a, char b) {
if (a > b) return Collections.emptyList();
return map(i -> (char) (i + a), randomInts(b - a + 1));
}
/**
* An {@code Iterable} that uniformly generates elements from a (possibly null-containing) list.
*
* <ul>
* <li>{@code xs} cannot be null.</li>
* <li>The result is non-removable and either empty or infinite.</li>
* </ul>
*
* Length is 0 if {@code xs} is empty, infinite otherwise
*
* @param xs the source list
* @param <T> the type of {@code xs}'s elements
* @return uniformly-distributed elements of {@code xs}
*/
@Override
public @NotNull <T> Iterable<T> uniformSample(@NotNull List<T> xs) {
return map(xs::get, range(0, xs.size() - 1));
}
/**
* An {@code Iterable} that uniformly generates {@code Character}s from a {@code String}.
*
* <ul>
* <li>{@code xs} cannot be null.</li>
* <li>The result is an empty or infinite non-removable {@code Iterable} containing {@code Character}s.</li>
* </ul>
*
* Length is 0 if {@code s} is empty, infinite otherwise
*
* @param s the source {@code String}
* @return uniformly-distributed {@code Character}s from {@code s}
*/
@Override
public @NotNull Iterable<Character> uniformSample(@NotNull String s) {
return map(s::charAt, range(0, s.length() - 1));
}
/**
* An {@code Iterator} that generates all {@code Ordering}s from a uniform distribution. Does not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Ordering> orderings() {
return uniformSample(toList(ExhaustiveProvider.INSTANCE.orderings()));
}
/**
* An {@code Iterable} that generates all {@code RoundingMode}s from a uniform distribution. Does not support
* removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<RoundingMode> roundingModes() {
return uniformSample(toList(ExhaustiveProvider.INSTANCE.roundingModes()));
}
/**
* An {@code Iterable} that generates all positive {@code Byte}s from a uniform distribution. Does not support
* removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Byte> positiveBytes() {
return map(Integer::byteValue, filter(i -> i != 0, randomIntsPow2(1 << 7)));
}
/**
* An {@code Iterable} that generates all positive {@code Short}s from a uniform distribution. Does not support
* removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Short> positiveShorts() {
return map(Integer::shortValue, filter(i -> i != 0, randomIntsPow2(1 << 15)));
}
/**
* An {@code Iterable} that generates all positive {@code Integer}s from a uniform distribution. Does not support
* removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Integer> positiveIntegers() {
return filter(i -> i > 0, integers());
}
/**
* An {@code Iterable} that generates all positive {@code Long}s from a uniform distribution from a uniform
* distribution. Does not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Long> positiveLongs() {
return filter(l -> l > 0, longs());
}
/**
* An {@code Iterable} that generates all negative {@code Byte}s from a uniform distribution. Does not support
* removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Byte> negativeBytes() {
return () -> new Iterator<Byte>() {
private Random generator = new Random(0x6af477d9a7e54fcaL);
@Override
public boolean hasNext() {
return true;
}
@Override
public Byte next() {
return (byte) (-1 - generator.nextInt(Byte.MAX_VALUE + 1));
}
@Override
public void remove() {
throw new UnsupportedOperationException("cannot remove from this iterator");
}
};
}
/**
* An {@code Iterable} that generates all negative {@code Short}s from a uniform distribution. Does not support
* removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Short> negativeShorts() {
return () -> new Iterator<Short>() {
private Random generator = new Random(0x6af477d9a7e54fcaL);
@Override
public boolean hasNext() {
return true;
}
@Override
public Short next() {
return (short) (-1 - generator.nextInt(Short.MAX_VALUE + 1));
}
@Override
public void remove() {
throw new UnsupportedOperationException("cannot remove from this iterator");
}
};
}
/**
* An {@code Iterable} that generates all negative {@code Integer}s from a uniform distribution. Does not support
* removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Integer> negativeIntegers() {
return filter(i -> i < 0, integers());
}
/**
* An {@code Iterable} that generates all negative {@code Long}s from a uniform distribution. Does not support
* removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Long> negativeLongs() {
return filter(l -> l < 0, longs());
}
/**
* An {@code Iterable} that generates all natural {@code Byte}s (including 0) from a uniform distribution. Does
* not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Byte> naturalBytes() {
return map(Integer::byteValue, randomIntsPow2(7));
}
/**
* An {@code Iterable} that generates all natural {@code Short}s (including 0) from a uniform distribution. Does
* not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Short> naturalShorts() {
return map(Integer::shortValue, randomIntsPow2(15));
}
/**
* An {@code Iterable} that generates all natural {@code Integer}s (including 0) from a uniform distribution.
* Does not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Integer> naturalIntegers() {
return randomIntsPow2(31);
}
/**
* An {@code Iterable} that generates all natural {@code Long}s (including 0) from a uniform distribution. Does
* not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Long> naturalLongs() {
return randomLongsPow2(63);
}
/**
* An {@code Iterable} that generates all {@code Byte}s from a uniform distribution. Does not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Byte> bytes() {
return map(Integer::byteValue, randomIntsPow2(8));
}
/**
* An {@code Iterable} that generates all {@code Short}s from a uniform distribution. Does not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Short> shorts() {
return map(Integer::shortValue, randomIntsPow2(16));
}
/**
* An {@code Iterable} that generates all ASCII {@code Character}s from a uniform distribution. Does not support
* removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Character> asciiCharacters() {
return map(i -> (char) (int) i, randomIntsPow2(7));
}
/**
* An {@code Iterable} that generates all {@code Character}s from a uniform distribution. Does not support
* removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Character> characters() {
return map(i -> (char) (int) i, randomIntsPow2(16));
}
/**
* An {@code Iterable} that generates all natural {@code Integer}s chosen from a geometric distribution with mean
* {@code mean}, or all zeros if {@code mean} is 0. Does not support removal.
*
* <ul>
* <li>{@code mean} cannot be negative.</li>
* <li>The result is an infinite pseudorandom sequence of all natural {@code Integer}s, or 0.</li>
* </ul>
*
* Length is infinite
*
* @param mean the approximate mean bit size of the {@code Integer}s generated
*/
public @NotNull Iterable<Integer> naturalIntegersGeometric(int mean) {
return map(i -> i - 1, positiveIntegersGeometric(mean));
}
/**
* An {@code Iterable} that generates all positive {@code Integer}s chosen from a geometric distribution with mean
* {@code mean}, or all ones if {@code mean} is 1. Does not support removal.
*
* <ul>
* <li>{@code mean} must be positive.</li>
* <li>The result is an infinite pseudorandom sequence of all positive {@code Integer}s, or 1.</li>
* </ul>
*
* Length is infinite
*
* @param mean the approximate mean size of the {@code Integer}s generated
*/
public @NotNull Iterable<Integer> positiveIntegersGeometric(int mean) {
//noinspection ConstantConditions
return map(p -> p.b, filter(p -> p.a, countAdjacent(map(i -> i != 0, range(0, mean - 1)))));
}
public @NotNull Iterable<Integer> negativeIntegersGeometric(int mean) {
return map(i -> -i, positiveIntegersGeometric(-mean));
}
public @NotNull Iterable<Integer> nonzeroIntegersGeometric(int mean) {
return zipWith((i, b) -> b ? i : -i, positiveIntegersGeometric(mean), booleans());
}
/**
* An {@code Iterable} that generates all {@code Integer}s whose absolute value is chosen from a geometric
* distribution with absolute mean {@code mean}, and whose sign is chosen uniformly. Does not support removal.
*
* <ul>
* <li>{@code mean} must be greater than 1.</li>
* <li>The result is an infinite pseudorandom sequence of all {@code Integer}s.</li>
* </ul>
*
* Length is infinite
*
* @param mean the approximate mean bit size of the {@code Integer}s generated
*/
public @NotNull Iterable<Integer> integersGeometric(int mean) {
if (mean < 0)
throw new IllegalArgumentException("mean cannot be negative.");
if (mean == 0) return repeat(0);
return () -> new Iterator<Integer>() {
private Iterator<Boolean> bs = booleans().iterator();
private final Iterator<Integer> nats = naturalIntegersGeometric(mean).iterator();
private final Iterator<Integer> negs = alt().negativeIntegersGeometric(-mean).iterator();
@Override
public boolean hasNext() {
return true;
}
@Override
public Integer next() {
return bs.next() ? nats.next() : negs.next();
}
@Override
public void remove() {
throw new UnsupportedOperationException("cannot remove from this iterator");
}
};
}
/**
* An {@code Iterable} that generates all positive {@code BigInteger}s. The bit size is chosen from a geometric
* distribution with mean approximately {@code meanBitSize} (The ratio between the actual mean and
* {@code meanBitSize} decreases as {@code meanBitSize} increases). Does not support removal.
*
* <ul>
* <li>{@code meanBitSize} must be greater than 2.</li>
* <li>The is an infinite pseudorandom sequence of all {@code BigInteger}s</li>
* </ul>
*
* Length is infinite
*/
public @NotNull Iterable<BigInteger> positiveBigIntegers() {
if (scale <= 2)
throw new IllegalArgumentException("meanBitSize must be greater than 2.");
return () -> new Iterator<BigInteger>() {
private Random generator = new Random(0x6af477d9a7e54fcaL);
private Iterator<Integer> geos = positiveIntegersGeometric(scale).iterator();
@Override
public boolean hasNext() {
return true;
}
@Override
public BigInteger next() {
List<Boolean> bits = new ArrayList<>();
bits.add(true);
int bitSize = geos.next();
for (int i = 0; i < bitSize - 1; i++) {
bits.add(generator.nextBoolean());
}
return MathUtils.fromBigEndianBits(bits);
}
@Override
public void remove() {
throw new UnsupportedOperationException("cannot remove from this iterator");
}
};
}
/**
* An {@code Iterable} that generates all negative {@code BigInteger}s. The bit size is chosen from a geometric
* distribution with mean approximately {@code meanBitSize} (The ratio between the actual mean and
* {@code meanBitSize} decreases as {@code meanBitSize} increases). Does not support removal.
*
* <ul>
* <li>{@code meanBitSize} must be greater than 2.</li>
* <li>The result is an infinite pseudorandom sequence of all {@code BigInteger}s.</li>
* </ul>
*
* Length is infinite
*/
@Override
public @NotNull Iterable<BigInteger> negativeBigIntegers() {
return map(BigInteger::negate, positiveBigIntegers());
}
/**
* An {@code Iterable} that generates all natural {@code BigInteger}s (including 0). The bit size is chosen from a
* geometric distribution with mean approximately {@code meanBitSize} (The ratio between the actual mean and
* {@code meanBitSize} decreases as {@code meanBitSize} increases). Does not support removal.
*
* <ul>
* <li>{@code meanBitSize} must be greater than 2.</li>
* <li>The result is an infinite pseudorandom sequence of all {@code BigInteger}s.</li>
* </ul>
*
* Length is infinite
*/
@Override
public @NotNull Iterable<BigInteger> naturalBigIntegers() {
if (scale <= 2)
throw new IllegalArgumentException("meanBitSize must be greater than 2.");
return () -> new Iterator<BigInteger>() {
private Random generator = new Random(0x6af477d9a7e54fcaL);
Iterator<Integer> geos = positiveIntegersGeometric(scale + 1).iterator();
@Override
public boolean hasNext() {
return true;
}
@Override
public BigInteger next() {
List<Boolean> bits = new ArrayList<>();
int bitSize = geos.next() - 1;
if (bitSize != 0) {
bits.add(true);
}
for (int i = 0; i < bitSize - 1; i++) {
bits.add(generator.nextBoolean());
}
return MathUtils.fromBigEndianBits(bits);
}
@Override
public void remove() {
throw new UnsupportedOperationException("cannot remove from this iterator");
}
};
}
/**
* An {@code Iterable} that generates all {@code BigInteger}s. The bit size is chosen from a geometric distribution
* with mean approximately {@code meanBitSize} (The ratio between the actual mean and {@code meanBitSize} decreases
* as {@code meanBitSize} increases). Does not support removal.
*
* <ul>
* <li>{@code meanBitSize} must be greater than 2.</li>
* <li>The result is an infinite pseudorandom sequence of all {@code BigInteger}s.</li>
* </ul>
*
* Length is infinite
*/
@Override
public @NotNull Iterable<BigInteger> bigIntegers() {
if (scale <= 2)
throw new IllegalArgumentException("meanBitSize must be greater than 2.");
return () -> new Iterator<BigInteger>() {
private Random generator = new Random(0x6af477d9a7e54fcaL);
private final Iterator<BigInteger> it = naturalBigIntegers().iterator();
@Override
public boolean hasNext() {
return true;
}
@Override
public BigInteger next() {
BigInteger nbi = it.next();
if (generator.nextBoolean()) {
nbi = nbi.negate().subtract(BigInteger.ONE);
}
return nbi;
}
@Override
public void remove() {
throw new UnsupportedOperationException("cannot remove from this iterator");
}
};
}
/**
* An {@code Iterable} that generates all ordinary (neither NaN nor infinite) positive floats from a uniform
* distribution. Does not support removal.
*
* Length is infinite.
*/
@Override
public @NotNull Iterable<Float> positiveOrdinaryFloats() {
return map(Math::abs, filter(
f -> Float.isFinite(f) && !Float.isNaN(f) && !f.equals(-0.0f) && !f.equals(0.0f),
floats()
));
}
/**
* An {@code Iterable} that generates all ordinary (neither NaN nor infinite) negative floats from a uniform
* distribution. Negative zero is not included. Does not support removal.
*
* Length is infinite.
*/
@Override
public @NotNull Iterable<Float> negativeOrdinaryFloats() {
return map(f -> -f, positiveOrdinaryFloats());
}
/**
* An {@code Iterable} that generates all ordinary (neither NaN nor infinite) floats from a uniform distribution.
* Does not support removal.
*
* Length is infinite.
*/
@Override
public @NotNull Iterable<Float> ordinaryFloats() {
return filter(f -> Float.isFinite(f) && !Float.isNaN(f) && !f.equals(-0.0f), floats());
}
/**
* An {@code Iterable} that generates all {@code Float}s from a uniform distribution. Does not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Float> floats() {
return () -> new Iterator<Float>() {
private Random generator = new Random(0x6af477d9a7e54fcaL);
@Override
public boolean hasNext() {
return true;
}
@Override
public Float next() {
float next;
boolean problematicNaN;
do {
int floatBits = generator.nextInt();
next = Float.intBitsToFloat(floatBits);
problematicNaN = Float.isNaN(next) && floatBits != 0x7fc00000;
} while (problematicNaN);
return next;
}
@Override
public void remove() {
throw new UnsupportedOperationException("cannot remove from this iterator");
}
};
}
/**
* An {@code Iterable} that generates all ordinary (neither NaN nor infinite) positive floats from a uniform
* distribution. Does not support removal.
*
* Length is infinite.
*/
@Override
public @NotNull Iterable<Double> positiveOrdinaryDoubles() {
return map(Math::abs, filter(
d -> Double.isFinite(d) && !Double.isNaN(d) && !d.equals(-0.0) && !d.equals(0.0),
doubles()
));
}
/**
* An {@code Iterable} that generates all ordinary (neither NaN nor infinite) negative floats from a uniform
* distribution. Negative zero is not included. Does not support removal.
*
* Length is infinite.
*/
@Override
public @NotNull Iterable<Double> negativeOrdinaryDoubles() {
return map(d -> -d, positiveOrdinaryDoubles());
}
/**
* An {@code Iterable} that generates all ordinary (neither NaN nor infinite) floats from a uniform distribution.
* Does not support removal.
*
* Length is infinite.
*/
@Override
public @NotNull Iterable<Double> ordinaryDoubles() {
return filter(d -> Double.isFinite(d) && !Double.isNaN(d) && !d.equals(-0.0), doubles());
}
/**
* An {@code Iterable} that generates all {@code Double}s from a uniform distribution. Does not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Double> doubles() {
return () -> new Iterator<Double>() {
private Random generator = new Random(0x6af477d9a7e54fcaL);
@Override
public boolean hasNext() {
return true;
}
@Override
public Double next() {
double next;
boolean problematicNaN;
do {
long doubleBits = generator.nextLong();
next = Double.longBitsToDouble(doubleBits);
problematicNaN = Double.isNaN(next) && doubleBits != 0x7ff8000000000000L;
} while (problematicNaN);
return next;
}
@Override
public void remove() {
throw new UnsupportedOperationException("cannot remove from this iterator");
}
};
}
@Override
public @NotNull Iterable<BigDecimal> positiveBigDecimals() {
return map(
p -> new BigDecimal(p.a, p.b),
pairs(negativeBigIntegers(), integersGeometric(scale))
);
}
@Override
public @NotNull Iterable<BigDecimal> negativeBigDecimals() {
return map(
p -> new BigDecimal(p.a, p.b),
pairs(negativeBigIntegers(), integersGeometric(scale))
);
}
@Override
public @NotNull Iterable<BigDecimal> bigDecimals() {
return map(p -> new BigDecimal(p.a, p.b), pairs(bigIntegers(), integersGeometric(scale)));
}
public @NotNull <T> Iterable<T> addSpecialElement(@Nullable T x, @NotNull Iterable<T> xs) {
return () -> new Iterator<T>() {
private Iterator<T> xsi = xs.iterator();
private Iterator<Integer> specialSelector = randomInts(SPECIAL_ELEMENT_RATIO).iterator();
boolean specialSelection = specialSelector.next() == 0;
@Override
public boolean hasNext() {
return specialSelection || xsi.hasNext();
}
@Override
public T next() {
boolean previousSelection = specialSelection;
specialSelection = specialSelector.next() == 0;
return previousSelection ? x : xsi.next();
}
@Override
public void remove() {
throw new UnsupportedOperationException("cannot remove from this iterator");
}
};
}
@Override
public @NotNull <T> Iterable<T> withNull(@NotNull Iterable<T> xs) {
return addSpecialElement(null, xs);
}
@Override
public @NotNull <T> Iterable<Optional<T>> optionals(@NotNull Iterable<T> xs) {
return addSpecialElement(Optional.<T>empty(), map(Optional::of, xs));
}
@Override
public @NotNull <T> Iterable<NullableOptional<T>> nullableOptionals(@NotNull Iterable<T> xs) {
return addSpecialElement(NullableOptional.<T>empty(), map(NullableOptional::of, xs));
}
@Override
public @NotNull <A, B> Iterable<Pair<A, B>> pairs(@NotNull Iterable<A> as, @NotNull Iterable<B> bs) {
return zip(as, bs);
}
@Override
public @NotNull <A, B, C> Iterable<Triple<A, B, C>> triples(
@NotNull Iterable<A> as,
@NotNull Iterable<B> bs,
@NotNull Iterable<C> cs
) {
return zip3(as, bs, cs);
}
@Override
public @NotNull <A, B, C, D> Iterable<Quadruple<A, B, C, D>> quadruples(
@NotNull Iterable<A> as,
@NotNull Iterable<B> bs,
@NotNull Iterable<C> cs,
@NotNull Iterable<D> ds
) {
return zip4(as, bs, cs, ds);
}
@Override
public @NotNull <A, B, C, D, E> Iterable<Quintuple<A, B, C, D, E>> quintuples(
@NotNull Iterable<A> as,
@NotNull Iterable<B> bs,
@NotNull Iterable<C> cs,
@NotNull Iterable<D> ds,
@NotNull Iterable<E> es
) {
return zip5(as, bs, cs, ds, es);
}
@Override
public @NotNull <A, B, C, D, E, F> Iterable<Sextuple<A, B, C, D, E, F>> sextuples(
@NotNull Iterable<A> as,
@NotNull Iterable<B> bs,
@NotNull Iterable<C> cs,
@NotNull Iterable<D> ds,
@NotNull Iterable<E> es,
@NotNull Iterable<F> fs
) {
return zip6(as, bs, cs, ds, es, fs);
}
@Override
public @NotNull <A, B, C, D, E, F, G> Iterable<Septuple<A, B, C, D, E, F, G>> septuples(
@NotNull Iterable<A> as,
@NotNull Iterable<B> bs,
@NotNull Iterable<C> cs,
@NotNull Iterable<D> ds,
@NotNull Iterable<E> es,
@NotNull Iterable<F> fs,
@NotNull Iterable<G> gs
) {
return zip7(as, bs, cs, ds, es, fs, gs);
}
@Override
public @NotNull <T> Iterable<Pair<T, T>> pairs(@NotNull Iterable<T> xs) {
List<Iterable<T>> xss = demux(2, xs);
return zip(xss.get(0), xss.get(1));
}
@Override
public @NotNull <T> Iterable<Triple<T, T, T>> triples(@NotNull Iterable<T> xs) {
List<Iterable<T>> xss = demux(3, xs);
return zip3(xss.get(0), xss.get(1), xss.get(2));
}
@Override
public @NotNull <T> Iterable<Quadruple<T, T, T, T>> quadruples(@NotNull Iterable<T> xs) {
List<Iterable<T>> xss = demux(4, xs);
return zip4(xss.get(0), xss.get(1), xss.get(2), xss.get(3));
}
@Override
public @NotNull <T> Iterable<Quintuple<T, T, T, T, T>> quintuples(@NotNull Iterable<T> xs) {
List<Iterable<T>> xss = demux(5, xs);
return zip5(xss.get(0), xss.get(1), xss.get(2), xss.get(3), xss.get(4));
}
@Override
public @NotNull <T> Iterable<Sextuple<T, T, T, T, T, T>> sextuples(@NotNull Iterable<T> xs) {
List<Iterable<T>> xss = demux(6, xs);
return zip6(xss.get(0), xss.get(1), xss.get(2), xss.get(3), xss.get(4), xss.get(5));
}
@Override
public @NotNull <T> Iterable<Septuple<T, T, T, T, T, T, T>> septuples(@NotNull Iterable<T> xs) {
List<Iterable<T>> xss = demux(7, xs);
return zip7(xss.get(0), xss.get(1), xss.get(2), xss.get(3), xss.get(4), xss.get(5), xss.get(6));
}
@Override
public @NotNull <T> Iterable<List<T>> lists(int size, @NotNull Iterable<T> xs) {
if (size == 0) {
return repeat(Collections.emptyList());
} else {
return transpose(demux(size, xs));
}
}
@Override
public @NotNull <T> Iterable<List<T>> listsAtLeast(int minSize, @NotNull Iterable<T> xs) {
if (isEmpty(xs)) return Collections.singletonList(Collections.emptyList());
return () -> new Iterator<List<T>>() {
private final Iterator<T> xsi = cycle(xs).iterator();
private final Iterator<Integer> sizes = naturalIntegersGeometric(scale).iterator();
@Override
public boolean hasNext() {
return true;
}
@Override
public List<T> next() {
int size = sizes.next() + minSize;
List<T> list = new ArrayList<>();
for (int i = 0; i < size; i++) {
list.add(xsi.next());
}
return list;
}
@Override
public void remove() {
throw new UnsupportedOperationException("cannot remove from this iterator");
}
};
}
@Override
public @NotNull <T> Iterable<List<T>> lists(@NotNull Iterable<T> xs) {
if (isEmpty(xs)) return Collections.singletonList(Collections.emptyList());
return () -> new Iterator<List<T>>() {
private final Iterator<T> xsi = cycle(xs).iterator();
private final Iterator<Integer> sizes = naturalIntegersGeometric(scale).iterator();
@Override
public boolean hasNext() {
return true;
}
@Override
public List<T> next() {
int size = sizes.next();
List<T> list = new ArrayList<>();
for (int i = 0; i < size; i++) {
list.add(xsi.next());
}
return list;
}
@Override
public void remove() {
throw new UnsupportedOperationException("cannot remove from this iterator");
}
};
}
@Override
public @NotNull Iterable<String> strings(int size, @NotNull Iterable<Character> cs) {
return map(IterableUtils::charsToString, transpose(demux(size, cs)));
}
@Override
public @NotNull Iterable<String> stringsAtLeast(int minSize, @NotNull Iterable<Character> cs) {
if (isEmpty(cs)) return Arrays.asList("");
return () -> new Iterator<String>() {
private final Iterator<Character> csi = cycle(cs).iterator();
private final Iterator<Integer> sizes = naturalIntegersGeometric(scale).iterator();
@Override
public boolean hasNext() {
return true;
}
@Override
public String next() {
int size = sizes.next() + minSize;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size; i++) {
sb.append(csi.next());
}
return sb.toString();
}
@Override
public void remove() {
throw new UnsupportedOperationException("cannot remove from this iterator");
}
};
}
@Override
public @NotNull Iterable<String> strings(int size) {
return strings(size, characters());
}
@Override
public @NotNull Iterable<String> stringsAtLeast(int minSize) {
return stringsAtLeast(minSize, characters());
}
@Override
public @NotNull Iterable<String> strings(@NotNull Iterable<Character> cs) {
if (isEmpty(cs)) return Arrays.asList("");
return () -> new Iterator<String>() {
private final Iterator<Character> csi = cycle(cs).iterator();
private final Iterator<Integer> sizes = naturalIntegersGeometric(scale).iterator();
@Override
public boolean hasNext() {
return true;
}
@Override
public String next() {
int size = sizes.next();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size; i++) {
sb.append(csi.next());
}
return sb.toString();
}
@Override
public void remove() {
throw new UnsupportedOperationException("cannot remove from this iterator");
}
};
}
@Override
public @NotNull Iterable<String> strings() {
return strings(characters());
}
/**
* Determines whether {@code this} is equal to {@code that}.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>{@code that} may be any {@code Object}.</li>
* <li>The result may be either {@code boolean}.</li>
* </ul>
*
* @param that The {@code RandomProvider} to be compared with {@code this}
* @return {@code this}={@code that}
*/
@Override
public boolean equals(Object that) {
if (this == that) return true;
if (that == null || getClass() != that.getClass()) return false;
RandomProvider provider = (RandomProvider) that;
return scale == provider.scale && secondaryScale == provider.secondaryScale && seed.equals(provider.seed);
}
/**
* Calculates the hash code of {@code this}.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>(conjecture) The result may be any {@code int}.</li>
* </ul>
*
* @return {@code this}'s hash code.
*/
@Override
public int hashCode() {
int result = seed.hashCode();
result = 31 * result + scale;
result = 31 * result + secondaryScale;
return result;
}
/**
* Creates a {@code String} representation of {@code this}.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>See tests and demos for example results.</li>
* </ul>
*
* @return a {@code String} representation of {@code this}
*/
public String toString() {
return "RandomProvider[@" + new IsaacPRNG(seed).nextInt() + ", " + scale + ", " + secondaryScale + "]";
}
/**
* Ensures that {@code this} is valid. Must return true for any {@code RandomProvider} used outside this class.
*/
public void validate() {
assertEquals(toString(), seed.size(), IsaacPRNG.SIZE);
assertTrue(toString(), scale >= 0);
assertTrue(toString(), secondaryScale >= 0);
}
} |
package sword.java.class_analyzer;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import sword.java.class_analyzer.ref.ClassReference;
import sword.java.class_analyzer.ref.PackageReference;
import sword.java.class_analyzer.ref.RootReference;
public class ProjectAnalyzer {
private static final class ProgramArguments {
/**
* System dependet path to the folder where class fiels are located.
*/
public static final int CLASS_PATH = 0;
/**
* Qualified reference for a java class. It must be in the form "java.util.List"
*/
public static final int MAIN_JAVA_CLASS = 1;
public static final int LENGTH = 2;
}
private static final class ClassHolder {
public final ClassReference reference;
private boolean mChecked; // set to true if the classFile has been tried to be retrieved
private ClassFile mClassFile;
public ClassHolder(ClassReference reference) {
this.reference = reference;
if (reference == null) {
throw new IllegalArgumentException();
}
}
@Override
public int hashCode() {
return reference.hashCode();
}
@Override
public boolean equals(Object object) {
return object != null && object instanceof ClassHolder &&
reference.equals(((ClassHolder) object).reference);
}
public File getFile(File classPath) {
return reference.getFile(classPath);
}
/**
* Sets the reference in state checked. This action can only be
* performed once. The created ClassFile can be provided as a parameter.
* If the file is not expected this method con be called with a null
* reference.
* @param classFile ClassFile data structure for the file once loaded.
*/
public void setChecked(ClassFile classFile) {
if (mChecked) {
throw new UnsupportedOperationException();
}
mClassFile = classFile;
mChecked = true;
}
public boolean isChecked() {
return mChecked;
}
public boolean loaded() {
return mClassFile != null;
}
}
private static final ClassHolder findFirstNotChecked(Set<ClassHolder> holders) {
for (ClassHolder holder : holders) {
if (!holder.isChecked()) {
return holder;
}
}
return null;
}
private static void checkClassPath(File packageFile, PackageReference reference) {
final String list[] = packageFile.list();
if (list == null) return;
for (String name : list) {
File file = new File(packageFile, name);
if (file.isDirectory()) {
PackageReference newReference = reference.addPackage(name);
checkClassPath(file, newReference);
}
else if (file.isFile() && name.endsWith(ClassReference.FILE_EXTENSION) &&
name.length() > ClassReference.FILE_EXTENSION.length()) {
final int extensionPosition = name.length() - ClassReference.FILE_EXTENSION.length();
reference.addClass(name.substring(0, extensionPosition));
}
}
}
private static RootReference checkClassPath(File classPath) {
final RootReference root = new RootReference();
checkClassPath(classPath, root);
return root;
}
public static void main(String args[]) {
System.out.println("ClassAnalyzer v0.1");
if (args.length < ProgramArguments.LENGTH) {
System.out.println("Syntax: java " + ProjectAnalyzer.class.getName() + " <class-path> <full-qualified-java-class>");
System.out.println("");
}
else {
final File classPath = new File(args[ProgramArguments.CLASS_PATH]);
final RootReference dependenciesReference = new RootReference();
final ClassReference firstClass = dependenciesReference.addClass(args[ProgramArguments.MAIN_JAVA_CLASS]);
boolean error = true;
try {
if (firstClass == null || !classPath.isDirectory()) {
System.err.println("Wrong java reference provided.");
}
else {
error = false;
}
}
catch (SecurityException e) {
System.err.println("Unable to access the specified class path.");
}
if (!error) {
Set<ClassHolder> classHolders = new HashSet<ClassHolder>();
classHolders.add(new ClassHolder(firstClass));
int checkedAmount = 0;
int foundAmount = 0;
int successfullyRead = 0;
while (checkedAmount < classHolders.size()) {
final ClassHolder currentHolder = findFirstNotChecked(classHolders);
final File file = currentHolder.getFile(classPath);
InputStreamWrapper inStream = null;
ClassFile classFile = null;
try {
try {
inStream = new InputStreamWrapper(new FileInputStream(file));
foundAmount++;
System.out.println("Class " + currentHolder.reference.getQualifiedName() + " found at file " + file.getPath() + "...");
try {
classFile = new ClassFile(inStream, dependenciesReference);
successfullyRead++;
System.out.println(" Successfully loaded!");
Set<ClassReference> dependencies = classFile.getReferencedClasses();
for (ClassReference dependency : dependencies) {
classHolders.add(new ClassHolder(dependency));
System.out.println("Dependency: " + dependency.getQualifiedName());
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
inStream.close();
}
catch (IOException e) { }
}
}
catch (FileNotFoundException e) {
System.out.println("Class " + currentHolder.reference.getQualifiedName() + " not found in the classPath");
}
}
catch (FileError e) {
final int filePosition = inStream.readBytes();
System.out.println(" Error found when loading the file at position " + filePosition + " (0x" + Integer.toHexString(filePosition) + ')');
e.printStackTrace();
}
currentHolder.setChecked(classFile);
checkedAmount++;
}
System.out.println("");
System.out.println("Classes referenced and found in classPath:");
for (ClassHolder holder : classHolders) {
if (holder.loaded()) {
System.out.println(" " + holder.reference.getQualifiedName());
}
}
System.out.println("");
System.out.println("Classes referenced but not found in classPath:");
for (ClassHolder holder : classHolders) {
if (!holder.loaded()) {
System.out.println(" " + holder.reference.getQualifiedName());
}
}
System.out.println("");
System.out.println("Referenced " + checkedAmount + " classes. " +
foundAmount + " classes found in the classpath " + classPath +
" and " + successfullyRead + " read with no major errors.");
final RootReference classesInPath = checkClassPath(classPath);
Set<ClassReference> inPathSet = classesInPath.setOfClasses();
System.out.println("Found " + inPathSet.size() + " classes in the class path");
inPathSet.removeAll(dependenciesReference.setOfClasses());
System.out.println("Found " + inPathSet.size() + " files not referenced:");
for (ClassReference ref : inPathSet) {
System.out.println(" " + ref.getQualifiedName());
}
}
}
}
} |
// $Id: ResourceManager.java,v 1.34 2003/08/09 05:51:12 mdb Exp $
package com.threerings.resource;
import java.awt.EventQueue;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.StringTokenizer;
import javax.imageio.stream.FileImageInputStream;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.MemoryCacheImageInputStream;
import com.samskivert.util.ResultListener;
import com.samskivert.util.StringUtil;
import com.threerings.resource.DownloadManager.DownloadDescriptor;
import com.threerings.resource.DownloadManager.DownloadObserver;
/**
* The resource manager is responsible for maintaining a repository of
* resources that are synchronized with a remote source. This is
* accomplished in the form of sets of jar files (resource bundles) that
* contain resources and that are updated from a remote resource
* repository via HTTP. These resource bundles are organized into
* resource sets. A resource set contains one or more resource bundles and
* is defined much like a classpath.
*
* <p> The resource manager can load resources from the default resource
* set, and can make available named resource sets to entities that wish
* to do their own resource loading. If the resource manager fails to
* locate a resource in the default resource set, it falls back to loading
* the resource via the classloader (which will search the classpath).
*
* <p> Applications that wish to make use of resource sets and their
* associated bundles must call {@link #initBundles} after constructing
* the resource manager, providing the URL of a resource definition file
* which describes these resource sets. The definition file will be loaded
* and the resource bundles defined within will be loaded relative to the
* resource definition URL. The bundles will be cached in the user's home
* directory and only reloaded when the source resources have been
* updated. The resource definition file looks something like the
* following:
*
* <pre>
* resource.set.default = sets/misc/config.jar: \
* sets/misc/icons.jar
* resource.set.tiles = sets/tiles/ground.jar: \
* sets/tiles/objects.jar: \
* /global/resources/tiles/ground.jar: \
* /global/resources/tiles/objects.jar
* resource.set.sounds = sets/sounds/sfx.jar: \
* sets/sounds/music.jar: \
* /global/resources/sounds/sfx.jar: \
* /global/resources/sounds/music.jar
* </pre>
*
* <p> All resource set definitions are prefixed with
* <code>resource.set.</code> and all text following that string is
* considered to be the name of the resource set. The resource set named
* <code>default</code> is the default resource set and is the one that is
* searched for resources is a call to {@link #getResource}.
*
* <p> When a resource is loaded from a resource set, the set is searched
* in the order that entries are specified in the definition.
*/
public class ResourceManager
{
/**
* Provides facilities for notifying an observer of resource bundle
* download progress.
*/
public interface BundleDownloadObserver
{
/**
* If this method returns true the download observer callbacks
* will be called on the AWT thread, allowing the observer to do
* things like safely update user interfaces, etc. If false, it
* will be called on a special download thread.
*/
public boolean notifyOnAWTThread ();
/**
* Called when the resource manager is about to check for an
* update of any of our resource sets.
*/
public void checkingForUpdate ();
/**
* Called to inform the observer of ongoing progress toward
* completion of the overall bundle downloading task. The caller
* is guaranteed to get at least one call reporting 100%
* completion.
*
* @param percent the percent completion of the download.
* @param remaining the estimated download time remaining in
* seconds, or <code>-1</code> if the time can not yet be
* determined.
*/
public void downloadProgress (int percent, long remaining);
/**
* Called to inform the observer that the bundle patching process
* has begun. This follows the download phase, but is optional.
*/
public void patching ();
/**
* Called to inform the observer that the bundle unpacking process
* has begun. This follows the download or patching phase.
*/
public void unpacking ();
/**
* Called to indicate that we have validated and unpacked our
* bundles and are fully ready to go. A call to {@link
* #dowloadProgress} with 100 percent completion is guaranteed to
* precede this call and optionally one to {@link #patching} and
* {@link #unpacking}.
*/
public void downloadComplete ();
/**
* Called if a failure occurs while checking for an update or
* downloading all resource sets.
*/
public void downloadFailed (Exception e);
}
/**
* Constructs a resource manager which will load resources via the
* classloader, prepending <code>resourceRoot</code> to their path.
*
* @param resourceRoot the path to prepend to resource paths prior to
* attempting to load them via the classloader. When resources are
* bundled into the default resource bundle, they don't need this
* prefix, but if they're to be loaded from the classpath, it's likely
* that they'll live in some sort of <code>resources</code> directory
* to isolate them from the rest of the files in the classpath. This
* is not a platform dependent path (forward slash is always used to
* separate path elements).
*/
public ResourceManager (String resourceRoot)
{
// keep track of our root path
_rootPath = resourceRoot;
// make root path end with a slash (not the platform dependent
// file system separator character as resource paths are passed to
// ClassLoader.getResource() which requires / as its separator)
if (!_rootPath.endsWith("/")) {
_rootPath = _rootPath + "/";
}
// use the classloader that loaded us
_loader = getClass().getClassLoader();
// set up a URL handler so that things can be loaded via
// urls with the 'resource' protocol
Handler.registerHandler(this);
// sort our our default cache path
_baseCachePath = "";
try {
// first check for an explicitly specified cache directory
_baseCachePath = System.getProperty("narya.resource.cache_dir");
// if that's null, try putting it into their home directory
if (_baseCachePath == null) {
_baseCachePath = System.getProperty("user.home");
}
if (!_baseCachePath.endsWith(File.separator)) {
_baseCachePath += File.separator;
}
_baseCachePath += (CACHE_PATH + File.separator);
} catch (SecurityException se) {
Log.info("Can't obtain user.home system property. Probably " +
"won't be able to create our cache directory " +
"either. [error=" + se + "].");
}
}
/**
* Instructs the resource manager to store cached resources in the
* specified directory. This must be called before {@link
* #initBundles} if it is going to be called at all. If it is not
* called, the default cache directory will be used.
*/
public void setCachePath (String cachePath)
{
if (!cachePath.endsWith(File.separator)) {
cachePath += File.separator;
}
_baseCachePath = cachePath;
}
/**
* Initializes the bundle sets to be made available by this resource
* manager. Applications that wish to make use of resource bundles
* should call this method after constructing the resource manager.
*
* @param resourceURL the base URL from which resources are loaded.
* Relative paths specified in the resource definition file will be
* loaded relative to this path. If this is null, the system property
* <code>resource_url</code> will be used, if available.
* @param configPath the path (relative to the resource URL) of the
* resource definition file.
* @param version the version of the resource bundles to be
* downloaded.
* @param downloadObs the bundle download observer to notify of
* download progress and success or failure, or <code>null</code> if
* the caller doesn't care to be informed; note that in the latter
* case, the calling thread will block until bundle updating is
* complete.
*/
public void initBundles (String resourceURL, String configPath,
String version, BundleDownloadObserver downloadObs)
{
_version = version;
// if the resource URL wasn't provided, we try to figure it out
// for ourselves
if (resourceURL == null) {
try {
// first look for the explicit system property
resourceURL = System.getProperty("resource_url");
// if that doesn't work, fall back to the current directory
if (resourceURL == null) {
resourceURL = "file:" + System.getProperty("user.dir");
}
} catch (SecurityException se) {
resourceURL = "file:" + File.separator;
}
}
// make sure there's a slash at the end of the URL
if (!resourceURL.endsWith("/")) {
resourceURL += "/";
}
try {
_rurl = new URL(resourceURL);
} catch (MalformedURLException mue) {
Log.warning("Invalid resource URL [url=" + resourceURL +
", error=" + mue + "].");
}
// now attempt to locate the dynamic resource URL
try {
String dynResURL = System.getProperty("dyn_rsrc_url");
if (dynResURL != null) {
// make sure there's a slash at the end of the URL
if (!dynResURL.endsWith("/")) {
dynResURL += "/";
}
try {
_drurl = new URL(dynResURL);
} catch (MalformedURLException mue) {
Log.warning("Invalid dynamic resource URL " +
"[url=" + dynResURL + ", error=" + mue + "].");
}
}
} catch (SecurityException se) {
}
// if no dynamic resource URL was specified, use the normal
// resource URL in its stead
if (_drurl == null) {
_drurl = _rurl;
}
Log.debug("Resource manager ready [rurl=" + _rurl +
", drurl=" + _drurl + "].");
// load up our configuration
Properties config = loadConfig(configPath);
// resolve the configured resource sets
ArrayList dlist = new ArrayList();
Enumeration names = config.propertyNames();
while (names.hasMoreElements()) {
String key = (String)names.nextElement();
if (!key.startsWith(RESOURCE_SET_PREFIX)) {
continue;
}
String setName = key.substring(RESOURCE_SET_PREFIX.length());
resolveResourceSet(setName, config.getProperty(key), dlist);
}
// start the download, blocking if we've no observer
DownloadManager dlmgr = new DownloadManager();
if (downloadObs == null) {
downloadBlocking(dlmgr, dlist);
} else {
downloadNonBlocking(dlmgr, dlist, downloadObs);
}
}
/**
* Create the resource bundle for the specified set and path.
*/
protected ResourceBundle createResourceBundle (String setName, String path)
{
createCacheDirectory(setName);
File cfile = new File(genCachePath(setName, path));
return new ResourceBundle(cfile, true, true);
}
/**
* Checks to see if the specified dynamic bundle is already here
* and ready to roll.
*/
public boolean checkDynamicBundle (String path)
{
return createResourceBundle(DYNAMIC_BUNDLE_SET, path).isUnpacked();
}
/**
* Resolve the specified dynamic bundle and return it on the specified
* result listener.
*/
public void resolveDynamicBundle (String path, String version,
final ResultListener listener)
{
URL burl;
try {
burl = new URL(_drurl, path);
} catch (MalformedURLException mue) {
listener.requestFailed(mue);
return;
}
final ResourceBundle bundle = createResourceBundle(
DYNAMIC_BUNDLE_SET, path);
if (bundle.isUnpacked()) {
if (bundle.sourceIsReady()) {
listener.requestCompleted(bundle);
} else {
String errmsg = "Bundle initialization failed.";
listener.requestFailed(new IOException(errmsg));
}
return;
}
// slap this on the list for retrieval or update by the download
// manager
ArrayList list = new ArrayList();
list.add(new DownloadDescriptor(burl, bundle.getSource(), version));
// TODO: There should only be one download manager for all dynamic
// bundles, with each bundle waiting its turn to use it.
DownloadObserver obs = new DownloadObserver() {
public boolean notifyOnAWTThread () {
return false;
}
public void resolvingDownloads () {
}
public void downloadProgress (int percent, long remaining) {
}
public void patching () {
}
public void postDownloadHook () {
}
public void downloadComplete ()
{
final boolean unpacked = bundle.sourceIsReady();
EventQueue.invokeLater(new Runnable() {
public void run () {
if (unpacked) {
listener.requestCompleted(bundle);
} else {
String errmsg = "Bundle initialization failed.";
listener.requestFailed(new IOException(errmsg));
}
}
});
}
public void downloadFailed (
DownloadDescriptor desc, final Exception e)
{
Log.warning("Failed to download file " +
"[desc=" + desc + ", e=" + e + "].");
EventQueue.invokeLater(new Runnable() {
public void run () {
listener.requestFailed(e);
}
});
}
};
DownloadManager dlmgr = new DownloadManager();
dlmgr.download(list, true, obs);
}
/**
* Downloads the files in the supplied download list, blocking the
* calling thread until the download is complete or a failure has
* occurred.
*/
protected void downloadBlocking (DownloadManager dlmgr, List dlist)
{
// create an object to wait on while the download takes place
final Object lock = new Object();
// create the observer that will notify us when all is finished
DownloadObserver obs = new DownloadObserver() {
public boolean notifyOnAWTThread () {
return false;
}
public void resolvingDownloads () {
// nothing for now
}
public void downloadProgress (int percent, long remaining) {
// nothing for now
}
public void patching () {
// nothing for now
}
public void postDownloadHook () {
bundlesDownloaded();
}
public void downloadComplete () {
synchronized (lock) {
// wake things up as the download is finished
lock.notify();
}
}
public void downloadFailed (DownloadDescriptor desc, Exception e) {
Log.warning("Failed to download file " +
"[desc=" + desc + ", e=" + e + "].");
synchronized (lock) {
// wake things up since we're fragile and so a
// single failure means all is booched
lock.notify();
}
}
};
synchronized (lock) {
// pass the descriptors on to the download manager
dlmgr.download(dlist, true, obs);
try {
// block until the download has completed
lock.wait();
} catch (InterruptedException ie) {
Log.warning("Thread interrupted while waiting for download " +
"to complete [ie=" + ie + "].");
}
}
}
/**
* Downloads the files in the supplied download list asynchronously,
* notifying the download observer of ongoing progress.
*/
protected void downloadNonBlocking (
DownloadManager dlmgr, List dlist, final BundleDownloadObserver obs)
{
// pass the descriptors on to the download manager
dlmgr.download(dlist, true, new DownloadObserver() {
public boolean notifyOnAWTThread () {
return obs.notifyOnAWTThread();
}
public void resolvingDownloads () {
obs.checkingForUpdate();
}
public void downloadProgress (int percent, long remaining) {
obs.downloadProgress(percent, remaining);
}
public void patching () {
obs.patching();
}
public void postDownloadHook () {
obs.unpacking();
_unpacked = bundlesDownloaded();
}
public void downloadComplete () {
if (_unpacked) {
obs.downloadComplete();
} else {
String errmsg = "Bundle(s) failed initialization.";
obs.downloadFailed(new IOException(errmsg));
}
}
public void downloadFailed (DownloadDescriptor desc, Exception e) {
obs.downloadFailed(e);
}
protected boolean _unpacked;
});
}
/**
* Called when our resource bundle downloads have completed.
*
* @return true if we are fully operational, false if one or more
* bundles failed to initialize.
*/
protected boolean bundlesDownloaded ()
{
// let our bundles know that it's ok for them to access their
// resource files
Iterator iter = _sets.values().iterator();
boolean unpacked = true;
while (iter.hasNext()) {
ResourceBundle[] bundles = (ResourceBundle[])iter.next();
for (int ii = 0; ii < bundles.length; ii++) {
unpacked = bundles[ii].sourceIsReady() && unpacked;
}
}
return unpacked;
}
/**
* Loads up the most recent version of the resource manager
* configuration.
*/
protected Properties loadConfig (String configPath)
{
Properties config = new Properties();
URL curl = null;
try {
if (configPath != null) {
curl = new URL(_rurl, configPath);
config.load(curl.openStream());
}
} catch (MalformedURLException mue) {
Log.warning("Unable to construct config URL " +
"[resourceURL=" + _rurl +
", configPath=" + configPath +
", error=" + mue + "].");
} catch (IOException ioe) {
// complain if some other error occurs
Log.warning("Error loading resource manager configuration " +
"[url=" + curl + ", error=" + ioe + "].");
}
return config;
}
/**
* Ensures that the cache directory for the specified resource set is
* created.
*
* @return true if the directory was successfully created (or was
* already there), false if we failed to create it.
*/
protected boolean createCacheDirectory (String setName)
{
// compute the path to the top-level cache directory if we haven't
// already been so configured
if (_cachePath == null) {
// start with the base cache path
_cachePath = _baseCachePath;
if (!createDirectory(_cachePath)) {
return false;
}
// next incorporate the resource URL into the cache path so
// that files fetched from different resource roots do not
// overwrite one another
_cachePath += StringUtil.md5hex(_rurl.toString()) + File.separator;
if (!createDirectory(_cachePath)) {
return false;
}
Log.debug("Caching bundles in '" + _cachePath + "'.");
}
// ensure that the set-specific cache directory exists
return createDirectory(_cachePath + setName);
}
/**
* Creates the specified directory if it doesn't already exist.
*
* @return true if directory was created (or existed), false if not.
*/
protected boolean createDirectory (String path)
{
File cdir = new File(path);
if (cdir.exists()) {
if (!cdir.isDirectory()) {
Log.warning("Cache dir exists but isn't a directory?! " +
"[path=" + path + "].");
return false;
}
} else {
if (!cdir.mkdirs()) {
Log.warning("Unable to create cache dir. " +
"[path=" + path + "].");
return false;
}
}
return true;
}
/**
* Generates the name of the bundle cache file given the name of the
* resource set to which it belongs and the relative path URL.
*/
protected String genCachePath (String setName, String resourcePath)
{
return _cachePath + setName + File.separator +
StringUtil.replace(resourcePath, "/", "-");
}
/**
* Loads up a resource set based on the supplied definition
* information.
*/
protected void resolveResourceSet (
String setName, String definition, List dlist)
{
StringTokenizer tok = new StringTokenizer(definition, ":");
ArrayList set = new ArrayList();
while (tok.hasMoreTokens()) {
String path = tok.nextToken().trim();
URL burl = null;
try {
burl = new URL(_rurl, path);
// make sure the cache directory exists for this set
createCacheDirectory(setName);
// compute the path to the cache file for this bundle
File cfile = new File(genCachePath(setName, path));
// slap this on the list for retrieval or update by the
// download manager
dlist.add(new DownloadDescriptor(burl, cfile, _version));
// finally, add the file that will be cached to the set as
// a resource bundle
set.add(new ResourceBundle(cfile, true, true));
} catch (MalformedURLException mue) {
Log.warning("Unable to create URL for resource " +
"[set=" + setName + ", path=" + path +
", error=" + mue + "].");
}
}
// convert our array list into an array and stick it in the table
ResourceBundle[] setvec = new ResourceBundle[set.size()];
set.toArray(setvec);
_sets.put(setName, setvec);
// if this is our default resource bundle, keep a reference to it
if (DEFAULT_RESOURCE_SET.equals(setName)) {
_default = setvec;
}
}
/**
* Fetches a resource from the local repository.
*
* @param path the path to the resource
* (ie. "config/miso.properties"). This should not begin with a slash.
*
* @exception IOException thrown if a problem occurs locating or
* reading the resource.
*/
public InputStream getResource (String path)
throws IOException
{
InputStream in = null;
// first look for this resource in our default resource bundle
for (int i = 0; i < _default.length; i++) {
in = _default[i].getResource(path);
if (in != null) {
return in;
}
}
// if we didn't find anything, try the classloader
String rpath = _rootPath + path;
in = _loader.getResourceAsStream(rpath);
if (in != null) {
return in;
}
// if we still haven't found it, we throw an exception
String errmsg = "Unable to locate resource [path=" + path + "]";
throw new FileNotFoundException(errmsg);
}
/**
* Fetches the specified resource as an {@link ImageInputStream} and
* one that takes advantage, if possible, of caching of unpacked
* resources on the local filesystem.
*
* @exception FileNotFoundException thrown if the resource could not
* be located in any of the bundles in the specified set, or if the
* specified set does not exist.
* @exception IOException thrown if a problem occurs locating or
* reading the resource.
*/
public ImageInputStream getImageResource (String path)
throws IOException
{
// first look for this resource in our default resource bundle
for (int i = 0; i < _default.length; i++) {
File file = _default[i].getResourceFile(path);
if (file != null) {
return new FileImageInputStream(file);
}
}
// if we didn't find anything, try the classloader
String rpath = _rootPath + path;
InputStream in = _loader.getResourceAsStream(rpath);
if (in != null) {
return new MemoryCacheImageInputStream(new BufferedInputStream(in));
}
// if we still haven't found it, we throw an exception
String errmsg = "Unable to locate image resource [path=" + path + "]";
throw new FileNotFoundException(errmsg);
}
/**
* Returns an input stream from which the requested resource can be
* loaded. <em>Note:</em> this performs a linear search of all of the
* bundles in the set and returns the first resource found with the
* specified path, thus it is not extremely efficient and will behave
* unexpectedly if you use the same paths in different resource
* bundles.
*
* @exception FileNotFoundException thrown if the resource could not
* be located in any of the bundles in the specified set, or if the
* specified set does not exist.
* @exception IOException thrown if a problem occurs locating or
* reading the resource.
*/
public InputStream getResource (String rset, String path)
throws IOException
{
// grab the resource bundles in the specified resource set
ResourceBundle[] bundles = getResourceSet(rset);
if (bundles == null) {
throw new FileNotFoundException(
"Unable to locate resource [set=" + rset +
", path=" + path + "]");
}
// look for the resource in any of the bundles
int size = bundles.length;
for (int ii = 0; ii < size; ii++) {
InputStream instr = bundles[ii].getResource(path);
if (instr != null) {
// Log.info("Found resource [rset=" + rset +
// ", bundle=" + bundles[ii].getSource().getPath() +
// ", path=" + path + ", in=" + instr + "].");
return instr;
}
}
throw new FileNotFoundException(
"Unable to locate resource [set=" + rset + ", path=" + path + "]");
}
/**
* Fetches the specified resource as an {@link ImageInputStream} and
* one that takes advantage, if possible, of caching of unpacked
* resources on the local filesystem.
*
* @exception FileNotFoundException thrown if the resource could not
* be located in any of the bundles in the specified set, or if the
* specified set does not exist.
* @exception IOException thrown if a problem occurs locating or
* reading the resource.
*/
public ImageInputStream getImageResource (String rset, String path)
throws IOException
{
// grab the resource bundles in the specified resource set
ResourceBundle[] bundles = getResourceSet(rset);
if (bundles == null) {
throw new FileNotFoundException(
"Unable to locate image resource [set=" + rset +
", path=" + path + "]");
}
// look for the resource in any of the bundles
int size = bundles.length;
for (int ii = 0; ii < size; ii++) {
File file = bundles[ii].getResourceFile(path);
if (file != null) {
// Log.info("Found image resource [rset=" + rset +
// ", bundle=" + bundles[ii].getSource() +
// ", path=" + path + ", file=" + file + "].");
return new FileImageInputStream(file);
}
}
String errmsg = "Unable to locate image resource [set=" + rset +
", path=" + path + "]";
throw new FileNotFoundException(errmsg);
}
/**
* Returns a reference to the resource set with the specified name, or
* null if no set exists with that name. Services that wish to load
* their own resources can allow the resource manager to load up a
* resource set for them, from which they can easily load their
* resources.
*/
public ResourceBundle[] getResourceSet (String name)
{
return (ResourceBundle[])_sets.get(name);
}
/** The classloader we use for classpath-based resource loading. */
protected ClassLoader _loader;
/** The version of the resource bundles we'll be downloading. */
protected String _version;
/** The url via which we download our bundles. */
protected URL _rurl;
/** The url via which we download our dynamically generated bundles. */
protected URL _drurl;
/** The prefix we prepend to resource paths before attempting to load
* them from the classpath. */
protected String _rootPath;
/** The path to the directory that will contain our bundle cache. */
protected String _baseCachePath;
/** The path to our bundle cache directory. */
protected String _cachePath;
/** Our default resource set. */
protected ResourceBundle[] _default = new ResourceBundle[0];
/** A table of our resource sets. */
protected HashMap _sets = new HashMap();
/** The prefix of configuration entries that describe a resource
* set. */
protected static final String RESOURCE_SET_PREFIX = "resource.set.";
/** The name of the default resource set. */
protected static final String DEFAULT_RESOURCE_SET = "default";
/** The name of our resource bundle cache directory. */
protected static final String CACHE_PATH = ".narya";
/** The name of the resource set where we store dynamic bundles. */
protected static final String DYNAMIC_BUNDLE_SET = "_dynamic";
} |
package mho.wheels.iterables;
import mho.wheels.math.MathUtils;
import mho.wheels.ordering.Ordering;
import mho.wheels.random.IsaacPRNG;
import mho.wheels.structures.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.*;
import static mho.wheels.iterables.IterableUtils.*;
import static mho.wheels.ordering.Ordering.*;
import static mho.wheels.ordering.Ordering.lt;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* <p>A {@code RandomProvider} produces {@code Iterable}s that randomly generate some set of values with a specified
* distribution. A {@code RandomProvider} is deterministic, but not immutable: its state changes every time a random
* value is generated. It may be reverted to its original state with {@link RandomProvider#reset}.
*
* <p>{@code RandomProvider} uses the cryptographically-secure ISAAC pseudorandom number generator, implemented in
* {@link mho.wheels.random.IsaacPRNG}. The source of its randomness is a {@code int[]} seed. It contains two scale
* parameters which some of the distributions depend on; the exact relationship between the parameters and the
* distributions is specified in the distribution's documentation.
*
* <p>To create an instance which shares a generator with {@code this}, use {@link RandomProvider#copy()}. To create
* an instance which copies the generator, use {@link RandomProvider#deepCopy()}.
*
* <p>Note that sometimes the documentation will say things like "returns an {@code Iterable} containing all
* {@code String}s". This cannot strictly be true, since {@link java.util.Random} has a finite period, and will
* therefore produce only a finite number of {@code String}s. So in general, the documentation often pretends that the
* source of randomness is perfect (but still deterministic).
*/
public final strictfp class RandomProvider extends IterableProvider {
/**
* A list of all {@code Ordering}s.
*/
private static final List<Ordering> ORDERINGS = toList(ExhaustiveProvider.INSTANCE.orderings());
/**
* A list of all {@code RoundingMode}s.
*/
private static final List<RoundingMode> ROUNDING_MODES = toList(ExhaustiveProvider.INSTANCE.roundingModes());
/**
* The default value of {@code scale}.
*/
private static final int DEFAULT_SCALE = 32;
/**
* The default value of {@code secondaryScale}.
*/
private static final int DEFAULT_SECONDARY_SCALE = 8;
/**
* Sometimes a "special element" (for example, null) is inserted into an {@code Iterable} with some probability.
* That probability is 1/{@code SPECIAL_ELEMENT_RATIO}.
*/
private static final int SPECIAL_ELEMENT_RATIO = 50;
/**
* A list of numbers which determines exactly which values will be deterministically output over the life of
* {@code this}. It must have length {@link mho.wheels.random.IsaacPRNG#SIZE}.
*/
private final @NotNull List<Integer> seed;
/**
* A pseudorandom number generator. It changes state every time a random number is generated.
*/
private @NotNull IsaacPRNG prng;
/**
* A parameter that determines the size of some of the generated objects.
*/
private int scale = DEFAULT_SCALE;
/**
* Another parameter that determines the size of some of the generated objects.
*/
private int secondaryScale = DEFAULT_SECONDARY_SCALE;
/**
* Constructs a {@code RandomProvider} with a seed generated from the current system time.
*
* <ul>
* <li>(conjecture) Any {@code RandomProvider} with default {@code scale} and {@code secondaryScale} may be
* constructed with this constructor.</li>
* </ul>
*/
public RandomProvider() {
prng = new IsaacPRNG();
seed = new ArrayList<>();
for (int i = 0; i < IsaacPRNG.SIZE; i++) {
seed.add(prng.nextInt());
}
prng = new IsaacPRNG(seed);
}
/**
* Constructs a {@code RandomProvider} with a given seed.
*
* <ul>
* <li>{@code seed} must have length {@link mho.wheels.random.IsaacPRNG#SIZE}.</li>
* <li>Any {@code RandomProvider} with default {@code scale} and {@code secondaryScale} may be constructed with
* this constructor.</li>
* </ul>
*
* @param seed the source of randomness
*/
public RandomProvider(@NotNull List<Integer> seed) {
if (seed.size() != IsaacPRNG.SIZE) {
throw new IllegalArgumentException("seed must have length mho.wheels.random.IsaacPRNG#SIZE, which is " +
IsaacPRNG.SIZE + ". Length of invalid seed: " + seed.size());
}
this.seed = seed;
prng = new IsaacPRNG(seed);
}
/**
* A {@code RandomProvider} used for testing. This allows for deterministic testing without manually setting up a
* lengthy seed each time.
*/
public static @NotNull RandomProvider example() {
IsaacPRNG prng = IsaacPRNG.example();
List<Integer> seed = new ArrayList<>();
for (int i = 0; i < IsaacPRNG.SIZE; i++) {
seed.add(prng.nextInt());
}
return new RandomProvider(seed);
}
/**
* Returns {@code this}'s scale parameter.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result may be any {@code int}.</li>
* </ul>
*
* @return the scale parameter of {@code this}
*/
public int getScale() {
return scale;
}
/**
* Returns {@code this}'s other scale parameter.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result may be any {@code int}.</li>
* </ul>
*
* @return the other scale parameter of {@code this}
*/
public int getSecondaryScale() {
return secondaryScale;
}
/**
* Returns {@code this}'s seed. Makes a defensive copy.
*
* <ul>
* <li>The result is an array of {@link mho.wheels.random.IsaacPRNG#SIZE} {@code int}s.</li>
* </ul>
*
* @return the seed of {@code this}
*/
public @NotNull List<Integer> getSeed() {
return toList(seed);
}
/**
* A {@code RandomProvider} with the same fields as {@code this}. The copy shares {@code prng} with the original.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is not null.</li>
* </ul>
*
* @return A copy of {@code this}.
*/
public @NotNull RandomProvider copy() {
RandomProvider copy = new RandomProvider(seed);
copy.scale = scale;
copy.secondaryScale = secondaryScale;
copy.prng = prng;
return copy;
}
/**
* A {@code RandomProvider} with the same fields as {@code this}. The copy receives a new copy of {@code prng},
* so generating values from the copy will not affect the state of the original's {@code prng}.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is not null.</li>
* </ul>
*
* @return A copy of {@code this}.
*/
public @NotNull RandomProvider deepCopy() {
RandomProvider copy = new RandomProvider(seed);
copy.scale = scale;
copy.secondaryScale = secondaryScale;
copy.prng = prng.copy();
return copy;
}
/**
* A {@code RandomProvider} with the same fields as {@code this} except for a new scale.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>{@code scale} may be any {@code int}.</li>
* <li>The result is not null.</li>
* </ul>
*
* @param scale the new scale
* @return A copy of {@code this} with a new scale
*/
@Override
public @NotNull RandomProvider withScale(int scale) {
RandomProvider copy = copy();
copy.scale = scale;
return copy;
}
/**
* A {@code RandomProvider} with the same fields as {@code this} except for a new secondary scale.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>{@code secondaryScale} mat be any {@code int}.</li>
* <li>The result is not null.</li>
* </ul>
*
* @param secondaryScale the new secondary scale
* @return A copy of {@code this} with a new secondary scale
*/
@Override
public @NotNull RandomProvider withSecondaryScale(int secondaryScale) {
RandomProvider copy = copy();
copy.secondaryScale = secondaryScale;
return copy;
}
/**
* Put the {@code prng} back in its original state. Creating a {@code RandomProvider}, generating some values,
* resetting, and generating the same types of values again will result in the same values.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is not null.</li>
* </ul>
*/
@Override
public void reset() {
prng = new IsaacPRNG(seed);
}
/**
* Returns an id which has a good chance of being different in two instances with unequal {@code prng}s. It's used
* in {@link RandomProvider#toString()} to distinguish between different {@code RandomProvider} instances.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>{@code this} may be any {@code long}.</li>
* </ul>
*/
public long getId() {
return prng.getId();
}
/**
* Returns a randomly-generated {@code int} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result may be any {@code int}.</li>
* </ul>
*
* @return an {@code int}
*/
public int nextInt() {
return prng.nextInt();
}
/**
* An {@code Iterable} that generates all {@code Integer}s from a uniform distribution. Does not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Integer> integers() {
return fromSupplier(this::nextInt);
}
/**
* Returns a randomly-generated {@code long} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result may be any {@code long}.</li>
* </ul>
*
* @return a {@code long}
*/
public long nextLong() {
int a = nextInt();
int b = nextInt();
return (long) a << 32 | b & 0xffffffffL;
}
/**
* An {@code Iterable} that generates all {@code Long}s from a uniform distribution. Does not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Long> longs() {
return fromSupplier(this::nextLong);
}
/**
* Returns a randomly-generated {@code boolean} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result may be either {@code boolean}.</li>
* </ul>
*
* @return a {@code boolean}
*/
public boolean nextBoolean() {
return (nextInt() & 1) != 0;
}
/**
* An {@code Iterator} that generates both {@code Boolean}s from a uniform distribution. Does not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Boolean> booleans() {
return fromSupplier(this::nextBoolean);
}
private int nextIntPow2(int bits) {
return nextInt() & ((1 << bits) - 1);
}
private @NotNull Iterable<Integer> intsPow2(int bits) {
int mask = (1 << bits) - 1;
return map(i -> i & mask, integers());
}
private long nextLongPow2(int bits) {
return nextLong() & ((1L << bits) - 1);
}
private @NotNull Iterable<Long> longsPow2(int bits) {
long mask = (1L << bits) - 1;
return map(l -> l & mask, longs());
}
private @NotNull BigInteger nextBigIntegerPow2(int bits) {
byte[] bytes = new byte[bits / 8 + 1];
int x = 0;
for (int i = 0; i < bytes.length; i++) {
if (i % 4 == 0) {
x = nextInt();
}
bytes[i] = (byte) x;
x >>= 8;
}
bytes[0] &= (1 << (bits % 8)) - 1;
return new BigInteger(bytes);
}
private @NotNull Iterable<BigInteger> bigIntegersPow2(int bits) {
return fromSupplier(() -> this.nextBigIntegerPow2(bits));
}
private int nextIntBounded(int n) {
int i;
do {
i = nextIntPow2(MathUtils.ceilingLog2(n));
} while (i >= n);
return i;
}
private @NotNull Iterable<Integer> integersBounded(int n) {
return filter(i -> i < n, intsPow2(MathUtils.ceilingLog2(n)));
}
private long nextLongBounded(long n) {
long l;
do {
l = nextLongPow2(MathUtils.ceilingLog2(n));
} while (l >= n);
return l;
}
private @NotNull Iterable<Long> longsBounded(long n) {
return filter(l -> l < n, longsPow2(MathUtils.ceilingLog2(n)));
}
private @NotNull BigInteger nextBigIntegerBounded(@NotNull BigInteger n) {
int maxBits = MathUtils.ceilingLog2(n);
BigInteger i;
do {
i = nextBigIntegerPow2(maxBits);
} while (ge(i, n));
return i;
}
private @NotNull Iterable<BigInteger> bigIntegersBounded(@NotNull BigInteger n) {
return filter(i -> lt(i, n), bigIntegersPow2(MathUtils.ceilingLog2(n)));
}
/**
* Returns a randomly-generated value taken from a given list.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>{@code xs} cannot be empty.</li>
* <li>The result may be any value of type {@code T}, or null.</li>
* </ul>
*
* @param xs the source list
* @param <T> the type of {@code xs}'s elements
* @return a value from {@code xs}
*/
public @Nullable <T> T nextUniformSample(@NotNull List<T> xs) {
return xs.get(nextFromRange(0, xs.size() - 1));
}
/**
* An {@code Iterable} that uniformly generates elements from a (possibly null-containing) list.
*
* <ul>
* <li>{@code xs} cannot be null.</li>
* <li>The result is non-removable and either empty or infinite.</li>
* </ul>
*
* Length is 0 if {@code xs} is empty, infinite otherwise
*
* @param xs the source list
* @param <T> the type of {@code xs}'s elements
* @return uniformly-distributed elements of {@code xs}
*/
@Override
public @NotNull <T> Iterable<T> uniformSample(@NotNull List<T> xs) {
return map(xs::get, range(0, xs.size() - 1));
}
/**
* Returns a randomly-generated character taken from a given {@code String}.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>{@code s} cannot be empty.</li>
* <li>The result may be any {@code char}.</li>
* </ul>
*
* @param s the source {@code String}
* @return a {@code char} from {@code s}
*/
public char nextUniformSample(@NotNull String s) {
return s.charAt(nextFromRange(0, s.length() - 1));
}
/**
* An {@code Iterable} that uniformly generates {@code Character}s from a {@code String}.
*
* <ul>
* <li>{@code xs} cannot be null.</li>
* <li>The result is an empty or infinite non-removable {@code Iterable} containing {@code Character}s.</li>
* </ul>
*
* Length is 0 if {@code s} is empty, infinite otherwise
*
* @param s the source {@code String}
* @return uniformly-distributed {@code Character}s from {@code s}
*/
@Override
public @NotNull Iterable<Character> uniformSample(@NotNull String s) {
return map(s::charAt, range(0, s.length() - 1));
}
/**
* Returns a randomly-generated {@code Ordering} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is not null.</li>
* </ul>
*
* @return an {@code Ordering}
*/
public @NotNull Ordering nextOrdering() {
//noinspection ConstantConditions
return nextUniformSample(ORDERINGS);
}
/**
* An {@code Iterator} that generates all {@code Ordering}s from a uniform distribution. Does not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Ordering> orderings() {
return uniformSample(ORDERINGS);
}
/**
* Returns a randomly-generated {@code RoundingMode} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is not null.</li>
* </ul>
*
* @return a {@code RoundingMode}
*/
public @NotNull RoundingMode nextRoundingMode() {
//noinspection ConstantConditions
return nextUniformSample(ROUNDING_MODES);
}
/**
* An {@code Iterable} that generates all {@code RoundingMode}s from a uniform distribution. Does not support
* removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<RoundingMode> roundingModes() {
return uniformSample(ROUNDING_MODES);
}
public byte nextPositiveByte() {
byte b;
do {
b = nextNaturalByte();
} while (b == 0);
return b;
}
/**
* An {@code Iterable} that generates all positive {@code Byte}s from a uniform distribution. Does not support
* removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Byte> positiveBytes() {
return fromSupplier(this::nextPositiveByte);
}
public short nextPositiveShort() {
short s;
do {
s = nextNaturalShort();
} while (s == 0);
return s;
}
/**
* An {@code Iterable} that generates all positive {@code Short}s from a uniform distribution. Does not support
* removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Short> positiveShorts() {
return fromSupplier(this::nextPositiveShort);
}
public int nextPositiveInt() {
int i;
do {
i = nextInt();
} while (i <= 0);
return i;
}
/**
* An {@code Iterable} that generates all positive {@code Integer}s from a uniform distribution. Does not support
* removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Integer> positiveIntegers() {
return fromSupplier(this::nextPositiveInt);
}
public long nextPositiveLong() {
long l;
do {
l = nextLong();
} while (l <= 0);
return l;
}
/**
* An {@code Iterable} that generates all positive {@code Long}s from a uniform distribution from a uniform
* distribution. Does not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Long> positiveLongs() {
return fromSupplier(this::nextPositiveLong);
}
public byte nextNegativeByte() {
return (byte) ~nextNaturalByte();
}
/**
* An {@code Iterable} that generates all negative {@code Byte}s from a uniform distribution. Does not support
* removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Byte> negativeBytes() {
return fromSupplier(this::nextNegativeByte);
}
public short nextNegativeShort() {
return (short) ~nextNaturalShort();
}
/**
* An {@code Iterable} that generates all negative {@code Short}s from a uniform distribution. Does not support
* removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Short> negativeShorts() {
return fromSupplier(this::nextNegativeShort);
}
public int nextNegativeInt() {
int i;
do {
i = nextInt();
} while (i >= 0);
return i;
}
/**
* An {@code Iterable} that generates all negative {@code Integer}s from a uniform distribution. Does not support
* removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Integer> negativeIntegers() {
return fromSupplier(this::nextNegativeInt);
}
public long nextNegativeLong() {
long l;
do {
l = nextLong();
} while (l >= 0);
return l;
}
/**
* An {@code Iterable} that generates all negative {@code Long}s from a uniform distribution. Does not support
* removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Long> negativeLongs() {
return fromSupplier(this::nextNegativeLong);
}
public byte nextNaturalByte() {
return (byte) nextIntPow2(7);
}
/**
* An {@code Iterable} that generates all natural {@code Byte}s (including 0) from a uniform distribution. Does
* not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Byte> naturalBytes() {
return fromSupplier(this::nextNaturalByte);
}
public short nextNaturalShort() {
return (short) nextIntPow2(15);
}
/**
* An {@code Iterable} that generates all natural {@code Short}s (including 0) from a uniform distribution. Does
* not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Short> naturalShorts() {
return fromSupplier(this::nextNaturalShort);
}
public int nextNaturalInt() {
return nextIntPow2(31);
}
/**
* An {@code Iterable} that generates all natural {@code Integer}s (including 0) from a uniform distribution.
* Does not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Integer> naturalIntegers() {
return fromSupplier(this::nextNaturalInt);
}
public long nextNaturalLong() {
return nextLongPow2(63);
}
/**
* An {@code Iterable} that generates all natural {@code Long}s (including 0) from a uniform distribution. Does
* not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Long> naturalLongs() {
return fromSupplier(this::nextNaturalLong);
}
public byte nextByte() {
return (byte) nextIntPow2(8);
}
/**
* An {@code Iterable} that generates all {@code Byte}s from a uniform distribution. Does not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Byte> bytes() {
return fromSupplier(this::nextByte);
}
public short nextShort() {
return (short) nextIntPow2(16);
}
/**
* An {@code Iterable} that generates all {@code Short}s from a uniform distribution. Does not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Short> shorts() {
return fromSupplier(this::nextShort);
}
public char nextAsciiChar() {
return (char) nextIntPow2(7);
}
/**
* An {@code Iterable} that generates all ASCII {@code Character}s from a uniform distribution. Does not support
* removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Character> asciiCharacters() {
return fromSupplier(this::nextAsciiChar);
}
public char nextChar() {
return (char) nextIntPow2(16);
}
/**
* An {@code Iterable} that generates all {@code Character}s from a uniform distribution. Does not support
* removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Character> characters() {
return fromSupplier(this::nextChar);
}
public byte nextFromRangeUp(byte a) {
return (byte) (nextIntBounded((1 << 7) - a) + a);
}
/**
* An {@code Iterable} that uniformly generates {@code Byte}s greater than or equal to {@code a}.
*
* <ul>
* <li>{@code a} may be any {@code byte}.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code Byte}s.</li>
* </ul>
*
* Length is infinite
*
* @param a the inclusive lower bound of the generated elements
* @return uniformly-distributed {@code Byte}s greater than or equal to {@code a}
*/
@Override
public @NotNull Iterable<Byte> rangeUp(byte a) {
return map(i -> (byte) (i + a), integersBounded((1 << 7) - a));
}
public short nextFromRangeUp(short a) {
return (short) (nextIntBounded((1 << 15) - a) + a);
}
/**
* An {@code Iterable} that uniformly generates {@code Short}s greater than or equal to {@code a}.
*
* <ul>
* <li>{@code a} may be any {@code short}.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code Short}s.</li>
* </ul>
*
* Length is infinite
*
* @param a the inclusive lower bound of the generated elements
* @return uniformly-distributed {@code Short}s greater than or equal to {@code a}
*/
@Override
public @NotNull Iterable<Short> rangeUp(short a) {
return map(i -> (short) (i + a), integersBounded((1 << 15) - a));
}
public int nextFromRangeUp(int a) {
return (int) (nextLongBounded((1L << 31) - a) + a);
}
/**
* An {@code Iterable} that uniformly generates {@code Integer}s greater than or equal to {@code a}.
*
* <ul>
* <li>{@code a} may be any {@code int}.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code Integer}s.</li>
* </ul>
*
* Length is infinite
*
* @param a the inclusive lower bound of the generated elements
* @return uniformly-distributed {@code Integer}s greater than or equal to {@code a}
*/
@Override
public @NotNull Iterable<Integer> rangeUp(int a) {
return map(l -> (int) (l + a), longsBounded((1L << 31) - a));
}
public long nextFromRangeUp(long a) {
BigInteger ba = BigInteger.valueOf(a);
return nextBigIntegerBounded(BigInteger.ONE.shiftLeft(63).subtract(ba)).add(ba).longValueExact();
}
/**
* An {@code Iterable} that uniformly generates {@code Long}s greater than or equal to {@code a}.
*
* <ul>
* <li>{@code a} may be any {@code long}.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code Long}s.</li>
* </ul>
*
* Length is infinite
*
* @param a the inclusive lower bound of the generated elements
* @return uniformly-distributed {@code Long}s greater than or equal to {@code a}
*/
@Override
public @NotNull Iterable<Long> rangeUp(long a) {
return map(
i -> i.add(BigInteger.valueOf(a)).longValueExact(),
bigIntegersBounded(BigInteger.ONE.shiftLeft(63).subtract(BigInteger.valueOf(a)))
);
}
public char nextFromRangeUp(char a) {
return (char) (nextIntBounded((1 << 16) - a) + a);
}
/**
* An {@code Iterable} that uniformly generates {@code Characters}s greater than or equal to {@code a}.
*
* <ul>
* <li>{@code a} may be any {@code char}.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code Character}s.</li>
* </ul>
*
* Length is infinite
*
* @param a the inclusive lower bound of the generated elements
* @return uniformly-distributed {@code Character}s greater than or equal to {@code a}
*/
@Override
public @NotNull Iterable<Character> rangeUp(char a) {
return map(i -> (char) (i + a), integersBounded((1 << 16) - a));
}
public byte nextFromRangeDown(byte a) {
int offset = 1 << 7;
return (byte) (nextIntBounded(a + offset + 1) - offset);
}
/**
* An {@code Iterable} that uniformly generates {@code Byte}s less than or equal to {@code a}.
*
* <ul>
* <li>{@code a} may be any {@code byte}.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code Byte}s.</li>
* </ul>
*
* Length is infinite
*
* @param a the inclusive upper bound of the generated elements
* @return uniformly-distributed {@code Byte}s less than or equal to {@code a}
*/
@Override
public @NotNull Iterable<Byte> rangeDown(byte a) {
int offset = 1 << 7;
return map(i -> (byte) (i - offset), integersBounded(a + offset + 1));
}
public short nextFromRangeDown(short a) {
int offset = 1 << 15;
return (short) (nextIntBounded(a + offset + 1) - offset);
}
/**
* An {@code Iterable} that uniformly generates {@code Short}s less than or equal to {@code a}.
*
* <ul>
* <li>{@code a} may be any {@code short}.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code Short}s.</li>
* </ul>
*
* Length is infinite
*
* @param a the inclusive upper bound of the generated elements
* @return uniformly-distributed {@code Short}s less than or equal to {@code a}
*/
@Override
public @NotNull Iterable<Short> rangeDown(short a) {
int offset = 1 << 15;
return map(i -> (short) (i - offset), integersBounded(a + offset + 1));
}
public int nextFromRangeDown(int a) {
long offset = 1L << 31;
return (int) (nextLongBounded(a + offset + 1) - offset);
}
/**
* An {@code Iterable} that uniformly generates {@code Integer}s less than or equal to {@code a}.
*
* <ul>
* <li>{@code a} may be any {@code int}.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code Integer}s.</li>
* </ul>
*
* Length is infinite
*
* @param a the inclusive upper bound of the generated elements
* @return uniformly-distributed {@code Integer}s less than or equal to {@code a}
*/
@Override
public @NotNull Iterable<Integer> rangeDown(int a) {
long offset = 1L << 31;
return map(l -> (int) (l - offset), longsBounded(a + offset + 1));
}
public long nextFromRangeDown(long a) {
BigInteger offset = BigInteger.ONE.shiftLeft(63);
BigInteger ba = BigInteger.valueOf(a);
return nextBigIntegerBounded(ba.add(BigInteger.ONE).add(offset)).subtract(offset).longValueExact();
}
/**
* An {@code Iterable} that uniformly generates {@code Long}s less than or equal to {@code a}.
*
* <ul>
* <li>{@code a} may be any {@code long}.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code Long}s.</li>
* </ul>
*
* Length is infinite
*
* @param a the inclusive upper bound of the generated elements
* @return uniformly-distributed {@code Long}s less than or equal to {@code a}
*/
@Override
public @NotNull Iterable<Long> rangeDown(long a) {
BigInteger offset = BigInteger.ONE.shiftLeft(63);
return map(
i -> i.subtract(offset).longValueExact(),
bigIntegersBounded(BigInteger.valueOf(a).add(BigInteger.ONE).add(offset))
);
}
public char nextFromRangeDown(char a) {
return (char) nextIntBounded(a + 1);
}
/**
* An {@code Iterable} that uniformly generates {@code Character}s less than or equal to {@code a}.
*
* <ul>
* <li>{@code a} may be any {@code char}.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code Character}s.</li>
* </ul>
*
* Length is infinite
*
* @param a the inclusive upper bound of the generated elements
* @return uniformly-distributed {@code Character}s less than or equal to {@code a}
*/
@Override
public @NotNull Iterable<Character> rangeDown(char a) {
return fromSupplier(() -> nextFromRangeDown(a));
}
public byte nextFromRange(byte a, byte b) {
return (byte) (nextIntBounded((int) b - a + 1) + a);
}
@Override
public @NotNull Iterable<Byte> range(byte a, byte b) {
if (a > b) return Collections.emptyList();
return map(i -> (byte) (i + a), integersBounded((int) b - a + 1));
}
public short nextFromRange(short a, short b) {
return (short) (nextIntBounded((int) b - a + 1) + a);
}
@Override
public @NotNull Iterable<Short> range(short a, short b) {
if (a > b) return Collections.emptyList();
return map(i -> (short) (i + a), integersBounded((int) b - a + 1));
}
public int nextFromRange(int a, int b) {
return (int) (nextLongBounded((long) b - a + 1) + a);
}
@Override
public @NotNull Iterable<Integer> range(int a, int b) {
if (a > b) return Collections.emptyList();
return map(i -> (int) (i + a), longsBounded((long) b - a + 1));
}
public long nextFromRange(long a, long b) {
BigInteger ba = BigInteger.valueOf(a);
BigInteger bb = BigInteger.valueOf(b);
return nextBigIntegerBounded(bb.subtract(ba).add(BigInteger.ONE)).add(ba).longValueExact();
}
public @NotNull Iterable<Long> range(long a, long b) {
if (a > b) return Collections.emptyList();
return map(
i -> i.add(BigInteger.valueOf(a)).longValueExact(),
bigIntegersBounded(BigInteger.valueOf(b).subtract(BigInteger.valueOf(a)).add(BigInteger.ONE))
);
}
public @NotNull BigInteger nextFromRange(@NotNull BigInteger a, @NotNull BigInteger b) {
return nextBigIntegerBounded(b.subtract(a).add(BigInteger.ONE)).add(a);
}
@Override
public @NotNull Iterable<BigInteger> range(@NotNull BigInteger a, @NotNull BigInteger b) {
if (gt(a, b)) return Collections.emptyList();
return map(i -> i.add(a), bigIntegersBounded(b.subtract(a).add(BigInteger.ONE)));
}
public char nextFromRange(char a, char b) {
return (char) (nextIntBounded(b - a + 1) + a);
}
@Override
public @NotNull Iterable<Character> range(char a, char b) {
if (a > b) return Collections.emptyList();
return map(i -> (char) (i + a), integersBounded(b - a + 1));
}
public int nextPositiveIntGeometric() {
int i;
int j = 0;
do {
i = nextFromRange(0, scale - 1);
j++;
} while (i != 0);
return j;
}
/**
* An {@code Iterable} that generates all positive {@code Integer}s chosen from a geometric distribution with mean
* {@code scale}. The distribution is truncated at {@code Integer.MAX_VALUE}. Does not support removal.
*
* <ul>
* <li>{@code this} must have a scale of at least 2.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing positive {@code Integer}s.</li>
* </ul>
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Integer> positiveIntegersGeometric() {
if (scale < 2) {
throw new IllegalStateException("this must have a scale of at least 2. Invalid scale: " + scale);
}
return fromSupplier(this::nextPositiveIntGeometric);
}
public int nextNegativeIntGeometric() {
return -nextPositiveIntGeometric();
}
@Override
public @NotNull Iterable<Integer> negativeIntegersGeometric() {
if (scale < 2) {
throw new IllegalStateException("this must have a scale of at least 2. Invalid scale: " + scale);
}
return fromSupplier(this::nextNegativeIntGeometric);
}
public int nextNaturalIntGeometric() {
return withScale(scale + 1).nextPositiveIntGeometric() - 1;
}
/**
* An {@code Iterable} that generates all natural {@code Integer}s (including 0) chosen from a geometric
* distribution with mean {@code scale}. The distribution is truncated at {@code Integer.MAX_VALUE}. Does not
* support removal.
*
* <ul>
* <li>{@code this} must have a positive scale. The scale cannot be {@code Integer.MAX_VALUE}.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing natural {@code Integer}s.</li>
* </ul>
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Integer> naturalIntegersGeometric() {
if (scale < 1) {
throw new IllegalStateException("this must have a positive scale. Invalid scale: " + scale);
}
if (scale == Integer.MAX_VALUE) {
throw new IllegalStateException("this cannot have a scale of Integer.MAX_VALUE, or " + scale);
}
return map(i -> i - 1, withScale(scale + 1).positiveIntegersGeometric());
}
public int nextNonzeroIntGeometric() {
int i = nextPositiveIntGeometric();
return nextBoolean() ? i : -i;
}
@Override
public @NotNull Iterable<Integer> nonzeroIntegersGeometric() {
if (scale < 2) {
throw new IllegalStateException("this must have a scale of at least 2. Invalid scale: " + scale);
}
return fromSupplier(this::nextNonzeroIntGeometric);
}
public int nextIntGeometric() {
int i = nextNaturalIntGeometric();
return nextBoolean() ? i : -i;
}
@Override
public @NotNull Iterable<Integer> integersGeometric() {
if (scale < 1) {
throw new IllegalStateException("this must have a positive scale. Invalid scale: " + scale);
}
if (scale == Integer.MAX_VALUE) {
throw new IllegalStateException("this cannot have a scale of Integer.MAX_VALUE, or " + scale);
}
return fromSupplier(this::nextIntGeometric);
}
public int nextIntGeometricFromRangeUp(int a) {
int i;
do {
i = withScale(scale - a + 1).nextPositiveIntGeometric() + a - 1;
} while (i < a);
return i;
}
/**
* An {@code Iterable} that generates all natural {@code Integer}s greater than or equal to {@code a}, chosen from
* a geometric distribution with mean {@code scale}. Does not support removal.
*
* <ul>
* <li>{@code this} must have a scale greater than {@code a} and less than {@code Integer.MAX_VALUE}+a.</li>
* <li>{@code a} may be any {@code int}.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code Integer}s.</li>
* </ul>
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Integer> rangeUpGeometric(int a) {
if (scale <= a) {
throw new IllegalStateException("this must have a scale greater than a, which is " + a +
". Invalid scale: " + scale);
}
if (a < 1 && scale >= Integer.MAX_VALUE + a) {
throw new IllegalStateException("this must have a scale less than Integer.MAX_VALUE + a, which is " +
(Integer.MAX_VALUE + a));
}
return filter(j -> j >= a, map(i -> i + a - 1, withScale(scale - a + 1).positiveIntegersGeometric()));
}
public int nextIntGeometricFromRangeDown(int a) {
int i;
do {
i = a - withScale(scale - a + 1).nextPositiveIntGeometric() + 1;
} while (i > a);
return i;
}
@Override
public @NotNull Iterable<Integer> rangeDownGeometric(int a) {
if (scale >= a) {
throw new IllegalStateException("this must have a scale less than a, which is " + a + ". Invalid scale: " +
scale);
}
if (a > -1 && scale <= a - Integer.MAX_VALUE) {
throw new IllegalStateException("this must have a scale greater than a - Integer.MAX_VALUE, which is " +
(a - Integer.MAX_VALUE));
}
return filter(j -> j <= a, map(i -> a - i + 1, withScale(a - scale + 1).positiveIntegersGeometric()));
}
public @NotNull BigInteger nextPositiveBigInteger() {
int size = nextPositiveIntGeometric();
BigInteger i = nextBigIntegerPow2(size);
i = i.setBit(size - 1);
return i;
}
/**
* An {@code Iterable} that generates all positive {@code BigInteger}s. The bit size is chosen from a geometric
* distribution mean {@code scale}, and then the {@code BigInteger} is chosen uniformly from all
* {@code BigInteger}s with that bit size. Does not support removal.
*
* <ul>
* <li>{@code this} must have a scale of at least 2.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing positive {@code BigInteger}s.</li>
* </ul>
*
* Length is infinite
*/
public @NotNull Iterable<BigInteger> positiveBigIntegers() {
if (scale < 2) {
throw new IllegalStateException("this must have a scale of at least 2. Invalid scale: " + scale);
}
return fromSupplier(this::nextPositiveBigInteger);
}
public @NotNull BigInteger nextNegativeBigInteger() {
return nextPositiveBigInteger().negate();
}
/**
* An {@code Iterable} that generates all negative {@code BigInteger}s. The bit size is chosen from a geometric
* distribution with mean {@code scale}, and then the {@code BigInteger} is chosen uniformly from all
* {@code BigInteger}s with that bit size. Does not support removal.
*
* <ul>
* <li>{@code this} must have a scale of at least 2.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing negative {@code BigInteger}s.</li>
* </ul>
*
* Length is infinite
*/
@Override
public @NotNull Iterable<BigInteger> negativeBigIntegers() {
return map(BigInteger::negate, positiveBigIntegers());
}
public @NotNull BigInteger nextNaturalBigInteger() {
int size = nextNaturalIntGeometric();
BigInteger i = nextBigIntegerPow2(size);
if (size != 0) {
i = i.setBit(size - 1);
}
return i;
}
/**
* An {@code Iterable} that generates all natural {@code BigInteger}s (including 0). The bit size is chosen from a
* geometric distribution with mean {@code scale}, and then the {@code BigInteger} is chosen uniformly from all
* {@code BigInteger}s with that bit size. Does not support removal.
*
* <ul>
* <li>{@code this} must have a positive scale.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing negative {@code BigInteger}s.</li>
* </ul>
*
* Length is infinite
*/
@Override
public @NotNull Iterable<BigInteger> naturalBigIntegers() {
if (scale < 1) {
throw new IllegalStateException("this must have a positive scale. Invalid scale: " + scale);
}
return fromSupplier(this::nextNaturalBigInteger);
}
public @NotNull BigInteger nextNonzeroBigInteger() {
BigInteger i = nextPositiveBigInteger();
return nextBoolean() ? i : i.negate();
}
/**
* An {@code Iterable} that generates all nonzero {@code BigInteger}s. The bit size is chosen from a
* geometric distribution with mean {@code scale}, and then the {@code BigInteger} is chosen uniformly from all
* {@code BigInteger}s with that bit size; the sign is also chosen uniformly. Does not support removal.
*
* <ul>
* <li>{@code this} must have a scale of at least 2.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing nonzero {@code BigInteger}s.</li>
* </ul>
*
* Length is infinite
*/
@Override
public @NotNull Iterable<BigInteger> nonzeroBigIntegers() {
if (scale < 2) {
throw new IllegalStateException("this must have a scale of at least 2. Invalid scale: " + scale);
}
return fromSupplier(this::nextNonzeroBigInteger);
}
public @NotNull BigInteger nextBigInteger() {
BigInteger i = nextNaturalBigInteger();
return nextBoolean() ? i : i.negate();
}
/**
* An {@code Iterable} that generates all natural {@code BigInteger}s. The bit size is chosen from a
* geometric distribution with mean {@code scale}, and then the {@code BigInteger} is chosen uniformly from all
* {@code BigInteger}s with that bit size; the sign is also chosen uniformly. Does not support removal.
*
* <ul>
* <li>{@code this} must have a positive scale.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code BigInteger}s.</li>
* </ul>
*
* Length is infinite
*/
@Override
public @NotNull Iterable<BigInteger> bigIntegers() {
if (scale < 1) {
throw new IllegalStateException("this must have a positive scale. Invalid scale: " + scale);
}
return fromSupplier(this::nextBigInteger);
}
public @NotNull BigInteger nextFromRangeUp(@NotNull BigInteger a) {
int minBitLength = a.signum() == -1 ? 0 : a.bitLength();
int absBitLength = a.abs().bitLength();
int size = nextIntGeometricFromRangeUp(minBitLength);
BigInteger i;
if (size != absBitLength) {
i = nextBigIntegerPow2(size);
if (size != 0) {
boolean mostSignificantBit = i.testBit(size - 1);
if (!mostSignificantBit) {
i = i.setBit(size - 1);
if (size < absBitLength && a.signum() == -1) {
i = i.negate();
}
}
}
} else {
if (a.signum() != -1) {
i = nextBigIntegerBounded(BigInteger.ONE.shiftLeft(absBitLength).subtract(a)).add(a);
} else {
BigInteger b = BigInteger.ONE.shiftLeft(absBitLength - 1);
BigInteger x = nextBigIntegerBounded(b.add(a.negate().subtract(b)).add(BigInteger.ONE));
i = lt(x, b) ? x.add(b) : b.negate().subtract(x.subtract(b));
}
}
return i;
}
@Override
public @NotNull Iterable<BigInteger> rangeUp(@NotNull BigInteger a) {
int minBitLength = a.signum() == -1 ? 0 : a.bitLength();
if (scale <= minBitLength) {
throw new IllegalStateException("this must have a scale greater than minBitLength, which is " +
minBitLength + ". Invalid scale: " + scale);
}
if (minBitLength == 0 && scale == Integer.MAX_VALUE) {
throw new IllegalStateException("If {@code minBitLength} is 0, {@code scale} cannot be" +
" {@code Integer.MAX_VALUE}.");
}
return fromSupplier(() -> nextFromRangeUp(a));
}
public @NotNull BigInteger nextFromRangeDown(@NotNull BigInteger a) {
return nextFromRangeUp(a.negate()).negate();
}
@Override
public @NotNull Iterable<BigInteger> rangeDown(@NotNull BigInteger a) {
int minBitLength = a.signum() == 1 ? 0 : a.negate().bitLength();
if (scale <= minBitLength) {
throw new IllegalStateException("this must have a scale greater than minBitLength, which is " +
minBitLength + ". Invalid scale: " + scale);
}
if (minBitLength == 0 && scale == Integer.MAX_VALUE) {
throw new IllegalStateException("If {@code minBitLength} is 0, {@code scale} cannot be" +
" {@code Integer.MAX_VALUE}.");
}
return fromSupplier(() -> nextFromRangeDown(a));
}
/**
* An {@code Iterable} that generates all ordinary (neither NaN nor infinite) positive floats from a uniform
* distribution. Does not support removal.
*
* Length is infinite.
*/
@Override
public @NotNull Iterable<Float> positiveOrdinaryFloats() {
return map(Math::abs, filter(
f -> Float.isFinite(f) && !Float.isNaN(f) && !f.equals(-0.0f) && !f.equals(0.0f),
floats()
));
}
/**
* An {@code Iterable} that generates all ordinary (neither NaN nor infinite) negative floats from a uniform
* distribution. Negative zero is not included. Does not support removal.
*
* Length is infinite.
*/
@Override
public @NotNull Iterable<Float> negativeOrdinaryFloats() {
return map(f -> -f, positiveOrdinaryFloats());
}
/**
* An {@code Iterable} that generates all ordinary (neither NaN nor infinite) floats from a uniform distribution.
* Does not support removal.
*
* Length is infinite.
*/
@Override
public @NotNull Iterable<Float> ordinaryFloats() {
return filter(f -> Float.isFinite(f) && !Float.isNaN(f) && !f.equals(-0.0f), floats());
}
/**
* An {@code Iterable} that generates all {@code Float}s from a uniform distribution. Does not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Float> floats() {
return () -> new Iterator<Float>() {
private Random generator = new Random(0x6af477d9a7e54fcaL);
@Override
public boolean hasNext() {
return true;
}
@Override
public Float next() {
float next;
boolean problematicNaN;
do {
int floatBits = generator.nextInt();
next = Float.intBitsToFloat(floatBits);
problematicNaN = Float.isNaN(next) && floatBits != 0x7fc00000;
} while (problematicNaN);
return next;
}
@Override
public void remove() {
throw new UnsupportedOperationException("cannot remove from this iterator");
}
};
}
/**
* An {@code Iterable} that generates all ordinary (neither NaN nor infinite) positive floats from a uniform
* distribution. Does not support removal.
*
* Length is infinite.
*/
@Override
public @NotNull Iterable<Double> positiveOrdinaryDoubles() {
return map(Math::abs, filter(
d -> Double.isFinite(d) && !Double.isNaN(d) && !d.equals(-0.0) && !d.equals(0.0),
doubles()
));
}
/**
* An {@code Iterable} that generates all ordinary (neither NaN nor infinite) negative floats from a uniform
* distribution. Negative zero is not included. Does not support removal.
*
* Length is infinite.
*/
@Override
public @NotNull Iterable<Double> negativeOrdinaryDoubles() {
return map(d -> -d, positiveOrdinaryDoubles());
}
/**
* An {@code Iterable} that generates all ordinary (neither NaN nor infinite) floats from a uniform distribution.
* Does not support removal.
*
* Length is infinite.
*/
@Override
public @NotNull Iterable<Double> ordinaryDoubles() {
return filter(d -> Double.isFinite(d) && !Double.isNaN(d) && !d.equals(-0.0), doubles());
}
/**
* An {@code Iterable} that generates all {@code Double}s from a uniform distribution. Does not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Double> doubles() {
return () -> new Iterator<Double>() {
private Random generator = new Random(0x6af477d9a7e54fcaL);
@Override
public boolean hasNext() {
return true;
}
@Override
public Double next() {
double next;
boolean problematicNaN;
do {
long doubleBits = generator.nextLong();
next = Double.longBitsToDouble(doubleBits);
problematicNaN = Double.isNaN(next) && doubleBits != 0x7ff8000000000000L;
} while (problematicNaN);
return next;
}
@Override
public void remove() {
throw new UnsupportedOperationException("cannot remove from this iterator");
}
};
}
@Override
public @NotNull Iterable<BigDecimal> positiveBigDecimals() {
return map(
p -> new BigDecimal(p.a, p.b),
pairs(negativeBigIntegers(), integersGeometric())
);
}
@Override
public @NotNull Iterable<BigDecimal> negativeBigDecimals() {
return map(
p -> new BigDecimal(p.a, p.b),
pairs(negativeBigIntegers(), integersGeometric())
);
}
@Override
public @NotNull Iterable<BigDecimal> bigDecimals() {
return map(p -> new BigDecimal(p.a, p.b), pairs(bigIntegers(), integersGeometric()));
}
public @NotNull <T> Iterable<T> addSpecialElement(@Nullable T x, @NotNull Iterable<T> xs) {
return () -> new Iterator<T>() {
private Iterator<T> xsi = xs.iterator();
private Iterator<Integer> specialSelector = integersBounded(SPECIAL_ELEMENT_RATIO).iterator();
boolean specialSelection = specialSelector.next() == 0;
@Override
public boolean hasNext() {
return specialSelection || xsi.hasNext();
}
@Override
public T next() {
boolean previousSelection = specialSelection;
specialSelection = specialSelector.next() == 0;
return previousSelection ? x : xsi.next();
}
@Override
public void remove() {
throw new UnsupportedOperationException("cannot remove from this iterator");
}
};
}
@Override
public @NotNull <T> Iterable<T> withNull(@NotNull Iterable<T> xs) {
return addSpecialElement(null, xs);
}
@Override
public @NotNull <T> Iterable<Optional<T>> optionals(@NotNull Iterable<T> xs) {
return addSpecialElement(Optional.<T>empty(), map(Optional::of, xs));
}
@Override
public @NotNull <T> Iterable<NullableOptional<T>> nullableOptionals(@NotNull Iterable<T> xs) {
return addSpecialElement(NullableOptional.<T>empty(), map(NullableOptional::of, xs));
}
@Override
public @NotNull <A, B> Iterable<Pair<A, B>> pairs(@NotNull Iterable<A> as, @NotNull Iterable<B> bs) {
return zip(as, bs);
}
@Override
public @NotNull <A, B, C> Iterable<Triple<A, B, C>> triples(
@NotNull Iterable<A> as,
@NotNull Iterable<B> bs,
@NotNull Iterable<C> cs
) {
return zip3(as, bs, cs);
}
@Override
public
@NotNull <A, B, C, D> Iterable<Quadruple<A, B, C, D>> quadruples(
@NotNull Iterable<A> as,
@NotNull Iterable<B> bs,
@NotNull Iterable<C> cs,
@NotNull Iterable<D> ds
) {
return zip4(as, bs, cs, ds);
}
@Override
public @NotNull <A, B, C, D, E> Iterable<Quintuple<A, B, C, D, E>> quintuples(
@NotNull Iterable<A> as,
@NotNull Iterable<B> bs,
@NotNull Iterable<C> cs,
@NotNull Iterable<D> ds,
@NotNull Iterable<E> es
) {
return zip5(as, bs, cs, ds, es);
}
@Override
public @NotNull <A, B, C, D, E, F> Iterable<Sextuple<A, B, C, D, E, F>> sextuples(
@NotNull Iterable<A> as,
@NotNull Iterable<B> bs,
@NotNull Iterable<C> cs,
@NotNull Iterable<D> ds,
@NotNull Iterable<E> es,
@NotNull Iterable<F> fs
) {
return zip6(as, bs, cs, ds, es, fs);
}
@Override
public @NotNull <A, B, C, D, E, F, G> Iterable<Septuple<A, B, C, D, E, F, G>> septuples(
@NotNull Iterable<A> as,
@NotNull Iterable<B> bs,
@NotNull Iterable<C> cs,
@NotNull Iterable<D> ds,
@NotNull Iterable<E> es,
@NotNull Iterable<F> fs,
@NotNull Iterable<G> gs
) {
return zip7(as, bs, cs, ds, es, fs, gs);
}
@Override
public @NotNull <T> Iterable<Pair<T, T>> pairs(@NotNull Iterable<T> xs) {
List<Iterable<T>> xss = demux(2, xs);
return zip(xss.get(0), xss.get(1));
}
@Override
public @NotNull <T> Iterable<Triple<T, T, T>> triples(@NotNull Iterable<T> xs) {
List<Iterable<T>> xss = demux(3, xs);
return zip3(xss.get(0), xss.get(1), xss.get(2));
}
@Override
public @NotNull <T> Iterable<Quadruple<T, T, T, T>> quadruples(@NotNull Iterable<T> xs) {
List<Iterable<T>> xss = demux(4, xs);
return zip4(xss.get(0), xss.get(1), xss.get(2), xss.get(3));
}
@Override
public @NotNull <T> Iterable<Quintuple<T, T, T, T, T>> quintuples(@NotNull Iterable<T> xs) {
List<Iterable<T>> xss = demux(5, xs);
return zip5(xss.get(0), xss.get(1), xss.get(2), xss.get(3), xss.get(4));
}
@Override
public @NotNull <T> Iterable<Sextuple<T, T, T, T, T, T>> sextuples(@NotNull Iterable<T> xs) {
List<Iterable<T>> xss = demux(6, xs);
return zip6(xss.get(0), xss.get(1), xss.get(2), xss.get(3), xss.get(4), xss.get(5));
}
@Override
public @NotNull <T> Iterable<Septuple<T, T, T, T, T, T, T>> septuples(@NotNull Iterable<T> xs) {
List<Iterable<T>> xss = demux(7, xs);
return zip7(xss.get(0), xss.get(1), xss.get(2), xss.get(3), xss.get(4), xss.get(5), xss.get(6));
}
@Override
public @NotNull <T> Iterable<List<T>> lists(int size, @NotNull Iterable<T> xs) {
if (size == 0) {
return repeat(Collections.emptyList());
} else {
return transpose(demux(size, xs));
}
}
@Override
public @NotNull <T> Iterable<List<T>> listsAtLeast(int minSize, @NotNull Iterable<T> xs) {
if (isEmpty(xs)) return Collections.singletonList(Collections.emptyList());
return () -> new Iterator<List<T>>() {
private final Iterator<T> xsi = cycle(xs).iterator();
private final Iterator<Integer> sizes = naturalIntegersGeometric().iterator();
@Override
public boolean hasNext() {
return true;
}
@Override
public List<T> next() {
int size = sizes.next() + minSize;
List<T> list = new ArrayList<>();
for (int i = 0; i < size; i++) {
list.add(xsi.next());
}
return list;
}
@Override
public void remove() {
throw new UnsupportedOperationException("cannot remove from this iterator");
}
};
}
@Override
public @NotNull <T> Iterable<List<T>> lists(@NotNull Iterable<T> xs) {
if (isEmpty(xs)) return Collections.singletonList(Collections.emptyList());
return () -> new Iterator<List<T>>() {
private final Iterator<T> xsi = cycle(xs).iterator();
private final Iterator<Integer> sizes = naturalIntegersGeometric().iterator();
@Override
public boolean hasNext() {
return true;
}
@Override
public List<T> next() {
int size = sizes.next();
List<T> list = new ArrayList<>();
for (int i = 0; i < size; i++) {
list.add(xsi.next());
}
return list;
}
@Override
public void remove() {
throw new UnsupportedOperationException("cannot remove from this iterator");
}
};
}
@Override
public @NotNull Iterable<String> strings(int size, @NotNull Iterable<Character> cs) {
return map(IterableUtils::charsToString, transpose(demux(size, cs)));
}
@Override
public @NotNull Iterable<String> stringsAtLeast(int minSize, @NotNull Iterable<Character> cs) {
if (isEmpty(cs)) return Arrays.asList("");
return () -> new Iterator<String>() {
private final Iterator<Character> csi = cycle(cs).iterator();
private final Iterator<Integer> sizes = naturalIntegersGeometric().iterator();
@Override
public boolean hasNext() {
return true;
}
@Override
public String next() {
int size = sizes.next() + minSize;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size; i++) {
sb.append(csi.next());
}
return sb.toString();
}
@Override
public void remove() {
throw new UnsupportedOperationException("cannot remove from this iterator");
}
};
}
@Override
public @NotNull Iterable<String> strings(int size) {
return strings(size, characters());
}
@Override
public @NotNull Iterable<String> stringsAtLeast(int minSize) {
return stringsAtLeast(minSize, characters());
}
@Override
public @NotNull Iterable<String> strings(@NotNull Iterable<Character> cs) {
if (isEmpty(cs)) return Arrays.asList("");
return () -> new Iterator<String>() {
private final Iterator<Character> csi = cycle(cs).iterator();
private final Iterator<Integer> sizes = naturalIntegersGeometric().iterator();
@Override
public boolean hasNext() {
return true;
}
@Override
public String next() {
int size = sizes.next();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size; i++) {
sb.append(csi.next());
}
return sb.toString();
}
@Override
public void remove() {
throw new UnsupportedOperationException("cannot remove from this iterator");
}
};
}
@Override
public @NotNull Iterable<String> strings() {
return strings(characters());
}
/**
* Determines whether {@code this} is equal to {@code that}.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>{@code that} may be any {@code Object}.</li>
* <li>The result may be either {@code boolean}.</li>
* </ul>
*
* @param that The {@code RandomProvider} to be compared with {@code this}
* @return {@code this}={@code that}
*/
/**
* Calculates the hash code of {@code this}.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>(conjecture) The result may be any {@code int}.</li>
* </ul>
*
* @return {@code this}'s hash code.
*/
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
RandomProvider that = (RandomProvider) o;
return scale == that.scale && secondaryScale == that.secondaryScale &&
seed.equals(that.seed) && prng.equals(that.prng);
}
@Override
public int hashCode() {
int result = seed.hashCode();
result = 31 * result + prng.hashCode();
result = 31 * result + scale;
result = 31 * result + secondaryScale;
return result;
}
/**
* Creates a {@code String} representation of {@code this}.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>See tests and demos for example results.</li>
* </ul>
*
* @return a {@code String} representation of {@code this}
*/
public String toString() {
return "RandomProvider[@" + getId() + ", " + scale + ", " + secondaryScale + "]";
}
/**
* Ensures that {@code this} is valid. Must return true for any {@code RandomProvider} used outside this class.
*/
public void validate() {
prng.validate();
assertEquals(toString(), seed.size(), IsaacPRNG.SIZE);
}
} |
package tigase.server.sreceiver.sysmon;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.logging.MemoryHandler;
import tigase.conf.Configurator;
import tigase.util.LogFormatter;
/**
* Created: Dec 12, 2008 8:31:38 PM
*
* @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a>
* @version $Rev$
*/
public class LogMonitor extends AbstractMonitor {
private MonitorHandler monitorHandler = null;
private MemoryHandlerFlush memoryHandler = null;
private Map<String, String> monitorLevels =
new LinkedHashMap<String, String>();
private int loggerSize = 50;
private Level levelTreshold = Level.WARNING;
private int maxLogBuffer = 1000*1000;
private long lastWarningSent = 0;
private enum command {
setlevel(" [package=level] - Sets logging level for specified package."),
loggersize(" [N] - Sets memory logger size to specified value."),
leveltreshold(" [level] - Sets level treshold to specified level."),
logdump(" - retrieves all logs collected in the memory buffer and clears that buffer.");
private String helpText = null;
private command(String helpText) {
this.helpText = helpText;
}
public String getHelp() {
return helpText;
}
};
@Override
public String commandsHelp() {
StringBuilder sb = new StringBuilder();
for (command comm : command.values()) {
sb.append("//" + comm.name() + comm.getHelp() + "\n");
}
return sb.toString();
}
@Override
public String runCommand(String[] com) {
command comm = command.valueOf(com[0].substring(2));
switch (comm) {
case setlevel:
if (com.length > 1) {
String[] keyval = com[1].split("=");
if (keyval.length > 1) {
String key = (keyval[0].endsWith(".level") ? keyval[0].substring(
0, keyval[0].length() - 6) : keyval[0]);
try {
Level level = Level.parse(keyval[1]);
Logger.getLogger(key).setLevel(level);
monitorLevels.put(key + ".level", level.getName());
return "Level set successfuly: " + key + "=" + level.getName();
} catch (Exception e) {
return "Incorrect level name, use: ALL, FINEST, FINER, FINE, " +
"INFO, WARNING, SEVERE, OFF";
}
} else {
return "Incorrect level setting, use: package=level";
}
} else {
return "Current logging levels are:\n" + getCurrentLevels();
}
case loggersize:
if (com.length > 1) {
try {
int newLoggerSize = Integer.parseInt(com[1]);
loggerSize = newLoggerSize;
registerHandler();
return "New logger size successfuly set to: " + loggerSize;
} catch (Exception e) {
return "Incorrect logger size: " + com[1];
}
} else {
return "Current memory logger size is: " + loggerSize;
}
case leveltreshold:
if (com.length > 1) {
return "Setting logging treshold level is not supported yet.";
} else {
return "Current logging treshold level is: " + levelTreshold;
}
case logdump:
return "Memory logging buffer content:\n" +
memoryHandler.pushToString();
}
return null;
}
@Override
public boolean isMonitorCommand(String com) {
if (com != null) {
for (command comm: command.values()) {
if (com.startsWith("//" + comm.toString())) {
return true;
}
}
}
return false;
}
private void removeHandler() {
if (memoryHandler != null) {
Logger.getLogger("").removeHandler(memoryHandler);
}
}
private void registerHandler() {
removeHandler();
if (monitorHandler == null) {
monitorHandler = new MonitorHandler();
monitorHandler.setLevel(Level.ALL);
}
memoryHandler =
new MemoryHandlerFlush(monitorHandler, loggerSize, levelTreshold);
memoryHandler.setLevel(Level.ALL);
Logger.getLogger("").addHandler(memoryHandler);
}
@Override
public void init(String jid, double treshold, SystemMonitorTask smTask) {
super.init(jid, treshold, smTask);
registerHandler();
}
@Override
public void destroy() {
removeHandler();
}
private String getCurrentLevels() {
String[] configLines = Configurator.logManagerConfiguration.split("\n");
Map<String, String> results = new LinkedHashMap<String, String>();
for (String string : configLines) {
if (string.contains(".level") && !string.contains("FileHandler") &&
!string.contains("ConsoleHandler")) {
String[] keyval = string.split("=");
results.put(keyval[0], keyval[1]);
}
}
results.putAll(monitorLevels);
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : results.entrySet()) {
sb.append(entry.getKey() + "=" + entry.getValue() + "\n");
}
return sb.toString();
}
@Override
public String getState() {
StringBuilder sb = new StringBuilder("Logging levels:\n");
sb.append(getCurrentLevels());
sb.append("Monitor parameters:\n");
sb.append("loggerSize=" + loggerSize + "\n");
sb.append("levelTreshold=" + levelTreshold + "\n");
return sb.toString();
}
private class MonitorHandler extends Handler {
private LinkedList<String> logs = new LinkedList<String>();
private LogFormatter formatter = new LogFormatter();
@Override
public synchronized void publish(LogRecord record) {
String logEntry =
formatter.format(record).replace('<', '[').replace('>', ']');
logs.add(logEntry);
}
public synchronized String logsToString() {
StringBuilder sb = new StringBuilder();
String logEntry = null;
while (((logEntry = logs.pollLast()) != null) &&
(sb.length() < maxLogBuffer)) {
sb.insert(0, logEntry);
}
logs.clear();
String result = sb.length() <= maxLogBuffer ? sb.toString()
: sb.substring(sb.length() - maxLogBuffer);
return result;
}
@Override
public synchronized void flush() {
String logBuff = logsToString();
// We don't want to flood the system with this in case of
// some frequent error....
if (System.currentTimeMillis() - lastWarningSent > 5*MINUTE) {
sendWarningOut(logBuff, null);
lastWarningSent = System.currentTimeMillis();
}
}
@Override
public void close() throws SecurityException { }
}
private class MemoryHandlerFlush extends MemoryHandler {
MonitorHandler monHandle = null;
public MemoryHandlerFlush(MonitorHandler target, int size, Level pushLevel) {
super(target, size, pushLevel);
monHandle = target;
}
public String pushToString() {
super.push();
return monHandle.logsToString();
}
@Override
public void push() {
super.push();
flush();
}
}
} |
package io.compgen.ngsutils.cli.vcf;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.math3.distribution.PoissonDistribution;
import io.compgen.cmdline.annotation.Command;
import io.compgen.cmdline.annotation.Exec;
import io.compgen.cmdline.annotation.Option;
import io.compgen.cmdline.annotation.UnnamedArg;
import io.compgen.cmdline.exceptions.CommandArgumentException;
import io.compgen.cmdline.impl.AbstractOutputCommand;
import io.compgen.common.IterUtils;
import io.compgen.common.Pair;
import io.compgen.common.TabWriter;
import io.compgen.common.progress.ProgressUtils;
import io.compgen.ngsutils.NGSUtils;
import io.compgen.ngsutils.bed.BedReader;
import io.compgen.ngsutils.bed.BedRecord;
import io.compgen.ngsutils.vcf.VCFReader;
import io.compgen.ngsutils.vcf.VCFRecord;
@Command(name="vcf-bedcount", desc="For a given BED file, count the number of variants present in the BED region", doc="Note: this expects both the BED and VCF files to be sorted.", category="vcf")
public class VCFBedCount extends AbstractOutputCommand {
private String vcfFilename=null;
private String bedFilename=null;
private String sampleName=null;
private double tmb=-1;
private boolean onlyPassing=false;
private boolean altOnly=false;
@Option(desc = "Given a genome-wide TMB value (variants per megabase), calculate a p-value for the given count (Poisson test, P(X >= count, lambda=tmb)); Note: If you use this, your bin sizes should be larger than 1Mb", name = "tmb")
public void setTMB(double tmb) {
this.tmb = tmb;
}
@Option(desc = "Only count alt variants (requires GT FORMAT field, exports all non GT:0/0)", name = "alt")
public void setAltOnly(boolean altOnly) {
this.altOnly = altOnly;
}
@Option(desc="Only count passing variants", name="passing")
public void setOnlyOutputPass(boolean onlyPassing) {
this.onlyPassing = onlyPassing;
}
@Option(desc="Sample to use for vcf-counts (if VCF file has more than one sample, default: first sample)", name="sample")
public void setSampleName(String sampleName) {
this.sampleName = sampleName;
}
@UnnamedArg(name = "input.bed input.vcf", required=true)
public void setFilename(String[] filenames) throws CommandArgumentException {
if (filenames.length!=2) {
throw new CommandArgumentException("You must include a BED file and a VCF file.");
}
bedFilename = filenames[0];
vcfFilename = filenames[1];
}
@Exec
public void exec() throws Exception {
VCFReader reader;
if (vcfFilename.equals("-")) {
reader = new VCFReader(System.in);
} else {
reader = new VCFReader(vcfFilename);
}
int sampleIdx = 0;
if (sampleName != null) {
sampleIdx = reader.getHeader().getSamplePosByName(sampleName);
}
Map<String, Map<Pair<Integer, Integer>, Integer>> counts = new HashMap<String, Map<Pair<Integer, Integer>, Integer>>();
Iterator<BedRecord> bedIt = BedReader.readFile(bedFilename);
for (BedRecord bedRecord: IterUtils.wrap(bedIt)) {
if (!counts.containsKey(bedRecord.getCoord().ref)) {
counts.put(bedRecord.getCoord().ref, new HashMap<Pair<Integer, Integer>, Integer>());
}
counts.get(bedRecord.getCoord().ref).put(new Pair<Integer, Integer>(bedRecord.getCoord().start, bedRecord.getCoord().end), 0);
}
for (VCFRecord record: IterUtils.wrap(ProgressUtils.getIterator(vcfFilename.equals("-") ? "variants <stdin>": vcfFilename, reader.iterator(), null))) {
if (onlyPassing && record.isFiltered()) {
continue;
}
String ref = record.getChrom();
int pos = record.getPos()-1; // zero-based
if (altOnly) {
if (record.getSampleAttributes() == null || record.getSampleAttributes().get(sampleIdx) == null || !record.getSampleAttributes().get(sampleIdx).contains("GT")) {
throw new CommandArgumentException("Missing GT field");
}
String val = record.getSampleAttributes().get(sampleIdx).get("GT").asString(null);
// if 0/0 or 1/1, etc -- skip
if (val.indexOf('/')>-1) {
String[] v2 = val.split("/");
if (v2.length == 2 && v2[0].equals("0") && v2[1].equals("0")) {
continue;
}
} else if (val.indexOf('|')>-1) {
String[] v2 = val.split("\\|");
if (v2.length == 2 && v2[0].equals("0") && v2[1].equals("0")) {
continue;
}
}
}
if (counts.containsKey(ref)) {
for (Pair<Integer, Integer> coord: counts.get(ref).keySet()) {
if (coord.one <= pos && coord.two > pos) {
counts.get(ref).put(coord, counts.get(ref).get(coord)+1);
}
}
}
}
reader.close();
TabWriter writer = new TabWriter();
writer.write_line("## program: " + NGSUtils.getVersion());
writer.write_line("## cmd: " + NGSUtils.getArgs());
writer.write_line("## vcf-input: " + vcfFilename);
writer.write_line("## bed-input: " + bedFilename);
if (tmb > 0) {
writer.write_line("## TMB: "+tmb);
}
writer.write("chrom");
writer.write("start");
writer.write("end");
writer.write("varcount");
writer.write("variants_per_mb");
if (tmb > 0) {
writer.write("poisson_pvalue");
}
writer.eol();
Map<Integer, PoissonDistribution> ppois = new HashMap<Integer, PoissonDistribution>();
Iterator<BedRecord> bedIt2 = BedReader.readFile(bedFilename);
for (BedRecord bedRecord: IterUtils.wrap(bedIt2)) {
String ref = bedRecord.getCoord().ref;
int start = bedRecord.getCoord().start;
int end = bedRecord.getCoord().end;
int count = -1;
for (Pair<Integer, Integer> pair: counts.get(ref).keySet()) {
if (pair.one == start && pair.two == end) {
count = counts.get(ref).get(pair);
break;
}
}
writer.write(ref);
writer.write(start);
writer.write(end);
writer.write(count);
int length = end - start;
writer.write(count / (length / 1000000.0));
if (tmb > 0) {
if (!ppois.containsKey(length)) {
double lambda = tmb * length / 1000000;
ppois.put(length, new PoissonDistribution(lambda));
}
writer.write(1-ppois.get(length).cumulativeProbability(count-1));
}
writer.eol();
}
writer.close();
}
} |
package dr.evomodel.treelikelihood;
import dr.evolution.tree.NodeRef;
import dr.evolution.tree.Tree;
import dr.evolution.util.Taxa;
import dr.evolution.util.TaxonList;
import dr.evomodel.tree.TMRCAStatistic;
import dr.evomodel.tree.TreeModel;
import dr.inference.loggers.LogColumn;
import dr.inference.loggers.Loggable;
import dr.xml.*;
import java.util.Set;
/**
* A statistic that tracks the time of MRCA of a set of taxa
*
* @version $Id: TMRCAStatistic.java,v 1.21 2005/07/11 14:06:25 rambaut Exp $
*
* @author Alexei Drummond
* @author Andrew Rambaut
*
*/
public class AncestralState implements Loggable {
public static final String ANCESTRAL_STATE = "ancestralState";
public static final String NAME = "name";
public static final String MRCA = "mrca";
public AncestralState(String name, AncestralStateTreeLikelihood ancestralTreeLikelihood, Tree tree, TaxonList taxa) throws Tree.MissingTaxonException {
this.name = name;
this.tree = tree;
this.ancestralTreeLikelihood = ancestralTreeLikelihood;
this.leafSet = Tree.Utils.getLeavesForTaxa(tree, taxa);
}
public Tree getTree() { return tree; }
/** @return the ancestral state of the MRCA node. */
public String getAncestralState() {
NodeRef node = Tree.Utils.getCommonAncestorNode(tree, leafSet);
if (node == null) throw new RuntimeException("No node found that is MRCA of " + leafSet);
String rtn = null;
for(int i=0; i<tree.getNodeCount(); i++)
rtn = ancestralTreeLikelihood.getAttributeForNode(tree, node)[0];
return rtn;
}
// Loggable IMPLEMENTATION
/**
* @return the log columns.
*/
public LogColumn[] getColumns() {
LogColumn[] columns = new LogColumn[1];
columns[0] = new LogColumn.Abstract(name) {
protected String getFormattedValue() {
return getAncestralState();
}
};
return columns;
}
public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
public String getParserName() { return ANCESTRAL_STATE; }
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
String name;
if (xo.hasAttribute(NAME)) {
name = xo.getStringAttribute(NAME);
} else {
name = xo.getId();
}
Tree tree = (Tree)xo.getChild(Tree.class);
TaxonList taxa = (TaxonList)xo.getSocketChild(MRCA);
AncestralStateTreeLikelihood ancestralTreeLikelihood = (AncestralStateTreeLikelihood)xo.getChild(AncestralStateTreeLikelihood.class);
try {
return new AncestralState(name, ancestralTreeLikelihood, tree, taxa);
} catch (Tree.MissingTaxonException mte) {
throw new XMLParseException("Taxon, " + mte + ", in " + getParserName() + "was not found in the tree.");
}
} |
package mountainrangepvp.input;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.math.Vector2;
import mountainrangepvp.chat.ChatLine;
import mountainrangepvp.game.GameWorld;
import mountainrangepvp.player.Player;
/**
* @author lachlan
*/
public class InputHandler {
private static final int DOUBLE_JUMP_MIN = 50;
private static final int DOUBLE_JUMP_MAX = 500;
private static final int GUN_RATE = 100;
private final GameWorld world;
private final PlayerInputHandler playerInputHandler;
private final ChatInputHandler chatInputHandler;
private boolean up, down, left, right;
private int doubleJumpTimer;
private boolean gun;
private int gunTimer;
public InputHandler(GameWorld world) {
this.world = world;
playerInputHandler = new PlayerInputHandler();
chatInputHandler = new ChatInputHandler();
}
public void register() {
Gdx.input.setInputProcessor(playerInputHandler);
}
public void update(float dt) {
Player local = world.getPlayerManager().getLocalPlayer();
if (!local.isAlive()) {
gun = false;
doubleJumpTimer = 0;
gunTimer = 0;
return;
}
Vector2 vel = local.getVelocity();
doPlayerWalking(local, vel, dt);
doGunControl(local);
if (gun) {
doShooting(local);
gun = false;
}
gunTimer += (int) (1000 * dt);
}
private void doPlayerWalking(Player local, Vector2 vel, float dt) {
if (local.isOnGround()) {
if (left) {
vel.x = accelerate(vel.x, -Player.WALK_ACCELERATION,
-Player.WALK_SPEED);
} else if (right) {
vel.x = accelerate(vel.x, Player.WALK_ACCELERATION,
Player.WALK_SPEED);
} else {
vel.x *= Player.FRICTION;
}
if (up) {
vel.y = Player.JUMP_SPEED;
doubleJumpTimer = 0;
}
} else {
if (left) {
vel.x = accelerate(vel.x, -Player.AIR_ACCELERATION,
-Player.AIR_SPEED);
} else if (right) {
vel.x = accelerate(vel.x, Player.AIR_ACCELERATION,
Player.AIR_SPEED);
}
if (!up) {
doubleJumpTimer += (int) (dt * 1000);
} else {
if (doubleJumpTimer > DOUBLE_JUMP_MIN && doubleJumpTimer < DOUBLE_JUMP_MAX) {
vel.y = Player.JUMP_SPEED;
doubleJumpTimer = DOUBLE_JUMP_MAX;
}
}
}
if (down) {
vel.y -= Player.DOWN_ACCELERATION;
}
}
private float accelerate(float v, float accel, float max) {
if (Math.abs(v) < Math.abs(max)) {
v += accel;
return v;
} else if (Math.signum(v) != Math.signum(max)) {
v += accel;
return v;
} else {
v -= accel * 0.04f;
return v;
}
}
private void doGunControl(Player player) {
int x = Gdx.input.getX();
int y = Gdx.graphics.getHeight() - Gdx.input.getY();
Vector2 target = new Vector2(x, y);
target.x -= Gdx.graphics.getWidth() / 2;
target.y -= Gdx.graphics.getHeight() / 2;
target.nor();
Vector2 dir = player.getGunDirection();
float lerpSpeed = Math.min(0.8f, Math.max(0.3f, 10f / player.getVelocity().x));
dir.lerp(target, lerpSpeed);
}
private void doShooting(Player player) {
if (gunTimer > GUN_RATE) {
gunTimer = 0;
Vector2 pos = player.getCentralPosition();
world.getShotManager().addShot(pos,
player.getGunDirection().cpy(),
player);
Vector2 kickback = player.getGunDirection().cpy().scl(-90f);
player.getVelocity().add(kickback);
}
}
private void reset() {
up = down = left = right = false;
gun = false;
doubleJumpTimer = 0;
gunTimer = 0;
}
class PlayerInputHandler extends AbstractInputProcessor {
@Override
public boolean keyDown(int keycode) {
switch (keycode) {
case Keys.SPACE:
case Keys.W:
up = true;
break;
case Keys.A:
left = true;
break;
case Keys.D:
right = true;
break;
case Keys.S:
down = true;
break;
case Keys.ESCAPE:
Gdx.app.exit();
break;
}
return true;
}
@Override
public boolean keyUp(int keycode) {
switch (keycode) {
case Keys.SPACE:
case Keys.W:
up = false;
break;
case Keys.A:
left = false;
break;
case Keys.D:
right = false;
break;
case Keys.S:
down = false;
break;
case Keys.TAB:
Gdx.input.setInputProcessor(chatInputHandler);
world.getChatManager().setChatting(true);
reset();
break;
}
return true;
}
@Override
public boolean touchDown(int screenX, int screenY, int pointer,
int button) {
gun = true;
return true;
}
@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
gun = false;
return true;
}
}
class ChatInputHandler extends AbstractInputProcessor {
@Override
public boolean keyUp(int keycode) {
String line = world.getChatManager().getCurrentLine();
switch (keycode) {
case Keys.ENTER:
if (!line.isEmpty())
world.getChatManager().addLine(new ChatLine(world.
getPlayerManager().getLocalPlayer(), line));
case Keys.ESCAPE:
case Keys.TAB:
Gdx.input.setInputProcessor(playerInputHandler);
world.getChatManager().setChatting(false);
break;
case Keys.BACKSPACE:
if (!line.isEmpty())
line = line.substring(0, line.length() - 1);
break;
}
world.getChatManager().setCurrentLine(line);
return true;
}
@Override
public boolean keyTyped(char character) {
boolean acceptable = ("" + character).matches(
"[a-zA-Z0-9`\\~\\!\\@\\
if (!acceptable)
return true;
String line = world.getChatManager().getCurrentLine();
line += character;
world.getChatManager().setCurrentLine(line);
return true;
}
}
} |
package com.lightcrafts.platform;
import com.lightcrafts.app.Application;
import com.lightcrafts.app.ExceptionDialog;
import com.lightcrafts.splash.SplashImage;
import com.lightcrafts.splash.SplashWindow;
import com.lightcrafts.utils.ForkDaemon;
import com.lightcrafts.utils.Version;
import javax.swing.*;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.io.IOException;
/**
* Launch LightZone.
*/
public class Launcher {
/**
* @param args The command line arguments.
*/
public void init(String[] args) {
try {
setSystemProperties();
enableTextAntiAliasing();
showAppVersion();
showJavaVersion();
checkCpu();
UIManager.setLookAndFeel(Platform.getPlatform().getLookAndFeel());
final String licenseText = "Open Source";
final SplashImage splash = new SplashImage(
SplashImage.getDefaultSplashText(licenseText)
);
SplashWindow.splash(splash);
setColor();
Application.setStartupProgress(splash.getStartupProgress());
startForkDaemon();
Application.main(args);
SplashWindow.disposeSplash();
}
catch (Throwable t) {
(new ExceptionDialog()).handle(t);
}
}
protected void setSystemProperties() {
System.setProperty("awt.useSystemAAFontSettings", "on");
System.setProperty("com.sun.media.jai.disableMediaLib", "true");
}
protected void enableTextAntiAliasing() {
try {
Class<?> clazz0 = Class.forName("sun.swing.SwingUtilities2");
Method isLocalDisplay = clazz0.getMethod("isLocalDisplay");
final Object lafCond = isLocalDisplay.invoke(null);
Class<?> clazz = Class.forName("sun.swing.SwingUtilities2$AATextInfo");
Method method = clazz.getMethod("getAATextInfo", boolean.class);
Object aaTextInfo = method.invoke(null, lafCond);
Field field = clazz0.getField("AA_TEXT_PROPERTY_KEY");
Object aaTextPropertyKey = field.get(null);
UIManager.getDefaults().put(aaTextPropertyKey, aaTextInfo);
}
// Java 9 does not have the class SwingUtilities2.AATextInfo anymore,
// but text anti-aliasing is enabled by default.
catch (ClassNotFoundException ignored) {}
catch (NoSuchMethodException ignored) {}
catch (InvocationTargetException ignored) {}
catch (IllegalAccessException ignored) {}
catch (NoSuchFieldException ignored) {}
}
protected void showAppVersion() {
System.out.println(
"This is " + Version.getApplicationName() + ' '
+ Version.getVersionName() + ' '
+ '(' + Version.getRevisionNumber() + ')'
);
}
protected String showJavaVersion() {
final String javaVersion = System.getProperty( "java.version" );
System.out.println( "Running Java version " + javaVersion );
return javaVersion;
}
protected void checkCpu() {
// Do nothing by default.
}
protected void setColor() {
// Do nothing by default.
}
protected void startForkDaemon() throws IOException {
ForkDaemon.start();
}
} |
package tonius.simplyjetpacks.integration;
import net.minecraft.block.Block;
import net.minecraft.item.ItemStack;
import net.minecraftforge.oredict.OreDictionary;
import tonius.simplyjetpacks.SimplyJetpacks;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.registry.GameRegistry;
public abstract class BCItems {
// Transport
public static Object pipeFluidStone = null;
public static Object pipeEnergyGold = null;
// Energy
public static Object engineCombustion = null;
// Factory
public static Object tank = null;
// Silicon
public static Object chipsetGold = null;
public static void init() {
SimplyJetpacks.logger.info("Stealing BuildCraft's items");
if (Loader.isModLoaded("BuildCraft|Transport")) {
pipeFluidStone = new ItemStack(GameRegistry.findItem("BuildCraft|Transport", "item.buildcraftPipe.pipefluidsstone"));
pipeEnergyGold = new ItemStack(GameRegistry.findItem("BuildCraft|Transport", "item.buildcraftPipe.pipepowergold"));
} else {
pipeFluidStone = "blockGlass";
pipeEnergyGold = "dustRedstone";
}
if (Loader.isModLoaded("BuildCraft|Energy")) {
Block engine = GameRegistry.findBlock("BuildCraft|Energy", "engineBlock");
if (engine == null) {
engine = GameRegistry.findBlock("BuildCraft|Core", "engineBlock");
}
engineCombustion = new ItemStack(engine, 1, 2);
} else {
engineCombustion = "gearIron";
}
if (Loader.isModLoaded("BuildCraft|Factory")) {
tank = new ItemStack(GameRegistry.findBlock("BuildCraft|Factory", "tankBlock"));
} else {
tank = "blockGlass";
}
if (Loader.isModLoaded("BuildCraft|Silicon")) {
chipsetGold = new ItemStack(GameRegistry.findItem("BuildCraft|Silicon", "redstoneChipset"), 1, 2);
} else {
chipsetGold = "gearGold";
}
}
public static ItemStack getStack(Object o) {
if (o instanceof ItemStack) {
return ((ItemStack) o).copy();
}
if (o instanceof String) {
return OreDictionary.getOres((String) o).get(0);
}
return null;
}
} |
package dr.inferencexml.distribution;
import java.io.File;
import java.io.FileNotFoundException;
import dr.inference.distribution.DistributionLikelihood;
import dr.inference.model.Likelihood;
import dr.inference.model.Statistic;
import dr.inference.trace.LogFileTraces;
import dr.inference.trace.TraceException;
import dr.inferencexml.trace.MarginalLikelihoodAnalysisParser;
import dr.math.distributions.*;
import dr.util.DataTable;
import dr.util.FileHelpers;
import dr.xml.*;
public class PriorParsers {
public static final String UNIFORM_PRIOR = "uniformPrior";
public static final String EXPONENTIAL_PRIOR = "exponentialPrior";
public static final String POISSON_PRIOR = "poissonPrior";
public static final String NORMAL_PRIOR = "normalPrior";
public static final String NORMAL_REFERENCE_PRIOR = "normalReferencePrior";
public static final String LOG_NORMAL_PRIOR = "logNormalPrior";
public static final String GAMMA_PRIOR = "gammaPrior";
public static final String GAMMA_REFERENCE_PRIOR = "gammaReferencePrior";
public static final String INVGAMMA_PRIOR = "invgammaPrior";
public static final String INVGAMMA_PRIOR_CORRECT = "inverseGammaPrior";
public static final String LAPLACE_PRIOR = "laplacePrior";
public static final String BETA_PRIOR = "betaPrior";
public static final String PARAMETER_COLUMN = "parameterColumn";
public static final String UPPER = "upper";
public static final String LOWER = "lower";
public static final String MEAN = "mean";
public static final String MEAN_IN_REAL_SPACE = "meanInRealSpace";
public static final String STDEV = "stdev";
public static final String SHAPE = "shape";
public static final String SHAPEB = "shapeB";
public static final String SCALE = "scale";
public static final String OFFSET = "offset";
public static final String UNINFORMATIVE = "uninformative";
/**
* A special parser that reads a convenient short form of priors on parameters.
*/
public static XMLObjectParser UNIFORM_PRIOR_PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return UNIFORM_PRIOR;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
double lower = xo.getDoubleAttribute(LOWER);
double upper = xo.getDoubleAttribute(UPPER);
if (lower == Double.NEGATIVE_INFINITY || upper == Double.POSITIVE_INFINITY)
throw new XMLParseException("Uniform prior " + xo.getName() + " cannot take a bound at infinity, " +
"because it returns 1/(high-low) = 1/inf");
DistributionLikelihood likelihood = new DistributionLikelihood(new UniformDistribution(lower, upper));
for (int j = 0; j < xo.getChildCount(); j++) {
if (xo.getChild(j) instanceof Statistic) {
likelihood.addData((Statistic) xo.getChild(j));
} else {
throw new XMLParseException("illegal element in " + xo.getName() + " element");
}
}
return likelihood;
}
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
private final XMLSyntaxRule[] rules = {
AttributeRule.newDoubleRule(LOWER),
AttributeRule.newDoubleRule(UPPER),
new ElementRule(Statistic.class, 1, Integer.MAX_VALUE)
};
public String getParserDescription() {
return "Calculates the prior probability of some data under a given uniform distribution.";
}
public Class getReturnType() {
return Likelihood.class;
}
};
/**
* A special parser that reads a convenient short form of priors on parameters.
*/
public static XMLObjectParser EXPONENTIAL_PRIOR_PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return EXPONENTIAL_PRIOR;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
double scale;
if (xo.hasAttribute(SCALE)) {
scale = xo.getDoubleAttribute(SCALE);
} else {
scale = xo.getDoubleAttribute(MEAN);
}
final double offset = xo.hasAttribute(OFFSET) ? xo.getDoubleAttribute(OFFSET) : 0.0;
DistributionLikelihood likelihood = new DistributionLikelihood(new ExponentialDistribution(1.0 / scale), offset);
for (int j = 0; j < xo.getChildCount(); j++) {
if (xo.getChild(j) instanceof Statistic) {
likelihood.addData((Statistic) xo.getChild(j));
} else {
throw new XMLParseException("illegal element in " + xo.getName() + " element");
}
}
return likelihood;
}
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
private final XMLSyntaxRule[] rules = {
new XORRule(
AttributeRule.newDoubleRule(SCALE),
AttributeRule.newDoubleRule(MEAN)
),
AttributeRule.newDoubleRule(OFFSET, true),
new ElementRule(Statistic.class, 1, Integer.MAX_VALUE)
};
public String getParserDescription() {
return "Calculates the prior probability of some data under a given exponential distribution.";
}
public Class getReturnType() {
return Likelihood.class;
}
};
/**
* A special parser that reads a convenient short form of priors on parameters.
*/
public static XMLObjectParser POISSON_PRIOR_PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return POISSON_PRIOR;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
double mean = xo.getDoubleAttribute(MEAN);
double offset = xo.getDoubleAttribute(OFFSET);
DistributionLikelihood likelihood = new DistributionLikelihood(new PoissonDistribution(mean), offset);
for (int j = 0; j < xo.getChildCount(); j++) {
if (xo.getChild(j) instanceof Statistic) {
likelihood.addData((Statistic) xo.getChild(j));
} else {
throw new XMLParseException("illegal element in " + xo.getName() + " element");
}
}
return likelihood;
}
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
private final XMLSyntaxRule[] rules = {
AttributeRule.newDoubleRule(MEAN),
AttributeRule.newDoubleRule(OFFSET),
new ElementRule(Statistic.class, 1, Integer.MAX_VALUE)
};
public String getParserDescription() {
return "Calculates the prior probability of some data under a given poisson distribution.";
}
public Class getReturnType() {
return Likelihood.class;
}
};
/**
* A special parser that reads a convenient short form of priors on parameters.
*/
public static XMLObjectParser NORMAL_PRIOR_PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return NORMAL_PRIOR;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
double mean = xo.getDoubleAttribute(MEAN);
double stdev = xo.getDoubleAttribute(STDEV);
DistributionLikelihood likelihood = new DistributionLikelihood(new NormalDistribution(mean, stdev));
for (int j = 0; j < xo.getChildCount(); j++) {
if (xo.getChild(j) instanceof Statistic) {
likelihood.addData((Statistic) xo.getChild(j));
} else {
throw new XMLParseException("illegal element in " + xo.getName() + " element");
}
}
return likelihood;
}
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
private final XMLSyntaxRule[] rules = {
AttributeRule.newDoubleRule(MEAN),
AttributeRule.newDoubleRule(STDEV),
new ElementRule(Statistic.class, 1, Integer.MAX_VALUE)
};
public String getParserDescription() {
return "Calculates the prior probability of some data under a given normal distribution.";
}
public Class getReturnType() {
return Likelihood.class;
}
};
/**
* A special parser that reads a convenient short form of reference priors on parameters.
*/
public static XMLObjectParser GAMMA_REFERENCE_PRIOR_PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return GAMMA_REFERENCE_PRIOR;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
String fileName = xo.getStringAttribute(FileHelpers.FILE_NAME);
try {
File file = new File(fileName);
String parent = file.getParent();
if (!file.isAbsolute()) {
parent = System.getProperty("user.dir");
}
file = new File(parent, fileName);
fileName = file.getAbsolutePath();
String parameterName = xo.getStringAttribute(PARAMETER_COLUMN);
LogFileTraces traces = new LogFileTraces(fileName, file);
traces.loadTraces();
int maxState = traces.getMaxState();
// leaving the burnin attribute off will result in 10% being used
int burnin = xo.getAttribute("burnin", maxState / 10);
if (burnin < 0 || burnin >= maxState) {
burnin = maxState / 10;
System.out.println("WARNING: Burn-in larger than total number of states - using 10%");
}
traces.setBurnIn(burnin);
int traceIndexParameter = -1;
for (int i = 0; i < traces.getTraceCount(); i++) {
String traceName = traces.getTraceName(i);
if (traceName.trim().equals(parameterName)) {
traceIndexParameter = i;
}
}
if (traceIndexParameter == -1) {
throw new XMLParseException("Column '" + parameterName + "' can not be found for " + getParserName() + " element.");
}
Double[] parameterSamples = new Double[traces.getStateCount()];
DistributionLikelihood likelihood = new DistributionLikelihood(new GammaKDEDistribution((Double[]) traces.getValues(traceIndexParameter).toArray(parameterSamples)));
for (int j = 0; j < xo.getChildCount(); j++) {
if (xo.getChild(j) instanceof Statistic) {
likelihood.addData((Statistic) xo.getChild(j));
} else {
throw new XMLParseException("illegal element in " + xo.getName() + " element");
}
}
return likelihood;
} catch (FileNotFoundException fnfe) {
throw new XMLParseException("File '" + fileName + "' can not be opened for " + getParserName() + " element.");
} catch (java.io.IOException ioe) {
throw new XMLParseException(ioe.getMessage());
} catch (TraceException e) {
throw new XMLParseException(e.getMessage());
}
}
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
private final XMLSyntaxRule[] rules = {
AttributeRule.newStringRule("fileName"),
AttributeRule.newStringRule("parameterColumn"),
AttributeRule.newIntegerRule("burnin"),
new ElementRule(Statistic.class, 1, Integer.MAX_VALUE)
};
public String getParserDescription() {
return "Calculates the reference prior probability of some data under a given normal distribution.";
}
public Class getReturnType() {
return Likelihood.class;
}
};
/**
* A special parser that reads a convenient short form of reference priors on parameters.
*/
public static XMLObjectParser NORMAL_REFERENCE_PRIOR_PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return NORMAL_REFERENCE_PRIOR;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
String fileName = xo.getStringAttribute(FileHelpers.FILE_NAME);
try {
File file = new File(fileName);
String parent = file.getParent();
if (!file.isAbsolute()) {
parent = System.getProperty("user.dir");
}
file = new File(parent, fileName);
fileName = file.getAbsolutePath();
String parameterName = xo.getStringAttribute(PARAMETER_COLUMN);
LogFileTraces traces = new LogFileTraces(fileName, file);
traces.loadTraces();
int maxState = traces.getMaxState();
// leaving the burnin attribute off will result in 10% being used
int burnin = xo.getAttribute("burnin", maxState / 10);
if (burnin < 0 || burnin >= maxState) {
burnin = maxState / 10;
System.out.println("WARNING: Burn-in larger than total number of states - using 10%");
}
traces.setBurnIn(burnin);
int traceIndexParameter = -1;
for (int i = 0; i < traces.getTraceCount(); i++) {
String traceName = traces.getTraceName(i);
if (traceName.trim().equals(parameterName)) {
traceIndexParameter = i;
}
}
if (traceIndexParameter == -1) {
throw new XMLParseException("Column '" + parameterName + "' can not be found for " + getParserName() + " element.");
}
Double[] parameterSamples = new Double[traces.getStateCount()];
DistributionLikelihood likelihood = new DistributionLikelihood(new NormalKDEDistribution((Double[]) traces.getValues(traceIndexParameter).toArray(parameterSamples)));
for (int j = 0; j < xo.getChildCount(); j++) {
if (xo.getChild(j) instanceof Statistic) {
likelihood.addData((Statistic) xo.getChild(j));
} else {
throw new XMLParseException("illegal element in " + xo.getName() + " element");
}
}
return likelihood;
} catch (FileNotFoundException fnfe) {
throw new XMLParseException("File '" + fileName + "' can not be opened for " + getParserName() + " element.");
} catch (java.io.IOException ioe) {
throw new XMLParseException(ioe.getMessage());
} catch (TraceException e) {
throw new XMLParseException(e.getMessage());
}
}
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
private final XMLSyntaxRule[] rules = {
AttributeRule.newStringRule("fileName"),
AttributeRule.newStringRule("parameterColumn"),
AttributeRule.newIntegerRule("burnin"),
new ElementRule(Statistic.class, 1, Integer.MAX_VALUE)
};
public String getParserDescription() {
return "Calculates the reference prior probability of some data under a given normal distribution.";
}
public Class getReturnType() {
return Likelihood.class;
}
};
/**
* A special parser that reads a convenient short form of priors on parameters.
* <p/>
* If X ~ logNormal, then log(X) ~ Normal.
* <br>
* <br>
* If meanInRealSpace=false, <code>mean</code> specifies the mean of log(X) and
* <code>stdev</code> specifies the standard deviation of log(X).
* <br>
* <br>
* If meanInRealSpace=true, <code>mean</code> specifies the mean of X, but <code>
* stdev</code> specifies the standard deviation of log(X).
* <br>
*/
public static XMLObjectParser LOG_NORMAL_PRIOR_PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return LOG_NORMAL_PRIOR;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
double mean = xo.getDoubleAttribute(MEAN);
final double stdev = xo.getDoubleAttribute(STDEV);
final double offset = xo.getAttribute(OFFSET, 0.0);
final boolean meanInRealSpace = xo.getAttribute(MEAN_IN_REAL_SPACE, false);
if (meanInRealSpace) {
if (mean <= 0) {
throw new IllegalArgumentException("meanInRealSpace works only for a positive mean");
}
mean = Math.log(mean) - 0.5 * stdev * stdev;
}
final DistributionLikelihood likelihood = new DistributionLikelihood(new LogNormalDistribution(mean, stdev), offset);
for (int j = 0; j < xo.getChildCount(); j++) {
if (xo.getChild(j) instanceof Statistic) {
likelihood.addData((Statistic) xo.getChild(j));
} else {
throw new XMLParseException("illegal element in " + xo.getName() + " element");
}
}
return likelihood;
}
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
private final XMLSyntaxRule[] rules = {
AttributeRule.newDoubleRule(MEAN),
AttributeRule.newDoubleRule(STDEV),
AttributeRule.newDoubleRule(OFFSET, true),
AttributeRule.newBooleanRule(MEAN_IN_REAL_SPACE, true),
new ElementRule(Statistic.class, 1, Integer.MAX_VALUE)
};
public String getParserDescription() {
return "Calculates the prior probability of some data under a given lognormal distribution.";
}
public Class getReturnType() {
return Likelihood.class;
}
};
/**
* A special parser that reads a convenient short form of priors on parameters.
*/
public static XMLObjectParser GAMMA_PRIOR_PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return GAMMA_PRIOR;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
final double shape = xo.getDoubleAttribute(SHAPE);
final double scale = xo.getDoubleAttribute(SCALE);
final double offset = xo.getAttribute(OFFSET, 0.0);
DistributionLikelihood likelihood = new DistributionLikelihood(new GammaDistribution(shape, scale), offset);
for (int j = 0; j < xo.getChildCount(); j++) {
if (xo.getChild(j) instanceof Statistic) {
likelihood.addData((Statistic) xo.getChild(j));
} else {
throw new XMLParseException("illegal element in " + xo.getName() + " element");
}
}
return likelihood;
}
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
private final XMLSyntaxRule[] rules = {
AttributeRule.newDoubleRule(SHAPE),
AttributeRule.newDoubleRule(SCALE),
AttributeRule.newDoubleRule(OFFSET, true),
// AttributeRule.newBooleanRule(UNINFORMATIVE, true),
new ElementRule(Statistic.class, 1, Integer.MAX_VALUE)
};
public String getParserDescription() {
return "Calculates the prior probability of some data under a given gamma distribution.";
}
public Class getReturnType() {
return Likelihood.class;
}
};
/**
* A special parser that reads a convenient short form of priors on parameters.
*/
public static XMLObjectParser INVGAMMA_PRIOR_PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return INVGAMMA_PRIOR;
}
public String[] getParserNames() {
return new String[] { INVGAMMA_PRIOR, INVGAMMA_PRIOR_CORRECT };
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
final double shape = xo.getDoubleAttribute(SHAPE);
final double scale = xo.getDoubleAttribute(SCALE);
final double offset = xo.getDoubleAttribute(OFFSET);
DistributionLikelihood likelihood = new DistributionLikelihood(new InverseGammaDistribution(shape, scale), offset);
for (int j = 0; j < xo.getChildCount(); j++) {
if (xo.getChild(j) instanceof Statistic) {
likelihood.addData((Statistic) xo.getChild(j));
} else {
throw new XMLParseException("illegal element in " + xo.getName() + " element");
}
}
return likelihood;
}
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
private final XMLSyntaxRule[] rules = {
AttributeRule.newDoubleRule(SHAPE),
AttributeRule.newDoubleRule(SCALE),
AttributeRule.newDoubleRule(OFFSET),
new ElementRule(Statistic.class, 1, Integer.MAX_VALUE)
};
public String getParserDescription() {
return "Calculates the prior probability of some data under a given inverse gamma distribution.";
}
public Class getReturnType() {
return Likelihood.class;
}
};
public static XMLObjectParser LAPLACE_PRIOR_PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return LAPLACE_PRIOR;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
double mean = xo.getDoubleAttribute(MEAN);
double scale = xo.getDoubleAttribute(SCALE);
DistributionLikelihood likelihood = new DistributionLikelihood(new LaplaceDistribution(mean, scale));
for (int j = 0; j < xo.getChildCount(); j++) {
if (xo.getChild(j) instanceof Statistic) {
likelihood.addData((Statistic) xo.getChild(j));
} else {
throw new XMLParseException("illegal element in " + xo.getName() + " element");
}
}
return likelihood;
}
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
private final XMLSyntaxRule[] rules = {
AttributeRule.newDoubleRule(MEAN),
AttributeRule.newDoubleRule(SCALE),
new ElementRule(Statistic.class, 1, Integer.MAX_VALUE)
};
public String getParserDescription() {
return "Calculates the prior probability of some data under a given laplace distribution.";
}
public Class getReturnType() {
return Likelihood.class;
}
};
/**
* A special parser that reads a convenient short form of priors on parameters.
*/
public static XMLObjectParser BETA_PRIOR_PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return BETA_PRIOR;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
final double shape = xo.getDoubleAttribute(SHAPE);
final double shapeB = xo.getDoubleAttribute(SHAPEB);
final double offset = xo.getAttribute(OFFSET, 0.0);
DistributionLikelihood likelihood = new DistributionLikelihood(new BetaDistribution(shape, shapeB), offset);
for (int j = 0; j < xo.getChildCount(); j++) {
if (xo.getChild(j) instanceof Statistic) {
likelihood.addData((Statistic) xo.getChild(j));
} else {
throw new XMLParseException("illegal element in " + xo.getName() + " element");
}
}
return likelihood;
}
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
private final XMLSyntaxRule[] rules = {
AttributeRule.newDoubleRule(SHAPE),
AttributeRule.newDoubleRule(SHAPEB),
AttributeRule.newDoubleRule(OFFSET, true),
new ElementRule(Statistic.class, 1, Integer.MAX_VALUE)
};
public String getParserDescription() {
return "Calculates the prior probability of some data under a given beta distribution.";
}
public Class getReturnType() {
return Likelihood.class;
}
};
} |
package net.aksingh.owmjapis;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.*;
import java.util.zip.GZIPInputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
public class OpenWeatherMap {
/*
URLs and parameters for OWM.org
*/
private static final String URL_API = "http://api.openweathermap.org/data/2.5/";
private static final String URL_CURRENT = "weather?";
private static final String URL_HOURLY_FORECAST = "forecast?";
private static final String URL_DAILY_FORECAST = "forecast/daily?";
private static final String PARAM_COUNT = "cnt=";
private static final String PARAM_CITY_NAME = "q=";
private static final String PARAM_CITY_ID = "id=";
private static final String PARAM_LATITUDE = "lat=";
private static final String PARAM_LONGITUDE = "lon=";
private static final String PARAM_MODE = "mode=";
private static final String PARAM_UNITS = "units=";
private static final String PARAM_APPID = "appId=";
private static final String PARAM_LANG = "lang=";
/*
Instance Variables
*/
private final OWMAddress owmAddress;
private final OWMResponse owmResponse;
private final OWMProxy owmProxy;
public OpenWeatherMap(String apiKey) {
this(Units.IMPERIAL, Language.ENGLISH, apiKey);
}
public OpenWeatherMap(Units units, String apiKey) {
this(units, Language.ENGLISH, apiKey);
}
public OpenWeatherMap(Units units, Language lang, String apiKey) {
this.owmAddress = new OWMAddress(units, lang, apiKey);
this.owmProxy = new OWMProxy(null, Integer.MIN_VALUE, null, null);
this.owmResponse = new OWMResponse(owmAddress, owmProxy);
}
/*
Getters
*/
public OWMAddress getOwmAddressInstance() {
return owmAddress;
}
public String getApiKey() {
return owmAddress.getAppId();
}
public Units getUnits() {
return owmAddress.getUnits();
}
public String getMode() {
return owmAddress.getMode();
}
public Language getLang() {
return owmAddress.getLang();
}
/*
Setters
*/
/**
* Set units for getting data from OWM.org
*
* @param units Any constant from Units
* @see net.aksingh.owmjapis.OpenWeatherMap.Units
*/
public void setUnits(Units units) {
owmAddress.setUnits(units);
}
public void setApiKey(String appId) {
owmAddress.setAppId(appId);
}
public void setLang(Language lang) {
owmAddress.setLang(lang);
}
/**
* Set proxy for getting data from OWM.org
*
* @param ip IP address of the proxy
* @param port Port address of the proxy
*/
public void setProxy(String ip, int port) {
owmProxy.setIp(ip);
owmProxy.setPort(port);
owmProxy.setUser(null);
owmProxy.setPass(null);
}
/**
* Set proxy and authentication details for getting data from OWM.org
*
* @param ip IP address of the proxy
* @param port Port address of the proxy
* @param user User name for the proxy if required
* @param pass Password for the proxy if required
*/
public void setProxy(String ip, int port, String user, String pass) {
owmProxy.setIp(ip);
owmProxy.setPort(port);
owmProxy.setUser(user);
owmProxy.setPass(pass);
}
public CurrentWeather currentWeatherByCityName(String cityName)
throws IOException, JSONException {
String response = owmResponse.currentWeatherByCityName(cityName);
return this.currentWeatherFromRawResponse(response);
}
public CurrentWeather currentWeatherByCityName(String cityName, String countryCode)
throws IOException, JSONException {
String response = owmResponse.currentWeatherByCityName(cityName, countryCode);
return this.currentWeatherFromRawResponse(response);
}
public CurrentWeather currentWeatherByCityCode(long cityCode)
throws JSONException {
String response = owmResponse.currentWeatherByCityCode(cityCode);
return this.currentWeatherFromRawResponse(response);
}
public CurrentWeather currentWeatherByCoordinates(float latitude, float longitude)
throws JSONException {
String response = owmResponse.currentWeatherByCoordinates(latitude, longitude);
return this.currentWeatherFromRawResponse(response);
}
public CurrentWeather currentWeatherFromRawResponse(String response)
throws JSONException {
JSONObject jsonObj = (response != null) ? new JSONObject(response) : null;
return new CurrentWeather(jsonObj);
}
public HourlyForecast hourlyForecastByCityName(String cityName)
throws IOException, JSONException {
String response = owmResponse.hourlyForecastByCityName(cityName);
return this.hourlyForecastFromRawResponse(response);
}
public HourlyForecast hourlyForecastByCityName(String cityName, String countryCode)
throws IOException, JSONException {
String response = owmResponse.hourlyForecastByCityName(cityName, countryCode);
return this.hourlyForecastFromRawResponse(response);
}
public HourlyForecast hourlyForecastByCityCode(long cityCode)
throws JSONException {
String response = owmResponse.hourlyForecastByCityCode(cityCode);
return this.hourlyForecastFromRawResponse(response);
}
public HourlyForecast hourlyForecastByCoordinates(float latitude, float longitude)
throws JSONException {
String response = owmResponse.hourlyForecastByCoordinates(latitude, longitude);
return this.hourlyForecastFromRawResponse(response);
}
public HourlyForecast hourlyForecastFromRawResponse(String response)
throws JSONException {
JSONObject jsonObj = (response != null) ? new JSONObject(response) : null;
return new HourlyForecast(jsonObj);
}
public DailyForecast dailyForecastByCityName(String cityName, byte count)
throws IOException, JSONException {
String response = owmResponse.dailyForecastByCityName(cityName, count);
return this.dailyForecastFromRawResponse(response);
}
public DailyForecast dailyForecastByCityName(String cityName, String countryCode, byte count)
throws IOException, JSONException {
String response = owmResponse.dailyForecastByCityName(cityName, countryCode, count);
return this.dailyForecastFromRawResponse(response);
}
public DailyForecast dailyForecastByCityCode(long cityCode, byte count)
throws JSONException {
String response = owmResponse.dailyForecastByCityCode(cityCode, count);
return this.dailyForecastFromRawResponse(response);
}
public DailyForecast dailyForecastByCoordinates(float latitude, float longitude, byte count)
throws JSONException {
String response = owmResponse.dailyForecastByCoordinates(latitude, longitude, count);
return this.dailyForecastFromRawResponse(response);
}
public DailyForecast dailyForecastFromRawResponse(String response)
throws JSONException {
JSONObject jsonObj = (response != null) ? new JSONObject(response) : null;
return new DailyForecast(jsonObj);
}
/**
* Units that can be set for getting data from OWM.org
*
* @since 2.5.0.3
*/
public static enum Units {
METRIC("metric"),
IMPERIAL("imperial");
private final String unit;
Units(String unit) {
this.unit = unit;
}
}
/**
* Languages that can be set for getting data from OWM.org
*
* @since 2.5.0.3
*/
public static enum Language {
ENGLISH("en"),
RUSSIAN("ru"),
ITALIAN("it"),
SPANISH("es"),
UKRAINIAN("uk"),
GERMAN("de"),
PORTUGUESE("pt"),
ROMANIAN("ro"),
POLISH("pl"),
FINNISH("fi"),
DUTCH("nl"),
FRENCH("FR"),
BULGARIAN("bg"),
SWEDISH("sv"),
CHINESE_TRADITIONAL("zh_tw"),
CHINESE_SIMPLIFIED("zh"),
TURKISH("tr"),
CROATIAN("hr"),
CATALAN("ca");
private final String lang;
Language(String lang) {
this.lang = lang;
}
}
/**
* Proxifies the default HTTP requests
*
* @since 2.5.0.5
*/
private static class OWMProxy {
private String ip;
private int port;
private String user;
private String pass;
private OWMProxy(String ip, int port, String user, String pass) {
this.ip = ip;
this.port = port;
this.user = user;
this.pass = pass;
}
public Proxy getProxy() {
Proxy proxy = null;
if (ip != null && (! "".equals(ip)) && port != Integer.MIN_VALUE) {
proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ip, port));
}
if (user != null && (! "".equals(user)) && pass != null && (! "".equals(pass))) {
Authenticator.setDefault(getAuthenticatorInstance(user, pass));
}
return proxy;
}
private Authenticator getAuthenticatorInstance(final String user, final String pass) {
Authenticator authenticator = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return (new PasswordAuthentication(user, pass.toCharArray()));
}
};
return authenticator;
}
public void setIp(String ip) {
this.ip = ip;
}
public void setPort(int port) {
this.port = port;
}
public void setUser(String user) {
this.user = user;
}
public void setPass(String pass) {
this.pass = pass;
}
}
/**
* Generates addresses for accessing the information from OWM.org
*
* @since 2.5.0.3
*/
public static class OWMAddress {
private static final String MODE = "json";
private static final String ENCODING = "UTF-8";
private String mode;
private Units units;
private String appId;
private Language lang;
/*
Constructors
*/
private OWMAddress(String appId) {
this(Units.IMPERIAL, Language.ENGLISH, appId);
}
private OWMAddress(Units units, String appId) {
this(units, Language.ENGLISH, appId);
}
private OWMAddress(Units units, Language lang, String appId) {
this.mode = MODE;
this.units = units;
this.lang = lang;
this.appId = appId;
}
/*
Getters
*/
private String getAppId() {
return this.appId;
}
private Units getUnits() {
return this.units;
}
private String getMode() {
return this.mode;
}
private Language getLang() {
return this.lang;
}
/*
Setters
*/
private void setUnits(Units units) {
this.units = units;
}
private void setAppId(String appId) {
this.appId = appId;
}
private void setLang(Language lang) {
this.lang = lang;
}
/*
Addresses for current weather
*/
public String currentWeatherByCityName(String cityName) throws UnsupportedEncodingException {
return new StringBuilder()
.append(URL_API).append(URL_CURRENT)
.append(PARAM_CITY_NAME).append(URLEncoder.encode(cityName, ENCODING)).append("&")
.append(PARAM_MODE).append(this.mode).append("&")
.append(PARAM_UNITS).append(this.units).append("&")
.append(PARAM_LANG).append(this.lang).append("&")
.append(PARAM_APPID).append(this.appId)
.toString();
}
public String currentWeatherByCityName(String cityName, String countryCode) throws UnsupportedEncodingException {
return currentWeatherByCityName(new StringBuilder()
.append(cityName).append(",").append(countryCode)
.toString());
}
public String currentWeatherByCityCode(long cityCode) {
return new StringBuilder()
.append(URL_API).append(URL_CURRENT)
.append(PARAM_CITY_ID).append(Long.toString(cityCode)).append("&")
.append(PARAM_MODE).append(this.mode).append("&")
.append(PARAM_UNITS).append(this.units).append("&")
.append(PARAM_LANG).append(this.lang).append("&")
.append(PARAM_APPID).append(this.appId)
.toString();
}
public String currentWeatherByCoordinates(float latitude, float longitude) {
return new StringBuilder()
.append(URL_API).append(URL_CURRENT)
.append(PARAM_LATITUDE).append(Float.toString(latitude)).append("&")
.append(PARAM_LONGITUDE).append(Float.toString(longitude)).append("&")
.append(PARAM_MODE).append(this.mode).append("&")
.append(PARAM_UNITS).append(this.units).append("&")
.append(PARAM_APPID).append(this.appId)
.toString();
}
/*
Addresses for hourly forecasts
*/
public String hourlyForecastByCityName(String cityName) throws UnsupportedEncodingException {
return new StringBuilder()
.append(URL_API).append(URL_HOURLY_FORECAST)
.append(PARAM_CITY_NAME).append(URLEncoder.encode(cityName, ENCODING)).append("&")
.append(PARAM_MODE).append(this.mode).append("&")
.append(PARAM_UNITS).append(this.units).append("&")
.append(PARAM_LANG).append(this.lang).append("&")
.append(PARAM_APPID).append(this.appId)
.toString();
}
public String hourlyForecastByCityName(String cityName, String countryCode) throws UnsupportedEncodingException {
return hourlyForecastByCityName(new StringBuilder()
.append(cityName).append(",").append(countryCode)
.toString());
}
public String hourlyForecastByCityCode(long cityCode) {
return new StringBuilder()
.append(URL_API).append(URL_HOURLY_FORECAST)
.append(PARAM_CITY_ID).append(Long.toString(cityCode)).append("&")
.append(PARAM_MODE).append(this.mode).append("&")
.append(PARAM_UNITS).append(this.units).append("&")
.append(PARAM_LANG).append(this.lang).append("&")
.append(PARAM_APPID).append(this.appId)
.toString();
}
public String hourlyForecastByCoordinates(float latitude, float longitude) {
return new StringBuilder()
.append(URL_API).append(URL_HOURLY_FORECAST)
.append(PARAM_LATITUDE).append(Float.toString(latitude)).append("&")
.append(PARAM_LONGITUDE).append(Float.toString(longitude)).append("&")
.append(PARAM_MODE).append(this.mode).append("&")
.append(PARAM_UNITS).append(this.units).append("&")
.append(PARAM_LANG).append(this.lang).append("&")
.append(PARAM_APPID).append(this.appId)
.toString();
}
/*
Addresses for daily forecasts
*/
public String dailyForecastByCityName(String cityName, byte count) throws UnsupportedEncodingException {
return new StringBuilder()
.append(URL_API).append(URL_DAILY_FORECAST)
.append(PARAM_CITY_NAME).append(URLEncoder.encode(cityName, ENCODING)).append("&")
.append(PARAM_COUNT).append(Byte.toString(count)).append("&")
.append(PARAM_MODE).append(this.mode).append("&")
.append(PARAM_UNITS).append(this.units).append("&")
.append(PARAM_LANG).append(this.lang).append("&")
.append(PARAM_APPID).append(this.appId)
.toString();
}
public String dailyForecastByCityName(String cityName, String countryCode, byte count) throws UnsupportedEncodingException {
return dailyForecastByCityName(new StringBuilder()
.append(cityName).append(",").append(countryCode)
.toString(), count);
}
public String dailyForecastByCityCode(long cityCode, byte count) {
return new StringBuilder()
.append(URL_API).append(URL_DAILY_FORECAST)
.append(PARAM_CITY_ID).append(Long.toString(cityCode)).append("&")
.append(PARAM_COUNT).append(Byte.toString(count)).append("&")
.append(PARAM_MODE).append(this.mode).append("&")
.append(PARAM_UNITS).append(this.units).append("&")
.append(PARAM_LANG).append(this.lang).append("&")
.append(PARAM_APPID).append(this.appId)
.toString();
}
public String dailyForecastByCoordinates(float latitude, float longitude, byte count) {
return new StringBuilder()
.append(URL_API).append(URL_DAILY_FORECAST)
.append(PARAM_LATITUDE).append(Float.toString(latitude)).append("&")
.append(PARAM_LONGITUDE).append(Float.toString(longitude)).append("&")
.append(PARAM_COUNT).append(Byte.toString(count)).append("&")
.append(PARAM_MODE).append(this.mode).append("&")
.append(PARAM_UNITS).append(this.units).append("&")
.append(PARAM_LANG).append(this.lang).append("&")
.append(PARAM_APPID).append(this.appId)
.toString();
}
}
/**
* Requests OWM.org for data and provides back the incoming response.
*
* @since 2.5.0.3
*/
private static class OWMResponse {
private final OWMAddress owmAddress;
private final OWMProxy owmProxy;
public OWMResponse(OWMAddress owmAddress, OWMProxy owmProxy) {
this.owmAddress = owmAddress;
this.owmProxy = owmProxy;
}
/*
Responses for current weather
*/
public String currentWeatherByCityName(String cityName) throws UnsupportedEncodingException {
String address = owmAddress.currentWeatherByCityName(cityName);
return httpGET(address);
}
public String currentWeatherByCityName(String cityName, String countryCode) throws UnsupportedEncodingException {
String address = owmAddress.currentWeatherByCityName(cityName, countryCode);
return httpGET(address);
}
public String currentWeatherByCityCode(long cityCode) {
String address = owmAddress.currentWeatherByCityCode(cityCode);
return httpGET(address);
}
public String currentWeatherByCoordinates(float latitude, float longitude) {
String address = owmAddress.currentWeatherByCoordinates(latitude, longitude);
return httpGET(address);
}
/*
Responses for hourly forecasts
*/
public String hourlyForecastByCityName(String cityName) throws UnsupportedEncodingException {
String address = owmAddress.hourlyForecastByCityName(cityName);
return httpGET(address);
}
public String hourlyForecastByCityName(String cityName, String countryCode) throws UnsupportedEncodingException {
String address = owmAddress.hourlyForecastByCityName(cityName, countryCode);
return httpGET(address);
}
public String hourlyForecastByCityCode(long cityCode) {
String address = owmAddress.hourlyForecastByCityCode(cityCode);
return httpGET(address);
}
public String hourlyForecastByCoordinates(float latitude, float longitude) {
String address = owmAddress.hourlyForecastByCoordinates(latitude, longitude);
return httpGET(address);
}
/*
Responses for daily forecasts
*/
public String dailyForecastByCityName(String cityName, byte count) throws UnsupportedEncodingException {
String address = owmAddress.dailyForecastByCityName(cityName, count);
return httpGET(address);
}
public String dailyForecastByCityName(String cityName, String countryCode, byte count) throws UnsupportedEncodingException {
String address = owmAddress.dailyForecastByCityName(cityName, countryCode, count);
return httpGET(address);
}
public String dailyForecastByCityCode(long cityCode, byte count) {
String address = owmAddress.dailyForecastByCityCode(cityCode, count);
return httpGET(address);
}
public String dailyForecastByCoordinates(float latitude, float longitude, byte count) {
String address = owmAddress.dailyForecastByCoordinates(latitude, longitude, count);
return httpGET(address);
}
private String httpGET(String requestAddress) {
URL request;
HttpURLConnection connection = null;
BufferedReader reader = null;
String tmpStr;
String response = null;
try {
request = new URL(requestAddress);
if (owmProxy.getProxy() != null) {
connection = (HttpURLConnection) request.openConnection(owmProxy.getProxy());
} else {
connection = (HttpURLConnection) request.openConnection();
}
connection.setRequestMethod("GET");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(false);
connection.setRequestProperty("Accept-Encoding", "gzip, deflate");
connection.connect();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
String encoding = connection.getContentEncoding();
try {
if (encoding != null && "gzip".equalsIgnoreCase(encoding)) {
reader = new BufferedReader(new InputStreamReader(new GZIPInputStream(connection.getInputStream())));
} else if (encoding != null && "deflate".equalsIgnoreCase(encoding)) {
reader = new BufferedReader(new InputStreamReader(new InflaterInputStream(connection.getInputStream(), new Inflater(true))));
} else {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
}
while ((tmpStr = reader.readLine()) != null) {
response = tmpStr;
}
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
}
}
} else { // if HttpURLConnection is not okay
try {
reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
while ((tmpStr = reader.readLine()) != null) {
response = tmpStr;
}
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
}
}
// if response is bad
System.err.println("Bad Response: " + response + "\n");
return null;
}
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
response = null;
} finally {
if (connection != null) {
connection.disconnect();
}
}
return response;
}
}
} |
package uk.co.drnaylor.quickstart;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import ninja.leaping.configurate.ConfigurationNode;
import ninja.leaping.configurate.loader.ConfigurationLoader;
import ninja.leaping.configurate.objectmapping.ObjectMappingException;
import uk.co.drnaylor.quickstart.annotations.ModuleData;
import uk.co.drnaylor.quickstart.config.AbstractConfigAdapter;
import uk.co.drnaylor.quickstart.enums.ConstructionPhase;
import uk.co.drnaylor.quickstart.enums.LoadingStatus;
import uk.co.drnaylor.quickstart.enums.ModulePhase;
import uk.co.drnaylor.quickstart.exceptions.*;
import uk.co.drnaylor.quickstart.loaders.ModuleEnabler;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;
/**
* The ModuleContainer contains all modules for a particular modular system. It scans the provided {@link ClassLoader}
* classpath for {@link Module}s which has a root in the provided package. It handles all the discovery, module config
* file generation, loading and enabling of modules.
*
* <p>
* A system may have multiple module containers. Each module container is completely separate from one another.
* </p>
*/
public abstract class ModuleContainer {
/**
* The current phase of the container.
*/
private ConstructionPhase currentPhase = ConstructionPhase.INITALISED;
/**
* The modules that have been discovered by the container.
*/
protected final Map<String, ModuleSpec> discoveredModules = Maps.newLinkedHashMap();
/**
* Contains the main configuration file.
*/
protected final SystemConfig<?, ? extends ConfigurationLoader<?>> config;
/**
* The logger to use.
*/
protected final LoggerProxy loggerProxy;
/**
* Fires when the PREENABLE phase starts.
*/
private final Procedure onPreEnable;
/**
* Fires when the ENABLE phase starts.
*/
private final Procedure onEnable;
/**
* Fires when the POSTENABLE phase starts.
*/
private final Procedure onPostEnable;
/**
* Provides
*/
private final ModuleEnabler enabler;
/**
* Constructs a {@link ModuleContainer} and starts discovery of the modules.
*
* @param <N> The type of {@link ConfigurationNode} to use.
* @param configurationLoader The {@link ConfigurationLoader} that contains details of whether the modules should be enabled or not.
* @param moduleEnabler The {@link ModuleEnabler} that contains the logic to enable modules.
* @param loggerProxy The {@link LoggerProxy} that contains methods to send messages to the logger, or any other source.
* @param onPreEnable The {@link Procedure} to run on pre enable, before modules are pre-enabled.
* @param onEnable The {@link Procedure} to run on enable, before modules are pre-enabled.
* @param onPostEnable The {@link Procedure} to run on post enable, before modules are pre-enabled.
*
* @throws QuickStartModuleDiscoveryException if there is an error starting the Module Container.
*/
protected <N extends ConfigurationNode> ModuleContainer(ConfigurationLoader<N> configurationLoader,
LoggerProxy loggerProxy,
ModuleEnabler moduleEnabler,
Procedure onPreEnable,
Procedure onEnable,
Procedure onPostEnable) throws QuickStartModuleDiscoveryException {
try {
this.config = new SystemConfig<>(configurationLoader, loggerProxy);
this.loggerProxy = loggerProxy;
this.enabler = moduleEnabler;
this.onPreEnable = onPreEnable;
this.onPostEnable = onPostEnable;
this.onEnable = onEnable;
} catch (Exception e) {
throw new QuickStartModuleDiscoveryException("Unable to start QuickStart", e);
}
}
public final void startDiscover() throws QuickStartModuleDiscoveryException {
try {
Preconditions.checkState(currentPhase == ConstructionPhase.INITALISED);
currentPhase = ConstructionPhase.DISCOVERING;
Set<Class<? extends Module>> modules = discoverModules();
HashMap<String, ModuleSpec> discovered = Maps.newHashMap();
modules.forEach(s -> {
// If we have a module annotation, we are golden.
if (s.isAnnotationPresent(ModuleData.class)) {
ModuleData md = s.getAnnotation(ModuleData.class);
discovered.put(md.id().toLowerCase(), new ModuleSpec(s, md));
} else {
String id = s.getClass().getName().toLowerCase();
loggerProxy.warn(MessageFormat.format("The module {0} does not have a ModuleData annotation associated with it. We're just assuming an ID of {0}.", id));
discovered.put(id, new ModuleSpec(s, id, id, LoadingStatus.ENABLED, false));
}
});
// Create the dependency map.
resolveDependencyOrder(discovered);
// Modules discovered. Create the Module Config adapter.
Map<String, LoadingStatus> m = discoveredModules.entrySet().stream().filter(x -> !x.getValue().isMandatory())
.collect(Collectors.toMap(Map.Entry::getKey, v -> v.getValue().getStatus()));
// Attaches config adapter and loads in the defaults.
config.attachModulesConfig(m);
config.saveAdapterDefaults();
// Load what we have in config into our discovered modules.
try {
config.getConfigAdapter().getNode().forEach((k, v) -> {
try {
ModuleSpec ms = discoveredModules.get(k);
if (ms != null) {
ms.setStatus(v);
} else {
loggerProxy.warn(String.format("Ignoring module entry %s in the configuration file: module does not exist.", k));
}
} catch (IllegalStateException ex) {
loggerProxy.warn("A mandatory module can't have its status changed by config. Falling back to FORCELOAD for " + k);
}
});
} catch (ObjectMappingException e) {
loggerProxy.warn("Could not load modules config, falling back to defaults.");
e.printStackTrace();
}
// Modules have been discovered.
currentPhase = ConstructionPhase.DISCOVERED;
} catch (Exception e) {
throw new QuickStartModuleDiscoveryException("Unable to discover QuickStart modules", e);
}
}
private void resolveDependencyOrder(Map<String, ModuleSpec> modules) throws Exception {
// First, get the modules that have no deps.
processDependencyStep(modules, x -> x.getValue().getDeps().isEmpty() && x.getValue().getSoftDeps().isEmpty());
while (!modules.isEmpty()) {
Set<String> addedModules = discoveredModules.keySet();
processDependencyStep(modules, x -> addedModules.containsAll(x.getValue().getDeps()) && addedModules.containsAll(x.getValue().getSoftDeps()));
}
}
private void processDependencyStep(Map<String, ModuleSpec> modules, Predicate<Map.Entry<String, ModuleSpec>> predicate) throws Exception {
// Filter on the predicate
List<Map.Entry<String, ModuleSpec>> modulesToAdd = modules.entrySet().stream().filter(predicate)
.sorted((x, y) -> x.getValue().isMandatory() == y.getValue().isMandatory() ? x.getKey().compareTo(y.getKey()) : Boolean.compare(x.getValue().isMandatory(), y.getValue().isMandatory()))
.collect(Collectors.toList());
if (modulesToAdd.isEmpty()) {
throw new IllegalStateException("Some modules have circular dependencies: " + modules.keySet().stream().collect(Collectors.joining(", ")));
}
modulesToAdd.forEach(x -> {
discoveredModules.put(x.getKey(), x.getValue());
modules.remove(x.getKey());
});
}
protected abstract Set<Class<? extends Module>> discoverModules() throws Exception;
/**
* Gets the current phase of the module loader.
*
* @return The {@link ConstructionPhase}
*/
public ConstructionPhase getCurrentPhase() {
return currentPhase;
}
/**
* Gets a set of IDs of modules that are going to be loaded.
*
* @return The modules that are going to be loaded.
*/
public Set<String> getModules() {
return getModules(ModuleStatusTristate.ENABLE);
}
/**
* Gets a set of IDs of modules.
*
* @param enabledOnly If <code>true</code>, only return modules that are going to be loaded.
* @return The modules.
*/
public Set<String> getModules(final ModuleStatusTristate enabledOnly) {
Preconditions.checkNotNull(enabledOnly);
Preconditions.checkState(currentPhase != ConstructionPhase.INITALISED && currentPhase != ConstructionPhase.DISCOVERING);
return discoveredModules.entrySet().stream().filter(enabledOnly.statusPredicate).map(Map.Entry::getKey).collect(Collectors.toSet());
}
/**
* Gets an immutable {@link Map} of module IDs to their {@link LoadingStatus} (disabled, enabled, forceload).
*
* @return The modules with their loading states.
*/
public Map<String, LoadingStatus> getModulesWithLoadingState() {
Preconditions.checkState(currentPhase != ConstructionPhase.INITALISED && currentPhase != ConstructionPhase.DISCOVERING);
return ImmutableMap.copyOf(discoveredModules.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, v -> v.getValue().getStatus())));
}
/**
* Gets whether a module is enabled and loaded.
*
* @param moduleId The module ID to check for.
* @return <code>true</code> if it is enabled.
* @throws NoModuleException Thrown if the module does not exist and modules have been loaded.
*/
public boolean isModuleLoaded(String moduleId) throws NoModuleException {
if (currentPhase != ConstructionPhase.ENABLING && currentPhase != ConstructionPhase.ENABLED) {
return false;
}
ModuleSpec ms = discoveredModules.get(moduleId.toLowerCase());
if (ms == null) {
// No module
throw new NoModuleException(moduleId);
}
return ms.getPhase() == ModulePhase.ENABLED;
}
/**
* Requests that a module be disabled. This can only be run during the {@link ConstructionPhase#DISCOVERED} phase.
*
* @param moduleName The ID of the module.
* @throws UndisableableModuleException if the module can't be disabled.
* @throws NoModuleException if the module does not exist.
*/
public void disableModule(String moduleName) throws UndisableableModuleException, NoModuleException {
Preconditions.checkArgument(currentPhase == ConstructionPhase.DISCOVERED);
ModuleSpec ms = discoveredModules.get(moduleName.toLowerCase());
if (ms == null) {
// No module
throw new NoModuleException(moduleName);
}
if (ms.isMandatory() || ms.getStatus() == LoadingStatus.FORCELOAD) {
throw new UndisableableModuleException(moduleName);
}
ms.setStatus(LoadingStatus.DISABLED);
}
protected abstract Module getModule(ModuleSpec spec) throws Exception;
/**
* Starts the module construction and enabling phase. This is the final phase for loading the modules.
*
* <p>
* Once this method is called, modules can no longer be removed.
* </p>
*
* @param failOnOneError If set to <code>true</code>, one module failure will mark the whole loading sequence as failed.
* Otherwise, no modules being constructed will cause a failure.
*
* @throws uk.co.drnaylor.quickstart.exceptions.QuickStartModuleLoaderException.Construction if the modules cannot be constructed.
* @throws uk.co.drnaylor.quickstart.exceptions.QuickStartModuleLoaderException.Enabling if the modules cannot be enabled.
*/
public void loadModules(boolean failOnOneError) throws QuickStartModuleLoaderException.Construction, QuickStartModuleLoaderException.Enabling {
Preconditions.checkArgument(currentPhase == ConstructionPhase.DISCOVERED);
currentPhase = ConstructionPhase.ENABLING;
// Get the modules that are being disabled and mark them as such.
Set<String> disabledModules = getModules(ModuleStatusTristate.DISABLE);
while (!disabledModules.isEmpty()) {
// Find any modules that have dependencies on disabled modules, and disable them.
List<ModuleSpec> toDisable = getModules(ModuleStatusTristate.ENABLE).stream().map(discoveredModules::get).filter(x -> !Collections.disjoint(disabledModules, x.getDeps())).collect(Collectors.toList());
if (toDisable.isEmpty()) {
break;
}
if (toDisable.stream().anyMatch(ModuleSpec::isMandatory)) {
String s = toDisable.stream().filter(ModuleSpec::isMandatory).map(ModuleSpec::getId).collect(Collectors.joining(", "));
Class<? extends Module> m = toDisable.stream().filter(ModuleSpec::isMandatory).findFirst().get().getModuleClass();
throw new QuickStartModuleLoaderException.Construction(m, "Tried to disable mandatory module", new IllegalStateException("Dependency failure, tried to disable a mandatory module (" + s + ")"));
}
toDisable.forEach(k -> {
k.setStatus(LoadingStatus.DISABLED);
disabledModules.add(k.getId());
});
}
// Make sure we get a clean slate here.
getModules(ModuleStatusTristate.DISABLE).forEach(k -> discoveredModules.get(k).setPhase(ModulePhase.DISABLED));
// Modules to enable.
Map<String, Module> modules = Maps.newConcurrentMap();
// Construct them
for (String s : getModules(ModuleStatusTristate.ENABLE)) {
ModuleSpec ms = discoveredModules.get(s);
try {
modules.put(s, getModule(ms));
ms.setPhase(ModulePhase.CONSTRUCTED);
} catch (Exception construction) {
construction.printStackTrace();
ms.setPhase(ModulePhase.ERRORED);
loggerProxy.error("The module " + ms.getModuleClass().getName() + " failed to construct.");
if (failOnOneError) {
currentPhase = ConstructionPhase.ERRORED;
throw new QuickStartModuleLoaderException.Construction(ms.getModuleClass(), "The module " + ms.getModuleClass().getName() + " failed to construct.", construction);
}
}
}
if (modules.isEmpty()) {
currentPhase = ConstructionPhase.ERRORED;
throw new QuickStartModuleLoaderException.Construction(null, "No modules were constructed.", null);
}
// Enter Config Adapter phase - attaching before enabling so that enable methods can get any associated configurations.
for (String s : modules.keySet()) {
Module m = modules.get(s);
Optional<AbstractConfigAdapter<?>> a = m.getConfigAdapter();
if (a.isPresent()) {
try {
config.attachConfigAdapter(s, a.get());
} catch (IOException e) {
e.printStackTrace();
if (failOnOneError) {
throw new QuickStartModuleLoaderException.Enabling(m.getClass(), "Failed to attach config.", e);
}
}
}
}
// Enter Enable phase.
Map<String, Module> c = new HashMap<>(modules);
for (EnablePhase v : EnablePhase.values()) {
loggerProxy.info(String.format("Starting phase: %s", v.name()));
v.onStart(this);
for (String s : c.keySet()) {
ModuleSpec ms = discoveredModules.get(s);
try {
Module m = modules.get(s);
v.onModuleAction(enabler, m, ms);
} catch (Exception construction) {
construction.printStackTrace();
modules.remove(s);
if (v != EnablePhase.POSTENABLE) {
ms.setPhase(ModulePhase.ERRORED);
loggerProxy.error("The module " + ms.getModuleClass().getName() + " failed to enable.");
if (failOnOneError) {
currentPhase = ConstructionPhase.ERRORED;
throw new QuickStartModuleLoaderException.Enabling(ms.getModuleClass(), "The module " + ms.getModuleClass().getName() + " failed to enable.", construction);
}
} else {
loggerProxy.error("The module " + ms.getModuleClass().getName() + " failed to post-enable.");
}
}
}
}
if (c.isEmpty()) {
currentPhase = ConstructionPhase.ERRORED;
throw new QuickStartModuleLoaderException.Enabling(null, "No modules were enabled.", null);
}
try {
config.saveAdapterDefaults();
} catch (IOException e) {
e.printStackTrace();
}
currentPhase = ConstructionPhase.ENABLED;
}
@SuppressWarnings("unchecked")
public final <R extends AbstractConfigAdapter<?>> R getConfigAdapterForModule(String module, Class<R> adapterClass) throws NoModuleException, IncorrectAdapterTypeException {
return config.getConfigAdapterForModule(module, adapterClass);
}
/**
* Saves the {@link SystemConfig}.
*
* @throws IOException If the config could not be saved.
*/
public final void saveSystemConfig() throws IOException {
config.save();
}
/**
* Reloads the {@link SystemConfig}, but does not change any module status.
*
* @throws IOException If the config could not be reloaded.
*/
public final void reloadSystemConfig() throws IOException {
config.load();
}
/**
* Builder class to create a {@link ModuleContainer}
*/
protected static abstract class Builder<R extends ModuleContainer, T extends Builder<R, T>> {
protected ConfigurationLoader<? extends ConfigurationNode> configurationLoader;
protected LoggerProxy loggerProxy;
protected Procedure onPreEnable = () -> {};
protected Procedure onEnable = () -> {};
protected Procedure onPostEnable = () -> {};
protected ModuleEnabler enabler = ModuleEnabler.SIMPLE_INSTANCE;
protected abstract T getThis();
/**
* Sets the {@link ConfigurationLoader} that will handle the module loading.
*
* @param configurationLoader The loader to use.
* @return This {@link Builder}, for chaining.
*/
public T setConfigurationLoader(ConfigurationLoader<? extends ConfigurationNode> configurationLoader) {
this.configurationLoader = configurationLoader;
return getThis();
}
/**
* Sets the {@link LoggerProxy} to use for log messages.
*
* @param loggerProxy The logger proxy to use.
* @return This {@link Builder}, for chaining.
*/
public T setLoggerProxy(LoggerProxy loggerProxy) {
this.loggerProxy = loggerProxy;
return getThis();
}
/**
* Sets the {@link Procedure} to run when the pre-enable phase is about to start.
*
* @param onPreEnable The {@link Procedure}
* @return This {@link Builder}, for chaining.
*/
public T setOnPreEnable(Procedure onPreEnable) {
Preconditions.checkNotNull(onPreEnable);
this.onPreEnable = onPreEnable;
return getThis();
}
/**
* Sets the {@link Procedure} to run when the enable phase is about to start.
*
* @param onEnable The {@link Procedure}
* @return This {@link Builder}, for chaining.
*/
public T setOnEnable(Procedure onEnable) {
Preconditions.checkNotNull(onEnable);
this.onEnable = onEnable;
return getThis();
}
/**
* Sets the {@link Procedure} to run when the post-enable phase is about to start.
*
* @param onPostEnable The {@link Procedure}
* @return This {@link Builder}, for chaining.
*/
public T setOnPostEnable(Procedure onPostEnable) {
Preconditions.checkNotNull(onPostEnable);
this.onPostEnable = onPostEnable;
return getThis();
}
/**
* Sets the {@link ModuleEnabler} to run when enabling modules.
*
* @param enabler The {@link ModuleEnabler}, or {@code null} when the default should be used.
* @return This {@link Builder}, for chaining.
*/
public T setModuleEnabler(ModuleEnabler enabler) {
this.enabler = enabler;
return getThis();
}
protected void checkBuild() {
Preconditions.checkNotNull(configurationLoader);
if (loggerProxy == null) {
loggerProxy = DefaultLogger.INSTANCE;
}
if (enabler == null) {
enabler = ModuleEnabler.SIMPLE_INSTANCE;
}
Metadata.getStartupMessage().ifPresent(x -> loggerProxy.info(x));
}
public abstract R build() throws Exception;
}
public enum ModuleStatusTristate {
ENABLE(k -> k.getValue().getStatus() != LoadingStatus.DISABLED),
DISABLE(k -> k.getValue().getStatus() == LoadingStatus.DISABLED),
ALL(k -> true);
private final Predicate<Map.Entry<String, ModuleSpec>> statusPredicate;
ModuleStatusTristate(Predicate<Map.Entry<String, ModuleSpec>> p) {
statusPredicate = p;
}
}
private interface ConstructPhase {
void onStart(ModuleContainer container);
void onModuleAction(ModuleEnabler enabler, Module module, ModuleSpec ms) throws Exception;
}
private enum EnablePhase implements ConstructPhase {
PREENABLE {
@Override
public void onStart(ModuleContainer container) {
container.onPreEnable.invoke();
}
@Override
public void onModuleAction(ModuleEnabler enabler, Module module, ModuleSpec ms) throws Exception {
enabler.preEnableModule(module);
}
},
ENABLE {
@Override
public void onStart(ModuleContainer container) {
container.onEnable.invoke();
}
@Override
public void onModuleAction(ModuleEnabler enabler, Module module, ModuleSpec ms) throws Exception {
enabler.enableModule(module);
ms.setPhase(ModulePhase.ENABLED);
}
},
POSTENABLE {
@Override
public void onStart(ModuleContainer container) {
container.onPostEnable.invoke();
}
@Override
public void onModuleAction(ModuleEnabler enabler, Module module, ModuleSpec ms) throws Exception {
enabler.postEnableModule(module);
}
}
}
} |
package edu.mit.streamjit.impl.interp;
import static com.google.common.base.Preconditions.*;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableTable;
import com.google.common.collect.Iterables;
import edu.mit.streamjit.api.IllegalStreamGraphException;
import edu.mit.streamjit.api.Rate;
import edu.mit.streamjit.api.StatefulFilter;
import edu.mit.streamjit.api.Worker;
import edu.mit.streamjit.impl.blob.Blob;
import edu.mit.streamjit.impl.blob.BlobFactory;
import edu.mit.streamjit.impl.blob.Buffer;
import edu.mit.streamjit.impl.blob.DrainData;
import edu.mit.streamjit.impl.common.Configuration;
import edu.mit.streamjit.impl.common.Configuration.SwitchParameter;
import edu.mit.streamjit.impl.common.IOInfo;
import edu.mit.streamjit.impl.common.MessageConstraint;
import edu.mit.streamjit.impl.common.Workers;
import edu.mit.streamjit.util.EmptyRunnable;
import edu.mit.streamjit.util.Pair;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Deque;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
/**
* An Interpreter interprets a section of a stream graph. An Interpreter's
* interpret() method will run a pull schedule on the "bottom-most" filters in
* the section (filters that are not predecessor of other filters in the blob),
* firing them as many times as possible.
*
* An Interpreter has input and output channels, identified by opaque Token
* objects. An input channel is any channel from a worker not in the
* Interpreter's stream graph section to one inside it, and an output channel,
* vice versa. The Interpreter expects these channels to already be installed
* on the workers.
*
* To communicate between two Interpreter instances on the same machine, use
* a synchronized channel implementation to connect outputs of one interpreter
* to the inputs of the other.
*
* To communicate between interpreter instances on different machines, have a
* thread on one machine poll() on output channels (if you can afford one thread
* per output, use a blocking channel implementation) and send that data to the
* other machine, then use threads on the other machine to read the data and
* offer() it to input channels. It's tempting to put the send/receive in the
* channel implementations themselves, but this may block the interpreter on
* I/O, and makes implementing peek() on the receiving side tricky.
* @author Jeffrey Bosboom <jeffreybosboom@gmail.com>
* @since 3/22/2013
*/
public class Interpreter implements Blob {
private final ImmutableSet<Worker<?, ?>> workers, sinks;
private final Configuration config;
private final ImmutableSet<Token> inputs, outputs;
private final ImmutableMap<Token, Integer> minimumBufferSizes;
/**
* Maps workers to all constraints of which they are recipients.
*/
private final Map<Worker<?, ?>, List<MessageConstraint>> constraintsForRecipient = new IdentityHashMap<>();
/**
* When running normally, null. After drain() has been called, contains the
* callback we should execute. After the callback is executed, becomes an
* empty Runnable that we execute in place of interpret().
*/
private final AtomicReference<Runnable> callback = new AtomicReference<>();
private final ImmutableSet<IOInfo> ioinfo;
/**
* Maps Channels to the buffers they correspond to. Output channels are
* flushed to output buffers; input channels are checked for data when we
* can't fire a source.
*/
private ImmutableMap<Channel<?>, Buffer> inputBuffers, outputBuffers;
public Interpreter(Iterable<Worker<?, ?>> workersIter, Iterable<MessageConstraint> constraintsIter, Configuration config) {
this.workers = ImmutableSet.copyOf(workersIter);
this.sinks = Workers.getBottommostWorkers(workers);
this.config = config;
//Validate constraints.
for (MessageConstraint mc : constraintsIter)
if (this.workers.contains(mc.getSender()) != this.workers.contains(mc.getRecipient()))
throw new IllegalArgumentException("Constraint crosses interpreter boundary: "+mc);
for (MessageConstraint constraint : constraintsIter) {
Worker<?, ?> recipient = constraint.getRecipient();
List<MessageConstraint> constraintList = constraintsForRecipient.get(recipient);
if (constraintList == null) {
constraintList = new ArrayList<>();
constraintsForRecipient.put(recipient, constraintList);
}
constraintList.add(constraint);
}
//Create channels.
SwitchParameter<ChannelFactory> parameter = this.config.getParameter("channelFactory", SwitchParameter.class, ChannelFactory.class);
ChannelFactory factory = parameter.getValue();
for (IOInfo info : IOInfo.internalEdges(workers)) {
Channel channel = factory.makeChannel((Worker)info.upstream(), (Worker)info.downstream());
Workers.getOutputChannels(info.upstream()).set(info.getUpstreamChannelIndex(), channel);
Workers.getInputChannels(info.downstream()).set(info.getDownstreamChannelIndex(), channel);
}
ImmutableSet.Builder<Token> inputTokens = ImmutableSet.builder(), outputTokens = ImmutableSet.builder();
ImmutableMap.Builder<Token, Integer> minimumBufferSize = ImmutableMap.builder();
for (IOInfo info : IOInfo.externalEdges(workers)) {
Channel channel = factory.makeChannel((Worker)info.upstream(), (Worker)info.downstream());
List channelList;
int index;
if (info.isInput()) {
channelList = Workers.getInputChannels(info.downstream());
index = info.getDownstreamChannelIndex();
} else {
channelList = Workers.getOutputChannels(info.upstream());
index = info.getUpstreamChannelIndex();
}
if (channelList.isEmpty())
channelList.add(channel);
else
channelList.set(index, channel);
(info.isInput() ? inputTokens : outputTokens).add(info.token());
if (info.isInput()) {
Worker<?, ?> w = info.downstream();
int chanIdx = info.token().isOverallInput() ? 0 : Workers.getPredecessors(w).indexOf(info.upstream());
int rate = Math.max(w.getPeekRates().get(chanIdx).max(), w.getPopRates().get(chanIdx).max());
minimumBufferSize.put(info.token(), rate);
}
}
this.inputs = inputTokens.build();
this.outputs = outputTokens.build();
this.minimumBufferSizes = minimumBufferSize.build();
this.ioinfo = IOInfo.externalEdges(workers);
}
@Override
public Set<Token> getInputs() {
return inputs;
}
@Override
public Set<Token> getOutputs() {
return outputs;
}
@Override
public int getMinimumBufferCapacity(Token token) {
Integer i = minimumBufferSizes.get(token);
return (i != null) ? i : 1;
}
@Override
public void installBuffers(Map<Token, Buffer> buffers) {
ImmutableMap.Builder<Channel<?>, Buffer> inputBufferBuilder = ImmutableMap.builder(), outputBufferBuilder = ImmutableMap.builder();
for (IOInfo info : ioinfo) {
Buffer buffer = buffers.get(info.token());
if (buffer != null)
(info.isInput() ? inputBufferBuilder : outputBufferBuilder).put(info.channel(), buffer);
}
this.inputBuffers = inputBufferBuilder.build();
this.outputBuffers = outputBufferBuilder.build();
}
@Override
public ImmutableSet<Worker<?, ?>> getWorkers() {
return workers;
}
@Override
public int getCoreCount() {
return 1;
}
@Override
public Runnable getCoreCode(int core) {
checkElementIndex(core, getCoreCount());
return new Runnable() {
@Override
public void run() {
Runnable callback = Interpreter.this.callback.get();
if (callback == null)
interpret();
else {
//Do any remaining work.
interpret();
//Run the callback (which may be empty).
callback.run();
//Set the callback to empty so we only run it once.
Interpreter.this.callback.set(new EmptyRunnable());
}
}
};
}
@Override
public void drain(Runnable callback) {
//Set the callback; the core code will run it after its next interpret().
if (!this.callback.compareAndSet(null, checkNotNull(callback)))
throw new IllegalStateException("drain() called multiple times");
}
@Override
public DrainData getDrainData() {
ImmutableMap.Builder<Token, ImmutableList<Object>> dataBuilder = ImmutableMap.builder();
for (IOInfo info : IOInfo.allEdges(workers))
dataBuilder.put(info.token(), ImmutableList.copyOf(info.channel()));
ImmutableTable.Builder<Integer, String, Object> stateBuilder = ImmutableTable.builder();
for (Worker<?, ?> worker : workers) {
if (!(worker instanceof StatefulFilter))
continue;
int id = Workers.getIdentifier(worker);
for (Class<?> klass = worker.getClass(); !klass.equals(StatefulFilter.class); klass = klass.getSuperclass()) {
for (Field f : klass.getDeclaredFields()) {
if ((f.getModifiers() & (Modifier.STATIC | Modifier.FINAL)) != 0)
continue;
f.setAccessible(true);
try {
stateBuilder.put(id, f.getName(), f.get(worker));
} catch (IllegalArgumentException | IllegalAccessException ex) {
throw new AssertionError(ex);
}
}
}
}
return new DrainData(dataBuilder.build(), stateBuilder.build());
}
public static final class InterpreterBlobFactory implements BlobFactory {
@Override
public Blob makeBlob(Set<Worker<?, ?>> workers, Configuration config, int maxNumCores) {
//TODO: get the constraints!
return new Interpreter(workers, Collections.<MessageConstraint>emptyList(), config);
}
@Override
public Configuration getDefaultConfiguration(Set<Worker<?, ?>> workers) {
//TODO: more choices
List<ChannelFactory> channelFactories = Arrays.<ChannelFactory>asList(new ChannelFactory() {
@Override
public <E> Channel<E> makeChannel(Worker<?, E> upstream, Worker<E, ?> downstream) {
return new ArrayChannel<>();
}
@Override
public boolean equals(Object other) {
return getClass() == other.getClass();
}
@Override
public int hashCode() {
return 0;
}
});
Configuration.SwitchParameter<ChannelFactory> facParam
= new Configuration.SwitchParameter<>("channelFactory",
ChannelFactory.class, channelFactories.get(0), channelFactories);
return Configuration.builder().addParameter(facParam).build();
}
@Override
public boolean equals(Object o) {
//All InterpreterBlobFactory instances are equal.
return o != null && getClass() == o.getClass();
}
@Override
public int hashCode() {
return 9001;
}
}
/**
* Interprets the stream graph section by running a pull schedule on the
* "bottom-most" workers in the section (firing predecessors as required if
* possible) until no more progress can be made. Returns true if any
* "bottom-most" workers were fired. Note that returning false does not
* mean no workers were fired -- some predecessors might have been fired,
* but others prevented the "bottom-most" workers from firing.
* @return true iff progress was made
*/
public boolean interpret() {
//Fire each sink once if possible, then repeat until we can't fire any
//sinks.
boolean fired, everFired = false;
do {
fired = false;
for (Worker<?, ?> sink : sinks)
everFired |= fired |= pull(sink);
//Because we're using unbounded Channels, if we keep getting input,
//we'll keep firing our workers. We need to flush output to buffers
//to prevent memory exhaustion and starvation of the next Blob.
pushOutputs();
} while (fired);
return everFired;
}
private void pushOutputs() {
//Flush in a round-robin manner to avoid deadlocks where our consumer is
//blocked on another one of our channels.
List<Channel<?>> check = new ArrayList<>(outputBuffers.keySet());
while (!check.isEmpty()) {
for (int i = check.size()-1; i >= 0; --i) {
Channel<?> channel = check.get(i);
if (channel.isEmpty()) {
check.remove(i);
continue;
}
Buffer buffer = outputBuffers.get(channel);
int room = Math.min(buffer.capacity() - buffer.size(), channel.size());
if (room == 0)
continue;
Object[] data = new Object[room];
for (int j = 0; j < data.length; ++j)
data[j] = channel.pop();
int written = 0;
int tries = 0;
while (written < data.length) {
written += buffer.write(data, written, data.length - written);
++tries;
}
assert tries == 1 : "We checked we have space, but still needed "+tries+" tries";
}
}
}
/**
* Fires upstream filters just enough to allow worker to fire, or returns
* false if this is impossible.
*
* This is an implementation of Figure 3-12 from Bill's thesis.
*
* @param worker the worker to fire
* @return true if the worker fired, false if it didn't
*/
private boolean pull(Worker<?, ?> worker) {
//This stack holds all the unsatisfied workers we've encountered
//while trying to fire the argument.
Deque<Worker<?, ?>> stack = new ArrayDeque<>();
stack.push(worker);
recurse:
while (!stack.isEmpty()) {
Worker<?, ?> current = stack.element();
assert workers.contains(current) : "Executing outside stream graph section";
//If we're already trying to fire current, current depends on
//itself, so throw. TODO: explain which constraints are bad?
//We have to pop then push so contains can't just find the top
//of the stack every time. (no indexOf(), annoying)
stack.pop();
if (stack.contains(current))
throw new IllegalStreamGraphException("Unsatisfiable message constraints", current);
stack.push(current);
//Execute predecessors based on data dependencies.
int channel = indexOfUnsatisfiedChannel(current);
if (channel != -1) {
if (!workers.contains(Iterables.get(Workers.getPredecessors(current), channel, null))) {
//Try to get an item for this channel.
Channel unsatChannel = Workers.getInputChannels(current).get(channel);
Buffer buffer = inputBuffers.get(unsatChannel);
//TODO: compute how much and use readAll()
Object item = buffer.read();
if (item != null) {
unsatChannel.push(item);
continue recurse; //try again
} else
return false; //Couldn't fire.
}
//Otherwise, recursively fire the worker blocking us.
stack.push(Workers.getPredecessors(current).get(channel));
continue recurse;
}
List<MessageConstraint> constraints = constraintsForRecipient.get(current);
if (constraints != null)
//Execute predecessors based on message dependencies; that is,
//execute any filter that might send a message to the current
//worker for delivery just prior to its next firing, to ensure
//that delivery cannot be missed.
for (MessageConstraint constraint : constraintsForRecipient.get(current)) {
Worker<?, ?> sender = constraint.getSender();
long deliveryTime = constraint.getDeliveryTime(Workers.getExecutions(sender));
//If deliveryTime == current.getExecutions() + 1, it's for
//our next execution. (If it's <= current.getExecutions(),
//we already missed it!)
if (deliveryTime <= (Workers.getExecutions(current) + 1)) {
//We checked in our constructor that message constraints
//do not cross the interpreter boundary. Assert that.
assert workers.contains(sender);
stack.push(sender);
continue recurse;
}
}
Workers.doWork(current);
afterFire(current);
stack.pop(); //return from the recursion
}
//Stack's empty: we fired the argument.
return true;
}
/**
* Searches the given worker's input channels for one that requires more
* elements before the worker can fire, returning the index of the found
* channel or -1 if the worker can fire.
*/
private <I, O> int indexOfUnsatisfiedChannel(Worker<I, O> worker) {
List<Channel<? extends I>> channels = Workers.getInputChannels(worker);
List<Rate> peekRates = worker.getPeekRates();
List<Rate> popRates = worker.getPopRates();
for (int i = 0; i < channels.size(); ++i) {
Rate peek = peekRates.get(i), pop = popRates.get(i);
if (peek.max() == Rate.DYNAMIC || pop.max() == Rate.DYNAMIC)
throw new UnsupportedOperationException("Unbounded input rates not yet supported");
int required = Math.max(peek.max(), pop.max());
if (channels.get(i).size() < required)
return i;
}
return -1;
}
/**
* Called after the given worker is fired. Provided for the debug
* interpreter to check rate declarations.
* @param worker the worker that just fired
*/
protected void afterFire(Worker<?, ?> worker) {}
} |
package florian_haas.lucas.util;
import java.math.BigDecimal;
import java.util.*;
public class Utils {
@SuppressWarnings("unchecked")
public static <K, V> Map<K, V> deepUnmodifiableMap(Map<K, V> map) {
Map<K, V> tmp = new HashMap<>();
map.forEach((key, value) -> {
Object valueO = value;
if (value instanceof Map<?, ?>) {
Map<?, ?> val = deepUnmodifiableMap((Map<?, ?>) value);
valueO = val;
}
tmp.put(key, (V) valueO);
});
return Collections.unmodifiableMap(tmp);
}
public static <T extends Comparable<? super T>> Boolean isEqual(T comp1, T comp2) {
return comp1.compareTo(comp2) == 0;
}
public static <T extends Comparable<? super T>> Boolean isLessThan(T comp1, T comp2) {
return comp1.compareTo(comp2) < 0;
}
public static <T extends Comparable<? super T>> Boolean isGreatherThan(T comp1, T comp2) {
return comp1.compareTo(comp2) > 0;
}
public static <T extends Comparable<? super T>> Boolean isGreatherEqual(T comp1, T comp2) {
return comp1.compareTo(comp2) >= 0;
}
public static <T extends Comparable<? super T>> Boolean isLessEqual(T comp1, T comp2) {
return comp1.compareTo(comp2) <= 0;
}
public static Boolean isZero(BigDecimal decimal) {
return isEqual(decimal, BigDecimal.ZERO);
}
public static Boolean isLessThanZero(BigDecimal decimal) {
return isLessThan(decimal, BigDecimal.ZERO);
}
public static Boolean isGreatherThanZero(BigDecimal decimal) {
return isGreatherThan(decimal, BigDecimal.ZERO);
}
public static Boolean isGreatherEqualZero(BigDecimal decimal) {
return isGreatherEqual(decimal, BigDecimal.ZERO);
}
public static Boolean isLessEqualZero(BigDecimal decimal) {
return isLessEqual(decimal, BigDecimal.ZERO);
}
public static boolean isInRangeInclusive(long start, long end, long value) {
return value <= end && value >= start;
}
public static boolean isInRangeExclusive(long start, long end, long value) {
return value < end && value > start;
}
public static boolean isInRangeInclusive(int start, int end, int value) {
return value <= end && value >= start;
}
public static boolean isInRangeExclusive(int start, int end, int value) {
return value < end && value > start;
}
} |
package uk.co.pols.bamboo.gitplugin;
import com.atlassian.bamboo.commit.CommitFile;
import com.atlassian.bamboo.repository.*;
import com.atlassian.bamboo.v2.build.BuildChanges;
import com.atlassian.bamboo.v2.build.BuildContext;
import com.atlassian.bamboo.v2.build.repository.RepositoryEventAware;
import com.atlassian.bamboo.ww2.actions.build.admin.create.BuildConfiguration;
import com.atlassian.bamboo.command.CommandException;
import org.apache.commons.configuration.HierarchicalConfiguration;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.tools.ant.taskdefs.Execute;
import org.apache.tools.ant.taskdefs.PumpStreamHandler;
import java.util.ArrayList;
import java.util.List;
import java.io.File;
import java.io.IOException;
/**
* Provides GIT and GITHUB support for the Bamboo Build Server
*/
public class GitRepository extends AbstractRepository implements SelectableAuthenticationRepository, WebRepositoryEnabledRepository, InitialBuildAwareRepository, MutableQuietPeriodAwareRepository, RepositoryEventAware {
private static final Log log = LogFactory.getLog(GitRepository.class);
public static final String NAME = "Git";
public static final String KEY = "git";
private static final String REPO_PREFIX = "repository.git.";
public static final String GIT_REPO_URL = REPO_PREFIX + "repositoryUrl";
public static final String GIT_USERNAME = REPO_PREFIX + "username";
public static final String GIT_BRANCH = REPO_PREFIX + "branch";
public static final String GIT_PASSWORD = REPO_PREFIX + "userPassword";
public static final String GIT_PASSPHRASE = REPO_PREFIX + "passphrase";
public static final String GIT_AUTH_TYPE = REPO_PREFIX + "authType";
public static final String GIT_KEYFILE = REPO_PREFIX + "keyFile";
private String repositoryUrl;
private String branch;
private String authType;
private String keyFile;
private String passphrase;
public String getName() {
return NAME;
}
public String getHost() {
return UNKNOWN_HOST;
}
public String getBranch() {
return branch;
}
public boolean isRepositoryDifferent(Repository repository) {
return false;
}
public String getUrl() {
return "http://github.com/guides/home";
}
public BuildChanges collectChangesSinceLastBuild(String string, String string1) throws RepositoryException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public String retrieveSourceCode(String string, String string1) throws RepositoryException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public void prepareConfigObject(BuildConfiguration buildConfiguration) {
String repositoryKey = buildConfiguration.getString(SELECTED_REPOSITORY);
String authType = buildConfiguration.getString(GIT_AUTH_TYPE);
if (AuthenticationType.PASSWORD.getKey().equals(authType)) {
// boolean svnPasswordChanged = buildConfiguration.getBoolean(TEMPORARY_SVN_PASSWORD_CHANGE);
// if (svnPasswordChanged) {
// String newPassword = buildConfiguration.getString(TEMPORARY_SVN_PASSWORD);
// if (getKey().equals(repositoryKey)) {
// buildConfiguration.setProperty(SvnRepository.SVN_PASSWORD, stringEncrypter.get().encrypt(newPassword));
} else if (AuthenticationType.SSH.getKey().equals(authType)) {
// boolean passphraseChanged = buildConfiguration.getBoolean(TEMPORARY_SVN_PASSPHRASE_CHANGE);
// if (passphraseChanged) {
// String newPassphrase = buildConfiguration.getString(TEMPORARY_SVN_PASSPHRASE);
// buildConfiguration.setProperty(SvnRepository.SVN_PASSPHRASE, stringEncrypter.get().encrypt(newPassphrase));
} else if (AuthenticationType.SSL_CLIENT_CERTIFICATE.getKey().equals(authType)) {
// if (buildConfiguration.getBoolean(TEMPORARY_SVN_SSL_PASSPHRASE_CHANGE)) {
// String newPassphrase = buildConfiguration.getString(TEMPORARY_SVN_SSL_PASSPHRASE);
// buildConfiguration.setProperty(SVN_SSL_PASSPHRASE, stringEncrypter.get().encrypt(newPassphrase));
}
// Disabling advanced will clear all advanced
// if (!buildConfiguration.getBoolean(TEMPORARY_SVN_ADVANCED, false)) {
// quietPeriodHelper.clearFromBuildConfiguration(buildConfiguration);
// buildConfiguration.clearTree(USE_EXTERNALS);
}
public void populateFromConfig(HierarchicalConfiguration config) {
super.populateFromConfig(config);
setRepositoryUrl(config.getString(GIT_REPO_URL));
// setUsername(config.getString(GIT_USERNAME));
setAuthType(config.getString(GIT_AUTH_TYPE));
if (AuthenticationType.PASSWORD.getKey().equals(authType)) {
// setEncryptedPassword(config.getString(GIT_PASSWORD));
} else if (AuthenticationType.SSH.getKey().equals(authType)) {
setKeyFile(config.getString(GIT_KEYFILE));
setEncryptedPassphrase(config.getString(GIT_PASSPHRASE));
} else if (AuthenticationType.SSL_CLIENT_CERTIFICATE.getKey().equals(authType)) {
// setKeyFile(config.getString(GIT_SSL_KEYFILE));
// setEncryptedPassphrase(config.getString(GIT_SSL_PASSPHRASE));
}
setWebRepositoryUrl(config.getString(WEB_REPO_URL));
setWebRepositoryUrlRepoName(config.getString(WEB_REPO_MODULE_NAME));
// setUseExternals(config.getBoolean(USE_EXTERNALS, false));
// final Map<String, String> stringMaps = ConfigUtils.getMapFromConfiguration(EXTERNAL_PATH_MAPPINGS2, config);
// externalPathRevisionMappings = ConfigUtils.toLongMap(stringMaps);
// quietPeriodHelper.populateFromConfig(config, this);
}
public HierarchicalConfiguration toConfiguration() {
HierarchicalConfiguration configuration = super.toConfiguration();
configuration.setProperty(GIT_REPO_URL, getRepositoryUrl());
// configuration.setProperty(GIT_USERNAME, getUsername());
configuration.setProperty(GIT_AUTH_TYPE, getAuthType());
if (AuthenticationType.PASSWORD.getKey().equals(authType)) {
// configuration.setProperty(GIT_PASSWORD, getEncryptedPassword());
} else if (AuthenticationType.SSH.getKey().equals(authType)) {
configuration.setProperty(GIT_KEYFILE, getKeyFile());
configuration.setProperty(GIT_PASSPHRASE, getEncryptedPassphrase());
} else if (AuthenticationType.SSL_CLIENT_CERTIFICATE.getKey().equals(authType)) {
// configuration.setProperty(GIT_SSL_KEYFILE, getKeyFile());
// configuration.setProperty(SVN_SSL_PASSPHRASE, getEncryptedPassphrase());
}
configuration.setProperty(WEB_REPO_URL, getWebRepositoryUrl());
configuration.setProperty(WEB_REPO_MODULE_NAME, getWebRepositoryUrlRepoName());
// configuration.setProperty(USE_EXTERNALS, isUseExternals());
// If check externals && the externals map is empty, then inite it
// if (isUseExternals() && externalPathRevisionMappings.isEmpty()) {
// initExternalsRevisionMapping();
// final Map<String, String> stringMap = ConfigUtils.toStringMap(externalPathRevisionMappings);
// ConfigUtils.addMapToBuilConfiguration(EXTERNAL_PATH_MAPPINGS2, stringMap, configuration);
// Quiet period
// quietPeriodHelper.toConfiguration(configuration, this);
return configuration;
}
/**
* Specify the subversion repository we are using
*
* @param repositoryUrl The subversion repository
*/
public void setRepositoryUrl(String repositoryUrl) {
this.repositoryUrl = StringUtils.trim(repositoryUrl);
}
public void setBranch(String branch) {
this.branch = branch;
}
/**
* Which repository URL are we using?
*
* @return The subversion repository
*/
public String getRepositoryUrl() {
return repositoryUrl;
}
public String getAuthType() {
return authType;
}
public void setAuthType(String authType) {
this.authType = authType;
}
public boolean hasWebBasedRepositoryAccess() {
return false;
}
public void setWebRepositoryUrl(String string) {
}
public void setWebRepositoryUrlRepoName(String string) {
}
public String getWebRepositoryUrl() {
return null;
}
public String getWebRepositoryUrlRepoName() {
return null;
}
public String getWebRepositoryUrlForFile(CommitFile commitFile) {
return null;
}
public void onInitialBuild(BuildContext buildContext) {
}
public void setQuietPeriodEnabled(boolean b) {
}
public void setQuietPeriod(int i) {
}
public void setMaxRetries(int i) {
}
public String getKeyFile() {
return keyFile;
}
public String getSubstitutedKeyFile() {
return variableSubstitutionBean.substituteBambooVariables(keyFile);
}
public void setKeyFile(String myKeyFile) {
this.keyFile = myKeyFile;
}
public boolean isQuietPeriodEnabled() {
return false;
}
public int getQuietPeriod() {
return 0;
}
public int getMaxRetries() {
return 0;
}
public String getEncryptedPassphrase() {
return passphrase;
}
public void setEncryptedPassphrase(String encryptedPassphrase) {
passphrase = encryptedPassphrase;
}
public List<NameValuePair> getAuthenticationTypes() {
List<NameValuePair> types = new ArrayList<NameValuePair>();
types.add(AuthenticationType.SSH.getNameValue());
types.add(AuthenticationType.PASSWORD.getNameValue());
return types;
}
public void preRetrieveSourceCode(BuildContext buildContext) {
}
public void postRetrieveSourceCode(BuildContext buildContext) {
}
/*
cd working directory
git init
git remote add origin git@github.com:andypols/polsbusiness.git
git pull origin master
*/
/**
* Need
* - working directory
* - path to git client binary
* - github url
* - branch to pull from repository
*
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
String gitHome = "/opt/local/bin";
String gitExe = gitHome + "/git";
File workingDirectory = new File("/Users/andy/projects/git/temp/newrepo");
Execute execute = new Execute(new PumpStreamHandler(System.out));
execute.setWorkingDirectory(workingDirectory);
if (!workingDirectory.exists()) {
workingDirectory.mkdirs();
execute.setCommandline(new String[]{gitExe, "init"});
execute.execute();
execute.setCommandline(new String[]{ gitExe, "remote", "add", "origin", "git@github.com:andypols/git-bamboo-plugin.git"});
execute.execute();
}
execute.setCommandline(new String[]{ gitExe, "pull", "origin", "master"});
execute.execute();
}
} |
package org.apache.solr.core;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;
public class RefCntRamDirectory extends RAMDirectory {
private final AtomicInteger refCount = new AtomicInteger();
public RefCntRamDirectory() {
super();
incRef();
}
public RefCntRamDirectory(Directory dir) throws IOException {
this();
Directory.copy(dir, this, false);
}
public void incRef() {
ensureOpen();
refCount.incrementAndGet();
}
public void decRef() {
ensureOpen();
if (refCount.getAndDecrement() == 1) {
close();
}
}
public final synchronized void close() {
if (isOpen) {
decRef();
}
}
public boolean isOpen() {
return isOpen;
}
} |
package edu.wpi.first.wpilibj.templates;
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.command.CommandGroup;
import edu.wpi.first.wpilibj.command.Scheduler;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import edu.wpi.first.wpilibj.templates.commands.AutoCommandGroup;
import edu.wpi.first.wpilibj.templates.commands.CommandBase;
import edu.wpi.first.wpilibj.templates.commands.TelopCommandGroup;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the IterativeRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class Robot3331 extends IterativeRobot {
CommandGroup autonomousCommand, telopCommand;
public void robotInit() {
autonomousCommand = new AutoCommandGroup();
telopCommand = new TelopCommandGroup();
// Initialize all subsystems
CommandBase.init();
}
public void autonomousInit() {
// schedule the autonomous command
autonomousCommand.start();
}
// hello
/**
* This function is called periodically during autonomous
*/
public void autonomousPeriodic() {
Scheduler.getInstance().run();
}
public void teleopInit() {
// This makes sure that the autonomous stops running when
// teleop starts running. If you want the autonomous to
// continue until interrupted by another command, remove
// this line or comment it out.
autonomousCommand.cancel();
// schedule the telop command
telopCommand.start();
}
/**
* This function is called periodically during operator control
*/
public void teleopPeriodic() {
Scheduler.getInstance().run();
}
/**
* This function is called periodically during test mode
*/
public void testPeriodic() {
LiveWindow.run();
}
} |
package com.flybuy.cordova.location;
import java.util.List;
import java.util.Iterator;
import java.util.Random;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.TargetApi;
import android.media.AudioManager;
import android.media.ToneGenerator;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import static android.telephony.PhoneStateListener.*;
import android.telephony.CellLocation;
import android.app.AlarmManager;
import android.app.NotificationManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.BroadcastReceiver;
import android.location.Location;
import android.location.Criteria;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.SystemClock;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.FusedLocationProviderApi;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import static java.lang.Math.*;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.DisplayMetrics;
import android.content.res.Resources;
import com.google.android.gms.location.ActivityRecognition;
import com.google.android.gms.location.DetectedActivity;
import com.google.android.gms.location.ActivityRecognitionResult;
import java.util.ArrayList;
import com.google.android.gms.common.ConnectionResult;
//Detected Activities imports
public class BackgroundLocationUpdateService
extends Service
implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "BackgroundLocationUpdateService";
private Location lastLocation;
private DetectedActivity lastActivity;
private long lastUpdateTime = 0l;
private Boolean fastestSpeed = false;
private PendingIntent locationUpdatePI;
private GoogleApiClient locationClientAPI;
private PendingIntent detectedActivitiesPI;
private GoogleApiClient detectedActivitiesAPI;
private Integer desiredAccuracy = 100;
private Integer distanceFilter = 30;
private Integer activitiesInterval = 1000;
private static final Integer SECONDS_PER_MINUTE = 60;
private static final Integer MILLISECONDS_PER_SECOND = 60;
private long interval = (long) SECONDS_PER_MINUTE * MILLISECONDS_PER_SECOND * 5;
private long fastestInterval = (long) SECONDS_PER_MINUTE * MILLISECONDS_PER_SECOND;
private long aggressiveInterval = (long) MILLISECONDS_PER_SECOND * 4;
private Boolean isDebugging;
private String notificationTitle = "Background checking";
private String notificationText = "ENABLED";
private Boolean useActivityDetection = false;
private Boolean stopOnTerminate;
private Boolean isRequestingActivity = false;
private Boolean isRecording = false;
private ToneGenerator toneGenerator;
private Criteria criteria;
private ConnectivityManager connectivityManager;
private NotificationManager notificationManager;
private LocationRequest locationRequest;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
Log.i(TAG, "OnBind" + intent);
return null;
}
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "OnCreate");
toneGenerator = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 100);
notificationManager = (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
// Location Update PI
Intent locationUpdateIntent = new Intent(Constants.LOCATION_UPDATE);
locationUpdatePI = PendingIntent.getBroadcast(this, 9001, locationUpdateIntent, PendingIntent.FLAG_UPDATE_CURRENT);
registerReceiver(locationUpdateReceiver, new IntentFilter(Constants.LOCATION_UPDATE));
Intent detectedActivitiesIntent = new Intent(Constants.DETECTED_ACTIVITY_UPDATE);
detectedActivitiesPI = PendingIntent.getBroadcast(this, 9002, detectedActivitiesIntent, PendingIntent.FLAG_UPDATE_CURRENT);
registerReceiver(detectedActivitiesReceiver, new IntentFilter(Constants.DETECTED_ACTIVITY_UPDATE));
// Receivers for start/stop recording
registerReceiver(startRecordingReceiver, new IntentFilter(Constants.START_RECORDING));
registerReceiver(stopRecordingReceiver, new IntentFilter(Constants.STOP_RECORDING));
registerReceiver(startAggressiveReceiver, new IntentFilter(Constants.CHANGE_AGGRESSIVE));
// Location criteria
criteria = new Criteria();
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setSpeedRequired(true);
criteria.setCostAllowed(true);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "Received start id " + startId + ": " + intent);
if (intent != null) {
distanceFilter = Integer.parseInt(intent.getStringExtra("distanceFilter"));
desiredAccuracy = Integer.parseInt(intent.getStringExtra("desiredAccuracy"));
interval = Integer.parseInt(intent.getStringExtra("interval"));
fastestInterval = Integer.parseInt(intent.getStringExtra("fastestInterval"));
aggressiveInterval = Integer.parseInt(intent.getStringExtra("aggressiveInterval"));
activitiesInterval = Integer.parseInt(intent.getStringExtra("activitiesInterval"));
isDebugging = Boolean.parseBoolean(intent.getStringExtra("isDebugging"));
notificationTitle = intent.getStringExtra("notificationTitle");
notificationText = intent.getStringExtra("notificationText");
useActivityDetection = Boolean.parseBoolean(intent.getStringExtra("useActivityDetection"));
// Build the notification / pending intent
Intent main = new Intent(this, BackgroundLocationServicesPlugin.class);
main.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, main, PendingIntent.FLAG_UPDATE_CURRENT);
Context context = getApplicationContext();
Notification.Builder builder = new Notification.Builder(this);
builder.setContentTitle(notificationTitle);
builder.setContentText(notificationText);
builder.setSmallIcon(context.getApplicationInfo().icon);
Bitmap bm = BitmapFactory.decodeResource(context.getResources(),
context.getApplicationInfo().icon);
float mult = getImageFactor(getResources());
Bitmap scaledBm = Bitmap.createScaledBitmap(bm, (int)(bm.getWidth()*mult), (int)(bm.getHeight()*mult), false);
if(scaledBm != null) {
builder.setLargeIcon(scaledBm);
}
// Integer resId = getPluginResource("location_icon");
// //Scale our location_icon.png for different phone resolutions
// //TODO: Get this icon via a filepath from the user
// if(resId != 0) {
// Bitmap bm = BitmapFactory.decodeResource(getResources(), resId);
// float mult = getImageFactor(getResources());
// Bitmap scaledBm = Bitmap.createScaledBitmap(bm, (int)(bm.getWidth()*mult), (int)(bm.getHeight()*mult), false);
// if(scaledBm != null) {
// builder.setLargeIcon(scaledBm);
// } else {
// Log.w(TAG, "Could NOT find Resource for large icon");
//Make clicking the event link back to the main cordova activity
builder.setContentIntent(pendingIntent);
setClickEvent(builder);
Notification notification;
if (android.os.Build.VERSION.SDK_INT >= 16) {
notification = buildForegroundNotification(builder);
} else {
notification = buildForegroundNotificationCompat(builder);
}
notification.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_FOREGROUND_SERVICE | Notification.FLAG_NO_CLEAR;
startForeground(startId, notification);
}
// Log.i(TAG, "- url: " + url);
// Log.i(TAG, "- params: " + params.toString());
Log.i(TAG, "- interval: " + interval);
Log.i(TAG, "- fastestInterval: " + fastestInterval);
Log.i(TAG, "- distanceFilter: " + distanceFilter);
Log.i(TAG, "- desiredAccuracy: " + desiredAccuracy);
Log.i(TAG, "- isDebugging: " + isDebugging);
Log.i(TAG, "- notificationTitle: " + notificationTitle);
Log.i(TAG, "- notificationText: " + notificationText);
Log.i(TAG, "- useActivityDetection: " + useActivityDetection);
Log.i(TAG, "- activityDetectionInterval: " + activitiesInterval);
//We want this service to continue running until it is explicitly stopped
return START_REDELIVER_INTENT;
}
//Receivers for setting the plugin to a certain state
private BroadcastReceiver startAggressiveReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
setStartAggressiveTrackingOn();
}
};
private BroadcastReceiver startRecordingReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if(isDebugging) {
Log.d(TAG, "- Start Recording Receiver");
}
if(useActivityDetection) {
Log.d(TAG, "STARTING ACTIVITY DETECTION");
startDetectingActivities();
}
startRecording();
}
};
private BroadcastReceiver stopRecordingReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if(isDebugging) {
Log.d(TAG, "- Stop Recording Receiver");
}
if(useActivityDetection) {
stopDetectingActivities();
}
stopRecording();
}
};
/**
* Broadcast receiver for receiving a single-update from LocationManager.
*/
private BroadcastReceiver locationUpdateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String key = FusedLocationProviderApi.KEY_LOCATION_CHANGED;
Location location = (Location)intent.getExtras().get(key);
if (location != null) {
if(isDebugging) {
// Toast.makeText(context, "We recieveived a location update", Toast.LENGTH_SHORT).show();
Log.d(TAG, "- locationUpdateReceiver" + location.toString());
}
// Go ahead and cache, push to server
lastLocation = location;
//This is all for setting the callback for android which currently does not work
Intent mIntent = new Intent(Constants.CALLBACK_LOCATION_UPDATE);
mIntent.putExtras(createLocationBundle(location));
getApplicationContext().sendBroadcast(mIntent);
// postLocation(location);
}
}
};
private BroadcastReceiver detectedActivitiesReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);
ArrayList<DetectedActivity> detectedActivities = (ArrayList) result.getProbableActivities();
//Find the activity with the highest percentage
lastActivity = Constants.getProbableActivity(detectedActivities);
Log.w(TAG, "MOST LIKELY ACTIVITY: " + Constants.getActivityString(lastActivity.getType()) + " " + lastActivity.getConfidence());
Intent mIntent = new Intent(Constants.CALLBACK_ACTIVITY_UPDATE);
mIntent.putExtra(Constants.ACTIVITY_EXTRA, detectedActivities);
getApplicationContext().sendBroadcast(mIntent);
Log.w(TAG, "Activity is recording" + isRecording);
if(lastActivity.getType() == DetectedActivity.STILL && isRecording) {
Toast.makeText(context, "Detected Activity was STILL, Stop recording", Toast.LENGTH_SHORT).show();
stopRecording();
} else if(lastActivity.getType() != DetectedActivity.STILL && !isRecording) {
Toast.makeText(context, "Detected Activity was ACTIVE, Start Recording", Toast.LENGTH_SHORT).show();
startRecording();
}
//else do nothing
}
};
//Helper function to get the screen scale for our big icon
public float getImageFactor(Resources r) {
DisplayMetrics metrics = r.getDisplayMetrics();
float multiplier=metrics.density/3f;
return multiplier;
}
//retrieves the plugin resource ID from our resources folder for a given drawable name
public Integer getPluginResource(String resourceName) {
return getApplication().getResources().getIdentifier(resourceName, "drawable", getApplication().getPackageName());
}
/**
* Adds an onclick handler to the notification
*/
private Notification.Builder setClickEvent (Notification.Builder notification) {
Context context = getApplicationContext();
String packageName = context.getPackageName();
Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage(packageName);
launchIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_SINGLE_TOP);
int requestCode = new Random().nextInt();
PendingIntent contentIntent = PendingIntent.getActivity(context, requestCode, launchIntent, PendingIntent.FLAG_CANCEL_CURRENT);
return notification.setContentIntent(contentIntent);
}
private Bundle createLocationBundle(Location location) {
Bundle b = new Bundle();
b.putDouble("latitude", location.getLatitude());
b.putDouble("longitude", location.getLongitude());
b.putDouble("accuracy", location.getAccuracy());
b.putDouble("altitude", location.getAltitude());
b.putDouble("timestamp", location.getTime());
b.putDouble("speed", location.getSpeed());
b.putDouble("heading", location.getBearing());
return b;
}
private boolean enabled = false;
private boolean startRecordingOnConnect = true;
private void enable() {
this.enabled = true;
}
private void disable() {
this.enabled = false;
}
private void setStartAggressiveTrackingOn() {
if(!fastestSpeed && this.isRecording) {
detachRecorder();
desiredAccuracy = 10;
fastestInterval = (long) (aggressiveInterval / 2);
interval = aggressiveInterval;
attachRecorder();
Log.e(TAG, "Changed Location params" + locationRequest.toString());
fastestSpeed = true;
}
}
public void startDetectingActivities() {
this.isRequestingActivity = true;
attachDARecorder();
}
public void stopDetectingActivities() {
this.isRequestingActivity = false;
detatchDARecorder();
}
private void attachDARecorder() {
if (detectedActivitiesAPI == null) {
buildDAClient();
} else if (detectedActivitiesAPI.isConnected()) {
ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(
detectedActivitiesAPI,
this.activitiesInterval,
detectedActivitiesPI
);
if(isDebugging) {
Log.d(TAG, "- DA RECORDER attached - start recording location updates");
}
} else {
Log.i(TAG, "NOT CONNECTED, CONNECT");
detectedActivitiesAPI.connect();
}
}
private void detatchDARecorder() {
if (detectedActivitiesAPI == null) {
buildDAClient();
} else if (detectedActivitiesAPI.isConnected()) {
ActivityRecognition.ActivityRecognitionApi.removeActivityUpdates(detectedActivitiesAPI, detectedActivitiesPI);
if(isDebugging) {
Log.d(TAG, "- Recorder detached - stop recording activity updates");
}
} else {
detectedActivitiesAPI.connect();
}
}
public void startRecording() {
Log.w(TAG, "Started Recording Locations");
this.startRecordingOnConnect = true;
attachRecorder();
}
public void stopRecording() {
this.startRecordingOnConnect = false;
detachRecorder();
}
private GoogleApiClient.ConnectionCallbacks cb = new GoogleApiClient.ConnectionCallbacks() {
@Override
public void onConnected(Bundle bundle) {
Log.w(TAG, "Activity Client Connected");
ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(
detectedActivitiesAPI,
activitiesInterval,
detectedActivitiesPI
);
}
@Override
public void onConnectionSuspended(int i) {
Log.w(TAG, "Connection To Activity Suspended");
Toast.makeText(getApplicationContext(), "Activity Client Suspended", Toast.LENGTH_SHORT).show();
}
};
private GoogleApiClient.OnConnectionFailedListener failedCb = new GoogleApiClient.OnConnectionFailedListener() {
@Override
public void onConnectionFailed(ConnectionResult cr) {
Log.w(TAG, "ERROR CONNECTING TO DETECTED ACTIVITIES");
}
};
protected synchronized void buildDAClient() {
Log.i(TAG, "BUILDING DA CLIENT");
detectedActivitiesAPI = new GoogleApiClient.Builder(this)
.addApi(ActivityRecognition.API)
.addConnectionCallbacks(cb)
.addOnConnectionFailedListener(failedCb)
.build();
detectedActivitiesAPI.connect();
}
protected synchronized void connectToPlayAPI() {
locationClientAPI = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
locationClientAPI.connect();
}
private void attachRecorder() {
Log.i(TAG, "Attaching Recorder");
if (locationClientAPI == null) {
connectToPlayAPI();
} else if (locationClientAPI.isConnected()) {
locationRequest = LocationRequest.create()
.setPriority(translateDesiredAccuracy(desiredAccuracy))
.setFastestInterval(fastestInterval)
.setInterval(interval)
.setSmallestDisplacement(distanceFilter);
LocationServices.FusedLocationApi.requestLocationUpdates(locationClientAPI, locationRequest, locationUpdatePI);
this.isRecording = true;
if(isDebugging) {
Log.d(TAG, "- Recorder attached - start recording location updates");
}
} else {
locationClientAPI.connect();
}
}
private void detachRecorder() {
if (locationClientAPI == null) {
connectToPlayAPI();
} else if (locationClientAPI.isConnected()) {
//flush the location updates from the api
LocationServices.FusedLocationApi.removeLocationUpdates(locationClientAPI, locationUpdatePI);
this.isRecording = false;
if(isDebugging) {
Log.w(TAG, "- Recorder detached - stop recording location updates");
}
} else {
locationClientAPI.connect();
}
}
@Override
public void onConnected(Bundle connectionHint) {
Log.d(TAG, "- Connected to Play API -- All ready to record");
if (this.startRecordingOnConnect) {
attachRecorder();
} else {
detachRecorder();
}
}
@Override
public void onConnectionFailed(com.google.android.gms.common.ConnectionResult result) {
Log.e(TAG, "We failed to connect to the Google API! Possibly API is not installed on target.");
}
@Override
public void onConnectionSuspended(int cause) {
// locationClientAPI.connect();
}
@TargetApi(16)
private Notification buildForegroundNotification(Notification.Builder builder) {
return builder.build();
}
@SuppressWarnings("deprecation")
@TargetApi(15)
private Notification buildForegroundNotificationCompat(Notification.Builder builder) {
return builder.getNotification();
}
/**
* Translates a number representing desired accuracy of GeoLocation system from set [0, 10, 100, 1000].
* 0: most aggressive, most accurate, worst battery drain
* 1000: least aggressive, least accurate, best for battery.
*/
private Integer translateDesiredAccuracy(Integer accuracy) {
if(accuracy <= 0) {
accuracy = LocationRequest.PRIORITY_HIGH_ACCURACY;
} else if(accuracy <= 100) {
accuracy = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY;
} else if(accuracy <= 1000) {
accuracy = LocationRequest.PRIORITY_LOW_POWER;
} else if(accuracy <= 10000) {
accuracy = LocationRequest.PRIORITY_NO_POWER;
} else {
accuracy = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY;
}
return accuracy;
}
private boolean isNetworkConnected() {
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null) {
Log.d(TAG, "Network found, type = " + networkInfo.getTypeName());
return networkInfo.isConnected();
} else {
Log.d(TAG, "No active network info");
return false;
}
}
@Override
public boolean stopService(Intent intent) {
Log.i(TAG, "- Received stop: " + intent);
this.stopRecording();
this.cleanUp();
if (isDebugging) {
Toast.makeText(this, "Background location tracking stopped", Toast.LENGTH_SHORT).show();
}
return super.stopService(intent);
}
@Override
public void onDestroy() {
Log.w(TAG, "Destroyed Location Update Service - Cleaning up");
this.cleanUp();
super.onDestroy();
}
private void cleanUp() {
try {
unregisterReceiver(locationUpdateReceiver);
unregisterReceiver(startRecordingReceiver);
unregisterReceiver(stopRecordingReceiver);
unregisterReceiver(detectedActivitiesReceiver);
} catch(IllegalArgumentException e) {
Log.e(TAG, "Error: Could not unregister receiver", e);
}
try {
stopForeground(true);
} catch (Exception e) {
Log.e(TAG, "Error: Could not stop foreground process", e);
}
toneGenerator.release();
if(locationClientAPI != null) {
locationClientAPI.disconnect();
}
}
@Override
public void onTaskRemoved(Intent rootIntent) {
this.stopRecording();
this.stopSelf();
super.onTaskRemoved(rootIntent);
}
} |
/**
* Interfaces specifying operations on random variables. For implementation see also
* {@link net.finmath.montecarlo} e.g. {@link net.finmath.montecarlo.RandomVariableFromDoubleArray}.
*
* @author Christian Fries
*/
package net.finmath.stochastic; |
package plugin.google.maps;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import org.apache.cordova.CallbackContext;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class PluginMarker extends MyPlugin {
private HashMap<String, Bitmap> cache = null;
/**
* Create a marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void createMarker(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
if (cache == null) {
cache = new HashMap<String, Bitmap>();
}
// Create an instance of Marker class
final MarkerOptions markerOptions = new MarkerOptions();
final JSONObject opts = args.getJSONObject(1);
if (opts.has("position")) {
JSONObject position = opts.getJSONObject("position");
markerOptions.position(new LatLng(position.getDouble("lat"), position.getDouble("lng")));
}
if (opts.has("title")) {
markerOptions.title(opts.getString("title"));
}
if (opts.has("snippet")) {
markerOptions.snippet(opts.getString("snippet"));
}
if (opts.has("visible")) {
if (opts.has("icon") && "".equals(opts.getString("icon")) == false) {
markerOptions.visible(false);
} else {
markerOptions.visible(opts.getBoolean("visible"));
}
}
if (opts.has("draggable")) {
markerOptions.draggable(opts.getBoolean("draggable"));
}
if (opts.has("rotation")) {
markerOptions.rotation((float)opts.getDouble("rotation"));
}
if (opts.has("flat")) {
markerOptions.flat(opts.getBoolean("flat"));
}
if (opts.has("opacity")) {
markerOptions.alpha((float) opts.getDouble("opacity"));
}
markerOptions.anchor(0.5f, 0.5f);
Marker marker = map.addMarker(markerOptions);
// Store the marker
String id = "marker_" + marker.getId();
this.objects.put(id, marker);
JSONObject properties = new JSONObject();
if (opts.has("styles")) {
properties.put("styles", opts.getJSONObject("styles"));
}
if (opts.has("disableAutoPan")) {
properties.put("disableAutoPan", opts.getBoolean("disableAutoPan"));
} else {
properties.put("disableAutoPan", false);
}
this.objects.put("marker_property_" + marker.getId(), properties);
// Prepare the result
final JSONObject result = new JSONObject();
result.put("hashCode", marker.hashCode());
result.put("id", id);
// Load icon
if (opts.has("icon")) {
Bundle bundle = null;
Object value = opts.get("icon");
if (JSONObject.class.isInstance(value)) {
JSONObject iconProperty = (JSONObject)value;
bundle = PluginUtil.Json2Bundle(iconProperty);
// The `anchor` of the `icon` property
if (iconProperty.has("anchor")) {
value = iconProperty.get("anchor");
if (JSONArray.class.isInstance(value)) {
JSONArray points = (JSONArray)value;
double[] anchorPoints = new double[points.length()];
for (int i = 0; i < points.length(); i++) {
anchorPoints[i] = points.getDouble(i);
}
bundle.putDoubleArray("anchor", anchorPoints);
}
}
// The `infoWindowAnchor` property for infowindow
if (opts.has("infoWindowAnchor")) {
value = opts.get("infoWindowAnchor");
if (JSONArray.class.isInstance(value)) {
JSONArray points = (JSONArray)value;
double[] anchorPoints = new double[points.length()];
for (int i = 0; i < points.length(); i++) {
anchorPoints[i] = points.getDouble(i);
}
bundle.putDoubleArray("infoWindowAnchor", anchorPoints);
}
}
} else {
bundle = new Bundle();
bundle.putString("url", (String)value);
}
this.setIcon_(marker, bundle, new PluginMarkerInterface() {
@Override
public void onMarkerIconLoaded(Marker marker) {
if (opts.has("visible")) {
try {
marker.setVisible(opts.getBoolean("visible"));
} catch (JSONException e) {}
} else {
marker.setVisible(true);
}
callbackContext.success(result);
}
});
} else {
// Return the result if does not specify the icon property.
callbackContext.success(result);
}
}
/**
* Show the InfoWindow binded with the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void showInfoWindow(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String id = args.getString(1);
Marker marker = this.getMarker(id);
marker.showInfoWindow();
callbackContext.success();
}
/**
* Set rotation for the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void setRotation(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
float rotation = (float)args.getDouble(2);
String id = args.getString(1);
this.setFloat("setRotation", id, rotation, callbackContext);
callbackContext.success();
}
/**
* Set opacity for the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void setOpacity(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
float alpha = (float)args.getDouble(2);
String id = args.getString(1);
this.setFloat("setAlpha", id, alpha, callbackContext);
}
/**
* set position
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void setPosition(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String id = args.getString(1);
LatLng position = new LatLng(args.getDouble(2), args.getDouble(3));
Marker marker = this.getMarker(id);
marker.setPosition(position);
callbackContext.success();
}
/**
* Set flat for the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void setFlat(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
boolean isFlat = args.getBoolean(2);
String id = args.getString(1);
this.setBoolean("setFlat", id, isFlat, callbackContext);
}
/**
* Set visibility for the object
* @param args
* @param callbackContext
* @throws JSONException
*/
protected void setVisible(JSONArray args, CallbackContext callbackContext) throws JSONException {
boolean visible = args.getBoolean(2);
String id = args.getString(1);
this.setBoolean("setVisible", id, visible, callbackContext);
}
/**
* Set title for the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void setTitle(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String title = args.getString(2);
String id = args.getString(1);
this.setString("setTitle", id, title, callbackContext);
}
/**
* Set the snippet for the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void setSnippet(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String snippet = args.getString(2);
String id = args.getString(1);
this.setString("setSnippet", id, snippet, callbackContext);
}
/**
* Hide the InfoWindow binded with the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void hideInfoWindow(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String id = args.getString(1);
Marker marker = this.getMarker(id);
marker.hideInfoWindow();
callbackContext.success();
}
/**
* Return the position of the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void getPosition(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String id = args.getString(1);
Marker marker = this.getMarker(id);
LatLng position = marker.getPosition();
JSONObject result = new JSONObject();
result.put("lat", position.latitude);
result.put("lng", position.longitude);
callbackContext.success(result);
}
/**
* Return 1 if the InfoWindow of the marker is shown
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void isInfoWindowShown(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String id = args.getString(1);
Marker marker = this.getMarker(id);
Boolean isInfoWndShown = marker.isInfoWindowShown();
callbackContext.success(isInfoWndShown ? 1 : 0);
}
/**
* Remove the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void remove(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String id = args.getString(1);
Marker marker = this.getMarker(id);
if (marker == null) {
callbackContext.success();
return;
}
marker.remove();
this.objects.remove(id);
String styleId = "marker_style_" + id;
this.objects.remove(styleId);
callbackContext.success();
}
/**
* Set anchor for the icon of the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void setIconAnchor(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
float anchorX = (float)args.getDouble(2);
float anchorY = (float)args.getDouble(3);
String id = args.getString(1);
Marker marker = this.getMarker(id);
Bundle imageSize = (Bundle) this.objects.get("imageSize");
if (imageSize != null) {
this._setIconAnchor(marker, anchorX, anchorY, imageSize.getInt("width"), imageSize.getInt("height"));
}
callbackContext.success();
}
/**
* Set anchor for the InfoWindow of the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void setInfoWindowAnchor(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
float anchorX = (float)args.getDouble(2);
float anchorY = (float)args.getDouble(3);
String id = args.getString(1);
Marker marker = this.getMarker(id);
Bundle imageSize = (Bundle) this.objects.get("imageSize");
if (imageSize != null) {
this._setInfoWindowAnchor(marker, anchorX, anchorY, imageSize.getInt("width"), imageSize.getInt("height"));
}
callbackContext.success();
}
/**
* Set draggable for the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void setDraggable(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
Boolean draggable = args.getBoolean(2);
String id = args.getString(1);
this.setBoolean("setDraggable", id, draggable, callbackContext);
}
/**
* Set icon of the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void setIcon(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String id = args.getString(1);
Marker marker = this.getMarker(id);
Object value = args.get(2);
Bundle bundle = null;
if (JSONObject.class.isInstance(value)) {
JSONObject iconProperty = (JSONObject)value;
bundle = PluginUtil.Json2Bundle(iconProperty);
// The `anchor` for icon
if (iconProperty.has("anchor")) {
value = iconProperty.get("anchor");
if (JSONArray.class.isInstance(value)) {
JSONArray points = (JSONArray)value;
double[] anchorPoints = new double[points.length()];
for (int i = 0; i < points.length(); i++) {
anchorPoints[i] = points.getDouble(i);
}
bundle.putDoubleArray("anchor", anchorPoints);
}
}
} else if (String.class.isInstance(value)) {
bundle = new Bundle();
bundle.putString("url", (String)value);
}
if (bundle != null) {
this.setIcon_(marker, bundle, new PluginMarkerInterface() {
@Override
public void onMarkerIconLoaded(Marker marker) {
callbackContext.success();
}
});
} else {
callbackContext.success();
}
}
private void setIcon_(final Marker marker, final Bundle iconProperty, final PluginMarkerInterface callback) {
String iconUrl = iconProperty.getString("url");
if (iconUrl == null) {
callback.onMarkerIconLoaded(marker);
return;
}
if (iconUrl.indexOf("http") == -1) {
Bitmap image = null;
if (iconUrl.indexOf("data:image/") > -1 && iconUrl.indexOf(";base64,") > -1) {
String[] tmp = iconUrl.split(",");
image = PluginUtil.getBitmapFromBase64encodedImage(tmp[1]);
} else {
AssetManager assetManager = this.cordova.getActivity().getAssets();
InputStream inputStream;
try {
inputStream = assetManager.open(iconUrl);
image = BitmapFactory.decodeStream(inputStream);
} catch (IOException e) {
e.printStackTrace();
callback.onMarkerIconLoaded(marker);
return;
}
}
if (image == null) {
callback.onMarkerIconLoaded(marker);
return;
}
if (iconProperty.containsKey("size") == true) {
Object size = iconProperty.get("size");
if (Bundle.class.isInstance(size)) {
Bundle sizeInfo = (Bundle)size;
int width = sizeInfo.getInt("width", 0);
int height = sizeInfo.getInt("height", 0);
if (width > 0 && height > 0) {
//width = (int)Math.round(width * webView.getScale());
//height = (int)Math.round(height * webView.getScale());
image = PluginUtil.resizeBitmap(image, width, height);
}
}
}
image = PluginUtil.scaleBitmapForDevice(image);
BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(image);
marker.setIcon(bitmapDescriptor);
// Save the information for the anchor property
Bundle imageSize = new Bundle();
imageSize.putInt("width", image.getWidth());
imageSize.putInt("height", image.getHeight());
this.objects.put("imageSize", imageSize);
// The `anchor` of the `icon` property
if (iconProperty.containsKey("anchor") == true) {
double[] anchor = iconProperty.getDoubleArray("anchor");
if (anchor.length == 2) {
_setIconAnchor(marker, anchor[0], anchor[1], imageSize.getInt("width"), imageSize.getInt("height"));
}
}
// The `anchor` property for the infoWindow
if (iconProperty.containsKey("infoWindowAnchor") == true) {
double[] anchor = iconProperty.getDoubleArray("infoWindowAnchor");
if (anchor.length == 2) {
_setInfoWindowAnchor(marker, anchor[0], anchor[1], imageSize.getInt("width"), imageSize.getInt("height"));
}
}
callback.onMarkerIconLoaded(marker);
return;
}
if (iconUrl.indexOf("http") == 0) {
AsyncLoadImage task = new AsyncLoadImage(new AsyncLoadImageInterface() {
@Override
public void onPostExecute(Bitmap image) {
if (iconProperty.containsKey("size") == true) {
Bundle sizeInfo = (Bundle) iconProperty.get("size");
int width = sizeInfo.getInt("width", 0);
int height = sizeInfo.getInt("height", 0);
if (width > 0 && height > 0) {
//width = (int)Math.round(width * webView.getScale());
//height = (int)Math.round(height * webView.getScale());
image = PluginUtil.resizeBitmap(image, width, height);
}
BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(image);
marker.setIcon(bitmapDescriptor);
// Save the information for the anchor property
Bundle imageSize = new Bundle();
imageSize.putInt("width", image.getWidth());
imageSize.putInt("height", image.getHeight());
PluginMarker.this.objects.put("imageSize", imageSize);
// The `anchor` of the `icon` property
if (iconProperty.containsKey("anchor") == true) {
double[] anchor = iconProperty.getDoubleArray("anchor");
if (anchor.length == 2) {
_setIconAnchor(marker, anchor[0], anchor[1], imageSize.getInt("width"), imageSize.getInt("height"));
}
}
// The `anchor` property for the infoWindow
if (iconProperty.containsKey("infoWindowAnchor") == true) {
double[] anchor = iconProperty.getDoubleArray("infoWindowAnchor");
if (anchor.length == 2) {
_setInfoWindowAnchor(marker, anchor[0], anchor[1], imageSize.getInt("width"), imageSize.getInt("height"));
}
}
callback.onMarkerIconLoaded(marker);
}
}
}, cache);
task.execute(iconUrl);
}
}
private void _setIconAnchor(Marker marker, double anchorX, double anchorY, int imageWidth, int imageHeight) {
// The `anchor` of the `icon` property
anchorX = anchorX * this.density;
anchorY = anchorY * this.density;
marker.setAnchor((float)(anchorX / imageWidth), (float)(anchorY / imageHeight));
}
private void _setInfoWindowAnchor(Marker marker, double anchorX, double anchorY, int imageWidth, int imageHeight) {
// The `anchor` of the `icon` property
anchorX = anchorX * this.density;
anchorY = anchorY * this.density;
marker.setInfoWindowAnchor((float)(anchorX / imageWidth), (float)(anchorY / imageHeight));
}
} |
package net.imagej.patcher;
import java.util.HashSet;
import java.util.Set;
/**
* Assorted legacy patches / extension points for use in the legacy mode.
*
* <p>
* The Fiji distribution of ImageJ accumulated patches and extensions to ImageJ
* 1.x over the years.
* </p>
*
* <p>
* However, there was a lot of overlap with the ImageJ2 project, so it was
* decided to focus Fiji more on the life-science specific part and move all the
* parts that are of more general use into ImageJ2. That way, it is pretty
* clear-cut what goes into Fiji and what goes into ImageJ2.
* </p>
*
* <p>
* This class contains the extension points (such as being able to override the
* macro editor) ported from Fiji as well as the code for runtime patching
* ImageJ 1.x needed both for the extension points and for more backwards
* compatibility than ImageJ 1.x wanted to provide (e.g. when public methods or
* classes that were used by Fiji plugins were removed all of a sudden, without
* being deprecated first).
* </p>
*
* <p>
* The code in this class is only used in the legacy mode.
* </p>
*
* @author Johannes Schindelin
*/
class LegacyExtensions {
/*
* Extension points
*/
/*
* Runtime patches (using CodeHacker for patching)
*/
/**
* Applies runtime patches to ImageJ 1.x for backwards-compatibility and extension points.
*
* <p>
* These patches enable a patched ImageJ 1.x to call a different script editor or to override
* the application icon.
* </p>
*
* <p>
* This method is called by {@link LegacyInjector#injectHooks(ClassLoader)}.
* </p>
*
* @param hacker the {@link CodeHacker} instance
*/
public static void injectHooks(final CodeHacker hacker, boolean headless) {
// Below are patches to make ImageJ 1.x more backwards-compatible
// add back the (deprecated) killProcessor(), and overlay methods
final String[] imagePlusMethods = {
"public void killProcessor()",
"{}",
"public void setDisplayList(java.util.Vector list)",
"getCanvas().setDisplayList(list);",
"public java.util.Vector getDisplayList()",
"return getCanvas().getDisplayList();",
"public void setDisplayList(ij.gui.Roi roi, java.awt.Color strokeColor,"
+ " int strokeWidth, java.awt.Color fillColor)",
"setOverlay(roi, strokeColor, strokeWidth, fillColor);"
};
for (int i = 0; i < imagePlusMethods.length; i++) try {
hacker.insertNewMethod("ij.ImagePlus",
imagePlusMethods[i], imagePlusMethods[++i]);
} catch (Exception e) { /* ignore */ }
// make sure that ImageJ has been initialized in batch mode
hacker.insertAtTopOfMethod("ij.IJ",
"public static java.lang.String runMacro(java.lang.String macro, java.lang.String arg)",
"if (ij==null && ij.Menus.getCommands()==null) init();");
try {
hacker.insertNewMethod("ij.CompositeImage",
"public ij.ImagePlus[] splitChannels(boolean closeAfter)",
"ij.ImagePlus[] result = ij.plugin.ChannelSplitter.split(this);"
+ "if (closeAfter) close();"
+ "return result;");
hacker.insertNewMethod("ij.plugin.filter.RGBStackSplitter",
"public static ij.ImagePlus[] splitChannelsToArray(ij.ImagePlus imp, boolean closeAfter)",
"if (!imp.isComposite()) {"
+ " ij.IJ.error(\"splitChannelsToArray was called on a non-composite image\");"
+ " return null;"
+ "}"
+ "ij.ImagePlus[] result = ij.plugin.ChannelSplitter.split(imp);"
+ "if (closeAfter)"
+ " imp.close();"
+ "return result;");
} catch (IllegalArgumentException e) {
final Throwable cause = e.getCause();
if (cause != null && !cause.getClass().getName().endsWith("DuplicateMemberException")) {
throw e;
}
}
// handle mighty mouse (at least on old Linux, Java mistakes the horizontal wheel for a popup trigger)
for (String fullClass : new String[] {
"ij.gui.ImageCanvas",
"ij.plugin.frame.RoiManager",
"ij.text.TextPanel",
"ij.gui.Toolbar"
}) {
hacker.handleMightyMousePressed(fullClass);
}
// tell IJ#runUserPlugIn to catch NoSuchMethodErrors
final String runUserPlugInSig = "static java.lang.Object runUserPlugIn(java.lang.String commandName, java.lang.String className, java.lang.String arg, boolean createNewLoader)";
hacker.addCatch("ij.IJ", runUserPlugInSig, "java.lang.NoSuchMethodError",
"if (ij.IJ._hooks.handleNoSuchMethodError($e))"
+ " throw new RuntimeException(ij.Macro.MACRO_CANCELED);"
+ "throw $e;");
// tell IJ#runUserPlugIn to be more careful about catching NoClassDefFoundError
hacker.insertPrivateStaticField("ij.IJ", String.class, "originalClassName");
hacker.insertAtTopOfMethod("ij.IJ", runUserPlugInSig, "originalClassName = $2;");
hacker.insertAtTopOfExceptionHandlers("ij.IJ", runUserPlugInSig, "java.lang.NoClassDefFoundError",
"java.lang.String realClassName = $1.getMessage();"
+ "int spaceParen = realClassName.indexOf(\" (\");"
+ "if (spaceParen > 0) realClassName = realClassName.substring(0, spaceParen);"
+ "if (!originalClassName.replace('.', '/').equals(realClassName)) {"
+ " if (realClassName.startsWith(\"javax/vecmath/\") || realClassName.startsWith(\"com/sun/j3d/\") || realClassName.startsWith(\"javax/media/j3d/\"))"
+ " ij.IJ.error(\"The class \" + originalClassName + \" did not find Java3D (\" + realClassName + \")\\nPlease call Plugins>3D Viewer to install\");"
+ " else"
+ " ij.IJ.handleException($1);"
+ " return null;"
+ "}");
// let the plugin class loader find stuff in $HOME/.plugins, too
addExtraPlugins(hacker);
// make sure that the GenericDialog is disposed in macro mode
if (hacker.hasMethod("ij.gui.GenericDialog", "public void showDialog()")) {
hacker.insertAtTopOfMethod("ij.gui.GenericDialog", "public void showDialog()", "if (macro) dispose();");
}
// make sure NonBlockingGenericDialog does not wait in macro mode
hacker.replaceCallInMethod("ij.gui.NonBlockingGenericDialog", "public void showDialog()", "java.lang.Object", "wait", "if (isShowing()) wait();");
// tell the showStatus() method to show the version() instead of empty status
hacker.insertAtTopOfMethod("ij.ImageJ", "void showStatus(java.lang.String s)", "if ($1 == null || \"\".equals($1)) $1 = version();");
// make sure that the GenericDialog does not make a hidden main window visible
if (!headless) {
hacker.replaceCallInMethod("ij.gui.GenericDialog",
"public <init>(java.lang.String title, java.awt.Frame f)",
"java.awt.Dialog", "super",
"$proceed($1 != null && $1.isVisible() ? $1 : null, $2, $3);");
}
// handle custom icon (e.g. for Fiji)
addIconHooks(hacker);
// optionally disallow batch mode from calling System.exit()
hacker.insertPrivateStaticField("ij.ImageJ", Boolean.TYPE, "batchModeMayExit");
hacker.insertAtTopOfMethod("ij.ImageJ", "public static void main(java.lang.String[] args)",
"batchModeMayExit = true;"
+ "for (int i = 0; i < $1.length; i++) {"
+ " if (\"-batch-no-exit\".equals($1[i])) {"
+ " batchModeMayExit = false;"
+ " $1[i] = \"-batch\";"
+ " }"
+ "}");
hacker.replaceCallInMethod("ij.ImageJ", "public static void main(java.lang.String[] args)", "java.lang.System", "exit",
"if (batchModeMayExit) System.exit($1);"
+ "if ($1 == 0) return;"
+ "throw new RuntimeException(\"Exit code: \" + $1);");
// do not use the current directory as IJ home on Windows
String prefsDir = System.getenv("IJ_PREFS_DIR");
if (prefsDir == null && System.getProperty("os.name").startsWith("Windows")) {
prefsDir = System.getenv("user.home");
}
if (prefsDir != null) {
hacker.overrideFieldWrite("ij.Prefs", "public java.lang.String load(java.lang.Object ij, java.applet.Applet applet)",
"prefsDir", "$_ = \"" + prefsDir + "\";");
}
// tool names can be prefixes of other tools, watch out for that!
hacker.replaceCallInMethod("ij.gui.Toolbar", "public int getToolId(java.lang.String name)", "java.lang.String", "startsWith",
"$_ = $0.equals($1) || $0.startsWith($1 + \"-\") || $0.startsWith($1 + \" -\");");
// make sure Rhino gets the correct class loader
final String javascript = hacker.existsClass("JavaScriptEvaluator") ?
"JavaScriptEvaluator" : "ij.plugin.JavaScriptEvaluator";
hacker.insertAtTopOfMethod(javascript, "public void run()",
"Thread.currentThread().setContextClassLoader(ij.IJ.getClassLoader());");
// make sure that the check for Bio-Formats is correct
hacker.addToClassInitializer("ij.io.Opener",
"try {"
+ " ij.IJ.getClassLoader().loadClass(\"loci.plugins.LociImporter\");"
+ " bioformats = true;"
+ "} catch (ClassNotFoundException e) {"
+ " bioformats = false;"
+ "}");
// make sure that symbolic links are *not* resolved (because then the parent info in the FileInfo would be wrong)
hacker.replaceCallInMethod("ij.plugin.DragAndDrop", "public void openFile(java.io.File f)", "java.io.File", "getCanonicalPath",
"$_ = $0.getAbsolutePath();");
// make sure no dialog is opened in headless mode
hacker.insertAtTopOfMethod("ij.macro.Interpreter", "void showError(java.lang.String title, java.lang.String msg, java.lang.String[] variables)",
"if (ij.IJ.getInstance() == null) {"
+ " java.lang.System.err.println($1 + \": \" + $2);"
+ " return;"
+ "}");
// let IJ.handleException override the macro interpreter's call()'s exception handling
hacker.insertAtTopOfExceptionHandlers("ij.macro.Functions", "java.lang.String call()", "java.lang.reflect.InvocationTargetException",
"ij.IJ.handleException($1);"
+ "return null;");
// Add back the "Convert to 8-bit Grayscale" checkbox to Import>Image Sequence
if (!hacker.hasField("ij.plugin.FolderOpener", "convertToGrayscale")) {
hacker.insertPrivateStaticField("ij.plugin.FolderOpener", Boolean.TYPE, "convertToGrayscale");
hacker.replaceCallInMethod("ij.plugin.FolderOpener", "public void run(java.lang.String arg)", "ij.io.Opener", "openImage",
"$_ = $0.openImage($1, $2);"
+ "if (convertToGrayscale) {"
+ " final String saved = ij.Macro.getOptions();"
+ " ij.IJ.run($_, \"8-bit\", \"\");"
+ " if (saved != null && !saved.equals(\"\")) ij.Macro.setOptions(saved);"
+ "}");
hacker.replaceCallInMethod("ij.plugin.FolderOpener", "boolean showDialog(ij.ImagePlus imp, java.lang.String[] list)",
"ij.plugin.FolderOpener$FolderOpenerDialog", "addCheckbox",
"$0.addCheckbox(\"Convert to 8-bit Grayscale\", convertToGrayscale);"
+ "$0.addCheckbox($1, $2);", 1);
hacker.replaceCallInMethod("ij.plugin.FolderOpener", "boolean showDialog(ij.ImagePlus imp, java.lang.String[] list)",
"ij.plugin.FolderOpener$FolderOpenerDialog", "getNextBoolean",
"convertToGrayscale = $0.getNextBoolean();"
+ "$_ = $0.getNextBoolean();"
+ "if (convertToGrayscale && $_) {"
+ " ij.IJ.error(\"Cannot convert to grayscale and RGB at the same time.\");"
+ " return false;"
+ "}", 1);
}
// handle HTTPS in addition to HTTP
hacker.handleHTTPS("ij.macro.Functions", "java.lang.String exec()");
hacker.handleHTTPS("ij.plugin.DragAndDrop", "public void drop(java.awt.dnd.DropTargetDropEvent dtde)");
hacker.handleHTTPS(hacker.existsClass("ij.plugin.PluginInstaller") ? "ij.plugin.PluginInstaller" : "ij.io.PluginInstaller", "public boolean install(java.lang.String path)");
hacker.handleHTTPS("ij.plugin.ListVirtualStack", "public void run(java.lang.String arg)");
hacker.handleHTTPS("ij.plugin.ListVirtualStack", "java.lang.String[] open(java.lang.String path)");
addEditorExtensionPoints(hacker);
overrideAppVersion(hacker);
insertAppNameHooks(hacker);
insertRefreshMenusHook(hacker);
overrideStartupMacrosForFiji(hacker);
handleMacAdapter(hacker);
handleMenuCallbacks(hacker, headless);
installOpenInterceptor(hacker);
handleMacroGetOptions(hacker);
interceptCloseAllWindows(hacker);
interceptDisposal(hacker);
}
// -- methods to install additional hooks into ImageJ 1.x --
/**
* Install a hook to optionally run a Runnable at the end of Help>Refresh Menus.
*
* <p>
* See {@link LegacyExtensions#runAfterRefreshMenus(Runnable)}.
* </p>
*
* @param hacker the {@link CodeHacker} to use for patching
*/
private static void insertRefreshMenusHook(CodeHacker hacker) {
hacker.insertAtBottomOfMethod("ij.Menus", "public static void updateImageJMenus()",
"ij.IJ._hooks.runAfterRefreshMenus();");
}
private static void addEditorExtensionPoints(final CodeHacker hacker) {
hacker.insertAtTopOfMethod("ij.io.Opener", "public void open(java.lang.String path)",
"if (isText($1) && ij.IJ._hooks.openInEditor($1)) return;");
hacker.dontReturnOnNull("ij.plugin.frame.Recorder", "void createMacro()");
hacker.replaceCallInMethod("ij.plugin.frame.Recorder", "void createMacro()",
"ij.IJ", "runPlugIn",
"$_ = null;");
hacker.replaceCallInMethod("ij.plugin.frame.Recorder", "void createMacro()",
"ij.plugin.frame.Editor", "createMacro",
"if ($1.endsWith(\".txt\")) {"
+ " $1 = $1.substring($1.length() - 3) + \"ijm\";"
+ "}"
+ "if (!ij.IJ._hooks.createInEditor($1, $2)) {"
+ " ((ij.plugin.frame.Editor)ij.IJ.runPlugIn(\"ij.plugin.frame.Editor\", \"\")).createMacro($1, $2);"
+ "}");
hacker.insertPublicStaticField("ij.plugin.frame.Recorder", String.class, "nameForEditor", null);
hacker.insertAtTopOfMethod("ij.plugin.frame.Recorder", "void createPlugin(java.lang.String text, java.lang.String name)",
"this.nameForEditor = $2;");
hacker.replaceCallInMethod("ij.plugin.frame.Recorder", "void createPlugin(java.lang.String text, java.lang.String name)",
"ij.IJ", "runPlugIn",
"$_ = null;"
+ "new ij.plugin.NewPlugin().createPlugin(this.nameForEditor, ij.plugin.NewPlugin.PLUGIN, $2);"
+ "return;");
hacker.replaceCallInMethod("ij.plugin.NewPlugin", "public void createMacro(java.lang.String name)",
"ij.plugin.frame.Editor", "<init>",
"$_ = null;");
hacker.replaceCallInMethod("ij.plugin.NewPlugin", "public void createMacro(java.lang.String name)",
"ij.plugin.frame.Editor", "create",
"if ($1.endsWith(\".txt\")) {"
+ " $1 = $1.substring(0, $1.length() - 3) + \"ijm\";"
+ "}"
+ "if ($1.endsWith(\".ijm\") && ij.IJ._hooks.createInEditor($1, $2)) return;"
+ "int options = (monospaced ? ij.plugin.frame.Editor.MONOSPACED : 0)"
+ " | (menuBar ? ij.plugin.frame.Editor.MENU_BAR : 0);"
+ "new ij.plugin.frame.Editor(rows, columns, 0, options).create($1, $2);");
hacker.dontReturnOnNull("ij.plugin.NewPlugin", "public void createPlugin(java.lang.String name, int type, java.lang.String methods)");
hacker.replaceCallInMethod("ij.plugin.NewPlugin", "public void createPlugin(java.lang.String name, int type, java.lang.String methods)",
"ij.IJ", "runPlugIn",
"$_ = null;");
hacker.replaceCallInMethod("ij.plugin.NewPlugin", "public void createPlugin(java.lang.String name, int type, java.lang.String methods)",
"ij.plugin.frame.Editor", "create",
"if (!ij.IJ._hooks.createInEditor($1, $2)) {"
+ " ((ij.plugin.frame.Editor)ij.IJ.runPlugIn(\"ij.plugin.frame.Editor\", \"\")).create($1, $2);"
+ "}");
hacker.replaceCallInMethod("ij.plugin.Compiler",
"void edit()",
"ij.IJ", "runPlugIn",
"if (ij.IJ._hooks.openInEditor(dir + name)) $_ = null;" +
"else $_ = $proceed($$);");
hacker.replaceCallInMethod("ij.gui.Toolbar",
"public void itemStateChanged(java.awt.event.ItemEvent e)",
"ij.plugin.frame.Editor", "create",
"if ($1.endsWith(\".txt\")) $1 = $1.substring(0, $1.length() - 4);" +
"$1 += \".ijm\";" +
"if (!ij.IJ._hooks.createInEditor($1, $2)) $_ = $proceed($$);");
hacker.replaceCallInMethod("ij.plugin.CommandFinder",
"private boolean showMacro(java.lang.String cmd)",
"ij.plugin.frame.Editor", "create",
"if ($1.endsWith(\".txt\")) $1 = $1.substring(0, $1.length() - 4);" +
"$1 += \".ijm\";" +
"if (!ij.IJ._hooks.createInEditor($1, $2)) $_ = $proceed($$);");
}
private static void overrideAppVersion(final CodeHacker hacker) {
hacker.insertAtBottomOfMethod("ij.ImageJ",
"public java.lang.String version()",
"String version = ij.IJ._hooks.getAppVersion();" +
"if (version != null) {" +
" $_ = $_.replace(VERSION, version);" +
"}");
// Of course there is not a *single* way to obtain the version.
// That would have been too easy, wouldn't it?
hacker.insertAtTopOfMethod("ij.IJ",
"public static String getVersion()",
"String version = ij.IJ._hooks.getAppVersion();" +
"if (version != null) return version;");
}
/**
* Inserts hooks to replace the application name.
*/
private static void insertAppNameHooks(final CodeHacker hacker) {
final String appName = "ij.IJ._hooks.getAppName()";
final String replace = ".replace(\"ImageJ\", " + appName + ")";
hacker.insertAtTopOfMethod("ij.IJ", "public void error(java.lang.String title, java.lang.String msg)",
"if ($1 == null || $1.equals(\"ImageJ\")) $1 = " + appName + ";");
hacker.insertAtBottomOfMethod("ij.ImageJ", "public java.lang.String version()", "$_ = $_" + replace + ";");
hacker.replaceAppNameInCall("ij.ImageJ", "public <init>(java.applet.Applet applet, int mode)", "super", 1, appName);
hacker.replaceAppNameInNew("ij.ImageJ", "public void run()", "ij.gui.GenericDialog", 1, appName);
hacker.replaceAppNameInCall("ij.ImageJ", "public void run()", "addMessage", 1, appName);
if (hacker.hasMethod("ij.plugin.CommandFinder", "public void export()")) {
hacker.replaceAppNameInNew("ij.plugin.CommandFinder", "public void export()", "ij.text.TextWindow", 1, appName);
}
hacker.replaceAppNameInCall("ij.plugin.Hotkeys", "public void removeHotkey()", "addMessage", 1, appName);
hacker.replaceAppNameInCall("ij.plugin.Hotkeys", "public void removeHotkey()", "showStatus", 1, appName);
if (hacker.existsClass("ij.plugin.AppearanceOptions")) {
hacker.replaceAppNameInCall("ij.plugin.AppearanceOptions", "void showDialog()", "showMessage", 2, appName);
} else {
hacker.replaceAppNameInCall("ij.plugin.Options", "public void appearance()", "showMessage", 2, appName);
}
hacker.replaceAppNameInCall("ij.gui.YesNoCancelDialog", "public <init>(java.awt.Frame parent, java.lang.String title, java.lang.String msg)", "super", 2, appName);
hacker.replaceAppNameInCall("ij.gui.Toolbar", "private void showMessage(int toolId)", "showStatus", 1, appName);
}
private static void addIconHooks(final CodeHacker hacker) {
final String icon = "ij.IJ._hooks.getIconURL()";
hacker.replaceCallInMethod("ij.ImageJ", "void setIcon()", "java.lang.Class", "getResource",
"java.net.URL _iconURL = " + icon + ";\n" +
"if (_iconURL == null) $_ = $0.getResource($1);" +
"else $_ = _iconURL;");
hacker.insertAtTopOfMethod("ij.ImageJ", "public <init>(java.applet.Applet applet, int mode)",
"if ($2 != 2 /* ij.ImageJ.NO_SHOW */) setIcon();");
hacker.insertAtTopOfMethod("ij.WindowManager", "public void addWindow(java.awt.Frame window)",
"java.net.URL _iconURL = " + icon + ";\n"
+ "if (_iconURL != null && $1 != null) {"
+ " java.awt.Image img = $1.createImage((java.awt.image.ImageProducer)_iconURL.getContent());"
+ " if (img != null) {"
+ " $1.setIconImage(img);"
+ " }"
+ "}");
}
/**
* Makes sure that the legacy plugin class loader finds stuff in
* {@code $HOME/.plugins/}.
*/
private static void addExtraPlugins(final CodeHacker hacker) {
for (final String methodName : new String[] { "addJAR", "addJar" }) {
if (hacker.hasMethod("ij.io.PluginClassLoader", "private void "
+ methodName + "(java.io.File file)")) {
hacker.insertAtTopOfMethod("ij.io.PluginClassLoader",
"void init(java.lang.String path)",
extraPluginJarsHandler("if (file.isDirectory()) addDirectory(file);" +
"else " + methodName + "(file);"));
}
}
// avoid parsing ij.jar for plugins
hacker.replaceCallInMethod("ij.Menus",
"InputStream autoGenerateConfigFile(java.lang.String jar)",
"java.util.zip.ZipEntry", "getName",
"$_ = $proceed($$);" +
"if (\"IJ_Props.txt\".equals($_)) return null;");
// make sure that extra directories added to the plugin class path work, too
hacker.insertAtTopOfMethod("ij.Menus",
"InputStream getConfigurationFile(java.lang.String jar)",
"java.io.File isDir = new java.io.File($1);" +
"if (!isDir.exists()) return null;" +
"if (isDir.isDirectory()) {" +
" java.io.File config = new java.io.File(isDir, \"plugins.config\");" +
" if (config.exists()) return new java.io.FileInputStream(config);" +
" return ij.IJ._hooks.autoGenerateConfigFile(isDir);" +
"}");
// fix overzealous assumption that all plugins are in plugins.dir
hacker.insertPrivateStaticField("ij.Menus", Set.class, "_extraJars");
hacker.insertAtTopOfMethod("ij.Menus",
"java.lang.String getSubmenuName(java.lang.String jarPath)",
"if (_extraJars.contains($1)) return null;");
// make sure that .jar files are iterated in alphabetical order
hacker.replaceCallInMethod("ij.Menus",
"public static synchronized java.lang.String[] getPlugins()",
"java.io.File", "list",
"$_ = $proceed($$);"
+ "if ($_ != null) java.util.Arrays.sort($_);");
// add the extra .jar files to the list of plugin .jar files to be processed.
hacker.insertAtBottomOfMethod("ij.Menus",
"public static synchronized java.lang.String[] getPlugins()",
"if (_extraJars == null) _extraJars = new java.util.HashSet();" +
extraPluginJarsHandler("if (jarFiles == null) jarFiles = new java.util.Vector();" +
"jarFiles.addElement(file.getAbsolutePath());" +
"_extraJars.add(file.getAbsolutePath());"));
// exclude -sources.jar entries generated by Maven.
hacker.insertAtBottomOfMethod("ij.Menus",
"public static synchronized java.lang.String[] getPlugins()",
"if (jarFiles != null) {" +
" for (int i = jarFiles.size() - 1; i >= 0; i
" String entry = (String) jarFiles.elementAt(i);" +
" if (entry.endsWith(\"-sources.jar\")) {" +
" jarFiles.remove(i);" +
" }" +
" }" +
"}");
// force IJ.getClassLoader() to instantiate a PluginClassLoader
hacker.replaceCallInMethod(
"ij.IJ",
"public static ClassLoader getClassLoader()",
"java.lang.System",
"getProperty",
"$_ = System.getProperty($1);\n"
+ "if ($_ == null && $1.equals(\"plugins.dir\")) $_ = \"/non-existant/\";");
}
private static String extraPluginJarsHandler(final String code) {
return "for (java.util.Iterator iter = ij.IJ._hooks.handleExtraPluginJars().iterator();\n" +
"iter.hasNext(); ) {\n" +
"\tjava.io.File file = (java.io.File)iter.next();\n" +
code + "\n" +
"}\n";
}
private static void overrideStartupMacrosForFiji(CodeHacker hacker) {
hacker.replaceCallInMethod("ij.Menus", "void installStartupMacroSet()", "java.io.File", "<init>",
"if ($1.endsWith(\"StartupMacros.txt\")) {" +
" java.lang.String fijiPath = $1.substring(0, $1.length() - 3) + \"fiji.ijm\";" +
" java.io.File fijiFile = new java.io.File(fijiPath);" +
" $_ = fijiFile.exists() ? fijiFile : new java.io.File($1);" +
"} else $_ = new java.io.File($1);");
hacker.replaceCallInMethod("ij.Menus", "void installStartupMacroSet()", "ij.plugin.MacroInstaller", "installFile",
"if ($1.endsWith(\"StartupMacros.txt\")) {" +
" java.lang.String fijiPath = $1.substring(0, $1.length() - 3) + \"fiji.ijm\";" +
" java.io.File fijiFile = new java.io.File(fijiPath);" +
" $0.installFile(fijiFile.exists() ? fijiFile.getPath() : $1);" +
"} else $0.installFile($1);");
}
private static void handleMacAdapter(final CodeHacker hacker) {
// Without the ApplicationListener, MacAdapter cannot load, and hence CodeHacker would fail
// to load it if we patched the class.
if (!hacker.existsClass("com.apple.eawt.ApplicationListener")) return;
hacker.insertAtTopOfMethod("MacAdapter", "public void run(java.lang.String arg)",
"return;");
}
private static void handleMenuCallbacks(final CodeHacker hacker, boolean headless) {
hacker.insertAtTopOfMethod("ij.Menus",
"java.lang.String addMenuBar()",
"ij.IJ._hooks.addMenuItem(null, null);");
hacker.insertPrivateStaticField("ij.Menus", String.class, "_currentMenuPath");
// so that addSubMenu() has the correct menu path -- even in headless mode
hacker.insertAtTopOfMethod("ij.Menus",
"private static java.awt.Menu getMenu(java.lang.String menuName, boolean readFromProps)",
"_currentMenuPath = $1;");
// so that addPlugInItem() has the correct menu path -- even in headless mode
hacker.insertAtBottomOfMethod("ij.Menus",
"private static java.awt.Menu getMenu(java.lang.String menuName, boolean readFromProps)",
"_currentMenuPath = $1;");
hacker.insertAtTopOfMethod("ij.Menus",
"static java.awt.Menu addSubMenu(java.awt.Menu menu, java.lang.String name)",
"_currentMenuPath += \">\" + $2.replace('_', ' ');");
hacker.replaceCallInMethod("ij.Menus",
"void addPluginsMenu()",
"ij.Menus",
"addPluginItem",
"_currentMenuPath = \"Plugins\";" +
"$_ = $proceed($$);");
hacker.replaceCallInMethod("ij.Menus",
"void addPluginsMenu()",
"ij.Menus",
"addSubMenu",
"_currentMenuPath = \"Plugins\";" +
"$_ = $proceed($$);");
hacker.replaceCallInMethod("ij.Menus",
"java.lang.String addMenuBar()",
"ij.Menus",
"addPlugInItem",
"if (\"Quit\".equals($2) || \"Open...\".equals($2) || \"Close\".equals($2) || \"Revert\".equals($2))" +
" _currentMenuPath = \"File\";" +
"else if(\"Show Info...\".equals($2) || \"Crop\".equals($2))" +
" _currentMenuPath = \"Image\";" +
"else if (\"Image Calculator...\".equals($2))" +
" _currentMenuPath = \"Process\";" +
"else if (\"About ImageJ...\".equals($2))" +
" _currentMenuPath = \"Help\";" +
"$_ = $proceed($$);");
// Wow. There are so many different ways ImageJ 1.x adds menu entries. See e.g. "Repeat Command".
hacker.replaceCallInMethod("ij.Menus",
"java.lang.String addMenuBar()",
"ij.Menus",
"addItem",
"ij.IJ._hooks.addMenuItem(_currentMenuPath + \">\" + $2, null);" +
"$_ = $proceed($$);");
hacker.insertPrivateStaticField("ij.Menus",
HashSet.class, "_separators");
hacker.insertAtTopOfMethod("ij.Menus",
"void installJarPlugin(java.lang.String jar, java.lang.String s)",
" if (_separators == null) _separators = new java.util.HashSet();" +
"_currentMenuPath = \"Plugins\";");
hacker.replaceCallInMethod("ij.Menus",
"void installJarPlugin(java.lang.String jar, java.lang.String s)",
"java.lang.String", "substring",
"$_ = $proceed($$);" +
"ij.IJ._hooks.addMenuItem(_currentMenuPath, $_);",
4);
hacker.insertAtTopOfMethod("ij.Menus",
"void addPlugInItem(java.awt.Menu menu, java.lang.String label, java.lang.String className, int shortcut, boolean shift)",
"ij.IJ._hooks.addMenuItem(_currentMenuPath + \">\" + $2, $3);");
hacker.insertAtTopOfMethod("ij.Menus",
"static void addPluginItem(java.awt.Menu submenu, java.lang.String s)",
"int comma = $2.lastIndexOf(',');" +
"if (comma > 0) {" +
" java.lang.String label = $2.substring(1, comma - 1);" +
" if (label.endsWith(\"]\")) {" +
" int open = label.indexOf(\"[\");" +
" if (open > 0 && label.substring(open + 1, comma - 3).matches(\"[A-Za-z0-9]\"))" +
" label = label.substring(0, open);" +
" }" +
" while (comma + 2 < $2.length() && $2.charAt(comma + 1) == ' ')" +
" comma++;" +
" if (mbar == null && _separators != null) {" +
" if (!_separators.contains(_currentMenuPath)) {" +
" _separators.add(_currentMenuPath);" +
" ij.IJ._hooks.addMenuItem(_currentMenuPath + \">-\", null);" +
" }" +
" }" +
" ij.IJ._hooks.addMenuItem(_currentMenuPath + \">\" + label," +
" $2.substring(comma + 1));" +
"}");
hacker.insertAtTopOfMethod("ij.Menus",
"java.awt.CheckboxMenuItem addCheckboxItem(java.awt.Menu menu, java.lang.String label, java.lang.String className)",
"ij.IJ._hooks.addMenuItem(_currentMenuPath + \">\" + $2, $3);");
// handle separators (we cannot simply look for java.awt.Menu#addSeparator
// because we might be running in headless mode)
hacker.replaceCallInMethod("ij.Menus",
"java.lang.String addMenuBar()",
"ij.Menus",
"addPlugInItem",
"if (\"Cache Sample Images \".equals($2))" +
" ij.IJ._hooks.addMenuItem(\"File>Open Samples>-\", null);" +
"else if (\"Close\".equals($2) || \"Page Setup...\".equals($2) || \"Cut\".equals($2) ||" +
" \"Clear\".equals($2) || \"Crop\".equals($2) || \"Set Scale...\".equals($2) ||" +
" \"Dev. Resources...\".equals($2) || \"Update ImageJ...\".equals($2) ||" +
" \"Quit\".equals($2)) {" +
" int separator = _currentMenuPath.indexOf('>');" +
" if (separator < 0) separator = _currentMenuPath.length();" +
" ij.IJ._hooks.addMenuItem(_currentMenuPath.substring(0, separator) + \">-\", null);" +
"}" +
"$_ = $proceed($$);" +
"if (\"Tile\".equals($2))" +
" ij.IJ._hooks.addMenuItem(\"Window>-\", null);");
hacker.replaceCallInMethod("ij.Menus",
"java.lang.String addMenuBar()",
"ij.Menus",
"addCheckboxItem",
"if (\"RGB Stack\".equals($2))" +
" ij.IJ._hooks.addMenuItem(_currentMenuPath + \">-\", null);" +
"$_ = $proceed($$);");
hacker.replaceCallInMethod("ij.Menus",
"java.lang.String addMenuBar()",
"ij.Menus",
"getMenu",
"if (\"Edit>Selection\".equals($1) || \"Image>Adjust\".equals($1) || \"Image>Lookup Tables\".equals($1) ||" +
" \"Process>Batch\".equals($1) || \"Help>About Plugins\".equals($1)) {" +
" int separator = $1.indexOf('>');" +
" ij.IJ._hooks.addMenuItem($1.substring(0, separator) + \">-\", null);" +
"}" +
"$_ = $proceed($$);");
hacker.replaceCallInMethod("ij.Menus",
"static java.awt.Menu addSubMenu(java.awt.Menu menu, java.lang.String name)",
"java.lang.String",
"equals",
"$_ = $proceed($$);" +
"if ($_ && \"-\".equals($1))" +
" ij.IJ._hooks.addMenuItem(_currentMenuPath + \">-\", null);");
hacker.replaceCallInMethod("ij.Menus",
"static void addLuts(java.awt.Menu submenu)",
"ij.IJ",
"isLinux",
"ij.IJ._hooks.addMenuItem(_currentMenuPath + \">-\", null);" +
"$_ = $proceed($$);");
hacker.replaceCallInMethod("ij.Menus",
"void addPluginsMenu()",
"ij.Prefs",
"getString",
"$_ = $proceed($$);" +
"if ($_ != null && $_.startsWith(\"-\"))" +
" ij.IJ._hooks.addMenuItem(\"Plugins>-\", null);");
hacker.insertAtTopOfMethod("ij.Menus",
"static void addSeparator(java.awt.Menu menu)",
"ij.IJ._hooks.addMenuItem(_currentMenuPath + \">-\", null);");
hacker.replaceCallInMethod("ij.Menus", "void installPlugins()",
"ij.Prefs", "getString",
"$_ = $proceed($$);" +
"if ($_ != null && $_.length() > 0) {" +
" String className = $_.substring($_.lastIndexOf(',') + 1);" +
" if (!className.startsWith(\"ij.\")) _currentMenuPath = null;" +
" else {" +
" char c = $_.charAt(0);" +
" if (c == IMPORT_MENU) _currentMenuPath = \"File>Import\";" +
" else if (c == SAVE_AS_MENU) _currentMenuPath = \"File>Save As\";" +
" else if (c == SHORTCUTS_MENU) _currentMenuPath = \"Plugins>Shortcuts\";" +
" else if (c == ABOUT_MENU) _currentMenuPath = \"Help>About Plugins\";" +
" else if (c == FILTERS_MENU) _currentMenuPath = \"Process>Filters\";" +
" else if (c == TOOLS_MENU) _currentMenuPath = \"Analyze>Tools\";" +
" else if (c == UTILITIES_MENU) _currentMenuPath = \"Plugins>Utilities\";" +
" else _currentMenuPath = \"Plugins\";" +
" }" +
"}");
if (headless) {
hacker.replaceCallInMethod("ij.Menus", "void installPlugins()",
"java.lang.String", "substring",
"$_ = $proceed($$);" +
"if (_currentMenuPath != null) addPluginItem((java.awt.Menu) null, $_);", 2);
}
}
private static void installOpenInterceptor(CodeHacker hacker) {
// Intercept ij.IJ open methods
// If the open method is intercepted, the hooks.interceptOpen method needs
// to perform any necessary display operations
hacker.insertAtTopOfMethod("ij.IJ",
"public static void open(java.lang.String path)",
"Object result = ij.IJ._hooks.interceptFileOpen($1);" +
"if (result != null) {" +
"if (result instanceof java.lang.String) path = (java.lang.String)result;" +
"else return;" +
"}");
// If openImage is intercepted, we return the opened ImagePlus without displaying it
hacker.insertAtTopOfMethod("ij.IJ",
"public static ij.ImagePlus openImage(java.lang.String path)",
"Object result = ij.IJ._hooks.interceptOpenImage($1, -1);" +
"if (result != null) {" +
"if (result instanceof ij.ImagePlus) return (ij.ImagePlus)result;" +
"else if (result instanceof java.lang.String) path = (java.lang.String)result;" +
"else return null; " +
"}");
hacker.insertAtTopOfMethod("ij.IJ",
"public static ij.ImagePlus openImage(java.lang.String path, int sliceIndex)",
"Object result = ij.IJ._hooks.interceptOpenImage($1, $2);" +
"if (result != null) {" +
"if (result instanceof ij.ImagePlus) return (ij.ImagePlus)result;" +
"else if (result instanceof java.lang.String) path = (java.lang.String)result;" +
"else return null; " +
"}");
hacker.replaceCallInMethod("ij.plugin.FolderOpener", "public void run(java.lang.String arg)", "ij.io.Opener", "openImage",
"Object result = ij.IJ._hooks.interceptOpenImage($1 + $2, -1);" +
"if (result != null && result instanceof ij.ImagePlus) {" +
" $_ = (ij.ImagePlus)result;" +
"} else {" +
" $_ = $proceed($$);" +
"}");
// Intercept File > Open Recent
hacker.replaceCallInMethod("ij.RecentOpener", "public void run()",
"ij.io.Opener", "open",
"Object result = ij.IJ._hooks.interceptOpenRecent(path);" +
"if (result == null) o.open(path);" +
"else if (! (result instanceof ij.ImagePlus)) return;");
// Intercept DragAndDrop openings
hacker.insertAtTopOfMethod("ij.plugin.DragAndDrop",
"public void openFile(java.io.File f)",
"Object result = ij.IJ._hooks.interceptDragAndDropFile($1);" +
"if (result != null && !(result instanceof java.lang.String)) {" +
" return;" +
"}");
// Make sure that .lut files are not intercepted
hacker.replaceCallInMethod("ij.Executer",
"public static boolean loadLut(java.lang.String name)",
"ij.IJ", "open",
"ij.ImagePlus imp = (ij.ImagePlus) ij.IJ.runPlugIn(\"ij.plugin.LutLoader\", $1);" +
"if (imp != null && imp.getWidth() > 0) {" +
" imp.show();" +
"}");
}
private static void handleMacroGetOptions(CodeHacker hacker) {
// remove that pesky, pesky Run$_ restriction
hacker.replaceCallInMethod("ij.Macro", "public static java.lang.String getOptions()",
"java.lang.String", "startsWith",
"$_ = \"Run$_\".equals($1) ? true : $proceed($$);");
// look at more threads than just the current one, if the legacy hooks have some for us
hacker.replaceCallInMethod("ij.Macro", "public static java.lang.String getOptions()",
"java.util.Hashtable", "get",
"$_ = $proceed($$);" +
"if ($_ == null) {" +
" java.lang.Iterable ancestors = ij.IJ._hooks.getThreadAncestors();" +
" if (ancestors != null) {" +
" for (java.util.Iterator iter = ancestors.iterator(); $_ == null && iter.hasNext(); ) {" +
" $_ = $proceed(iter.next());" +
" }" +
" }" +
"}");
}
private static void interceptCloseAllWindows(final CodeHacker hacker) {
hacker.insertAtBottomOfMethod("ij.WindowManager",
"public synchronized static boolean closeAllWindows()",
"if ($_ == true) {" +
" $_ = ij.IJ._hooks.interceptCloseAllWindows();" +
"}");
}
private static void interceptDisposal(final CodeHacker hacker) {
hacker.replaceCallInMethod("ij.ImageJ", "public void run()", "ij.IJ",
"cleanup",
"if (!ij.IJ._hooks.disposing()) {" +
" quitting = false;" +
" return;" +
"}" +
"$_ = $proceed($$);");
}
// -- methods to configure LegacyEnvironment instances --
static void noPluginClassLoader(final CodeHacker hacker) {
hacker.insertPrivateStaticField("ij.IJ", ClassLoader.class, "_classLoader");
final String initClassLoader =
"_classLoader = Thread.currentThread().getContextClassLoader();";
hacker.insertAtTopOfMethod("ij.IJ",
"static void init()",
initClassLoader);
hacker.insertAtTopOfMethod("ij.IJ",
"static void init(ij.ImageJ imagej, java.applet.Applet theApplet)",
initClassLoader);
// Make sure that bare .class files in plugins/ and subdirectories are seen by ImageJ 1.x.
// This needs to be done *after* Menus made sure that IJ.getDirectory("plugins") returns non-null
final String supportBarePlugins =
"java.lang.ClassLoader loader = " + LegacyInjector.ESSENTIAL_LEGACY_HOOKS_CLASS +
" .missingSubdirs(_classLoader, true);" +
"if (loader != null) {" +
" Thread.currentThread().setContextClassLoader(loader);" +
" _classLoader = loader;" +
"}";
hacker.insertAtBottomOfMethod("ij.IJ",
"static void init()",
supportBarePlugins);
hacker.insertAtBottomOfMethod("ij.IJ",
"static void init(ij.ImageJ imagej, java.applet.Applet theApplet)",
supportBarePlugins);
hacker.insertAtTopOfMethod("ij.IJ",
"public static ClassLoader getClassLoader()",
"if (_classLoader == null) {" +
initClassLoader +
supportBarePlugins +
"}" +
"return _classLoader;");
hacker.insertAtTopOfMethod(LegacyInjector.ESSENTIAL_LEGACY_HOOKS_CLASS,
"public <init>()", "addThisLoadersClasspath();");
disableRefreshMenus(hacker);
// make sure that IJ#runUserPlugIn can execute package-less plugins in subdirectories of $IJ/plugin/
final String runUserPlugInSig = "static java.lang.Object runUserPlugIn(java.lang.String commandName, java.lang.String className, java.lang.String arg, boolean createNewLoader)";
hacker.insertAtTopOfExceptionHandlers("ij.IJ", runUserPlugInSig, "java.lang.NoClassDefFoundError",
"java.lang.ClassLoader loader = " + LegacyInjector.ESSENTIAL_LEGACY_HOOKS_CLASS +
" .missingSubdirs(getClassLoader(), false);" +
"if (loader != null) _classLoader = loader;");
hacker.replaceCallInMethod("ij.IJ", runUserPlugInSig,
"java.lang.ClassLoader", "loadClass",
"try {" +
" $_ = $proceed($$);" +
"} catch (java.lang.ClassNotFoundException e) {" +
" java.lang.ClassLoader loader = " + LegacyInjector.ESSENTIAL_LEGACY_HOOKS_CLASS +
" .missingSubdirs(getClassLoader(), true);" +
" if (loader == null) {" +
" throw e;" +
" } else {" +
" _classLoader = loader;" +
" $_ = loader.loadClass($1);" +
" }" +
"}");
}
static void disableRefreshMenus(final CodeHacker hacker) {
hacker.insertAtTopOfMethod("ij.IJ",
"static void setClassLoader(java.lang.ClassLoader loader)",
"ij.IJ.log(\"WARNING: The PluginClassLoader cannot be reset\");" +
"return;");
hacker.insertAtBottomOfMethod("ij.Menus", "java.lang.String addMenuBar()",
"if (mbar != null) {" +
" final java.awt.Menu help = mbar.getHelpMenu();" +
" if (help != null) {" +
" for (int i = 0; i < help.getItemCount(); i++) {" +
" final java.awt.MenuItem item = help.getItem(i);" +
" if (\"Refresh Menus\".equals(item.getLabel())) {" +
" item.setEnabled(false);" +
" break;" +
" }" +
" }" +
" }" +
"}");
}
static void suppressIJ1ScriptDiscovery(CodeHacker hacker) {
hacker.insertAtTopOfMethod("ij.Menus",
"private static boolean validMacroName(java.lang.String name, boolean hasUnderscore)",
"return false;");
}
} |
package plugin.google.maps;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Point;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.util.Log;
import android.view.animation.BounceInterpolator;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import com.google.android.gms.maps.Projection;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaResourceApi;
import org.apache.cordova.CordovaWebView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Set;
public class PluginMarker extends MyPlugin implements MyPluginInterface {
private enum Animation {
DROP,
BOUNCE
}
private ArrayList<AsyncTask> iconLoadingTasks = new ArrayList<AsyncTask>();
private ArrayList<String> iconCacheKeys = new ArrayList<String>();
private ArrayList<Bitmap> icons = new ArrayList<Bitmap>();
@Override
public void initialize(CordovaInterface cordova, final CordovaWebView webView) {
super.initialize(cordova, webView);
}
@Override
public void onDestroy() {
super.onDestroy();
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if (objects == null) {
return;
}
Set<String> keySet = objects.keySet();
String[] objectIdArray = keySet.toArray(new String[keySet.size()]);
for (String objectId : objectIdArray) {
if (objects.containsKey(objectId)) {
if (objectId.startsWith("marker_") &&
!objectId.startsWith("marker_property_")) {
Marker marker = (Marker) objects.remove(objectId);
marker.setIcon(null);
marker.remove();
marker = null;
} else {
Object object = objects.remove(objectId);
object = null;
}
}
}
objects.clear();
objects = null;
}
});
}
@Override
protected void clear() {
// Cancel tasks
cordova.getThreadPool().submit(new Runnable() {
@Override
public void run() {
for (int i = 0, ilen=iconLoadingTasks.size(); i < ilen; i++) {
iconLoadingTasks.get(i).cancel(true);
iconLoadingTasks.set(i, null);
}
iconLoadingTasks = null;
}
});
// Recycle bitmaps as much as possible
String[] cacheKeys = iconCacheKeys.toArray(new String[iconCacheKeys.size()]);
for (int i = 0; i < cacheKeys.length; i++) {
AsyncLoadImage.removeBitmapFromMemCahce(iconCacheKeys.remove(0));
}
Bitmap[] cachedBitmaps = icons.toArray(new Bitmap[icons.size()]);
Bitmap image;
for (int i = 0; i < cachedBitmaps.length; i++) {
image = icons.remove(0);
if (image != null && !image.isRecycled()) {
image.recycle();
}
image = null;
}
icons.clear();
// clean up properties as much as possible
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Set<String> keySet = objects.keySet();
String[] objectIdArray = keySet.toArray(new String[keySet.size()]);
for (String objectId : objectIdArray) {
if (objects.containsKey(objectId)) {
if (objectId.startsWith("marker_") &&
!objectId.startsWith("marker_property_")) {
Marker marker = (Marker) objects.remove(objectId);
marker.setIcon(null);
marker.remove();
marker = null;
} else {
Object object = objects.remove(objectId);
object = null;
}
}
}
objects.clear();
PluginMarker.super.clear();
}
});
}
/**
* Create a marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
public void create(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
// Create an instance of Marker class
final MarkerOptions markerOptions = new MarkerOptions();
final JSONObject properties = new JSONObject();
final JSONObject opts = args.getJSONObject(1);
if (opts.has("position")) {
JSONObject position = opts.getJSONObject("position");
markerOptions.position(new LatLng(position.getDouble("lat"), position.getDouble("lng")));
}
if (opts.has("title")) {
markerOptions.title(opts.getString("title"));
}
if (opts.has("snippet")) {
markerOptions.snippet(opts.getString("snippet"));
}
if (opts.has("visible")) {
if (opts.has("icon") && !"".equals(opts.getString("icon"))) {
markerOptions.visible(false);
properties.put("isVisible", false);
} else {
markerOptions.visible(opts.getBoolean("visible"));
properties.put("isVisible", markerOptions.isVisible());
}
}
if (opts.has("draggable")) {
markerOptions.draggable(opts.getBoolean("draggable"));
}
if (opts.has("rotation")) {
markerOptions.rotation((float)opts.getDouble("rotation"));
}
if (opts.has("flat")) {
markerOptions.flat(opts.getBoolean("flat"));
}
if (opts.has("opacity")) {
markerOptions.alpha((float) opts.getDouble("opacity"));
}
if (opts.has("zIndex")) {
markerOptions.zIndex((float) opts.getDouble("zIndex"));
}
if (opts.has("styles")) {
properties.put("styles", opts.getJSONObject("styles"));
}
if (opts.has("disableAutoPan")) {
properties.put("disableAutoPan", opts.getBoolean("disableAutoPan"));
} else {
properties.put("disableAutoPan", false);
}
if (opts.has("noCache")) {
properties.put("noCache", opts.getBoolean("noCache"));
} else {
properties.put("noCache", false);
}
if (opts.has("useHtmlInfoWnd")) {
properties.put("useHtmlInfoWnd", opts.getBoolean("useHtmlInfoWnd"));
} else {
properties.put("useHtmlInfoWnd", false);
}
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
final Marker marker = map.addMarker(markerOptions);
marker.hideInfoWindow();
cordova.getThreadPool().execute(new Runnable() {
@Override
public void run() {
try {
// Store the marker
String id = "marker_" + marker.getId();
self.objects.put(id, marker);
self.objects.put("marker_property_" + marker.getId(), properties);
// Prepare the result
final JSONObject result = new JSONObject();
result.put("hashCode", marker.hashCode());
result.put("id", id);
// Load icon
if (opts.has("icon")) {
// Case: have the icon property
Bundle bundle = null;
Object value = opts.get("icon");
if (JSONObject.class.isInstance(value)) {
JSONObject iconProperty = (JSONObject) value;
bundle = PluginUtil.Json2Bundle(iconProperty);
// The `anchor` of the `icon` property
if (iconProperty.has("anchor")) {
value = iconProperty.get("anchor");
if (JSONArray.class.isInstance(value)) {
JSONArray points = (JSONArray) value;
double[] anchorPoints = new double[points.length()];
for (int i = 0; i < points.length(); i++) {
anchorPoints[i] = points.getDouble(i);
}
bundle.putDoubleArray("anchor", anchorPoints);
}
}
// The `infoWindowAnchor` property for infowindow
if (opts.has("infoWindowAnchor")) {
value = opts.get("infoWindowAnchor");
if (JSONArray.class.isInstance(value)) {
JSONArray points = (JSONArray) value;
double[] anchorPoints = new double[points.length()];
for (int i = 0; i < points.length(); i++) {
anchorPoints[i] = points.getDouble(i);
}
bundle.putDoubleArray("infoWindowAnchor", anchorPoints);
}
}
} else if (JSONArray.class.isInstance(value)) {
float[] hsv = new float[3];
JSONArray arrayRGBA = (JSONArray) value;
Color.RGBToHSV(arrayRGBA.getInt(0), arrayRGBA.getInt(1), arrayRGBA.getInt(2), hsv);
bundle = new Bundle();
bundle.putFloat("iconHue", hsv[0]);
} else {
bundle = new Bundle();
bundle.putString("url", (String) value);
}
if (opts.has("animation")) {
bundle.putString("animation", opts.getString("animation"));
}
PluginMarker.this.setIcon_(marker, bundle, new PluginAsyncInterface() {
@Override
public void onPostExecute(final Object object) {
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Marker marker = (Marker) object;
if (opts.has("visible")) {
try {
marker.setVisible(opts.getBoolean("visible"));
} catch (JSONException e) {
}
} else {
marker.setVisible(true);
}
// Animation
String markerAnimation = null;
if (opts.has("animation")) {
try {
markerAnimation = opts.getString("animation");
} catch (JSONException e) {
e.printStackTrace();
}
}
if (markerAnimation != null) {
PluginMarker.this.setMarkerAnimation_(marker, markerAnimation, new PluginAsyncInterface() {
@Override
public void onPostExecute(Object object) {
Marker marker = (Marker) object;
callbackContext.success(result);
}
@Override
public void onError(String errorMsg) {
callbackContext.error(errorMsg);
}
});
} else {
callbackContext.success(result);
}
}
});
}
@Override
public void onError(String errorMsg) {
callbackContext.error(errorMsg);
}
});
} else {
// Case: no icon property
String markerAnimation = null;
if (opts.has("animation")) {
markerAnimation = opts.getString("animation");
}
if (markerAnimation != null) {
// Execute animation
PluginMarker.this.setMarkerAnimation_(marker, markerAnimation, new PluginAsyncInterface() {
@Override
public void onPostExecute(Object object) {
callbackContext.success(result);
}
@Override
public void onError(String errorMsg) {
callbackContext.error(errorMsg);
}
});
} else {
// Return the result if does not specify the icon property.
callbackContext.success(result);
}
}
} catch (Exception e) {
e.printStackTrace();
callbackContext.error("" + e.getMessage());
}
}
});
}
});
}
private void setDropAnimation_(final Marker marker, final PluginAsyncInterface callback) {
final long startTime = SystemClock.uptimeMillis();
final long duration = 100;
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
final Handler handler = new Handler();
final Projection proj = map.getProjection();
final LatLng markerLatLng = marker.getPosition();
final Point markerPoint = proj.toScreenLocation(markerLatLng);
final Point startPoint = new Point(markerPoint.x, 0);
final Interpolator interpolator = new LinearInterpolator();
handler.post(new Runnable() {
@Override
public void run() {
LatLng startLatLng = proj.fromScreenLocation(startPoint);
long elapsed = SystemClock.uptimeMillis() - startTime;
float t = interpolator.getInterpolation((float) elapsed / duration);
double lng = t * markerLatLng.longitude + (1 - t) * startLatLng.longitude;
double lat = t * markerLatLng.latitude + (1 - t) * startLatLng.latitude;
marker.setPosition(new LatLng(lat, lng));
if (t < 1.0) {
// Post again 16ms later.
handler.postDelayed(this, 16);
} else {
marker.setPosition(markerLatLng);
callback.onPostExecute(marker);
}
}
});
}
});
}
private void setBounceAnimation_(final Marker marker, final PluginAsyncInterface callback) {
final long startTime = SystemClock.uptimeMillis();
final long duration = 2000;
final Interpolator interpolator = new BounceInterpolator();
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
final Handler handler = new Handler();
final Projection projection = map.getProjection();
final LatLng markerLatLng = marker.getPosition();
final Point startPoint = projection.toScreenLocation(markerLatLng);
startPoint.offset(0, -200);
handler.post(new Runnable() {
@Override
public void run() {
LatLng startLatLng = projection.fromScreenLocation(startPoint);
long elapsed = SystemClock.uptimeMillis() - startTime;
float t = interpolator.getInterpolation((float) elapsed / duration);
double lng = t * markerLatLng.longitude + (1 - t) * startLatLng.longitude;
double lat = t * markerLatLng.latitude + (1 - t) * startLatLng.latitude;
marker.setPosition(new LatLng(lat, lng));
if (t < 1.0) {
// Post again 16ms later.
handler.postDelayed(this, 16);
} else {
marker.setPosition(markerLatLng);
callback.onPostExecute(marker);
}
}
});
}
});
}
private void setMarkerAnimation_(Marker marker, String animationType, PluginAsyncInterface callback) {
Animation animation = null;
try {
animation = Animation.valueOf(animationType.toUpperCase(Locale.US));
} catch (Exception e) {
e.printStackTrace();
}
if (animation == null) {
callback.onPostExecute(marker);
return;
}
switch(animation) {
case DROP:
this.setDropAnimation_(marker, callback);
break;
case BOUNCE:
this.setBounceAnimation_(marker, callback);
break;
default:
break;
}
}
public void setAnimation(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String markerId = args.getString(0);
String animation = args.getString(1);
final Marker marker = this.getMarker(markerId);
this.setMarkerAnimation_(marker, animation, new PluginAsyncInterface() {
@Override
public void onPostExecute(Object object) {
callbackContext.success();
}
@Override
public void onError(String errorMsg) {
callbackContext.error(errorMsg);
}
});
}
/**
* Show the InfoWindow bound with the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
public void showInfoWindow(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
final String id = args.getString(0);
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Marker marker = getMarker(id);
if (marker != null) {
marker.showInfoWindow();
}
sendNoResult(callbackContext);
}
});
}
/**
* Set rotation for the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
public void setRotation(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
float rotation = (float)args.getDouble(1);
String id = args.getString(0);
this.setFloat("setRotation", id, rotation, callbackContext);
}
/**
* Set opacity for the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
public void setOpacity(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
float alpha = (float)args.getDouble(1);
String id = args.getString(0);
this.setFloat("setAlpha", id, alpha, callbackContext);
}
/**
* Set zIndex for the marker (dummy code, not available on Android V2)
* @param args
* @param callbackContext
* @throws JSONException
*/
public void setZIndex(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
float zIndex = (float)args.getDouble(1);
String id = args.getString(0);
Marker marker = getMarker(id);
this.setFloat("setZIndex", id, zIndex, callbackContext);
}
/**
* set position
* @param args
* @param callbackContext
* @throws JSONException
*/
public void setPosition(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
final String id = args.getString(0);
final LatLng position = new LatLng(args.getDouble(1), args.getDouble(2));
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Marker marker = getMarker(id);
if (marker != null) {
marker.setPosition(position);
}
sendNoResult(callbackContext);
}
});
}
/**
* Set flat for the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
public void setFlat(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
boolean isFlat = args.getBoolean(1);
String id = args.getString(0);
this.setBoolean("setFlat", id, isFlat, callbackContext);
}
/**
* Set visibility for the object
* @param args
* @param callbackContext
* @throws JSONException
*/
public void setVisible(JSONArray args, CallbackContext callbackContext) throws JSONException {
boolean isVisible = args.getBoolean(1);
String id = args.getString(0);
Marker marker = this.getMarker(id);
if (marker == null) {
this.sendNoResult(callbackContext);
return;
}
String propertyId = "marker_property_" + marker.getId();
JSONObject properties = null;
if (self.objects.containsKey(propertyId)) {
properties = (JSONObject)self.objects.get(propertyId);
} else {
properties = new JSONObject();
}
properties.put("isVisible", isVisible);
self.objects.put(propertyId, properties);
this.setBoolean("setVisible", id, isVisible, callbackContext);
}
/**
* @param args
* @param callbackContext
* @throws JSONException
*/
public void setDisableAutoPan(JSONArray args, CallbackContext callbackContext) throws JSONException {
boolean disableAutoPan = args.getBoolean(1);
String id = args.getString(0);
Marker marker = this.getMarker(id);
if (marker == null) {
this.sendNoResult(callbackContext);
return;
}
String propertyId = "marker_property_" + marker.getId();
JSONObject properties = null;
if (self.objects.containsKey(propertyId)) {
properties = (JSONObject)self.objects.get(propertyId);
} else {
properties = new JSONObject();
}
properties.put("disableAutoPan", disableAutoPan);
self.objects.put(propertyId, properties);
this.sendNoResult(callbackContext);
}
/**
* Set title for the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
public void setTitle(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String title = args.getString(1);
String id = args.getString(0);
this.setString("setTitle", id, title, callbackContext);
}
/**
* Set the snippet for the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
public void setSnippet(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String snippet = args.getString(1);
String id = args.getString(0);
this.setString("setSnippet", id, snippet, callbackContext);
}
/**
* Hide the InfoWindow binded with the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
public void hideInfoWindow(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
final String id = args.getString(0);
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Marker marker = getMarker(id);
if (marker != null) {
marker.hideInfoWindow();
}
sendNoResult(callbackContext);
}
});
}
/**
* Remove the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
public void remove(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
final String id = args.getString(0);
final Marker marker = this.getMarker(id);
if (marker == null) {
callbackContext.success();
return;
}
String[] cacheKeys = iconCacheKeys.toArray(new String[iconCacheKeys.size()]);
for (int i = 0; i < cacheKeys.length; i++) {
AsyncLoadImage.removeBitmapFromMemCahce(cacheKeys[i]);
}
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
marker.remove();
objects.remove(id);
String propertyId = "marker_property_" + id;
objects.remove(propertyId);
sendNoResult(callbackContext);
}
});
}
/**
* Set anchor for the icon of the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
public void setIconAnchor(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
float anchorX = (float)args.getDouble(1);
float anchorY = (float)args.getDouble(2);
String id = args.getString(0);
Marker marker = this.getMarker(id);
Bundle imageSize = (Bundle) self.objects.get("imageSize");
if (imageSize != null) {
this._setIconAnchor(marker, anchorX, anchorY, imageSize.getInt("width"), imageSize.getInt("height"));
}
this.sendNoResult(callbackContext);
}
/**
* Set anchor for the InfoWindow of the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
public void setInfoWindowAnchor(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
float anchorX = (float)args.getDouble(1);
float anchorY = (float)args.getDouble(2);
String id = args.getString(0);
Marker marker = this.getMarker(id);
Bundle imageSize = (Bundle) self.objects.get("imageSize");
if (imageSize != null) {
this._setInfoWindowAnchor(marker, anchorX, anchorY, imageSize.getInt("width"), imageSize.getInt("height"));
}
this.sendNoResult(callbackContext);
}
/**
* Set draggable for the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
public void setDraggable(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
Boolean draggable = args.getBoolean(1);
String id = args.getString(0);
this.setBoolean("setDraggable", id, draggable, callbackContext);
}
/**
* Set icon of the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
public void setIcon(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String id = args.getString(0);
Marker marker = this.getMarker(id);
Object value = args.get(1);
Bundle bundle = null;
if (JSONObject.class.isInstance(value)) {
JSONObject iconProperty = (JSONObject)value;
bundle = PluginUtil.Json2Bundle(iconProperty);
// The `anchor` for icon
if (iconProperty.has("anchor")) {
value = iconProperty.get("anchor");
if (JSONArray.class.isInstance(value)) {
JSONArray points = (JSONArray)value;
double[] anchorPoints = new double[points.length()];
for (int i = 0; i < points.length(); i++) {
anchorPoints[i] = points.getDouble(i);
}
bundle.putDoubleArray("anchor", anchorPoints);
}
}
} else if (JSONArray.class.isInstance(value)) {
float[] hsv = new float[3];
JSONArray arrayRGBA = (JSONArray)value;
Color.RGBToHSV(arrayRGBA.getInt(0), arrayRGBA.getInt(1), arrayRGBA.getInt(2), hsv);
bundle = new Bundle();
bundle.putFloat("iconHue", hsv[0]);
} else if (String.class.isInstance(value)) {
bundle = new Bundle();
bundle.putString("url", (String)value);
}
if (bundle != null) {
this.setIcon_(marker, bundle, new PluginAsyncInterface() {
@Override
public void onPostExecute(Object object) {
PluginMarker.this.sendNoResult(callbackContext);
}
@Override
public void onError(String errorMsg) {
callbackContext.error(errorMsg);
}
});
} else {
this.sendNoResult(callbackContext);
}
}
private void setIcon_(final Marker marker, final Bundle iconProperty, final PluginAsyncInterface callback) {
boolean noCaching = false;
if (iconProperty.containsKey("noCache")) {
noCaching = iconProperty.getBoolean("noCache");
}
if (iconProperty.containsKey("iconHue")) {
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
float hue = iconProperty.getFloat("iconHue");
marker.setIcon(BitmapDescriptorFactory.defaultMarker(hue));
}
});
callback.onPostExecute(marker);
}
String iconUrl = iconProperty.getString("url");
if (iconUrl == null) {
callback.onPostExecute(marker);
return;
}
if (!iconUrl.contains(":
!iconUrl.startsWith("/") &&
!iconUrl.startsWith("www/") &&
!iconUrl.startsWith("data:image") &&
!iconUrl.startsWith("./") &&
!iconUrl.startsWith("../")) {
iconUrl = "./" + iconUrl;
}
if (iconUrl.startsWith("./") || iconUrl.startsWith("../")) {
iconUrl = iconUrl.replace("././", "./");
String currentPage = CURRENT_PAGE_URL;
currentPage = currentPage.replaceAll("[^\\/]*$", "");
iconUrl = currentPage + "/" + iconUrl;
}
if (iconUrl == null) {
callback.onPostExecute(marker);
return;
}
iconProperty.putString("url", iconUrl);
if (iconUrl.indexOf("http") != 0) {
// Load icon from local file
AsyncTask<Void, Void, Bitmap> task = new AsyncTask<Void, Void, Bitmap>() {
@Override
protected Bitmap doInBackground(Void... params) {
String iconUrl = iconProperty.getString("url");
if (iconUrl == null) {
return null;
}
Bitmap image = null;
if (iconUrl.indexOf("cdvfile:
CordovaResourceApi resourceApi = webView.getResourceApi();
iconUrl = PluginUtil.getAbsolutePathFromCDVFilePath(resourceApi, iconUrl);
}
if (iconUrl == null) {
return null;
}
if (iconUrl.indexOf("data:image/") == 0 && iconUrl.contains(";base64,")) {
String[] tmp = iconUrl.split(",");
image = PluginUtil.getBitmapFromBase64encodedImage(tmp[1]);
} else if (iconUrl.indexOf("file:
!iconUrl.contains("file:///android_asset/")) {
iconUrl = iconUrl.replace("file:
File tmp = new File(iconUrl);
if (tmp.exists()) {
image = BitmapFactory.decodeFile(iconUrl);
} else {
//if (PluginMarker.this.mapCtrl.mPluginLayout.isDebug) {
Log.w("GoogleMaps", "icon is not found (" + iconUrl + ")");
}
} else {
//Log.d(TAG, "iconUrl = " + iconUrl);
if (iconUrl.indexOf("file:///android_asset/") == 0) {
iconUrl = iconUrl.replace("file:///android_asset/", "");
}
//Log.d(TAG, "iconUrl = " + iconUrl);
if (iconUrl.contains("./")) {
try {
boolean isAbsolutePath = iconUrl.startsWith("/");
File relativePath = new File(iconUrl);
iconUrl = relativePath.getCanonicalPath();
//Log.d(TAG, "iconUrl = " + iconUrl);
if (!isAbsolutePath) {
iconUrl = iconUrl.substring(1);
}
//Log.d(TAG, "iconUrl = " + iconUrl);
} catch (Exception e) {
e.printStackTrace();
}
}
AssetManager assetManager = PluginMarker.this.cordova.getActivity().getAssets();
InputStream inputStream;
try {
inputStream = assetManager.open(iconUrl);
image = BitmapFactory.decodeStream(inputStream);
inputStream.close()
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
if (image == null) {
return null;
}
Boolean isResized = false;
if (iconProperty.containsKey("size")) {
Object size = iconProperty.get("size");
if (Bundle.class.isInstance(size)) {
Bundle sizeInfo = (Bundle)size;
int width = sizeInfo.getInt("width", 0);
int height = sizeInfo.getInt("height", 0);
if (width > 0 && height > 0) {
isResized = true;
width = (int)Math.round(width * PluginMarker.this.density);
height = (int)Math.round(height * PluginMarker.this.density);
image = PluginUtil.resizeBitmap(image, width, height);
}
}
}
if (!isResized) {
image = PluginUtil.scaleBitmapForDevice(image);
}
icons.add(image);
return image;
}
@Override
protected void onPostExecute(Bitmap image) {
if (image == null) {
callback.onPostExecute(marker);
return;
}
try {
//TODO: check image is valid?
BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(image);
marker.setIcon(bitmapDescriptor);
// Save the information for the anchor property
Bundle imageSize = new Bundle();
imageSize.putInt("width", image.getWidth());
imageSize.putInt("height", image.getHeight());
self.objects.put("imageSize", imageSize);
// The `anchor` of the `icon` property
if (iconProperty.containsKey("anchor")) {
double[] anchor = iconProperty.getDoubleArray("anchor");
if (anchor.length == 2) {
_setIconAnchor(marker, anchor[0], anchor[1], imageSize.getInt("width"), imageSize.getInt("height"));
}
}
// The `anchor` property for the infoWindow
if (iconProperty.containsKey("infoWindowAnchor")) {
double[] anchor = iconProperty.getDoubleArray("infoWindowAnchor");
if (anchor.length == 2) {
_setInfoWindowAnchor(marker, anchor[0], anchor[1], imageSize.getInt("width"), imageSize.getInt("height"));
}
}
callback.onPostExecute(marker);
} catch (java.lang.IllegalArgumentException e) {
Log.e(TAG,"PluginMarker: Warning - marker method called when marker has been disposed, wait for addMarker callback before calling more methods on the marker (setIcon etc).");
//e.printStackTrace();
}
}
};
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
iconLoadingTasks.add(task);
return;
}
if (iconUrl.indexOf("http") == 0) {
// Load icon from on the internet
int width = -1;
int height = -1;
if (iconProperty.containsKey("size")) {
Bundle sizeInfo = (Bundle) iconProperty.get("size");
width = sizeInfo.getInt("width", width);
height = sizeInfo.getInt("height", height);
}
String cacheKey = AsyncLoadImage.getCacheKey(iconUrl, width, height);
iconCacheKeys.add(cacheKey);
AsyncLoadImage task = new AsyncLoadImage("Mozilla", width, height, noCaching, new AsyncLoadImageInterface() {
@Override
public void onPostExecute(Bitmap image) {
if (image == null) {
callback.onPostExecute(marker);
return;
}
try {
icons.add(image);
BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(image);
marker.setIcon(bitmapDescriptor);
// Save the information for the anchor property
Bundle imageSize = new Bundle();
imageSize.putInt("width", image.getWidth());
imageSize.putInt("height", image.getHeight());
self.objects.put("imageSize", imageSize);
// The `anchor` of the `icon` property
if (iconProperty.containsKey("anchor")) {
double[] anchor = iconProperty.getDoubleArray("anchor");
if (anchor.length == 2) {
_setIconAnchor(marker, anchor[0], anchor[1], imageSize.getInt("width"), imageSize.getInt("height"));
}
}
// The `anchor` property for the infoWindow
if (iconProperty.containsKey("infoWindowAnchor")) {
double[] anchor = iconProperty.getDoubleArray("infoWindowAnchor");
if (anchor.length == 2) {
_setInfoWindowAnchor(marker, anchor[0], anchor[1], imageSize.getInt("width"), imageSize.getInt("height"));
}
}
image.recycle();
callback.onPostExecute(marker);
} catch (Exception e) {
//e.printStackTrace();
try {
marker.remove();
} catch (Exception ignore) {
ignore = null;
}
callback.onError(e.getMessage() + "");
}
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, iconUrl);
iconLoadingTasks.add(task);
}
}
private void _setIconAnchor(final Marker marker, double anchorX, double anchorY, final int imageWidth, final int imageHeight) {
// The `anchor` of the `icon` property
anchorX = anchorX * this.density;
anchorY = anchorY * this.density;
final double fAnchorX = anchorX;
final double fAnchorY = anchorY;
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
marker.setAnchor((float)(fAnchorX / imageWidth), (float)(fAnchorY / imageHeight));
}
});
}
private void _setInfoWindowAnchor(final Marker marker, double anchorX, double anchorY, final int imageWidth, final int imageHeight) {
// The `anchor` of the `icon` property
anchorX = anchorX * this.density;
anchorY = anchorY * this.density;
final double fAnchorX = anchorX;
final double fAnchorY = anchorY;
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
marker.setInfoWindowAnchor((float)(fAnchorX / imageWidth), (float)(fAnchorY / imageHeight));
}
});
}
} |
package net.mcft.copy.backpacks;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.client.renderer.color.IItemColor;
import net.minecraft.client.renderer.color.IBlockColor;
import net.minecraft.client.renderer.entity.Render;
import net.minecraft.client.renderer.entity.RenderLivingBase;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.client.renderer.entity.RenderPlayer;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.client.renderer.vertex.VertexFormat;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EnumPlayerModelParts;
import net.minecraft.item.ItemStack;
import net.minecraft.network.datasync.DataParameter;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraftforge.client.event.ModelBakeEvent;
import net.minecraftforge.client.event.ModelRegistryEvent;
import net.minecraftforge.client.event.RenderPlayerEvent;
import net.minecraftforge.client.model.IModel;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.client.model.ModelLoaderRegistry;
import net.minecraftforge.client.model.pipeline.IVertexConsumer;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.client.registry.ClientRegistry;
import net.minecraftforge.fml.common.eventhandler.EventPriority;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import net.mcft.copy.backpacks.BackpacksContent;
import net.mcft.copy.backpacks.WearableBackpacks;
import net.mcft.copy.backpacks.api.BackpackHelper;
import net.mcft.copy.backpacks.api.BackpackRegistry;
import net.mcft.copy.backpacks.api.IBackpack;
import net.mcft.copy.backpacks.api.BackpackRegistry.BackpackEntityEntry;
import net.mcft.copy.backpacks.ProxyCommon;
import net.mcft.copy.backpacks.block.entity.TileEntityBackpack;
import net.mcft.copy.backpacks.client.BakedModelDefaultTexture;
import net.mcft.copy.backpacks.client.KeyBindingHandler;
import net.mcft.copy.backpacks.client.RendererBackpack;
import net.mcft.copy.backpacks.item.ItemBackpack;
import net.mcft.copy.backpacks.misc.util.MiscUtils;
import net.mcft.copy.backpacks.misc.util.NbtUtils;
import net.mcft.copy.backpacks.misc.util.ReflectUtils;
@SideOnly(Side.CLIENT)
public class ProxyClient extends ProxyCommon {
public static IBakedModel MODEL_BACKPACK;
public static IBakedModel MODEL_BACKPACK_TOP;
public static IBakedModel MODEL_BACKPACK_STRAPS;
public static IBakedModel MODEL_BACKPACK_ENCH;
public static IBakedModel MODEL_BACKPACK_ENCH_TOP;
public static AxisAlignedBB MODEL_BACKPACK_BOX;
@Override
public void preInit() {
super.preInit();
MinecraftForge.EVENT_BUS.register(new KeyBindingHandler());
}
@Override
public void init() {
super.init();
Minecraft mc = Minecraft.getMinecraft();
if (BackpacksContent.BACKPACK != null) {
mc.getBlockColors().registerBlockColorHandler(BLOCK_COLOR, MiscUtils.getBlockFromItem(BackpacksContent.BACKPACK));
mc.getItemColors().registerItemColorHandler(ITEM_COLOR, BackpacksContent.BACKPACK);
ClientRegistry.bindTileEntitySpecialRenderer(TileEntityBackpack.class, new RendererBackpack.TileEntity());
}
RenderManager manager = mc.getRenderManager();
Map<String, RenderPlayer> skinMap = manager.getSkinMap();
for (RenderPlayer renderer : skinMap.values()) {
renderer.addLayer(new RendererBackpack.Layer(renderer));
}
}
@Override
public void initBackpackLayers() {
// A for loop would be one less line.. but streams are pretty! >.<
BackpackRegistry.getEntityEntries().stream()
.map(BackpackEntityEntry::getEntityClass)
.filter(Objects::nonNull)
.forEach(ProxyClient::ensureHasBackpackLayer);
}
private static final Set<Class<? extends EntityLivingBase>> _hasLayerChecked = new HashSet<>();
/** Ensures that the specified entity class' renderer has a backpack layer - if possible. */
public static void ensureHasBackpackLayer(Class<? extends EntityLivingBase> entityClass) {
if (!_hasLayerChecked.add(entityClass)) return;
RenderManager manager = Minecraft.getMinecraft().getRenderManager();
Render<?> render = manager.getEntityClassRenderObject(entityClass);
if (!(render instanceof RenderLivingBase)) return;
((RenderLivingBase<?>)render).addLayer(new RendererBackpack.Layer((RenderLivingBase<?>)render));
}
// Model related
@SubscribeEvent
public void onModelBake(ModelBakeEvent event) {
MODEL_BACKPACK = bakeBlockModel("wearablebackpacks:block/backpack");
MODEL_BACKPACK_TOP = bakeBlockModel("wearablebackpacks:block/backpack_top");
MODEL_BACKPACK_STRAPS = bakeBlockModel("wearablebackpacks:block/backpack_straps");
MODEL_BACKPACK_ENCH = new BakedModelDefaultTexture(MODEL_BACKPACK);
MODEL_BACKPACK_ENCH_TOP = new BakedModelDefaultTexture(MODEL_BACKPACK_TOP);
MODEL_BACKPACK_BOX = ModelAABBCalculator.calcFrom(MODEL_BACKPACK, MODEL_BACKPACK_TOP);
}
private static IBakedModel bakeBlockModel(String location) {
IModel model = getModel(new ResourceLocation(location));
return model.bake(model.getDefaultState(), DefaultVertexFormats.BLOCK, loc ->
Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite(loc.toString()));
}
private static IModel getModel(ResourceLocation location) {
try {
IModel model = ModelLoaderRegistry.getModel(location);
if (model == null) WearableBackpacks.LOG.error(
"Model " + location + " is missing! THIS WILL CAUSE A CRASH!");
return model;
} catch (Exception e) { e.printStackTrace(); return null; }
}
@SubscribeEvent
public void onRegisterModels(ModelRegistryEvent event) {
if (BackpacksContent.BACKPACK != null) {
ModelLoader.setCustomModelResourceLocation(BackpacksContent.BACKPACK, 0,
new ModelResourceLocation("wearablebackpacks:backpack", "inventory"));
}
}
private static class ModelAABBCalculator implements IVertexConsumer {
public static AxisAlignedBB calcFrom(IBakedModel... models) {
ModelAABBCalculator calc = new ModelAABBCalculator();
for (IBakedModel model : models) calc.put(model);
return calc.getAABB();
}
private double minX = 1.0F, minY = 1.0F, minZ = 1.0F;
private double maxX = 0.0F, maxY = 0.0F, maxZ = 0.0F;
public void put(IBakedModel model)
{ for (BakedQuad quad : model.getQuads(null, null, 0)) quad.pipe(this); }
public AxisAlignedBB getAABB()
{ return new AxisAlignedBB(minX, minY, minZ, maxX, maxY, maxZ); }
// IVertexConsumer implementation
public VertexFormat getVertexFormat() { return DefaultVertexFormats.POSITION; }
public void setQuadTint(int tint) { }
public void setQuadOrientation(EnumFacing orientation) { }
public void setApplyDiffuseLighting(boolean diffuse) { }
public void setTexture(TextureAtlasSprite texture) { }
public void put(int element, float... data) {
if (data[0] < minX) minX = data[0];
if (data[0] > maxX) maxX = data[0];
if (data[1] < minY) minY = data[1];
if (data[1] > maxY) maxY = data[1];
if (data[2] < minZ) minZ = data[2];
if (data[2] > maxZ) maxZ = data[2];
}
}
// IItemColor and IBlockColor implementations
// TODO: Make this work for different default colors / non-dyeable backpacks.
public static final IItemColor ITEM_COLOR = (stack, tintIndex) ->
NbtUtils.get(stack, ItemBackpack.DEFAULT_COLOR, "display", "color");
public static final IBlockColor BLOCK_COLOR = (state, world, pos, tintIndex) -> {
ItemStack stack = ItemStack.EMPTY;
if ((world != null) && (pos != null)) {
IBackpack backpack = BackpackHelper.getBackpack(world.getTileEntity(pos));
if (backpack != null) stack = backpack.getStack();
}
return ITEM_COLOR.colorMultiplier(stack, tintIndex);
};
// Lots of code just to disable capes when backpacks are equipped!
private static DataParameter<Byte> PLAYER_MODEL_FLAG =
ReflectUtils.get(EntityPlayer.class, "PLAYER_MODEL_FLAG", "field_184827_bp");
/** Sets whether the player is currently wearing the specified model part.
* This is the opposite of the {@link EntityPlayer#isWearing} method. */
private static void setWearing(EntityPlayer player, EnumPlayerModelParts part, boolean value) {
byte current = player.getDataManager().get(PLAYER_MODEL_FLAG).byteValue();
if (value) current |= part.getPartMask();
else current &= ~part.getPartMask();
player.getDataManager().set(PLAYER_MODEL_FLAG, current);
}
private boolean _disabledCape = false;
@SubscribeEvent(priority=EventPriority.LOWEST)
public void onRenderPlayerPre(RenderPlayerEvent.Pre event) {
EntityPlayer player = event.getEntityPlayer();
if ((BackpackHelper.getBackpack(player) == null) ||
!player.isWearing(EnumPlayerModelParts.CAPE)) return;
// Disable player rendering for players with equipped backpacks
// by temporarily setting whether they are wearing it to false.
setWearing(player, EnumPlayerModelParts.CAPE, false);
_disabledCape = true;
}
@SubscribeEvent(priority=EventPriority.HIGHEST)
public void onRenderPlayerPost(RenderPlayerEvent.Post event) {
if (!_disabledCape) return;
// Reenable cape rendering if it was disabled.
EntityPlayer player = event.getEntityPlayer();
setWearing(player, EnumPlayerModelParts.CAPE, true);
_disabledCape = false;
}
} |
package plugin.google.maps;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaResourceApi;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Point;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.util.Log;
import android.view.animation.BounceInterpolator;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import com.google.android.gms.maps.Projection;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class PluginMarker extends MyPlugin {
private enum Animation {
DROP,
BOUNCE
}
/**
* Create a marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void createMarker(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
// Create an instance of Marker class
final MarkerOptions markerOptions = new MarkerOptions();
final JSONObject opts = args.getJSONObject(1);
if (opts.has("position")) {
JSONObject position = opts.getJSONObject("position");
markerOptions.position(new LatLng(position.getDouble("lat"), position.getDouble("lng")));
}
if (opts.has("title")) {
markerOptions.title(opts.getString("title"));
}
if (opts.has("snippet")) {
markerOptions.snippet(opts.getString("snippet"));
}
if (opts.has("visible")) {
if (opts.has("icon") && "".equals(opts.getString("icon")) == false) {
markerOptions.visible(false);
} else {
markerOptions.visible(opts.getBoolean("visible"));
}
}
if (opts.has("draggable")) {
markerOptions.draggable(opts.getBoolean("draggable"));
}
if (opts.has("rotation")) {
markerOptions.rotation((float)opts.getDouble("rotation"));
}
if (opts.has("flat")) {
markerOptions.flat(opts.getBoolean("flat"));
}
if (opts.has("opacity")) {
markerOptions.alpha((float) opts.getDouble("opacity"));
}
if (opts.has("zIndex")) {
// do nothing, API v2 has no zIndex :(
}
Marker marker = map.addMarker(markerOptions);
// Store the marker
String id = "marker_" + marker.getId();
this.objects.put(id, marker);
JSONObject properties = new JSONObject();
if (opts.has("styles")) {
properties.put("styles", opts.getJSONObject("styles"));
}
if (opts.has("disableAutoPan")) {
properties.put("disableAutoPan", opts.getBoolean("disableAutoPan"));
} else {
properties.put("disableAutoPan", false);
}
this.objects.put("marker_property_" + marker.getId(), properties);
// Prepare the result
final JSONObject result = new JSONObject();
result.put("hashCode", marker.hashCode());
result.put("id", id);
// Load icon
if (opts.has("icon")) {
Bundle bundle = null;
Object value = opts.get("icon");
if (JSONObject.class.isInstance(value)) {
JSONObject iconProperty = (JSONObject)value;
bundle = PluginUtil.Json2Bundle(iconProperty);
// The `anchor` of the `icon` property
if (iconProperty.has("anchor")) {
value = iconProperty.get("anchor");
if (JSONArray.class.isInstance(value)) {
JSONArray points = (JSONArray)value;
double[] anchorPoints = new double[points.length()];
for (int i = 0; i < points.length(); i++) {
anchorPoints[i] = points.getDouble(i);
}
bundle.putDoubleArray("anchor", anchorPoints);
}
}
// The `infoWindowAnchor` property for infowindow
if (opts.has("infoWindowAnchor")) {
value = opts.get("infoWindowAnchor");
if (JSONArray.class.isInstance(value)) {
JSONArray points = (JSONArray)value;
double[] anchorPoints = new double[points.length()];
for (int i = 0; i < points.length(); i++) {
anchorPoints[i] = points.getDouble(i);
}
bundle.putDoubleArray("infoWindowAnchor", anchorPoints);
}
}
} else if (JSONArray.class.isInstance(value)) {
float[] hsv = new float[3];
JSONArray arrayRGBA = (JSONArray)value;
Color.RGBToHSV(arrayRGBA.getInt(0), arrayRGBA.getInt(1), arrayRGBA.getInt(2), hsv);
bundle = new Bundle();
bundle.putFloat("iconHue", hsv[0]);
} else {
bundle = new Bundle();
bundle.putString("url", (String)value);
}
if (opts.has("animation")) {
bundle.putString("animation", opts.getString("animation"));
}
this.setIcon_(marker, bundle, new PluginAsyncInterface() {
@Override
public void onPostExecute(Object object) {
Marker marker = (Marker)object;
if (opts.has("visible")) {
try {
marker.setVisible(opts.getBoolean("visible"));
} catch (JSONException e) {}
} else {
marker.setVisible(true);
}
// Animation
String markerAnimation = null;
if (opts.has("animation")) {
try {
markerAnimation = opts.getString("animation");
} catch (JSONException e) {
e.printStackTrace();
}
}
if (markerAnimation != null) {
PluginMarker.this.setMarkerAnimation_(marker, markerAnimation, new PluginAsyncInterface() {
@Override
public void onPostExecute(Object object) {
Marker marker = (Marker)object;
callbackContext.success(result);
}
@Override
public void onError(String errorMsg) {
callbackContext.error(errorMsg);
}
});
} else {
callbackContext.success(result);
}
callbackContext.success(result);
}
@Override
public void onError(String errorMsg) {
callbackContext.error(errorMsg);
}
});
} else {
String markerAnimation = null;
if (opts.has("animation")) {
markerAnimation = opts.getString("animation");
}
if (markerAnimation != null) {
// Execute animation
this.setMarkerAnimation_(marker, markerAnimation, new PluginAsyncInterface() {
@Override
public void onPostExecute(Object object) {
callbackContext.success(result);
}
@Override
public void onError(String errorMsg) {
callbackContext.error(errorMsg);
}
});
} else {
// Return the result if does not specify the icon property.
callbackContext.success(result);
}
}
}
private void setDropAnimation_(final Marker marker, final PluginAsyncInterface callback) {
final Handler handler = new Handler();
final long startTime = SystemClock.uptimeMillis();
final long duration = 100;
final Projection proj = this.map.getProjection();
final LatLng markerLatLng = marker.getPosition();
final Point markerPoint = proj.toScreenLocation(markerLatLng);
final Point startPoint = new Point(markerPoint.x, 0);
final Interpolator interpolator = new LinearInterpolator();
handler.post(new Runnable() {
@Override
public void run() {
LatLng startLatLng = proj.fromScreenLocation(startPoint);
long elapsed = SystemClock.uptimeMillis() - startTime;
float t = interpolator.getInterpolation((float) elapsed / duration);
double lng = t * markerLatLng.longitude + (1 - t) * startLatLng.longitude;
double lat = t * markerLatLng.latitude + (1 - t) * startLatLng.latitude;
marker.setPosition(new LatLng(lat, lng));
if (t < 1.0) {
// Post again 16ms later.
handler.postDelayed(this, 16);
} else {
marker.setPosition(markerLatLng);
callback.onPostExecute(marker);
}
}
});
}
private void setBounceAnimation_(final Marker marker, final PluginAsyncInterface callback) {
final Handler handler = new Handler();
final long startTime = SystemClock.uptimeMillis();
final long duration = 2000;
final Projection proj = this.map.getProjection();
final LatLng markerLatLng = marker.getPosition();
final Point startPoint = proj.toScreenLocation(markerLatLng);
startPoint.offset(0, -200);
final Interpolator interpolator = new BounceInterpolator();
handler.post(new Runnable() {
@Override
public void run() {
LatLng startLatLng = proj.fromScreenLocation(startPoint);
long elapsed = SystemClock.uptimeMillis() - startTime;
float t = interpolator.getInterpolation((float) elapsed / duration);
double lng = t * markerLatLng.longitude + (1 - t) * startLatLng.longitude;
double lat = t * markerLatLng.latitude + (1 - t) * startLatLng.latitude;
marker.setPosition(new LatLng(lat, lng));
if (t < 1.0) {
// Post again 16ms later.
handler.postDelayed(this, 16);
} else {
marker.setPosition(markerLatLng);
callback.onPostExecute(marker);
}
}
});
}
private void setMarkerAnimation_(Marker marker, String animationType, PluginAsyncInterface callback) {
Animation animation = null;
try {
animation = Animation.valueOf(animationType.toUpperCase(Locale.US));
} catch (Exception e) {
e.printStackTrace();
}
if (animation == null) {
callback.onPostExecute(marker);
return;
}
switch(animation) {
case DROP:
this.setDropAnimation_(marker, callback);
break;
case BOUNCE:
this.setBounceAnimation_(marker, callback);
break;
default:
break;
}
}
@SuppressWarnings("unused")
private void setAnimation(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String id = args.getString(1);
String animation = args.getString(2);
final Marker marker = this.getMarker(id);
this.setMarkerAnimation_(marker, animation, new PluginAsyncInterface() {
@Override
public void onPostExecute(Object object) {
callbackContext.success();
}
@Override
public void onError(String errorMsg) {
callbackContext.error(errorMsg);
}
});
}
/**
* Show the InfoWindow binded with the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void showInfoWindow(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String id = args.getString(1);
Marker marker = this.getMarker(id);
marker.showInfoWindow();
this.sendNoResult(callbackContext);
}
/**
* Set rotation for the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void setRotation(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
float rotation = (float)args.getDouble(2);
String id = args.getString(1);
this.setFloat("setRotation", id, rotation, callbackContext);
}
/**
* Set opacity for the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void setOpacity(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
float alpha = (float)args.getDouble(2);
String id = args.getString(1);
this.setFloat("setAlpha", id, alpha, callbackContext);
}
/**
* Set zIndex for the marker (dummy code, not available on Android V2)
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void setZIndex(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
// nothing to do :(
// it's a shame google...
}
/**
* set position
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void setPosition(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String id = args.getString(1);
LatLng position = new LatLng(args.getDouble(2), args.getDouble(3));
Marker marker = this.getMarker(id);
marker.setPosition(position);
this.sendNoResult(callbackContext);
}
/**
* Set flat for the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void setFlat(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
boolean isFlat = args.getBoolean(2);
String id = args.getString(1);
this.setBoolean("setFlat", id, isFlat, callbackContext);
}
/**
* Set visibility for the object
* @param args
* @param callbackContext
* @throws JSONException
*/
protected void setVisible(JSONArray args, CallbackContext callbackContext) throws JSONException {
boolean visible = args.getBoolean(2);
String id = args.getString(1);
this.setBoolean("setVisible", id, visible, callbackContext);
}
/**
* @param args
* @param callbackContext
* @throws JSONException
*/
protected void setDisableAutoPan(JSONArray args, CallbackContext callbackContext) throws JSONException {
boolean disableAutoPan = args.getBoolean(2);
String id = args.getString(1);
Marker marker = this.getMarker(id);
String propertyId = "marker_property_" + marker.getId();
JSONObject properties = null;
if (this.objects.containsKey(propertyId)) {
properties = (JSONObject)this.objects.get(propertyId);
} else {
properties = new JSONObject();
}
properties.put("disableAutoPan", disableAutoPan);
this.objects.put(propertyId, properties);
this.sendNoResult(callbackContext);
}
/**
* Set title for the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void setTitle(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String title = args.getString(2);
String id = args.getString(1);
this.setString("setTitle", id, title, callbackContext);
}
/**
* Set the snippet for the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void setSnippet(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String snippet = args.getString(2);
String id = args.getString(1);
this.setString("setSnippet", id, snippet, callbackContext);
}
/**
* Hide the InfoWindow binded with the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void hideInfoWindow(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String id = args.getString(1);
Marker marker = this.getMarker(id);
marker.hideInfoWindow();
this.sendNoResult(callbackContext);
}
/**
* Return the position of the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void getPosition(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String id = args.getString(1);
Marker marker = this.getMarker(id);
LatLng position = marker.getPosition();
JSONObject result = new JSONObject();
result.put("lat", position.latitude);
result.put("lng", position.longitude);
callbackContext.success(result);
}
/**
* Return 1 if the InfoWindow of the marker is shown
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void isInfoWindowShown(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String id = args.getString(1);
Marker marker = this.getMarker(id);
Boolean isInfoWndShown = marker.isInfoWindowShown();
callbackContext.success(isInfoWndShown ? 1 : 0);
}
/**
* Remove the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void remove(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String id = args.getString(1);
Marker marker = this.getMarker(id);
if (marker == null) {
callbackContext.success();
return;
}
marker.remove();
this.objects.remove(id);
String propertyId = "marker_property_" + id;
this.objects.remove(propertyId);
this.sendNoResult(callbackContext);
}
/**
* Set anchor for the icon of the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void setIconAnchor(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
float anchorX = (float)args.getDouble(2);
float anchorY = (float)args.getDouble(3);
String id = args.getString(1);
Marker marker = this.getMarker(id);
Bundle imageSize = (Bundle) this.objects.get("imageSize");
if (imageSize != null) {
this._setIconAnchor(marker, anchorX, anchorY, imageSize.getInt("width"), imageSize.getInt("height"));
}
this.sendNoResult(callbackContext);
}
/**
* Set anchor for the InfoWindow of the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void setInfoWindowAnchor(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
float anchorX = (float)args.getDouble(2);
float anchorY = (float)args.getDouble(3);
String id = args.getString(1);
Marker marker = this.getMarker(id);
Bundle imageSize = (Bundle) this.objects.get("imageSize");
if (imageSize != null) {
this._setInfoWindowAnchor(marker, anchorX, anchorY, imageSize.getInt("width"), imageSize.getInt("height"));
}
this.sendNoResult(callbackContext);
}
/**
* Set draggable for the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void setDraggable(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
Boolean draggable = args.getBoolean(2);
String id = args.getString(1);
this.setBoolean("setDraggable", id, draggable, callbackContext);
}
/**
* Set icon of the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void setIcon(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String id = args.getString(1);
Marker marker = this.getMarker(id);
Object value = args.get(2);
Bundle bundle = null;
if (JSONObject.class.isInstance(value)) {
JSONObject iconProperty = (JSONObject)value;
bundle = PluginUtil.Json2Bundle(iconProperty);
// The `anchor` for icon
if (iconProperty.has("anchor")) {
value = iconProperty.get("anchor");
if (JSONArray.class.isInstance(value)) {
JSONArray points = (JSONArray)value;
double[] anchorPoints = new double[points.length()];
for (int i = 0; i < points.length(); i++) {
anchorPoints[i] = points.getDouble(i);
}
bundle.putDoubleArray("anchor", anchorPoints);
}
}
} else if (JSONArray.class.isInstance(value)) {
float[] hsv = new float[3];
JSONArray arrayRGBA = (JSONArray)value;
Color.RGBToHSV(arrayRGBA.getInt(0), arrayRGBA.getInt(1), arrayRGBA.getInt(2), hsv);
bundle = new Bundle();
bundle.putFloat("iconHue", hsv[0]);
} else if (String.class.isInstance(value)) {
bundle = new Bundle();
bundle.putString("url", (String)value);
}
if (bundle != null) {
this.setIcon_(marker, bundle, new PluginAsyncInterface() {
@Override
public void onPostExecute(Object object) {
PluginMarker.this.sendNoResult(callbackContext);
}
@Override
public void onError(String errorMsg) {
callbackContext.error(errorMsg);
}
});
} else {
this.sendNoResult(callbackContext);
}
}
private void setIcon_(final Marker marker, final Bundle iconProperty, final PluginAsyncInterface callback) {
if (iconProperty.containsKey("iconHue")) {
float hue = iconProperty.getFloat("iconHue");
marker.setIcon(BitmapDescriptorFactory.defaultMarker(hue));
callback.onPostExecute(marker);
return;
}
String iconUrl = iconProperty.getString("url");
if (iconUrl.indexOf(":
iconUrl.startsWith("/") == false &&
iconUrl.startsWith("www/") == false &&
iconUrl.startsWith("data:image") == false) {
iconUrl = "./" + iconUrl;
}
if (iconUrl.indexOf("./") == 0) {
String currentPage = this.webView.getUrl();
currentPage = currentPage.replaceAll("[^\\/]*$", "");
iconUrl = iconUrl.replace("./", currentPage);
}
if (iconUrl == null) {
callback.onPostExecute(marker);
return;
}
if (iconUrl.indexOf("http") != 0) {
AsyncTask<Void, Void, Bitmap> task = new AsyncTask<Void, Void, Bitmap>() {
@Override
protected Bitmap doInBackground(Void... params) {
String iconUrl = iconProperty.getString("url");
Bitmap image = null;
if (iconUrl.indexOf("cdvfile:
CordovaResourceApi resourceApi = webView.getResourceApi();
iconUrl = PluginUtil.getAbsolutePathFromCDVFilePath(resourceApi, iconUrl);
}
if (iconUrl.indexOf("data:image/") == 0 && iconUrl.indexOf(";base64,") > -1) {
String[] tmp = iconUrl.split(",");
image = PluginUtil.getBitmapFromBase64encodedImage(tmp[1]);
} else if (iconUrl.indexOf("file:
iconUrl.indexOf("file:///android_asset/") == -1) {
iconUrl = iconUrl.replace("file:
File tmp = new File(iconUrl);
if (tmp.exists()) {
image = BitmapFactory.decodeFile(iconUrl);
} else {
if (PluginMarker.this.mapCtrl.isDebug) {
Log.w("GoogleMaps", "icon is not found (" + iconUrl + ")");
}
}
} else {
if (iconUrl.indexOf("file:///android_asset/") == 0) {
iconUrl = iconUrl.replace("file:///android_asset/", "");
}
if (iconUrl.indexOf("./") == 0) {
iconUrl = iconUrl.replace("./", "www/");
}
AssetManager assetManager = PluginMarker.this.cordova.getActivity().getAssets();
InputStream inputStream;
try {
inputStream = assetManager.open(iconUrl);
image = BitmapFactory.decodeStream(inputStream);
} catch (IOException e) {
e.printStackTrace();
callback.onPostExecute(marker);
return null;
}
}
if (image == null) {
callback.onPostExecute(marker);
return null;
}
Boolean isResized = false;
if (iconProperty.containsKey("size") == true) {
Object size = iconProperty.get("size");
if (Bundle.class.isInstance(size)) {
Bundle sizeInfo = (Bundle)size;
int width = sizeInfo.getInt("width", 0);
int height = sizeInfo.getInt("height", 0);
if (width > 0 && height > 0) {
isResized = true;
width = (int)Math.round(width * PluginMarker.this.density);
height = (int)Math.round(height * PluginMarker.this.density);
image = PluginUtil.resizeBitmap(image, width, height);
}
}
}
if (isResized == false) {
image = PluginUtil.scaleBitmapForDevice(image);
}
return image;
}
@Override
protected void onPostExecute(Bitmap image) {
if (image == null) {
callback.onPostExecute(marker);
return;
}
try {
//TODO: check image is valid?
BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(image);
marker.setIcon(bitmapDescriptor);
// Save the information for the anchor property
Bundle imageSize = new Bundle();
imageSize.putInt("width", image.getWidth());
imageSize.putInt("height", image.getHeight());
PluginMarker.this.objects.put("imageSize", imageSize);
// The `anchor` of the `icon` property
if (iconProperty.containsKey("anchor") == true) {
double[] anchor = iconProperty.getDoubleArray("anchor");
if (anchor.length == 2) {
_setIconAnchor(marker, anchor[0], anchor[1], imageSize.getInt("width"), imageSize.getInt("height"));
}
}
// The `anchor` property for the infoWindow
if (iconProperty.containsKey("infoWindowAnchor") == true) {
double[] anchor = iconProperty.getDoubleArray("infoWindowAnchor");
if (anchor.length == 2) {
_setInfoWindowAnchor(marker, anchor[0], anchor[1], imageSize.getInt("width"), imageSize.getInt("height"));
}
}
callback.onPostExecute(marker);
} catch (java.lang.IllegalArgumentException e) {
Log.e("GoogleMapsPlugin","PluginMarker: Warning - marker method called when marker has been disposed, wait for addMarker callback before calling more methods on the marker (setIcon etc).");
//e.printStackTrace();
}
}
};
task.execute();
return;
}
if (iconUrl.indexOf("http") == 0) {
int width = -1;
int height = -1;
if (iconProperty.containsKey("size") == true) {
Bundle sizeInfo = (Bundle) iconProperty.get("size");
width = sizeInfo.getInt("width", width);
height = sizeInfo.getInt("height", height);
}
AsyncLoadImage task = new AsyncLoadImage(width, height, new AsyncLoadImageInterface() {
@Override
public void onPostExecute(Bitmap image) {
if (image == null) {
callback.onPostExecute(marker);
return;
}
BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(image);
marker.setIcon(bitmapDescriptor);
// Save the information for the anchor property
Bundle imageSize = new Bundle();
imageSize.putInt("width", image.getWidth());
imageSize.putInt("height", image.getHeight());
PluginMarker.this.objects.put("imageSize", imageSize);
// The `anchor` of the `icon` property
if (iconProperty.containsKey("anchor") == true) {
double[] anchor = iconProperty.getDoubleArray("anchor");
if (anchor.length == 2) {
_setIconAnchor(marker, anchor[0], anchor[1], imageSize.getInt("width"), imageSize.getInt("height"));
}
}
// The `anchor` property for the infoWindow
if (iconProperty.containsKey("infoWindowAnchor") == true) {
double[] anchor = iconProperty.getDoubleArray("infoWindowAnchor");
if (anchor.length == 2) {
_setInfoWindowAnchor(marker, anchor[0], anchor[1], imageSize.getInt("width"), imageSize.getInt("height"));
}
}
image.recycle();
callback.onPostExecute(marker);
}
});
task.execute(iconUrl);
}
}
private void _setIconAnchor(Marker marker, double anchorX, double anchorY, int imageWidth, int imageHeight) {
// The `anchor` of the `icon` property
anchorX = anchorX * this.density;
anchorY = anchorY * this.density;
marker.setAnchor((float)(anchorX / imageWidth), (float)(anchorY / imageHeight));
}
private void _setInfoWindowAnchor(Marker marker, double anchorX, double anchorY, int imageWidth, int imageHeight) {
// The `anchor` of the `icon` property
anchorX = anchorX * this.density;
anchorY = anchorY * this.density;
marker.setInfoWindowAnchor((float)(anchorX / imageWidth), (float)(anchorY / imageHeight));
}
} |
package net.mingsoft.cms.util;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.PageUtil;
import freemarker.cache.FileTemplateLoader;
import freemarker.core.ParseException;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateNotFoundException;
import net.mingsoft.base.constant.Const;
import net.mingsoft.basic.entity.ColumnEntity;
import net.mingsoft.basic.util.BasicUtil;
import net.mingsoft.basic.util.SpringUtil;
import net.mingsoft.cms.bean.ColumnArticleIdBean;
import net.mingsoft.cms.constant.e.ColumnTypeEnum;
import net.mingsoft.mdiy.biz.IContentModelBiz;
import net.mingsoft.mdiy.entity.ContentModelEntity;
import net.mingsoft.mdiy.parser.TagParser;
import net.mingsoft.mdiy.util.ParserUtil;
public class CmsParserUtil extends ParserUtil {
/**
* pc
*
* @param templatePath
*
* @param targetPath
* html.html
* @throws IOException
*/
public static void generate(String templatePath, String targetPath) throws IOException {
Map<String, Object> map = new HashMap<String, Object>();
map.put(IS_DO, false);
String content = CmsParserUtil.generate(templatePath, map, false);
FileUtil.writeString(content, ParserUtil.buildHtmlPath(targetPath), Const.UTF8);
if (ParserUtil.hasMobileFile(templatePath)) {
map.put(ParserUtil.MOBILE, BasicUtil.getApp().getAppMobileStyle());
content = CmsParserUtil.generate(templatePath, map, true);
FileUtil.writeString(content, ParserUtil.buildMobileHtmlPath(targetPath), Const.UTF8);
}
}
/**
*
* @param column
* @param articleIdTotal
* @throws TemplateNotFoundException
* @throws MalformedTemplateNameException
* @throws ParseException
* @throws IOException
*/
public static void generateList(ColumnEntity column, int articleIdTotal)
throws TemplateNotFoundException, MalformedTemplateNameException, ParseException, IOException {
// cfg
if (ftl == null) {
ftl = new FileTemplateLoader(new File(ParserUtil.buildTempletPath()));
cfg.setTemplateLoader(ftl);
}
Template mobileTemplate = cfg.getTemplate(
BasicUtil.getApp().getAppMobileStyle() + File.separator + column.getColumnListUrl(), Const.UTF8);
Template template = cfg.getTemplate(File.separator + column.getColumnListUrl(), Const.UTF8);
StringWriter writer = new StringWriter();
try {
// column,
template.process(null, writer);
String content = writer.toString();
int pageSize = TagParser.getPageSize(content);
int totalPageSize = PageUtil.totalPage(articleIdTotal, pageSize);
String columnListPath;
String mobilePath;
int pageNo = 1;
for (int i = 0; i < totalPageSize; i++) {
Map parserParams = new HashMap();
parserParams.put(COLUMN, column);
parserParams.put(TOTAL, totalPageSize);
parserParams.put(RCOUNT, pageSize);
parserParams.put(TYPE_ID, column.getCategoryId());
parserParams.put(IS_DO, false);
parserParams.put(HTML, HTML);
if(ParserUtil.IS_SINGLE) {
parserParams.put(ParserUtil.URL, BasicUtil.getUrl());
}
if (i == 0) {
// 0*size
// index.html
mobilePath = ParserUtil
.buildMobileHtmlPath(column.getColumnPath() + File.separator + ParserUtil.INDEX);
columnListPath = ParserUtil
.buildHtmlPath(column.getColumnPath() + File.separator + ParserUtil.INDEX);
} else {
// list-2.html
mobilePath = ParserUtil.buildMobileHtmlPath(
column.getColumnPath() + File.separator + ParserUtil.PAGE_LIST + pageNo);
columnListPath = ParserUtil
.buildHtmlPath(column.getColumnPath() + File.separator + ParserUtil.PAGE_LIST + pageNo);
}
parserParams.put(PAGE_NO, pageNo);
TagParser tag = new TagParser(content,parserParams);
FileUtil.writeString(tag.rendering(), columnListPath, Const.UTF8);
if (ParserUtil.hasMobileFile(column.getColumnListUrl())) {
writer = new StringWriter();
mobileTemplate.process(null, writer);
tag = new TagParser(writer.toString(),parserParams);
// tag.getContent()
FileUtil.writeString(tag.rendering(), mobilePath, Const.UTF8);
}
writer = new StringWriter();
pageNo++;
}
} catch (TemplateException e) {
e.printStackTrace();
}
}
/**
*
*
* @param articleIdList
*
* @return
* @throws IOException
* @throws ParseException
* @throws MalformedTemplateNameException
* @throws TemplateNotFoundException
*/
public static void generateBasic(List<ColumnArticleIdBean> articleIdList)
throws TemplateNotFoundException, MalformedTemplateNameException, ParseException, IOException {
Map<Object, Object> contentModelMap = new HashMap<Object, Object>();
ContentModelEntity contentModel = null;
String writePath = null;
List<Integer> generateIds = new ArrayList<>();
for (int ai = 0; ai < articleIdList.size();) {
int articleId = articleIdList.get(ai).getArticleId();
String articleColumnPath = articleIdList.get(ai).getColumnPath();
String columnUrl = articleIdList.get(ai).getColumnUrl();
int columnContentModelId = articleIdList.get(ai).getColumnContentModelId();
if (generateIds.contains(articleId)) {
ai++;
continue;
}
if (!FileUtil.exist(ParserUtil.buildTempletPath(columnUrl))) {
ai++;
continue;
}
generateIds.add(articleId);
// :html/id/id/id.html
writePath = ParserUtil.buildHtmlPath(articleColumnPath + File.separator + articleId);
//index.html
if(articleIdList.get(ai).getColumnType() == ColumnTypeEnum.COLUMN_TYPE_COVER.toInt()) {
writePath = ParserUtil.buildHtmlPath(articleColumnPath + File.separator + ParserUtil.INDEX);
}
Map<String, Object> parserParams = new HashMap<String, Object>();
if (columnContentModelId > 0) {
if (contentModelMap.containsKey(columnContentModelId)) {
parserParams.put(TABLE_NAME, contentModel.getCmTableName());
} else {
contentModel = (ContentModelEntity) SpringUtil.getBean(IContentModelBiz.class)
.getEntity(columnContentModelId);
// key
contentModelMap.put(columnContentModelId, contentModel.getCmTableName());
parserParams.put(TABLE_NAME, contentModel.getCmTableName());
}
}
parserParams.put(ID, articleId);
if (ai > 0) {
ColumnArticleIdBean preCaBean = articleIdList.get(ai - 1);
if(articleColumnPath.contains(preCaBean.getCategoryId()+"")){
parserParams.put(PRE_ID, preCaBean.getArticleId());
}
}
if (ai + 1 < articleIdList.size()) {
ColumnArticleIdBean nextCaBean = articleIdList.get(ai + 1);
if(articleColumnPath.contains(nextCaBean.getCategoryId()+"")){
parserParams.put(NEXT_ID, nextCaBean.getArticleId());
}
}
parserParams.put(IS_DO, false);
String content = CmsParserUtil.generate(articleIdList.get(ai).getColumnUrl(), parserParams, false);
FileUtil.writeString(content, writePath, Const.UTF8);
if (ParserUtil.hasMobileFile(columnUrl)) {
writePath = ParserUtil.buildMobileHtmlPath(articleColumnPath + File.separator + articleId);
//index.html
if(articleIdList.get(ai).getColumnType() == ColumnTypeEnum.COLUMN_TYPE_COVER.toInt()) {
writePath = ParserUtil.buildMobileHtmlPath(articleColumnPath + File.separator + ParserUtil.INDEX);
}
if (!FileUtil.exist(ParserUtil.buildTempletPath(MOBILE + File.separator + columnUrl))) {
ai++;
continue;
}
parserParams.put(MOBILE, BasicUtil.getApp().getAppMobileStyle());
content = CmsParserUtil.generate(articleIdList.get(ai).getColumnUrl(), parserParams, true);
FileUtil.writeString(content, writePath, Const.UTF8);
}
ai++;
}
}
} |
package dyvilx.tools.gensrc.ast;
import dyvil.annotation.internal.NonNull;
import dyvil.lang.Name;
import dyvil.reflect.Modifiers;
import dyvilx.tools.compiler.DyvilCompiler;
import dyvilx.tools.compiler.ast.attribute.AttributeList;
import dyvilx.tools.compiler.ast.classes.ClassBody;
import dyvilx.tools.compiler.ast.classes.CodeClass;
import dyvilx.tools.compiler.ast.classes.IClass;
import dyvilx.tools.compiler.ast.expression.IValue;
import dyvilx.tools.compiler.ast.expression.access.ConstructorCall;
import dyvilx.tools.compiler.ast.expression.access.FieldAccess;
import dyvilx.tools.compiler.ast.expression.access.MethodCall;
import dyvilx.tools.compiler.ast.expression.constant.StringValue;
import dyvilx.tools.compiler.ast.field.IDataMember;
import dyvilx.tools.compiler.ast.header.ClassUnit;
import dyvilx.tools.compiler.ast.header.ICompilationUnit;
import dyvilx.tools.compiler.ast.header.PackageDeclaration;
import dyvilx.tools.compiler.ast.imports.ImportDeclaration;
import dyvilx.tools.compiler.ast.method.CodeMethod;
import dyvilx.tools.compiler.ast.method.IMethod;
import dyvilx.tools.compiler.ast.method.MatchList;
import dyvilx.tools.compiler.ast.parameter.ArgumentList;
import dyvilx.tools.compiler.ast.parameter.CodeParameter;
import dyvilx.tools.compiler.ast.parameter.ParameterList;
import dyvilx.tools.compiler.ast.statement.StatementList;
import dyvilx.tools.compiler.ast.structure.Package;
import dyvilx.tools.compiler.ast.type.IType;
import dyvilx.tools.compiler.ast.type.builtin.Types;
import dyvilx.tools.compiler.ast.type.compound.ArrayType;
import dyvilx.tools.compiler.parser.DyvilSymbols;
import dyvilx.tools.gensrc.lang.I18n;
import dyvilx.tools.gensrc.lexer.GenSrcLexer;
import dyvilx.tools.gensrc.parser.BlockParser;
import dyvilx.tools.gensrc.sources.GenSrcFileType;
import dyvilx.tools.parsing.ParserManager;
import dyvilx.tools.parsing.marker.MarkerList;
import java.io.File;
public class Template extends ClassUnit
{
public static class LazyTypes
{
public static final Package dyvilxToolsGensrc = Package.rootPackage
.resolveInternalPackage("dyvilx/tools/gensrc");
public static final IType Writer = Package.javaIO.resolveClass("Writer").getClassType();
public static final IType StringWriter = Package.javaIO.resolveClass("StringWriter").getClassType();
public static final IType IOException = Package.javaIO.resolveClass("IOException").getClassType();
public static final IType Specialization = dyvilxToolsGensrc.resolveClass("Specialization").getClassType();
public static final IType Template = dyvilxToolsGensrc.resolveClass("Template").getClassType();
public static final IClass Builtins_CLASS = dyvilxToolsGensrc.resolveClass("Builtins");
}
private IClass templateClass;
private IMethod genMethod;
private IMethod mainMethod;
public Template(DyvilCompiler compiler, Package pack, File input, File output)
{
super(compiler, pack, input, output);
this.markers = new MarkerList(I18n.INSTANCE);
}
// Resolution
@Override
public IDataMember resolveField(Name name)
{
final IDataMember superField = super.resolveField(name);
if (superField != null)
{
return superField;
}
return LazyTypes.Builtins_CLASS.resolveField(name);
}
@Override
public void getMethodMatches(MatchList<IMethod> list, IValue receiver, Name name, ArgumentList arguments)
{
super.getMethodMatches(list, receiver, name, arguments);
if (list.hasCandidate())
{
return;
}
LazyTypes.Builtins_CLASS.getMethodMatches(list, receiver, name, arguments);
}
// Phases
@Override
public void tokenize()
{
if (this.load())
{
this.tokens = new GenSrcLexer(this.markers).tokenize(this.fileSource.text());
}
}
@Override
public void parse()
{
// class NAME { }
final CodeClass theClass = new CodeClass(null, this.name, AttributeList.of(Modifiers.PUBLIC));
final ClassBody classBody = new ClassBody(theClass);
theClass.setBody(classBody);
this.addClass(theClass);
this.templateClass = theClass;
// func generate(spec, writer) -> void = { ... }
final CodeMethod genMethod = new CodeMethod(theClass, Name.fromRaw("generate"), Types.VOID,
AttributeList.of(Modifiers.PUBLIC | Modifiers.OVERRIDE));
final StatementList directives = new StatementList();
genMethod.setValue(directives);
classBody.addMethod(genMethod);
this.genMethod = genMethod;
// func main(args) -> void
final CodeMethod mainMethod = new CodeMethod(theClass, Name.fromRaw("main"), Types.VOID,
AttributeList.of(Modifiers.PUBLIC | Modifiers.STATIC));
classBody.addMethod(mainMethod);
this.mainMethod = mainMethod;
// Parse
new ParserManager(DyvilSymbols.INSTANCE, this.tokens.iterator(), this.markers)
.parse(new BlockParser(this, directives));
}
@Override
public void resolveTypes()
{
this.makeGenerateSpecMethod();
this.makeMainMethod();
// automatically infer package declaration
this.packageDeclaration = new PackageDeclaration(null, this.getPackage().getFullName());
this.templateClass.setSuperType(LazyTypes.Template);
this.templateClass.setSuperConstructorArguments(new ArgumentList(new StringValue(this.getInternalName())));
super.resolveTypes();
}
private void makeMainMethod()
{
// func main(args: [String]) -> void = new TemplateName().mainImpl(args)
final ParameterList params = this.mainMethod.getParameters();
final CodeParameter argsParam = new CodeParameter(this.mainMethod, null, Name.fromRaw("args"),
new ArrayType(Types.STRING));
params.add(argsParam);
final IValue newTemplate = new ConstructorCall(null, this.templateClass.getClassType(), ArgumentList.EMPTY);
this.mainMethod.setValue(
new MethodCall(null, newTemplate, Name.fromRaw("mainImpl"), new ArgumentList(new FieldAccess(argsParam))));
}
private void makeGenerateSpecMethod()
{
// func generate(spec: Specialization, writer: java.io.Writer) throws IOException -> void = { ... }
final ParameterList params = this.genMethod.getParameters();
final CodeParameter specParam = new CodeParameter(this.genMethod, null, Name.fromRaw("spec"),
Template.LazyTypes.Specialization);
final CodeParameter writerParam = new CodeParameter(this.genMethod, null, Name.fromRaw("writer"),
Template.LazyTypes.Writer);
params.add(specParam);
params.add(writerParam);
this.genMethod.getExceptions().add(Template.LazyTypes.IOException);
}
@Override
protected boolean printMarkers()
{
return ICompilationUnit
.printMarkers(this.compiler, this.markers, GenSrcFileType.TEMPLATE, this.name, this.fileSource);
}
@Override
public void toString(@NonNull String indent, @NonNull StringBuilder buffer)
{
for (int i = 0; i < this.importCount; i++)
{
buffer.append(indent);
appendImport(indent, buffer, this.importDeclarations[i]);
buffer.append('\n');
}
final IValue directives = this.genMethod.getValue();
if (!(directives instanceof StatementList))
{
directives.toString(indent, buffer);
return;
}
final StatementList statements = (StatementList) directives;
for (int i = 0, count = statements.size(); i < count; i++)
{
statements.get(i).toString(indent, buffer);
buffer.append('\n');
}
}
public static void appendImport(@NonNull String indent, @NonNull StringBuilder buffer,
ImportDeclaration importDeclaration)
{
buffer.append('
final int position = buffer.length() + "import".length();
importDeclaration.toString(indent, buffer);
buffer.setCharAt(position, '('); // insert open paren in place of the space after import
buffer.append(')');
}
} |
package net.mingsoft.cms.util;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.PageUtil;
import freemarker.cache.FileTemplateLoader;
import freemarker.core.ParseException;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateNotFoundException;
import net.mingsoft.base.constant.Const;
import net.mingsoft.basic.util.BasicUtil;
import net.mingsoft.basic.util.SpringUtil;
import net.mingsoft.cms.bean.ContentBean;
import net.mingsoft.cms.constant.e.ColumnTypeEnum;
import net.mingsoft.cms.entity.CategoryEntity;
import net.mingsoft.mdiy.bean.PageBean;
import net.mingsoft.mdiy.biz.IModelBiz;
import net.mingsoft.mdiy.biz.impl.ModelBizImpl;
import net.mingsoft.mdiy.entity.ModelEntity;
import net.mingsoft.mdiy.parser.TagParser;
import net.mingsoft.mdiy.util.ParserUtil;
import org.apache.commons.lang3.StringUtils;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CmsParserUtil extends ParserUtil {
private static int COLUMN_TYPE_COVER = 2;
/**
* pc
*
* @param templatePath
*
* @param targetPath
* html.html
* @throws IOException
*/
public static void generate(String templatePath, String targetPath) throws IOException {
Map<String, Object> map = new HashMap<String, Object>();
map.put(IS_DO, false);
CategoryEntity column = new CategoryEntity();
map.put(COLUMN, column);
String content = CmsParserUtil.generate(templatePath, map, false);
FileUtil.writeString(content, ParserUtil.buildHtmlPath(targetPath), Const.UTF8);
if (ParserUtil.hasMobileFile(templatePath)) {
map.put(ParserUtil.MOBILE, BasicUtil.getApp().getAppMobileStyle());
content = CmsParserUtil.generate(templatePath, map, true);
FileUtil.writeString(content, ParserUtil.buildMobileHtmlPath(targetPath), Const.UTF8);
}
}
/**
*
* @param column
* @param articleIdTotal
* @throws TemplateNotFoundException
* @throws MalformedTemplateNameException
* @throws ParseException
* @throws IOException
*/
public static void generateList(CategoryEntity column, int articleIdTotal)
throws TemplateNotFoundException, MalformedTemplateNameException, ParseException, IOException {
// cfg
if (ftl == null) {
ftl = new FileTemplateLoader(new File(ParserUtil.buildTempletPath()));
cfg.setTemplateLoader(ftl);
}
try{
Template mobileTemplate = cfg.getTemplate(
BasicUtil.getApp().getAppMobileStyle() + File.separator + column.getCategoryListUrl(), Const.UTF8);
Template template = cfg.getTemplate(File.separator + column.getCategoryListUrl(), Const.UTF8);
String columnContentModelId = column.getMdiyModelId();
StringWriter writer = new StringWriter();
try {
// column,
template.process(null, writer);
String content = writer.toString();
int pageSize = TagParser.getPageSize(content);
int totalPageSize = PageUtil.totalPage(articleIdTotal, pageSize);
String columnListPath;
String mobilePath;
ModelEntity contentModel = null;
if (StringUtils.isNotBlank(columnContentModelId)) {
contentModel = (ModelEntity) SpringUtil.getBean(ModelBizImpl.class).getEntity(Integer.parseInt(columnContentModelId));
}
int pageNo = 1;
PageBean page = new PageBean();
page.setSize(pageSize);
Map<String, Object> parserParams = new HashMap<String, Object>();
parserParams.put(COLUMN, column);
page.setTotal(totalPageSize);
parserParams.put(IS_DO, false);
parserParams.put(HTML, HTML);
parserParams.put(APP_ID, BasicUtil.getAppId());
if (contentModel!=null) {
// key
parserParams.put(TABLE_NAME, contentModel.getModelTableName());
}
if(ParserUtil.IS_SINGLE) {
parserParams.put(ParserUtil.URL, BasicUtil.getUrl());
}
if (totalPageSize <= 0) {
// 0*size
// index.html
mobilePath = ParserUtil.buildMobileHtmlPath(column.getCategoryPath() + File.separator + ParserUtil.INDEX);
columnListPath = ParserUtil.buildHtmlPath(column.getCategoryPath() + File.separator + ParserUtil.INDEX);
page.setPageNo(pageNo);
parserParams.put(ParserUtil.PAGE, page);
TagParser tag = new TagParser(content,parserParams);
FileUtil.writeString(tag.rendering(), columnListPath, Const.UTF8);
if (ParserUtil.hasMobileFile(column.getCategoryListUrl())) {
writer = new StringWriter();
mobileTemplate.process(null, writer);
tag = new TagParser(writer.toString(), parserParams);
// tag.getContent()
FileUtil.writeString(tag.rendering(), mobilePath, Const.UTF8);
}
writer = new StringWriter();
} else {
for (int i = 0; i < totalPageSize; i++) {
if (i == 0) {
// 0*size
// index.html
mobilePath = ParserUtil
.buildMobileHtmlPath(column.getCategoryPath() + File.separator + ParserUtil.INDEX);
columnListPath = ParserUtil
.buildHtmlPath(column.getCategoryPath() + File.separator + ParserUtil.INDEX);
} else {
// list-2.html
mobilePath = ParserUtil.buildMobileHtmlPath(
column.getCategoryPath() + File.separator + ParserUtil.PAGE_LIST + pageNo);
columnListPath = ParserUtil
.buildHtmlPath(column.getCategoryPath() + File.separator + ParserUtil.PAGE_LIST + pageNo);
}
page.setPageNo(pageNo);
parserParams.put(ParserUtil.PAGE, page);
TagParser tag = new TagParser(content,parserParams);
FileUtil.writeString(tag.rendering(), columnListPath, Const.UTF8);
if (ParserUtil.hasMobileFile(column.getCategoryListUrl())) {
writer = new StringWriter();
mobileTemplate.process(null, writer);
tag = new TagParser(writer.toString(),parserParams);
// tag.getContent()
FileUtil.writeString(tag.rendering(), mobilePath, Const.UTF8);
}
writer = new StringWriter();
pageNo++;
}
}
} catch (TemplateException e) {
e.printStackTrace();
}
}catch (TemplateNotFoundException e){
e.printStackTrace();
}
}
/**
*
*
* @param articleIdList
*
* @return
* @throws IOException
* @throws ParseException
* @throws MalformedTemplateNameException
* @throws TemplateNotFoundException
*/
public static void generateBasic(List<ContentBean> articleIdList)
throws TemplateNotFoundException, MalformedTemplateNameException, ParseException, IOException {
Map<Object, Object> contentModelMap = new HashMap<Object, Object>();
ModelEntity contentModel = null;
String writePath = null;
List<Integer> generateIds = new ArrayList<>();
for (int artId = 0; artId < articleIdList.size();) {
PageBean page = new PageBean();
int articleId = articleIdList.get(artId).getArticleId();
String articleColumnPath = articleIdList.get(artId).getCategoryPath();
String columnUrl = articleIdList.get(artId).getCategoryUrl();
String columnContentModelId = "";
if(StringUtils.isNotBlank(articleIdList.get(artId).getMdiyModelId()) && Integer.parseInt(articleIdList.get(artId).getMdiyModelId())>0){
columnContentModelId = articleIdList.get(artId).getMdiyModelId();
}
if (generateIds.contains(articleId)) {
artId++;
continue;
}
if (!FileUtil.exist(ParserUtil.buildTempletPath(columnUrl))||StringUtils.isBlank(articleIdList.get(artId).getCategoryId())) {
artId++;
continue;
}
generateIds.add(articleId);
// :html/id/id/id.html
writePath = ParserUtil.buildHtmlPath(articleColumnPath + File.separator + articleId);
//index.html
if(Integer.parseInt(articleIdList.get(artId).getCategoryType()) == ColumnTypeEnum.COLUMN_TYPE_COVER.toInt()) {
writePath = ParserUtil.buildHtmlPath(articleColumnPath + File.separator + ParserUtil.INDEX);
}
Map<String, Object> parserParams = new HashMap<String, Object>();
parserParams.put(ParserUtil.COLUMN, articleIdList.get(artId));
if (StringUtils.isNotBlank(columnContentModelId)) {
if (contentModelMap.containsKey(columnContentModelId)) {
parserParams.put(TABLE_NAME, contentModel.getModelTableName());
} else {
contentModel = (ModelEntity) SpringUtil.getBean(IModelBiz.class)
.getEntity(Integer.parseInt(columnContentModelId));
// key
contentModelMap.put(columnContentModelId, contentModel.getModelTableName());
parserParams.put(TABLE_NAME, contentModel.getModelTableName());
}
}
parserParams.put(ID, articleId);
if (artId > 0) {
ContentBean preCaBean = articleIdList.get(artId - 1);
if( articleColumnPath.contains(preCaBean.getCategoryId()+"")){
page.setPreId(preCaBean.getArticleId());
}
}
if (artId + 1 < articleIdList.size()) {
ContentBean nextCaBean = articleIdList.get(artId + 1);
if(articleColumnPath.contains(nextCaBean.getCategoryId()+"")){
page.setNextId(nextCaBean.getArticleId());
}
}
parserParams.put(IS_DO, false);
parserParams.put(ParserUtil.PAGE, page);
String content = CmsParserUtil.generate(articleIdList.get(artId).getCategoryUrl(), parserParams, false);
FileUtil.writeString(content, writePath, Const.UTF8);
if (ParserUtil.hasMobileFile(columnUrl)) {
writePath = ParserUtil.buildMobileHtmlPath(articleColumnPath + File.separator + articleId);
//index.html
if(Integer.parseInt(articleIdList.get(artId).getCategoryType()) == ColumnTypeEnum.COLUMN_TYPE_COVER.toInt()) {
writePath = ParserUtil.buildMobileHtmlPath(articleColumnPath + File.separator + ParserUtil.INDEX);
}
if (!FileUtil.exist(ParserUtil.buildTempletPath(MOBILE + File.separator + columnUrl))) {
artId++;
continue;
}
parserParams.put(MOBILE, BasicUtil.getApp().getAppMobileStyle());
content = CmsParserUtil.generate(articleIdList.get(artId).getCategoryUrl(), parserParams, true);
FileUtil.writeString(content, writePath, Const.UTF8);
}
artId++;
}
}
} |
package no.sonat.battleships;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import no.sonat.battleships.models.*;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class VerySmartRobot {
final public static ArrayList<Coordinate> hitCoordinates = new ArrayList<>();
final ObjectMapper json = new ObjectMapper();
final public static List<Coordinate> availableCoordinates = new ArrayList<>();
final String gameId;
final int player;
WebSocketClient wsClient;
private Coordinate lastFired;
private FiringState state = FiringState.SEEKING;
private DirectionStrategy ds;
private String lastFiredResult;
public VerySmartRobot(String gameId, int player) throws Exception {
this.gameId = gameId;
this.player = player;
}
public void initiate() throws URISyntaxException {
this.wsClient = new WebSocketClient(new URI("ws://10.0.0.4:9000/game/" + gameId + "/socket")) {
@Override
public void onOpen(ServerHandshake serverHandshake) {
System.out.println("onOpen");
//placeShipsDefault();
placeShipsForReal();
}
@Override
public void onMessage(String s) {
// System.out.println(String.format("message received: %1$s", s));
final JsonNode msg;
try {
msg = json.readTree(s);
} catch (IOException e) {
throw new RuntimeException("error reading json", e);
}
final String type = msg.get("class").asText();
switch (type) {
case "game.broadcast.GameIsStarted":
onGameStart(msg);
break;
case "game.broadcast.NextPlayerTurn":
if (msg.get("playerTurn").asInt() == player) {
shoot();
}
break;
case "game.result.ShootResult":
handleResult(msg);
break;
case "game.broadcast.GameOver":
boolean weWon = msg.get("andTheWinnerIs").asInt() == player;
System.out.println(weWon ? "We Won!!!" : "Wo lost!!!");
System.exit(0);
default:
break;
}
}
@Override
public void onClose(int i, String s, boolean b) {
System.out.println("onclose");
}
@Override
public void onError(Exception e) {
System.out.println("onError");
e.printStackTrace();
System.out.println(e.getMessage());
}
};
wsClient.connect();
}
private void handleResult(JsonNode msg) {
String hitResult = msg.get("hit").asText();
if( hitResult.equalsIgnoreCase("SPLASH")){
System.out.println(lastFired + " Miss");
lastFiredResult = "MISS";
} else if(hitResult.equalsIgnoreCase("BANG")){
System.out.println("HIT: " + lastFired);
state = FiringState.SINKING;
hitCoordinates.add(lastFired);
lastFiredResult = "HIT";
} else {
System.out.println("SUNK: " + lastFired);
state = FiringState.SEEKING;
hitCoordinates.add(lastFired);
lastFiredResult = "SUNK";
ds = null;
}
}
public void placeShipsDefault() {
SetShipMessage ship1 = new SetShipMessage(new Ship(new Coordinate[] {new Coordinate(2,2), new Coordinate(2,3)}), player);
SetShipMessage ship2 = new SetShipMessage(new Ship(new Coordinate[] {new Coordinate(4,4), new Coordinate(4,5), new Coordinate(4,6)}), player);
SetShipMessage ship3 = new SetShipMessage(new Ship(new Coordinate[] {new Coordinate(8,1), new Coordinate(9,1), new Coordinate(10, 1)}), player);
SetShipMessage ship4 = new SetShipMessage(new Ship(new Coordinate[] {new Coordinate(1,1), new Coordinate(2,1), new Coordinate(3,1), new Coordinate(4,1)}), player);
SetShipMessage ship5 = new SetShipMessage(new Ship(new Coordinate[] {new Coordinate(8,5), new Coordinate(9,5), new Coordinate(10,5), new Coordinate(11,5)}), player);
SetShipMessage ship6 = new SetShipMessage(new Ship(new Coordinate[] {new Coordinate(11,7), new Coordinate(11,8),new Coordinate(11,9), new Coordinate(11,10), new Coordinate(11, 11)}), player);
try {
wsClient.send(json.writeValueAsString(ship1));
wsClient.send(json.writeValueAsString(ship2));
wsClient.send(json.writeValueAsString(ship3));
wsClient.send(json.writeValueAsString(ship4));
wsClient.send(json.writeValueAsString(ship5));
wsClient.send(json.writeValueAsString(ship6));
} catch (Exception e) {
throw new RuntimeException("marshalling failure", e);
}
}
public void placeShipsForReal() {
SetShipMessage ship1 = new SetShipMessage(new Ship(new Coordinate[] {new Coordinate(5,5), new Coordinate(6,5)}), player);
SetShipMessage ship2 = new SetShipMessage(new Ship(new Coordinate[] {new Coordinate(7,4), new Coordinate(7,5), new Coordinate(7,6)}), player);
SetShipMessage ship3 = new SetShipMessage(new Ship(new Coordinate[] {new Coordinate(4,6), new Coordinate(4,7), new Coordinate(4, 8)}), player);
// SetShipMessage ship4 = new SetShipMessage(new Ship(new Coordinate[] {new Coordinate(10,5), new Coordinate(10,6), new Coordinate(10,7), new Coordinate(10,8)}), player);
// SetShipMessage ship5 = new SetShipMessage(new Ship(new Coordinate[] {new Coordinate(11,5), new Coordinate(11,6), new Coordinate(11,7), new Coordinate(11,8)}), player);
SetShipMessage ship4 = new SetShipMessage(new Ship(new Coordinate[] {new Coordinate(8,5), new Coordinate(9,5), new Coordinate(10,5), new Coordinate(11,5)}), player);
SetShipMessage ship5 = new SetShipMessage(new Ship(new Coordinate[] {new Coordinate(8,6), new Coordinate(9,6), new Coordinate(10,6), new Coordinate(11,6)}), player);
SetShipMessage ship6 = new SetShipMessage(new Ship(new Coordinate[] {new Coordinate(0,2), new Coordinate(0,3),new Coordinate(0,4), new Coordinate(0,5), new Coordinate(0, 6)}), player);
try {
wsClient.send(json.writeValueAsString(ship1));
wsClient.send(json.writeValueAsString(ship2));
wsClient.send(json.writeValueAsString(ship3));
wsClient.send(json.writeValueAsString(ship4));
wsClient.send(json.writeValueAsString(ship5));
wsClient.send(json.writeValueAsString(ship6));
} catch (Exception e) {
throw new RuntimeException("marshalling failure", e);
}
}
final Random rand = new Random();
public void onGameStart(JsonNode msg) {
for (int x = 0; x < 12; x++) {
for (int y = 0; y < 12; y++) {
availableCoordinates.add(new Coordinate(x, y));
}
}
// if it's my turn, fire!
if (msg.get("playerTurn").asInt() == player) {
shoot();
}
}
public void shoot() {
if (state == FiringState.SEEKING){
int idx = 0;
Coordinate coord = null;
do {
idx = rand.nextInt(availableCoordinates.size());
coord = availableCoordinates.get(idx);
}while(!(coord.y % 2 == 0 && coord.x % 2 ==0 || coord.y % 2 != 0 && coord.x % 2 != 0));
availableCoordinates.remove(idx);
ShootMessage shootMessage = new ShootMessage(coord, player);
try {
wsClient.send(json.writeValueAsString(shootMessage));
lastFired = coord;
} catch (JsonProcessingException e) {
throw new RuntimeException("Error marshalling object", e);
}
}else{
if (ds == null){
ds = new DirectionStrategy(lastFired);
}
Coordinate coord = null;
try {
if( lastFiredResult.equalsIgnoreCase("HIT")) {
coord = ds.nextHit();
} else {
coord = ds.nextMiss();
}
} catch (ExhaustedDirectionsException e) {
coord = availableCoordinates.get(rand.nextInt(availableCoordinates.size())); // TODO: fix
System.out.printf("Exhausted all possibilities ;/");
state = FiringState.SEEKING;
ds = null;
}
availableCoordinates.remove(coord);
ShootMessage shootMessage = new ShootMessage(coord, player);
try {
wsClient.send(json.writeValueAsString(shootMessage));
lastFired = coord;
} catch (JsonProcessingException e) {
throw new RuntimeException("Error marshalling object", e);
}
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.