answer stringlengths 17 10.2M |
|---|
package to.etc.domui.server;
import java.io.*;
import java.util.*;
import java.util.logging.Logger;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.UnavailableException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import to.etc.domui.trouble.*;
import to.etc.domui.util.*;
import to.etc.util.*;
import to.etc.webapp.nls.*;
public class AppFilter implements Filter {
static final Logger LOG = Logger.getLogger(AppFilter.class.getName());
private ConfigParameters m_config;
private String m_applicationClassName;
private boolean m_logRequest;
/**
* If a reloader is needed for debug/development pps this will hold the reloader.
*/
private ContextMaker m_contextMaker;
public void destroy() {
}
static public String minitime() {
Calendar cal = Calendar.getInstance();
return cal.get(Calendar.HOUR_OF_DAY)+StringTool.intToStr(cal.get(Calendar.MINUTE), 10, 2)+StringTool.intToStr(cal.get(Calendar.SECOND), 10, 2)+"."+cal.get(Calendar.MILLISECOND);
}
public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) throws IOException, ServletException {
try {
HttpServletRequest rq = (HttpServletRequest)req;
rq.setCharacterEncoding("UTF-8"); // jal 20080804 Encoding of input was incorrect?
if(m_logRequest) {
String rs = rq.getQueryString();
rs = rs == null ? "" : "?"+rs;
System.out.println(minitime()+" rq="+rq.getRequestURI()+rs);
}
NlsContext.setLocale(rq.getLocale());
// NlsContext.setLocale(new Locale("nl", "NL"));
if(m_contextMaker.handleRequest(rq, (HttpServletResponse)res))
return;
} catch(RuntimeException x) {
DomUtil.dumpException(x);
throw x;
} catch(ServletException x) {
DomUtil.dumpException(x);
throw x;
} catch(Exception x) {
DomUtil.dumpException(x);
throw new JamesGoslingIsAnIdiotException(x); // James Gosling is an idiot
}
chain.doFilter(req, res);
}
/**
* Initialize by reading config from the web.xml.
* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
public void init(final FilterConfig config) throws ServletException {
try {
java.util.logging.LogManager.getLogManager().reset();
java.util.logging.LogManager.getLogManager().readConfiguration(AppFilter.class.getResourceAsStream("logging.properties"));
} catch(IOException x) {
throw new JamesGoslingIsAnIdiotException(x);
}
System.out.println("Init logger");
// System.out.println("QDataContext="+QDataContext.class.getClassLoader());
m_logRequest = DeveloperOptions.getBool("domui.logurl", false);
//-- Get the root for all files in the webapp
File approot = new File(config.getServletContext().getRealPath("/"));
System.out.println("WebApp root="+approot);
if(! approot.exists() || ! approot.isDirectory())
throw new IllegalStateException("Internal: cannot get webapp root directory");
m_config = new ConfigParameters(config, approot);
//-- Handle application construction
m_applicationClassName = getApplicationClassName(m_config);
if(m_applicationClassName == null)
throw new UnavailableException("The application class name is not set. Use 'application' in the Filter parameters to set a main class.");
//-- Are we running in debug mode?
try {
String autoload = m_config.getString("auto-reload");
if(autoload != null && autoload.trim().length() > 0)
m_contextMaker = new ReloadingContextMaker(m_applicationClassName, m_config, autoload);
else
m_contextMaker = new NormalContextMaker(m_applicationClassName, m_config);
} catch(RuntimeException x) {
throw x;
} catch(ServletException x) {
throw x;
} catch(Exception x) {
throw new JamesGoslingIsAnIdiotException(x); // James Gosling is an idiot
}
}
public String getApplicationClassName(final ConfigParameters p) {
return p.getString("application");
}
} |
package com.plugin.gcm;
import java.util.List;
import com.google.android.gcm.GCMBaseIntentService;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
@SuppressLint("NewApi")
public class GCMIntentService extends GCMBaseIntentService {
public static final String DEFAULT_NOTIFICATION_ID = "1";
private static final String TAG = "GCMIntentService";
public GCMIntentService() {
super("GCMIntentService");
}
@Override
public void onRegistered(Context context, String regId) {
Log.v(TAG, "onRegistered: "+ regId);
JSONObject json;
try
{
json = new JSONObject().put("event", "registered");
json.put("regid", regId);
Log.v(TAG, "onRegistered: " + json.toString());
// Send this JSON data to the JavaScript application above EVENT should be set to the msg type
// In this case this is the registration ID
PushPlugin.sendJavascript( json );
}
catch( JSONException e)
{
// No message to the user is sent, JSON failed
Log.e(TAG, "onRegistered: JSON exception");
}
}
@Override
public void onUnregistered(Context context, String regId) {
Log.d(TAG, "onUnregistered - regId: " + regId);
}
@Override
protected void onMessage(Context context, Intent intent) {
Log.d(TAG, "onMessage - context: " + context);
// Extract the payload from the message
Bundle extras = intent.getExtras();
if (extras != null)
{
String action = extras.getString("action");
if (action == null) {
Log.d(TAG, "onMessage - missing action");
} else {
Log.d(TAG, "onMessage - action: [" + action + "]");
}
if (action != null && action.equals("dismiss_notification")) {
dismissNotification(context, extras);
return;
}
// if we are in the foreground, surface the payload with foreground = true.
if (PushPlugin.isInForeground()) {
extras.putBoolean("foreground", true);
extras.putBoolean("user_click", false);
PushPlugin.sendExtras(extras);
}
// Send a notification if there is a message
if (extras.getString("message") != null && extras.getString("message").length() != 0) {
extras.putBoolean("foreground", false);
extras.putBoolean("user_click", true);
createNotification(context, extras);
}
}
}
public void createNotification(Context context, Bundle extras)
{
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(this, PushHandlerActivity.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
notificationIntent.putExtra("pushBundle", extras);
PendingIntent contentIntent = PendingIntent.getActivity(this, getTagName(context, extras).hashCode(), notificationIntent, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setDefaults(Notification.DEFAULT_ALL)
.setSmallIcon(context.getApplicationInfo().icon)
.setWhen(System.currentTimeMillis())
.setContentTitle(extras.getString("title"))
.setTicker(extras.getString("title"))
.setContentIntent(contentIntent)
.setAutoCancel(true);
String message = extras.getString("message");
if (message != null) {
mBuilder.setContentText(message);
} else {
mBuilder.setContentText("<missing message content>");
}
String msgcnt = extras.getString("msgcnt");
if (msgcnt != null) {
mBuilder.setNumber(Integer.parseInt(msgcnt));
}
mNotificationManager.notify(getTagName(context, extras), 0, mBuilder.build());
}
public static void dismissNotification(Context context, Bundle extras)
{
Log.d(TAG, "dismissNotification " + getMessageID(extras));
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.cancel(getTagName(context, extras), 0);
}
private static String getTagName(Context context, Bundle extras)
{
return getAppName(context) + getMessageID(extras);
}
private static String getAppName(Context context)
{
CharSequence appName =
context
.getPackageManager()
.getApplicationLabel(context.getApplicationInfo());
return (String)appName;
}
public static String getMessageID(Bundle extras) {
if (extras == null) {
Log.i(TAG, "extras is null, using default message id.");
return DEFAULT_NOTIFICATION_ID;
}
String id = extras.getString("notification_id");
if (id == null) {
Log.i(TAG, "notification id not specified, using default one.");
return DEFAULT_NOTIFICATION_ID;
}
return id;
}
@Override
public void onError(Context context, String errorId) {
Log.e(TAG, "onError - errorId: " + errorId);
}
} |
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"));
}
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();
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 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 (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) {
PluginMarker.this.sendNoResult(callbackContext);
}
});
} else {
this.sendNoResult(callbackContext);
}
}
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) {
int width = image.getWidth();
int height = image.getHeight();
if (iconProperty.containsKey("size") == true) {
Bundle sizeInfo = (Bundle) iconProperty.get("size");
width = sizeInfo.getInt("width", width);
height = sizeInfo.getInt("height", height);
if (width != image.getWidth() && height > image.getHeight()) {
//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 sgdk.rescomp.type;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.geom.Area;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import sgdk.tool.ImageUtil;
import sgdk.tool.Random;
public class SpriteCell extends Rectangle implements Comparable<SpriteCell>
{
public static enum OptimizationType
{
BALANCED, MIN_SPRITE, MIN_TILE, NONE
};
public static final Comparator<SpriteCell> sizeAndCoverageComparator = new Comparator<SpriteCell>()
{
@Override
public int compare(SpriteCell o1, SpriteCell o2)
{
int result = Integer.compare(o1.numTile, o2.numTile);
if (result == 0)
result = java.lang.Double.compare(o1.getCoverage(), o2.getCoverage());
// we want ascending order
return -result;
}
};
public final OptimizationType opt;
public final int numTile;
public int coveredPix;
public SpriteCell(Rectangle r, OptimizationType opt)
{
super(r);
this.opt = opt;
numTile = (width * height) / 64;
coveredPix = -1;
}
public SpriteCell(int x, int y, int width, int height, OptimizationType opt)
{
super(x, y, width, height);
this.opt = opt;
numTile = (width * height) / 64;
coveredPix = -1;
}
public boolean isSingleTile()
{
return (width == 8) && (height == 8);
}
public List<SpriteCell> mutate()
{
final List<SpriteCell> result = new ArrayList<>(4);
// switch (Random.nextInt() % 3)
// default:
// case 0:
// // small move mutation
// result.add(mutateMove(1));
// break;
// case 1:
// // size mutation
// result.add(mutateSize(false));
// break;
// case 2:
// // split mutation
// result.addAll(mutateSplit());
// break;
switch (Random.nextInt() & 7)
{
default:
case 0:
// small move mutation
result.add(mutateMove(1));
break;
case 1:
// big move mutation
result.add(mutateMove(4));
break;
case 2:
// size mutation
result.add(mutateSize(false));
break;
case 3:
// multi size mutation
result.add(mutateSize(true));
break;
case 4:
// move + size mutation
result.add(mutateMove(1).mutateSize(false));
break;
case 5:
// big move + multi size mutation
result.add(mutateMove(4).mutateSize(true));
break;
case 6:
// split mutation
result.addAll(mutateSplit());
break;
case 7:
// move + split mutation
result.addAll(mutateMove(1).mutateSplit());
break;
}
return result;
}
private SpriteCell mutateMove(int move)
{
final Rectangle newRegion = new Rectangle(this);
switch (Random.nextInt() & 3)
{
default:
case 0:
newRegion.x += move;
break;
case 1:
newRegion.x -= move;
break;
case 2:
newRegion.y += move;
break;
case 3:
newRegion.y -= move;
break;
}
return new SpriteCell(newRegion, opt);
}
private SpriteCell mutateSize(boolean multi)
{
final Rectangle newRegion = new Rectangle(this);
int it = 1;
if (multi)
it += Random.nextInt() & 3;
while (it > 0)
{
switch (Random.nextInt() & 3)
{
default:
case 0:
if (newRegion.width < 32)
{
newRegion.width += 8;
it
}
break;
case 1:
if (newRegion.width > 8)
{
newRegion.width -= 8;
it
}
break;
case 2:
if (newRegion.height < 32)
{
newRegion.height += 8;
it
}
break;
case 3:
if (newRegion.height > 8)
{
newRegion.height -= 8;
it
}
break;
}
}
return new SpriteCell(newRegion, opt);
}
private List<SpriteCell> mutateSplit()
{
final List<SpriteCell> result = new ArrayList<>(4);
final Rectangle newRegion = new Rectangle(this);
final int sw = Random.nextInt(newRegion.width / 8) * 8;
final int sh = Random.nextInt(newRegion.height / 8) * 8;
if ((sw > 32) || (sh > 32))
System.out.println("error");
final Rectangle r1 = new Rectangle(x, y, sw, sh);
final Rectangle r2 = new Rectangle(x + sw, y, width - sw, sh);
final Rectangle r3 = new Rectangle(x, y + sh, sw, height - sh);
final Rectangle r4 = new Rectangle(x + sw, y + sh, width - sw, height - sh);
if (!r1.isEmpty())
result.add(new SpriteCell(r1, opt));
if (!r2.isEmpty())
result.add(new SpriteCell(r2, opt));
if (!r3.isEmpty())
result.add(new SpriteCell(r3, opt));
if (!r4.isEmpty())
result.add(new SpriteCell(r4, opt));
return result;
}
public double getScore()
{
return getBaseScore() + (getCoveragePenalty() / 10d);
}
public double getBaseScore()
{
switch (opt)
{
default:
case BALANCED:
return 5d + (numTile * 2d) + (getWidth() / 32d);
case MIN_SPRITE:
return 15d + (numTile * 1d) + (getWidth() / 32d);
case MIN_TILE:
return 2d + (numTile * 5d) + (getWidth() / 32d);
}
// return (1 / 10d);
// return (numTile / 20d) + (1 / 8d) + ((region.width / 8) / 10d);
// return (numTile / 20d) + (1 / 8d);
// return (numTile / 20d) + (1 / 50d);
// return (numTile / 20d);
// return (numTile / 20d) + (1 / 10d);
}
public double getCoverage()
{
if (coveredPix == -1)
return 0d;
return (double) coveredPix / (double) (numTile * 64);
}
public double getCoveragePenalty()
{
return 1d - getCoverage();
}
public boolean optimizeOverdraw(Dimension imageDim, List<SpriteCell> allSpr)
{
final Area area = new Area();
// build area corresponding to others sprites
for (SpriteCell sc : allSpr)
if (sc != this)
area.add(new Area(sc));
// get intersection with others sprites
area.intersects(this);
// no overdraw --> ok
if (area.isEmpty())
return false;
final Point initialPos = getLocation();
final Rectangle bounds = new Rectangle(imageDim);
final Rectangle rectH = new Rectangle(0, 0, width, 1);
final Rectangle rectV = new Rectangle(0, 0, 1, height);
while (canMoveLeft(area, x, y, rectH, rectV))
{
x
// outside image bounds ? --> stop
if (!bounds.contains(this))
{
x++;
break;
}
}
while (canMoveRight(area, x, y, rectH, rectV))
{
x++;
// outside image bounds ? --> stop
if (!bounds.contains(this))
{
x
break;
}
}
while (canMoveTop(area, x, y, rectH, rectV))
{
y
// outside image bounds ? --> stop
if (!bounds.contains(this))
{
y++;
break;
}
}
while (canMoveBottom(area, x, y, rectH, rectV))
{
y++;
// outside image bounds ? --> stop
if (!bounds.contains(this))
{
y
break;
}
}
return !getLocation().equals(initialPos);
}
@Override
public int compareTo(SpriteCell o)
{
return java.lang.Double.compare(getScore(), o.getScore());
}
@Override
public String toString()
{
return "[" + x + "," + y + "-" + width + "," + height + "] cov= " + (int) (getCoverage() * 100d) + "%";
}
public static SpriteCell optimizePosition(byte[] image, Dimension imageDim, SpriteCell spr)
{
final Rectangle imageBounds = new Rectangle(imageDim);
Rectangle region = new Rectangle(spr);
// optimize on right
while (!ImageUtil.hasOpaquePixelOnEdge(image, imageDim, region, false, false, true, false)
&& region.intersects(imageBounds))
region.x
// optimize on bottom
while (!ImageUtil.hasOpaquePixelOnEdge(image, imageDim, region, false, false, false, true)
&& region.intersects(imageBounds))
region.y
// optimize on left
while (!ImageUtil.hasOpaquePixelOnEdge(image, imageDim, region, true, false, false, false)
&& region.intersects(imageBounds))
region.x++;
// optimize on top
while (!ImageUtil.hasOpaquePixelOnEdge(image, imageDim, region, false, true, false, false)
&& region.intersects(imageBounds))
region.y++;
return new SpriteCell(region, spr.opt);
}
public static SpriteCell optimizeSize(byte[] image, Dimension imageDim, SpriteCell spr)
{
Rectangle region = new Rectangle(spr);
final int coveredPixel = ImageUtil.getOpaquePixelCount(image, imageDim, region);
// don't need sprite here
if (coveredPixel == 0)
return null;
// optimize on left
do
{
region.x += 8;
region.width -= 8;
}
while ((region.width > 0) && (ImageUtil.getOpaquePixelCount(image, imageDim, region) == coveredPixel));
// restore last change
region.x -= 8;
region.width += 8;
// optimize on top
do
{
region.y += 8;
region.height -= 8;
}
while ((region.height > 0) && (ImageUtil.getOpaquePixelCount(image, imageDim, region) == coveredPixel));
// restore last change
region.y -= 8;
region.height += 8;
// optimize on right
do
region.width -= 8;
while ((region.width > 0) && (ImageUtil.getOpaquePixelCount(image, imageDim, region) == coveredPixel));
region.width += 8;
// optimize on bottom
do
region.height -= 8;
while ((region.height > 0) && (ImageUtil.getOpaquePixelCount(image, imageDim, region) == coveredPixel));
region.height += 8;
return new SpriteCell(region, spr.opt);
}
private static boolean canMoveTop(Area area, int x, int y, Rectangle rectH, Rectangle rectV)
{
// move rect to bottom
rectH.setLocation(x, y + (rectV.height - 1));
// overdraw on bottom line ?
if (area.contains(rectH))
{
// move rect to top-1
rectH.setLocation(x, y - 1);
// nothing on top ?
if (!area.intersects(rectH))
return true;
}
return false;
}
private static boolean canMoveBottom(Area area, int x, int y, Rectangle rectH, Rectangle rectV)
{
// move rect to top
rectH.setLocation(x, y);
// overdraw on top line ?
if (area.contains(rectH))
{
// move rect to bottom+1
rectH.setLocation(x, y + rectV.height);
// nothing on bottom ?
if (!area.intersects(rectH))
return true;
}
return false;
}
private static boolean canMoveLeft(Area area, int x, int y, Rectangle rectH, Rectangle rectV)
{
// move rect to right
rectV.setLocation(x + (rectH.width - 1), y);
// overdraw on right line ?
if (area.contains(rectV))
{
// move rect to left-1
rectV.setLocation(x - 1, y);
// nothing on left ?
if (!area.intersects(rectV))
return true;
}
return false;
}
private static boolean canMoveRight(Area area, int x, int y, Rectangle rectH, Rectangle rectV)
{
// move rect to left
rectV.setLocation(x, y);
// overdraw on left line ?
if (area.contains(rectV))
{
// move rect to right+1
rectV.setLocation(x + rectH.width, y);
// nothing on right ?
if (!area.intersects(rectV))
return true;
}
return false;
}
/**
* Try to optimize the input position / size part depending the given intersecting parts list
*/
public static SpriteCell optimizeSpritePart(SpriteCell part, List<SpriteCell> intersectingParts)
{
final Area area = new Area(part);
for (SpriteCell sp : intersectingParts)
area.subtract(new Area(sp));
// get area bounds
final Rectangle bounds = area.getBounds();
// align size on 8
bounds.setBounds(bounds.x, bounds.y, ((bounds.width + 7) / 8) * 8, ((bounds.height + 7) / 8) * 8);
return new SpriteCell(bounds, part.opt);
}
/**
* Fix cell position (cannot be negative)
*/
public static SpriteCell fixPosition(Dimension imageDim, SpriteCell spr)
{
Rectangle region = new Rectangle(spr);
// fix on right
if (region.getMaxX() > imageDim.getWidth())
region.x -= region.getMaxX() - imageDim.getWidth();
// fix on bottom
if (region.getMaxY() > imageDim.getHeight())
region.y -= region.getMaxY() - imageDim.getHeight();
// fix on left
if (region.x < 0)
region.x = 0;
// fix on top
if (region.y < 0)
region.y = 0;
return new SpriteCell(region, spr.opt);
}
} |
package com.openxc;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import com.openxc.sinks.DataSinkException;
import com.openxc.sources.bluetooth.BluetoothVehicleDataSource;
import com.openxc.sources.DataSourceException;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Binder;
import android.os.IBinder;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.util.Log;
import com.google.common.base.Objects;
import com.openxc.measurements.BaseMeasurement;
import com.openxc.measurements.Measurement;
import com.openxc.measurements.UnrecognizedMeasurementTypeException;
import com.openxc.NoValueException;
import com.openxc.remote.RawMeasurement;
import com.openxc.remote.VehicleServiceException;
import com.openxc.remote.VehicleServiceInterface;
import com.openxc.sinks.FileRecorderSink;
import com.openxc.sinks.MeasurementListenerSink;
import com.openxc.sinks.MockedLocationSink;
import com.openxc.sinks.UploaderSink;
import com.openxc.sinks.VehicleDataSink;
import com.openxc.sources.NativeLocationSource;
import com.openxc.sources.RemoteListenerSource;
import com.openxc.sources.SourceCallback;
import com.openxc.sources.VehicleDataSource;
import com.openxc.sources.usb.UsbVehicleDataSource;
import com.openxc.util.AndroidFileOpener;
/**
* The VehicleManager is an in-process Android service and the primary entry
* point into the OpenXC library.
*
* An OpenXC application should bind to this service and request vehicle
* measurements through it either synchronously or asynchronously. The service
* will shut down when no more clients are bound to it.
*
* Synchronous measurements are obtained by passing the type of the desired
* measurement to the get method. Asynchronous measurements are obtained by
* defining a Measurement.Listener object and passing it to the service via the
* addListener method.
*
* The sources of data and any post-processing that happens is controlled by
* modifying a list of "sources" and "sinks". When a message is received from a
* data source, it is passed to any and all registered message "sinks" - these
* receivers conform to the {@link com.openxc.sinks.VehicleDataSink}.
* There will always be at least one sink that stores the latest messages and
* handles passing on data to users of the VehicleManager class. Other possible
* sinks include the {@link com.openxc.sinks.FileRecorderSink} which records a
* trace of the raw OpenXC measurements to a file and a web streaming sink
* (which streams the raw data to a web application). Other possible sources
* include the {@link com.openxc.sources.trace.TraceVehicleDataSource} which
* reads a previously recorded vehicle data trace file and plays back the
* measurements
* in real-time.
*
* One small inconsistency is that if a Bluetooth data source is added, any
* calls to set() will be sent to that device. If no Belutooth data source is
* in the pipeline, the standard USB device will be used instead. There is
* currently no way to modify this behavior.
*/
public class VehicleManager extends Service implements SourceCallback {
public final static String VEHICLE_LOCATION_PROVIDER =
MockedLocationSink.VEHICLE_LOCATION_PROVIDER;
private final static String TAG = "VehicleManager";
private boolean mIsBound;
private Lock mRemoteBoundLock;
private Condition mRemoteBoundCondition;
private PreferenceListener mPreferenceListener;
private SharedPreferences mPreferences;
private IBinder mBinder = new VehicleBinder();
private VehicleServiceInterface mRemoteService;
private DataPipeline mPipeline;
private RemoteListenerSource mRemoteSource;
private VehicleDataSink mFileRecorder;
private VehicleDataSource mNativeLocationSource;
private BluetoothVehicleDataSource mBluetoothSource;
private MockedLocationSink mMockedLocationSink;
private VehicleDataSink mUploader;
private MeasurementListenerSink mNotifier;
// The DataPipeline in this class must only have 1 source - the special
// RemoteListenerSource that receives measurements from the
// VehicleService and propagates them to all of the user-registered
// sinks. Any user-registered sources must live in a separate array,
// unfortunately, so they don't try to circumvent the VehicleService
// and send their values directly to the in-process sinks (otherwise no
// other applications could receive updates from that source). For most
// applications that might be fine, but since we want to control trace
// playback from the Enabler, it needs to be able to inject those into the
// RVS. TODO actually, maybe that's the only case. If there are no other
// cases where a user application should be able to inject source data for
// all other apps to share, we should reconsider this and special case the
// trace source.
private CopyOnWriteArrayList<VehicleDataSource> mSources;
/**
* Binder to connect IBinder in a ServiceConnection with the VehicleManager.
*
* This class is used in the onServiceConnected method of a
* ServiceConnection in a client of this service - the IBinder given to the
* application can be cast to the VehicleBinder to retrieve the
* actual service instance. This is required to actaully call any of its
* methods.
*/
public class VehicleBinder extends Binder {
/*
* Return this Binder's parent VehicleManager instance.
*
* @return an instance of VehicleManager.
*/
public VehicleManager getService() {
return VehicleManager.this;
}
}
/**
* Block until the VehicleManager is alive and can return measurements.
*
* Most applications don't need this and don't wait this method, but it can
* be useful for testing when you need to make sure you will get a
* measurement back from the system.
*/
public void waitUntilBound() {
mRemoteBoundLock.lock();
Log.i(TAG, "Waiting for the VehicleService to bind to " + this);
while(!mIsBound) {
try {
mRemoteBoundCondition.await();
} catch(InterruptedException e) {}
}
Log.i(TAG, mRemoteService + " is now bound");
mRemoteBoundLock.unlock();
}
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "Service starting");
mRemoteBoundLock = new ReentrantLock();
mRemoteBoundCondition = mRemoteBoundLock.newCondition();
mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
mPreferenceListener = watchPreferences(mPreferences);
mPipeline = new DataPipeline();
initializeDefaultSinks(mPipeline);
mSources = new CopyOnWriteArrayList<VehicleDataSource>();
bindRemote();
}
private void initializeDefaultSinks(DataPipeline pipeline) {
mNotifier = new MeasurementListenerSink();
mMockedLocationSink = new MockedLocationSink(this);
pipeline.addSink(mNotifier);
pipeline.addSink(mMockedLocationSink);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "Service being destroyed");
if(mPipeline != null) {
mPipeline.stop();
}
if(mBluetoothSource != null) {
mBluetoothSource.close();
}
unwatchPreferences(mPreferences, mPreferenceListener);
unbindRemote();
}
@Override
public IBinder onBind(Intent intent) {
Log.i(TAG, "Service binding in response to " + intent);
bindRemote();
return mBinder;
}
/**
* Retrieve the most current value of a measurement.
*
* Regardless of if a measurement is available or not, return a
* Measurement instance of the specified type. The measurement can be
* checked to see if it has a value.
*
* @param measurementType The class of the requested Measurement
* (e.g. VehicleSpeed.class)
* @return An instance of the requested Measurement which may or may
* not have a value.
* @throws UnrecognizedMeasurementTypeException if passed a measurementType
* that does not extend Measurement
* @throws NoValueException if no value has yet been received for this
* measurementType
* @see BaseMeasurement
*/
public Measurement get(
Class<? extends Measurement> measurementType)
throws UnrecognizedMeasurementTypeException, NoValueException {
if(mRemoteService == null) {
Log.w(TAG, "Not connected to the VehicleService
"throwing a NoValueException");
throw new NoValueException();
}
Log.d(TAG, "Looking up measurement for " + measurementType);
try {
RawMeasurement rawMeasurement = mRemoteService.get(
BaseMeasurement.getIdForClass(measurementType));
return BaseMeasurement.getMeasurementFromRaw(measurementType,
rawMeasurement);
} catch(RemoteException e) {
Log.w(TAG, "Unable to get value from remote vehicle service", e);
throw new NoValueException();
}
}
/**
* Send a command back to the vehicle.
*
* This fails silently if it is unable to connect to the remote vehicle
* service.
*
* @param command The desired command to send to the vehicle.
*/
public void set(Measurement command) throws
UnrecognizedMeasurementTypeException {
Log.d(TAG, "Sending command " + command);
// TODO measurement should know how to convert itself back to raw...
// or maybe we don't even need raw in this case. oh wait, we can't
// send templated class over AIDL so we do.
RawMeasurement rawCommand = new RawMeasurement(command.getGenericName(),
command.getSerializedValue(),
command.getSerializedEvent());
// prefer the Bluetooth controller, if connected
if(mBluetoothSource != null) {
Log.d(TAG, "Sending " + rawCommand + " over Bluetooth to " +
mBluetoothSource);
mBluetoothSource.set(rawCommand);
} else {
if(mRemoteService == null) {
Log.w(TAG, "Not connected to the VehicleService");
return;
}
try {
mRemoteService.set(rawCommand);
} catch(RemoteException e) {
Log.w(TAG, "Unable to send command to remote vehicle service",
e);
}
}
}
/**
* Register to receive async updates for a specific Measurement type.
*
* Use this method to register an object implementing the
* Measurement.Listener interface to receive real-time updates
* whenever a new value is received for the specified measurementType.
*
* @param measurementType The class of the Measurement
* (e.g. VehicleSpeed.class) the listener was listening for
* @param listener An Measurement.Listener instance that was
* previously registered with addListener
* @throws VehicleServiceException if the listener is unable to be
* unregistered with the library internals - an exceptional situation
* that shouldn't occur.
* @throws UnrecognizedMeasurementTypeException if passed a measurementType
* not extend Measurement
*/
public void addListener(
Class<? extends Measurement> measurementType,
Measurement.Listener listener)
throws VehicleServiceException,
UnrecognizedMeasurementTypeException {
Log.i(TAG, "Adding listener " + listener + " to " + measurementType);
mNotifier.register(measurementType, listener);
}
/**
* Reset vehicle service to use only the default vehicle sources.
*
* The default vehicle data source is USB. If a USB CAN translator is not
* connected, there will be no more data.
*
* @throws VehicleServiceException if the listener is unable to be
* unregistered with the library internals - an exceptional situation
* that shouldn't occur.
*/
public void initializeDefaultSources()
throws VehicleServiceException {
Log.i(TAG, "Resetting data sources");
if(mRemoteService != null) {
try {
mRemoteService.initializeDefaultSources();
} catch(RemoteException e) {
throw new VehicleServiceException(
"Unable to reset data sources");
}
} else {
Log.w(TAG, "Can't reset data sources
"not connected to remote service yet");
}
}
public void clearSources() throws VehicleServiceException {
Log.i(TAG, "Clearing all data sources");
if(mRemoteService != null) {
try {
mRemoteService.clearSources();
} catch(RemoteException e) {
throw new VehicleServiceException(
"Unable to clear data sources");
}
} else {
Log.w(TAG, "Can't clear all data sources
"not connected to remote service yet");
}
mSources.clear();
}
/**
* Unregister a previously reigstered Measurement.Listener instance.
*
* When an application is no longer interested in received measurement
* updates (e.g. when it's pausing or exiting) it should unregister all
* previously registered listeners to save on CPU.
*
* @param measurementType The class of the requested Measurement
* (e.g. VehicleSpeed.class)
* @param listener An object implementing the Measurement.Listener
* interface that should be called with any new measurements.
* @throws VehicleServiceException if the listener is unable to be
* registered with the library internals - an exceptional situation
* that shouldn't occur.
* @throws UnrecognizedMeasurementTypeException if passed a class that does
* not extend Measurement
*/
public void removeListener(Class<? extends Measurement>
measurementType, Measurement.Listener listener)
throws VehicleServiceException {
Log.i(TAG, "Removing listener " + listener + " from " +
measurementType);
mNotifier.unregister(measurementType, listener);
}
/**
* Add a new data source to the vehicle service.
*
* For example, to use the trace data source to playback a trace file, call
* the addSource method after binding with VehicleManager:
*
* service.addSource(new TraceVehicleDataSource(
* new URI("/sdcard/openxc/trace.json"))));
*
* The {@link UsbVehicleDataSource} exists by default with the default USB
* device ID. To clear all existing sources, use the {@link #clearSources()}
* method. To revert back to the default set of sources, use
* {@link #initializeDefaultSources}.
*
* @param source an instance of a VehicleDataSource
*/
public void addSource(VehicleDataSource source) {
Log.i(TAG, "Adding data source " + source);
source.setCallback(this);
mSources.add(source);
}
/**
* Return a list of all sources active in the system, suitable for
* displaying in a status view.
*
* This method is soley for being able to peek into the system to see what's
* active, which is why it returns strings intead of the actual source
* objects. We don't want applications to be able to modify the sources
* through this method.
*
* @return A list of the names and status of all sources.
*/
public List<String> getSourceSummaries() {
ArrayList<String> sources = new ArrayList<String>();
for(VehicleDataSource source : mSources) {
sources.add(source.toString());
}
for(VehicleDataSource source : mPipeline.getSources()) {
sources.add(source.toString());
}
if(mRemoteService != null) {
try {
sources.addAll(mRemoteService.getSourceSummaries());
} catch(RemoteException e) {
Log.w(TAG, "Unable to retreive remote source summaries", e);
}
}
return sources;
}
/**
* Return a list of all sinks active in the system.
*
* The motivation for this method is the same as {@link #getSources}.
*
* @return A list of the names and status of all sinks.
*/
public List<String> getSinkSummaries() {
ArrayList<String> sinks = new ArrayList<String>();
for(VehicleDataSink sink : mPipeline.getSinks()) {
sinks.add(sink.toString());
}
if(mRemoteService != null) {
try {
sinks.addAll(mRemoteService.getSinkSummaries());
} catch(RemoteException e) {
Log.w(TAG, "Unable to retreive remote sink summaries", e);
}
}
return sinks;
}
/**
* Remove a previously registered source from the data pipeline.
*/
public void removeSource(VehicleDataSource source) {
if(source != null) {
mSources.remove(source);
source.stop();
}
}
/**
* Add a new data sink to the vehicle service.
*
* A data sink added with this method will receive all new measurements as
* they arrive from registered data sources. For example, to use the trace
* file recorder sink, call the addSink method after binding with
* VehicleManager:
*
* service.addSink(new FileRecorderSink(
* new AndroidFileOpener("openxc", this)));
*
* @param sink an instance of a VehicleDataSink
*/
public void addSink(VehicleDataSink sink) {
Log.i(TAG, "Adding data sink " + sink);
mPipeline.addSink(sink);
}
/**
* Remove a previously registered sink from the data pipeline.
*/
public void removeSink(VehicleDataSink sink) {
if(sink != null) {
mPipeline.removeSink(sink);
sink.stop();
}
}
/**
* Enable or disable uploading of a vehicle trace to a remote web server.
*
* The URL of the web server to upload the trace to is read from the shared
* preferences.
*
* @param enabled true if uploading should be enabled
* @throws VehicleServiceException if the listener is unable to be
* unregistered with the library internals - an exceptional situation
* that shouldn't occur.
*/
public void setUploadingStatus(boolean enabled)
throws VehicleServiceException {
Log.i(TAG, "Setting uploading to " + enabled);
if(enabled) {
String path = mPreferences.getString(
getString(R.string.uploading_path_key), null);
String error = "Target URL in preferences not valid " +
"-- not starting uploading a trace";
if(!UploaderSink.validatePath(path)) {
Log.w(TAG, error);
} else {
try {
mUploader = mPipeline.addSink(new UploaderSink(this, path));
} catch(java.net.URISyntaxException e) {
Log.w(TAG, error, e);
}
}
} else {
mPipeline.removeSink(mUploader);
}
}
/**
* Enable or disable receiving vehicle data from a Bluetooth CAN device.
*
* @param enabled true if bluetooth should be enabled
* @throws VehicleServiceException if the listener is unable to be
* unregistered with the library internals - an exceptional
* situation that shouldn't occur.
*/
public void setBluetoothSourceStatus(boolean enabled)
throws VehicleServiceException {
Log.i(TAG, "Setting bluetooth data source to " + enabled);
if(enabled) {
String deviceAddress = mPreferences.getString(
getString(R.string.bluetooth_mac_key), null);
if(deviceAddress != null) {
if(mBluetoothSource != null) {
mBluetoothSource.close();
}
try {
mBluetoothSource =
new BluetoothVehicleDataSource(this, deviceAddress);
} catch(DataSourceException e) {
Log.w(TAG, "Unable to add Bluetooth source", e);
return;
}
addSource(mBluetoothSource);
} else {
Log.d(TAG, "No Bluetooth device MAC set yet (" + deviceAddress +
"), not starting source");
}
}
else {
removeSource(mBluetoothSource);
if(mBluetoothSource != null) {
mBluetoothSource.close();
}
}
}
/**
* Enable or disable recording of a trace file.
*
* @param enabled true if recording should be enabled
* @throws VehicleServiceException if the listener is unable to be
* unregistered with the library internals - an exceptional
* situation that shouldn't occur.
*/
public void setFileRecordingStatus(boolean enabled)
throws VehicleServiceException {
Log.i(TAG, "Setting recording to " + enabled);
if(enabled) {
String directory = mPreferences.getString(
getString(R.string.recording_directory_key), null);
try {
mFileRecorder = mPipeline.addSink(new FileRecorderSink(
new AndroidFileOpener(this, directory)));
} catch(DataSinkException e) {
Log.w(TAG, "Unable to start trace recording", e);
}
}
else {
mPipeline.removeSink(mFileRecorder);
}
}
/**
* Enable or disable reading GPS from the native Android stack.
*
* @param enabled true if native GPS should be passed through
* @throws VehicleServiceException if native GPS status is unable to be set
* - an exceptional situation that shouldn't occur.
*/
public void setNativeGpsStatus(boolean enabled)
throws VehicleServiceException {
Log.i(TAG, "Setting native GPS to " + enabled);
if(enabled) {
mNativeLocationSource = mPipeline.addSource(
new NativeLocationSource(this));
} else if(mNativeLocationSource != null) {
mPipeline.removeSource(mNativeLocationSource);
mNativeLocationSource = null;
}
}
/**
* Enable or disable overwriting native GPS measurements with those from the
* vehicle.
*
* @see MockedLocationSink#setOverwritingStatus
*
* @param enabled true if native GPS should be overwritte.
* @throws VehicleServiceException if GPS overwriting status is unable to be
* set - an exceptional situation that shouldn't occur.
*/
public void setNativeGpsOverwriteStatus(boolean enabled)
throws VehicleServiceException {
Log.i(TAG, "Setting native GPS overwriting to " + enabled);
mMockedLocationSink.setOverwritingStatus(enabled);
}
/**
* Read the number of messages received by the vehicle service.
*
* @throws VehicleServiceException if the listener is unable to be
* unregistered with the library internals - an exceptional situation
* that shouldn't occur.
*/
public int getMessageCount() throws VehicleServiceException {
if(mRemoteService != null) {
try {
return mRemoteService.getMessageCount();
} catch(RemoteException e) {
throw new VehicleServiceException(
"Unable to retrieve message count", e);
}
} else {
throw new VehicleServiceException(
"Unable to retrieve message count");
}
}
@Override
public String toString() {
return Objects.toStringHelper(this)
.add("bound", mIsBound)
.toString();
}
public void receive(RawMeasurement measurement) {
if(mRemoteService != null) {
try {
mRemoteService.receive(measurement);
} catch(RemoteException e) {
Log.d(TAG, "Unable to send message to remote service", e);
}
}
}
private void unwatchPreferences(SharedPreferences preferences,
PreferenceListener listener) {
if(preferences != null && listener != null) {
preferences.unregisterOnSharedPreferenceChangeListener(listener);
}
}
private PreferenceListener watchPreferences(SharedPreferences preferences) {
if(preferences != null) {
PreferenceListener listener = new PreferenceListener(preferences);
preferences.registerOnSharedPreferenceChangeListener(listener);
return listener;
}
return null;
}
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder service) {
Log.i(TAG, "Bound to VehicleService");
mRemoteService = VehicleServiceInterface.Stub.asInterface(
service);
mRemoteSource = new RemoteListenerSource(mRemoteService);
mPipeline.addSource(mRemoteSource);
mPreferenceListener.readStoredPreferences();
mRemoteBoundLock.lock();
mIsBound = true;
mRemoteBoundCondition.signal();
mRemoteBoundLock.unlock();
}
public void onServiceDisconnected(ComponentName className) {
Log.w(TAG, "VehicleService disconnected unexpectedly");
mRemoteService = null;
mIsBound = false;
mPipeline.removeSource(mRemoteSource);
}
};
private void bindRemote() {
Log.i(TAG, "Binding to VehicleService");
Intent intent = new Intent(
VehicleServiceInterface.class.getName());
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
private void unbindRemote() {
if(mRemoteBoundLock != null) {
mRemoteBoundLock.lock();
}
if(mIsBound) {
Log.i(TAG, "Unbinding from VehicleService");
unbindService(mConnection);
mIsBound = false;
}
if(mRemoteBoundLock != null) {
mRemoteBoundLock.unlock();
}
}
private class PreferenceListener
implements SharedPreferences.OnSharedPreferenceChangeListener {
SharedPreferences mPreferences;
public PreferenceListener(SharedPreferences preferences) {
mPreferences = preferences;
}
public void readStoredPreferences() {
try {
setFileRecordingStatus(mPreferences.getBoolean(
getString(R.string.recording_checkbox_key), false));
setNativeGpsStatus(mPreferences.getBoolean(
getString(R.string.native_gps_checkbox_key), false));
setNativeGpsOverwriteStatus(mPreferences.getBoolean(
getString(R.string.gps_overwrite_checkbox_key),
false));
setUploadingStatus(mPreferences.getBoolean(
getString(R.string.uploading_checkbox_key), false));
setBluetoothSourceStatus(mPreferences.getBoolean(
getString(R.string.bluetooth_checkbox_key), false));
} catch(VehicleServiceException e) {
Log.w(TAG, "Unable to initialize vehicle service with stored "
+ "preferences", e);
}
}
public void onSharedPreferenceChanged(SharedPreferences preferences,
String key) {
try {
if(key.equals(getString(R.string.recording_checkbox_key))) {
setFileRecordingStatus(preferences.getBoolean(key, false));
} else if(key.equals(getString(R.string.native_gps_checkbox_key))) {
setNativeGpsStatus(preferences.getBoolean(key, false));
} else if(key.equals(getString(R.string.gps_overwrite_checkbox_key))) {
setNativeGpsOverwriteStatus(preferences.getBoolean(key, false));
} else if(key.equals(getString(R.string.uploading_checkbox_key))) {
setUploadingStatus(preferences.getBoolean(key, false));
} else if(key.equals(getString(R.string.bluetooth_checkbox_key))
|| key.equals(getString(R.string.bluetooth_mac_key))) {
setBluetoothSourceStatus(preferences.getBoolean(
getString(R.string.bluetooth_checkbox_key), false));
}
} catch(VehicleServiceException e) {
Log.w(TAG, "Unable to update vehicle service when preference \""
+ key + "\" changed", e);
}
}
}
} |
package com.cloudera.kitten.appmaster;
import gr.ntua.cslab.asap.rest.beans.OperatorDictionary;
import gr.ntua.cslab.asap.rest.beans.WorkflowDictionary;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class AbstractClient {
private static final Log LOG = LogFactory.getLog(AbstractClient.class);
/**
* Issues a new Request and returns a string with the response - if any.
* @param requestType
* @param document
* @param input
* @return
* @throws MalformedURLException
* @throws IOException
*/
public static String issueRequest(String id, WorkflowDictionary workflow) {
String urlString = "http://master:1323/runningWorkflows/report/"+id+"/";
String ret="";
try {
LOG.info("Issuing urlString: "+urlString);
System.out.println("Issuing urlString: "+urlString);
URL url = new URL(urlString);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("accept", "application/octet-stream");
con.setRequestProperty("Content-type", "application/octet-stream");
con.setDoInput(true);
con.setDoOutput(true);
OutputStream out = con.getOutputStream();
JAXBContext jaxbContext = JAXBContext.newInstance(WorkflowDictionary.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(workflow,out);
int responseCode = con.getResponseCode();
StringBuilder builder = new StringBuilder();
InputStream in = con.getInputStream();
byte[] buffer = new byte[1024];
int count;
while((count = in.read(buffer))!=-1) {
builder.append(new String(buffer,0,count));
}
ret = builder.toString();
System.out.println("Output: "+ret);
LOG.info("Output: "+ret);
} catch (Exception e) {
LOG.error(e.getStackTrace());
e.printStackTrace();
}
return ret;
}
} |
package org.jboss.as.clustering.infinispan.invoker;
import org.infinispan.Cache;
import org.infinispan.configuration.cache.TransactionConfiguration;
import org.infinispan.context.Flag;
import org.infinispan.transaction.LockingMode;
/**
* Locates a value from the cache.
* @author Paul Ferraro
*/
public interface Locator<K, V> {
/**
* Locates the value in the cache with the specified identifier.
* @param id the cache entry identifier
* @return the value of the cache entry, or null if not found.
*/
V findValue(K id);
/**
* Reusable lookup operation.
*/
class FindOperation<K, V> implements CacheInvoker.Operation<K, V, V> {
final K key;
public FindOperation(K key) {
this.key = key;
}
@Override
public V invoke(Cache<K, V> cache) {
return cache.get(this.key);
}
}
/**
* Reusable lookup operation.that first acquires a pessimistic lock if necessary.
*/
class LockingFindOperation<K, V> extends FindOperation<K, V> {
public LockingFindOperation(K key) {
super(key);
}
@Override
public V invoke(Cache<K, V> cache) {
TransactionConfiguration transaction = cache.getCacheConfiguration().transaction();
if (transaction.transactionMode().isTransactional()) {
if (transaction.lockingMode() == LockingMode.PESSIMISTIC) {
return super.invoke(cache.getAdvancedCache().withFlags(Flag.FORCE_WRITE_LOCK));
}
}
return super.invoke(cache);
}
}
} |
package org.ccnx.ccn.impl;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.PortUnreachableException;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Timer;
import java.util.logging.Level;
import org.ccnx.ccn.config.SystemConfiguration;
import org.ccnx.ccn.impl.CCNNetworkManager.NetworkProtocol;
import org.ccnx.ccn.impl.encoding.XMLEncodable;
import org.ccnx.ccn.impl.support.Log;
import org.ccnx.ccn.protocol.WirePacket;
/**
* This guy manages all of the access to the network connection.
* It is capable of supporting both UDP and TCP transport protocols
*
* It also creates a stream interface for input to the decoders. It is necessary to
* create our own input stream for TCP because the stream that can be obtained via the
* socket interface is not markable. Originally the UDP code used to translate the UDP
* input data into a ByteArrayInputStream after reading it in, but we now an use the
* same input stream for both transports.
*/
public class CCNNetworkChannel extends InputStream {
public static final int HEARTBEAT_PERIOD = 3500;
public static final int SOCKET_TIMEOUT = SystemConfiguration.MEDIUM_TIMEOUT; // period to wait in ms.
public static final int DOWN_DELAY = SystemConfiguration.SHORT_TIMEOUT; // Wait period for retry when ccnd is down
public static final int LINGER_TIME = 10; // In seconds
protected String _ncHost;
protected int _ncPort;
protected NetworkProtocol _ncProto;
protected int _ncLocalPort;
protected DatagramChannel _ncDGrmChannel = null;
protected SocketChannel _ncSockChannel = null;
protected Selector _ncReadSelector = null;
protected Selector _ncWriteSelector = null; // Not needed for UDP
protected Boolean _ncConnected = new Boolean(false); // Actually asking the channel if its connected doesn't appear to be reliable
protected boolean _ncInitialized = false;
protected Timer _ncHeartBeatTimer = null;
protected Boolean _ncStarted = false;
protected FileOutputStream _ncTapStreamIn = null;
// Allocate datagram buffer
protected ByteBuffer _datagram = ByteBuffer.allocateDirect(CCNNetworkManager.MAX_PAYLOAD);
// The following lines can be uncommented to help with debugging (i.e. you can't easily look at
// what's in the buffer when an allocateDirect is done.
// TODO - this should be under the control of a debugging flag instead
//private byte[] buffer = new byte[MAX_PAYLOAD];
//protected ByteBuffer _datagram = ByteBuffer.wrap(buffer);
private int _mark = -1;
private int _readLimit = 0;
private int _lastMark = 0;
public CCNNetworkChannel(String host, int port, NetworkProtocol proto, FileOutputStream tapStreamIn) throws IOException {
_ncHost = host;
_ncPort = port;
_ncProto = proto;
_ncTapStreamIn = tapStreamIn;
_ncReadSelector = Selector.open();
if (Log.isLoggable(Log.FAC_NETMANAGER, Level.INFO))
Log.info(Log.FAC_NETMANAGER, "Starting up CCNNetworkChannel using {0}.", proto);
}
/**
* Open the channel to ccnd depending on the protocol, connect on the ccnd port and
* set up the selector
*
* @throws IOException
*/
public void open() throws IOException {
if (_ncProto == NetworkProtocol.UDP) {
try {
_ncDGrmChannel = DatagramChannel.open();
_ncDGrmChannel.connect(new InetSocketAddress(_ncHost, _ncPort));
_ncDGrmChannel.configureBlocking(false);
// For some weird reason we seem to have to test writing twice when ccnd is down
// before the channel actually notices. There might be some kind of timing/locking
// problem responsible for this but I can't figure out what it is.
ByteBuffer test = ByteBuffer.allocate(1);
if (_ncInitialized)
_ncDGrmChannel.write(test);
wakeup();
_ncDGrmChannel.register(_ncReadSelector, SelectionKey.OP_READ);
_ncLocalPort = _ncDGrmChannel.socket().getLocalPort();
if (_ncInitialized) {
test.flip();
_ncDGrmChannel.write(test);
}
} catch (IOException ioe) {
return;
}
} else if (_ncProto == NetworkProtocol.TCP) {
_ncSockChannel = SocketChannel.open();
_ncSockChannel.connect(new InetSocketAddress(_ncHost, _ncPort));
_ncSockChannel.configureBlocking(false);
_ncSockChannel.register(_ncReadSelector, SelectionKey.OP_READ);
_ncWriteSelector = Selector.open();
_ncSockChannel.register(_ncWriteSelector, SelectionKey.OP_WRITE);
_ncLocalPort = _ncSockChannel.socket().getLocalPort();
//_ncSockChannel.socket().setSoLinger(true, LINGER_TIME);
} else {
throw new IOException("NetworkChannel: invalid protocol specified");
}
String connecting = (_ncInitialized ? "Reconnecting to" : "Contacting");
if (Log.isLoggable(Log.FAC_NETMANAGER, Level.INFO))
Log.info(Log.FAC_NETMANAGER, connecting + " CCN agent at " + _ncHost + ":" + _ncPort + " on local port " + _ncLocalPort);
initStream();
_ncInitialized = true;
_ncConnected = true;
}
/**
* Get the next packet from the network. It could be either an interest or data. If ccnd is
* down this is where we do a sleep to avoid a busy wait. We go ahead and try to read in
* the initial data here also because if there isn't any we want to find out here, not in the middle
* of thinking we might be able to decode something. Also since this is supposed to happen
* on packet boundaries, we reset the data buffer to its start during the initial read. We only do
* the initial read if there's nothing already in the buffer though because in TCP we could have
* read in some or all of a preceding packet during the last reading.
*
* Also it should be noted that we are relying on ccnd to guarantee that all packets sent
* to us are complete ccn packets. This code does not have the ability to recover from
* receiving a partial ccn packet followed by correctly formed ones.
*
* @return a ContentObject, an Interest, or null if there's no data waiting
* @throws IOException
*/
public XMLEncodable getPacket() throws IOException {
if (isConnected()) {
_mark = -1;
_readLimit = 0;
if (! _datagram.hasRemaining()) {
int ret = doReadIn(0);
if (ret <= 0 || !isConnected())
return null;
}
WirePacket packet = new WirePacket();
packet.decode(this);
return packet.getPacket();
} else {
try {
Thread.sleep(DOWN_DELAY);
} catch (InterruptedException e) {}
}
return null;
}
/**
* Close the channel depending on the protocol
* @throws IOException
*/
public void close() throws IOException {
_ncConnected = false;
if (_ncProto == NetworkProtocol.UDP) {
wakeup();
_ncDGrmChannel.close();
} else if (_ncProto == NetworkProtocol.TCP) {
_ncSockChannel.close();
} else {
throw new IOException("NetworkChannel: invalid protocol specified");
}
}
/**
* Check whether the channel is currently connected. This is really a test
* to see whether ccnd is running. If it isn't the channel is not connected.
* @return true if connected
*/
public boolean isConnected() {
return _ncConnected;
}
/**
* Write to ccnd using methods based on the protocol type
* @param src - ByteBuffer to write
* @return - number of bytes written
* @throws IOException
*/
public int write(ByteBuffer src) throws IOException {
if (! _ncConnected)
return -1; // XXX - is this documented?
if (Log.isLoggable(Log.FAC_NETMANAGER, Level.FINEST))
Log.finest(Log.FAC_NETMANAGER, "NetworkChannel.write() on port " + _ncLocalPort);
try {
if (_ncProto == NetworkProtocol.UDP) {
return (_ncDGrmChannel.write(src));
} else {
// Need to handle partial writes
int written = 0;
while (src.hasRemaining()) {
if (! _ncConnected)
return -1;
int b = _ncSockChannel.write(src);
if (b > 0) {
written += b;
} else {
_ncWriteSelector.selectedKeys().clear();
_ncWriteSelector.select();
}
}
return written;
}
} catch (PortUnreachableException pue) {}
catch (ClosedChannelException cce) {}
close();
return -1;
}
/**
* Force wakeup from a select
* @return the selector
*/
public Selector wakeup() {
return (_ncReadSelector.wakeup());
}
/**
* Initialize the channel at the point when we are actually ready to create faces
* with ccnd
* @throws IOException
*/
public void init() throws IOException {
}
private void initStream() {
_datagram.clear();
_datagram.limit(0);
}
@Override
public int read() throws IOException {
while (true) {
try {
if (_datagram.hasRemaining()) {
int ret = (int)_datagram.get();
return ret & 0xff;
}
} catch (BufferUnderflowException bfe) {}
int ret = fill();
if (ret < 0) {
return ret;
}
}
}
@Override
public int read(byte[] b) throws IOException {
return read(b, 0, b.length);
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
int ret = 0;
if (len > b.length - off) {
throw new IndexOutOfBoundsException();
}
if (! _datagram.hasRemaining()) {
int tmpRet = fill();
if (tmpRet <= 0) {
return tmpRet;
}
}
ret = _datagram.remaining() > len ? len : _datagram.remaining();
_datagram.get(b, off, ret);
return ret;
}
@Override
public boolean markSupported() {
return true;
}
@Override
public void mark(int readlimit) {
_readLimit = readlimit;
_mark = _datagram.position();
}
@Override
public void reset() throws IOException {
if (_mark < 0)
throw new IOException("Reset called with no mark set - readlimit: " + _readLimit + " lastMark: " + _lastMark);
if ((_datagram.position() - _mark) > _readLimit) {
throw new IOException("Invalid reset called past readlimit");
}
_datagram.position(_mark);
}
/**
* Refill the buffer. We don't reset the start of it unless necessary (i.e. we have
* reached the end of the buffer). If the start is reset and a mark has been set within
* "readLimit" bytes of the end, we need to copy the end of the previous buffer out
* to the start so that a reset is possible.
*
* @return
* @throws IOException
*/
private int fill() throws IOException {
int position = _datagram.position();
if (position >= _datagram.capacity()) {
byte[] b = null;
boolean doCopy = false;
int checkPosition = position - 1;
doCopy = _mark >= 0 && _mark + _readLimit >= checkPosition;
if (doCopy) {
b = new byte[checkPosition - (_mark - 1)];
_datagram.position(_mark);
_datagram.get(b);
}
_datagram.clear();
if (doCopy) {
_datagram.put(b);
_mark = 0;
} else {
_lastMark = _mark;
_mark = -1;
}
position = _datagram.position();
}
return doReadIn(position);
}
/**
* Read in data to the buffer starting at the specified position.
* @param position
* @return
* @throws IOException
*/
private int doReadIn(int position) throws IOException {
int ret = 0;
_ncReadSelector.selectedKeys().clear();
if (_ncReadSelector.select() != 0) {
if (! _ncConnected)
return -1;
// Note that we must set limit first before setting position because setting
// position larger than limit causes an exception.
_datagram.limit(_datagram.capacity());
_datagram.position(position);
if (_ncProto == NetworkProtocol.UDP) {
ret = _ncDGrmChannel.read(_datagram);
} else {
ret = _ncSockChannel.read(_datagram);
}
if (ret >= 0) {
// The following is the equivalent to doing a flip except we don't
// want to reset the position to 0 as flip would do (because we
// potentially want to preserve a mark). But the read positions
// the buffer to end of the read and we want to reposition to the start
// of the data just read in.
_datagram.limit(position + ret);
_datagram.position(position);
if (null != _ncTapStreamIn) {
byte [] b = new byte[ret];
_datagram.get(b);
_ncTapStreamIn.write(b);
// Got the data so we have to redo the "hand flip" to read from the
// correct position.
_datagram.limit(position + ret);
_datagram.position(position);
}
} else
close();
}
return ret;
}
/**
* @return true if heartbeat sent
*/
public boolean heartbeat() {
try {
ByteBuffer heartbeat = ByteBuffer.allocate(1);
_ncDGrmChannel.write(heartbeat);
return true;
} catch (IOException io) {
// We do not see errors on send typically even if
// agent is gone, so log each but do not track
Log.warning(Log.FAC_NETMANAGER, "Error sending heartbeat packet: {0}", io.getMessage());
try {
close();
} catch (IOException e) {}
}
return false;
}
} /* NetworkChannel */ |
package org.jboss.as.controller.operations.global;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ACCESS_CONTROL;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ATTRIBUTES;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.DEFAULT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FAILURE_DESCRIPTION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_ATTRIBUTE_OPERATION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_RESOURCE_OPERATION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT;
import static org.jboss.as.controller.operations.global.GlobalOperationAttributes.INCLUDE_ALIASES;
import static org.jboss.as.controller.operations.global.GlobalOperationAttributes.INCLUDE_DEFAULTS;
import static org.jboss.as.controller.operations.global.GlobalOperationAttributes.INCLUDE_RUNTIME;
import static org.jboss.as.controller.operations.global.GlobalOperationAttributes.PROXIES;
import static org.jboss.as.controller.operations.global.GlobalOperationAttributes.RECURSIVE;
import static org.jboss.as.controller.operations.global.GlobalOperationAttributes.RECURSIVE_DEPTH;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.NoSuchResourceException;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationDefinition;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.SimpleOperationDefinitionBuilder;
import org.jboss.as.controller.UnauthorizedException;
import org.jboss.as.controller.access.Action;
import org.jboss.as.controller.access.AuthorizationResult;
import org.jboss.as.controller.descriptions.DescriptionProvider;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.descriptions.common.ControllerResolver;
import org.jboss.as.controller.logging.ControllerLogger;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.controller.operations.validation.ParametersValidator;
import org.jboss.as.controller.registry.AttributeAccess;
import org.jboss.as.controller.registry.ImmutableManagementResourceRegistration;
import org.jboss.as.controller.registry.PlaceholderResource;
import org.jboss.as.controller.registry.Resource;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import org.jboss.dmr.Property;
/**
* {@link org.jboss.as.controller.OperationStepHandler} reading a part of the model. The result will only contain the current attributes of a node by default,
* excluding all addressable children and runtime attributes. Setting the request parameter "recursive" to "true" will recursively include
* all children and configuration attributes. Queries can include runtime attributes by setting the request parameter
* "include-runtime" to "true".
*
* @author <a href="kabir.khan@jboss.com">Kabir Khan</a>
*/
public class ReadResourceHandler extends GlobalOperationHandlers.AbstractMultiTargetHandler {
private static final SimpleAttributeDefinition ATTRIBUTES_ONLY = new SimpleAttributeDefinitionBuilder(ModelDescriptionConstants.ATTRIBUTES_ONLY, ModelType.BOOLEAN)
.setAllowNull(true)
.setDefaultValue(new ModelNode(false))
.build();
public static final OperationDefinition DEFINITION = new SimpleOperationDefinitionBuilder(READ_RESOURCE_OPERATION, ControllerResolver.getResolver("global"))
.setParameters(RECURSIVE, RECURSIVE_DEPTH, PROXIES, INCLUDE_RUNTIME, INCLUDE_DEFAULTS, ATTRIBUTES_ONLY, INCLUDE_ALIASES)
.setReadOnly()
.setRuntimeOnly()
.setReplyType(ModelType.OBJECT)
.build();
public static final OperationStepHandler INSTANCE = new ReadResourceHandler();
private static final SimpleAttributeDefinition RESOLVE = new SimpleAttributeDefinitionBuilder(ModelDescriptionConstants.RESOLVE_EXPRESSIONS, ModelType.BOOLEAN)
.setAllowNull(true)
.setDefaultValue(new ModelNode(false))
.build();
public static final OperationDefinition RESOLVE_DEFINITION = new SimpleOperationDefinitionBuilder(READ_RESOURCE_OPERATION, ControllerResolver.getResolver("global"))
.setParameters(RESOLVE, RECURSIVE, RECURSIVE_DEPTH, PROXIES, INCLUDE_RUNTIME, INCLUDE_DEFAULTS, ATTRIBUTES_ONLY, INCLUDE_ALIASES)
.setReadOnly()
.setRuntimeOnly()
.setReplyType(ModelType.OBJECT)
.build();
public static final OperationStepHandler RESOLVE_INSTANCE = new ReadResourceHandler(true);
private final ParametersValidator validator = new ParametersValidator() {
@Override
public void validate(ModelNode operation) throws OperationFailedException {
super.validate(operation);
for (AttributeDefinition def : DEFINITION.getParameters()) {
def.validateOperation(operation);
}
if (operation.hasDefined(ModelDescriptionConstants.ATTRIBUTES_ONLY)) {
if (operation.hasDefined(ModelDescriptionConstants.RECURSIVE)) {
throw ControllerLogger.ROOT_LOGGER.cannotHaveBothParameters(ModelDescriptionConstants.ATTRIBUTES_ONLY, ModelDescriptionConstants.RECURSIVE);
}
if (operation.hasDefined(ModelDescriptionConstants.RECURSIVE_DEPTH)) {
throw ControllerLogger.ROOT_LOGGER.cannotHaveBothParameters(ModelDescriptionConstants.ATTRIBUTES_ONLY, ModelDescriptionConstants.RECURSIVE_DEPTH);
}
}
if( operation.hasDefined(ModelDescriptionConstants.RESOLVE_EXPRESSIONS)){
if(operation.get(ModelDescriptionConstants.RESOLVE_EXPRESSIONS).asBoolean(false) && !resolvable){
throw ControllerLogger.ROOT_LOGGER.unableToResolveExpressions();
}
}
}
};
private final OperationStepHandler overrideHandler;
private final boolean resolvable;
public ReadResourceHandler() {
this(null, null, false);
}
public ReadResourceHandler(boolean resolvable){
this(null,null,resolvable);
}
ReadResourceHandler(final FilteredData filteredData, OperationStepHandler overrideHandler, boolean resolvable) {
super(filteredData);
this.overrideHandler = overrideHandler;
this.resolvable = resolvable;
}
@Override
void doExecute(OperationContext context, ModelNode operation, FilteredData filteredData) throws OperationFailedException {
if (filteredData == null) {
doExecuteInternal(context, operation);
} else {
try {
if (overrideHandler == null) {
doExecuteInternal(context, operation);
} else {
overrideHandler.execute(context, operation);
}
} catch (NoSuchResourceException nsre) {
// Just report the failure to the filter and complete normally
PathAddress pa = PathAddress.pathAddress(operation.get(OP_ADDR));
filteredData.addAccessRestrictedResource(pa);
context.getResult().set(new ModelNode());
context.stepCompleted();
} catch (UnauthorizedException ue) {
// Just report the failure to the filter and complete normally
PathAddress pa = PathAddress.pathAddress(operation.get(OP_ADDR));
filteredData.addReadRestrictedResource(pa);
context.getResult().set(new ModelNode());
context.stepCompleted();
}
}
}
void doExecuteInternal(OperationContext context, ModelNode operation) throws OperationFailedException {
validator.validate(operation);
final String opName = operation.require(OP).asString();
final PathAddress address = PathAddress.pathAddress(operation.get(OP_ADDR));
// WFCORE-76
final boolean recursive = GlobalOperationHandlers.getRecursive(context, operation);
final boolean queryRuntime = operation.get(ModelDescriptionConstants.INCLUDE_RUNTIME).asBoolean(false);
final boolean proxies = operation.get(ModelDescriptionConstants.PROXIES).asBoolean(false);
final boolean aliases = operation.get(ModelDescriptionConstants.INCLUDE_ALIASES).asBoolean(false);
final boolean defaults = operation.get(ModelDescriptionConstants.INCLUDE_DEFAULTS).asBoolean(true);
final boolean attributesOnly = operation.get(ModelDescriptionConstants.ATTRIBUTES_ONLY).asBoolean(false);
final boolean resolve = RESOLVE.resolveModelAttribute(context, operation).asBoolean();
// Child types with no actual children
final Set<String> nonExistentChildTypes = new HashSet<String>();
// Children names read directly from the model where we didn't call read-resource to gather data
// We wouldn't call read-resource if the recursive=false
final Map<String, ModelNode> directChildren = new HashMap<String, ModelNode>();
// Attributes of AccessType.METRIC
final Map<String, ModelNode> metrics = queryRuntime ? new HashMap<String, ModelNode>() : Collections.<String, ModelNode>emptyMap();
// Non-AccessType.METRIC attributes with a special read handler registered
final Map<String, ModelNode> otherAttributes = new HashMap<String, ModelNode>();
// Child resources recursively read
final Map<PathElement, ModelNode> childResources = recursive ? new LinkedHashMap<PathElement, ModelNode>() : Collections.<PathElement, ModelNode>emptyMap();
final FilteredData localFilteredData = getFilteredData() == null ? new FilteredData(address) : getFilteredData();
// We're going to add a bunch of steps that should immediately follow this one. We are going to add them
// in reverse order of how they should execute, as that is the way adding a Stage.IMMEDIATE step works
final ReadResourceAssemblyHandler assemblyHandler = new ReadResourceAssemblyHandler(address, metrics,
otherAttributes, directChildren, childResources, nonExistentChildTypes, localFilteredData);
context.addStep(assemblyHandler, queryRuntime ? OperationContext.Stage.VERIFY : OperationContext.Stage.MODEL, true);
final ImmutableManagementResourceRegistration registry = context.getResourceRegistration();
// Get the model for this resource.
final Resource resource = nullSafeReadResource(context, registry);
final Map<String, Set<String>> childrenByType = registry != null ? GlobalOperationHandlers.getChildAddresses(context, address, registry, resource, null) : Collections.<String, Set<String>>emptyMap();
if (!attributesOnly) {
// Next, process child resources
for (Map.Entry<String, Set<String>> entry : childrenByType.entrySet()) {
String childType = entry.getKey();
// child type has no children until we add one
nonExistentChildTypes.add(childType);
if(!aliases && (entry.getValue() == null || entry.getValue().isEmpty())) {
if(isGlobalAlias(registry, childType)) {
nonExistentChildTypes.remove(childType);
}
}
for (String child : entry.getValue()) {
PathElement childPE = PathElement.pathElement(childType, child);
PathAddress absoluteChildAddr = address.append(childPE);
ModelNode rrOp = Util.createEmptyOperation(READ_RESOURCE_OPERATION, absoluteChildAddr);
PathAddress relativeAddr = PathAddress.pathAddress(childPE);
if (recursive) {
ImmutableManagementResourceRegistration childReg = registry.getSubModel(relativeAddr);
if (childReg == null) {
throw new OperationFailedException(ControllerLogger.ROOT_LOGGER.noChildRegistry(childType, child));
}
// Decide if we want to invoke on this child resource
boolean proxy = childReg.isRemote();
boolean runtimeResource = childReg.isRuntimeOnly();
boolean getChild = !runtimeResource || (queryRuntime && !proxy) || (proxies && proxy);
if (!aliases && childReg.isAlias()) {
nonExistentChildTypes.remove(childType);
getChild = false;
}
if (getChild) {
nonExistentChildTypes.remove(childType);
// WFCORE-76
GlobalOperationHandlers.setNextRecursive(context, operation, rrOp);
rrOp.get(ModelDescriptionConstants.PROXIES).set(proxies);
rrOp.get(ModelDescriptionConstants.INCLUDE_RUNTIME).set(queryRuntime);
rrOp.get(ModelDescriptionConstants.INCLUDE_ALIASES).set(aliases);
rrOp.get(ModelDescriptionConstants.INCLUDE_DEFAULTS).set(defaults);
ModelNode rrRsp = new ModelNode();
childResources.put(childPE, rrRsp);
// See if there was an override registered for the standard :read-resource handling (unlikely!!!)
OperationStepHandler overrideHandler = childReg.getOperationHandler(PathAddress.EMPTY_ADDRESS, opName);
if (overrideHandler != null && overrideHandler.getClass() == getClass()) {
// not an override
overrideHandler = null;
}
OperationStepHandler rrHandler = new ReadResourceHandler(localFilteredData, overrideHandler, resolvable);
context.addStep(rrRsp, rrOp, rrHandler, OperationContext.Stage.MODEL, true);
}
} else {
// Non-recursive. Just output the names of the children
// But filter inaccessible children
AuthorizationResult ar = context.authorize(rrOp, EnumSet.of(Action.ActionEffect.ADDRESS));
if (ar.getDecision() == AuthorizationResult.Decision.DENY) {
localFilteredData.addAccessRestrictedResource(absoluteChildAddr);
} else {
ModelNode childMap = directChildren.get(childType);
if (childMap == null) {
nonExistentChildTypes.remove(childType);
childMap = new ModelNode();
childMap.setEmptyObject();
directChildren.put(childType, childMap);
}
// Add a "child" => undefined
childMap.get(child);
}
}
}
}
}
// Handle registered attributes
final Set<String> attributeNames = registry != null ? registry.getAttributeNames(PathAddress.EMPTY_ADDRESS) : Collections.<String>emptySet();
for (final String attributeName : attributeNames) {
final AttributeAccess access = registry.getAttributeAccess(PathAddress.EMPTY_ADDRESS, attributeName);
if ((aliases || !access.getFlags().contains(AttributeAccess.Flag.ALIAS))
&& (queryRuntime || access.getStorageType() == AttributeAccess.Storage.CONFIGURATION)) {
Map<String, ModelNode> responseMap = access.getAccessType() == AttributeAccess.AccessType.METRIC ? metrics : otherAttributes;
addReadAttributeStep(context, address, defaults, resolve, localFilteredData, registry, attributeName, responseMap);
}
}
// Any attributes stored in the model but without a registry entry
final ModelNode model = resource.getModel();
if (model.isDefined()) {
for (String key : model.keys()) {
// Skip children and attributes already handled
if (!otherAttributes.containsKey(key) && !childrenByType.containsKey(key) && !metrics.containsKey(key)) {
addReadAttributeStep(context, address, defaults, resolve, localFilteredData, registry, key, otherAttributes);
}
}
}
// Last, if defaults are desired, look for unregistered attributes also not in the model
// by checking the resource description
if (defaults) {
//get the model description
final DescriptionProvider descriptionProvider = registry.getModelDescription(PathAddress.EMPTY_ADDRESS);
final Locale locale = GlobalOperationHandlers.getLocale(context, operation);
final ModelNode nodeDescription = descriptionProvider.getModelDescription(locale);
if (nodeDescription.isDefined() && nodeDescription.hasDefined(ATTRIBUTES)) {
for (String key : nodeDescription.get(ATTRIBUTES).keys()) {
if ((!childrenByType.containsKey(key)) &&
!otherAttributes.containsKey(key) &&
!metrics.containsKey(key) &&
nodeDescription.get(ATTRIBUTES).hasDefined(key) &&
nodeDescription.get(ATTRIBUTES, key).hasDefined(DEFAULT)) {
addReadAttributeStep(context, address, defaults, resolve, localFilteredData, registry, key, otherAttributes);
}
}
}
}
context.stepCompleted();
}
private boolean isSquatterResource(final ImmutableManagementResourceRegistration registry, final String key) {
return registry.getSubModel(PathAddress.pathAddress(PathElement.pathElement(key))) == null;
}
private boolean isGlobalAlias(final ImmutableManagementResourceRegistration registry, final String childName) {
if(isSquatterResource(registry, childName)) {
Set<PathElement> childrenPath = registry.getChildAddresses(PathAddress.EMPTY_ADDRESS);
boolean found = false;
boolean alias = true;
for(PathElement childPath : childrenPath) {
if(childPath.getKey().equals(childName)) {
found = true;
ImmutableManagementResourceRegistration squatterRegistration = registry.getSubModel(PathAddress.pathAddress(childPath));
alias = alias && (squatterRegistration != null && squatterRegistration.isAlias());
}
}
return (found && alias);
}
return registry.getSubModel(PathAddress.pathAddress(PathElement.pathElement(childName))).isAlias();
}
private void addReadAttributeStep(OperationContext context, PathAddress address, boolean defaults, boolean resolve, FilteredData localFilteredData, ImmutableManagementResourceRegistration registry, String attributeName, Map<String, ModelNode> responseMap) {
// See if there was an override registered for the standard :read-attribute handling (unlikely!!!)
OperationStepHandler overrideHandler = registry.getOperationHandler(PathAddress.EMPTY_ADDRESS, READ_ATTRIBUTE_OPERATION);
if (overrideHandler != null &&
(overrideHandler == ReadAttributeHandler.INSTANCE || overrideHandler == ReadAttributeHandler.RESOLVE_INSTANCE)) {
// not an override
overrideHandler = null;
}
OperationStepHandler readAttributeHandler = new ReadAttributeHandler(localFilteredData, overrideHandler, (resolve && resolvable));
final ModelNode attributeOperation = Util.getReadAttributeOperation(address, attributeName);
attributeOperation.get(ModelDescriptionConstants.INCLUDE_DEFAULTS).set(defaults);
attributeOperation.get(ModelDescriptionConstants.RESOLVE_EXPRESSIONS).set(resolve);
final ModelNode attrResponse = new ModelNode();
responseMap.put(attributeName, attrResponse);
context.addStep(attrResponse, attributeOperation, readAttributeHandler, OperationContext.Stage.MODEL, true);
}
/**
* Provides a resource for the current step, either from the context, if the context doesn't have one
* and {@code registry} is runtime-only, it creates a dummy resource.
*/
private static Resource nullSafeReadResource(final OperationContext context, final ImmutableManagementResourceRegistration registry) {
Resource result;
if (registry != null && registry.isRuntimeOnly()) {
try {
//TODO check that having changed this from false to true does not break anything
//If it does, consider adding a Resource.alwaysClone() method that can be used in
//OperationContextImpl.readResourceFromRoot(final PathAddress address, final boolean recursive)
//instead of the recursive check
result = context.readResource(PathAddress.EMPTY_ADDRESS, true);
} catch (RuntimeException e) {
result = PlaceholderResource.INSTANCE;
}
} else {
//TODO check that having changed this from false to true does not break anything
//If it does, consider adding a Resource.alwaysClone() method that can be used in
//OperationContextImpl.readResourceFromRoot(final PathAddress address, final boolean recursive)
//instead of the recursive check
result = context.readResource(PathAddress.EMPTY_ADDRESS, true);
}
return result;
}
/**
* Assembles the response to a read-resource request from the components gathered by earlier steps.
*/
private static class ReadResourceAssemblyHandler implements OperationStepHandler {
private final PathAddress address;
private final Map<String, ModelNode> directChildren;
private final Map<String, ModelNode> metrics;
private final Map<String, ModelNode> otherAttributes;
private final Map<PathElement, ModelNode> childResources;
private final Set<String> nonExistentChildTypes;
private final FilteredData filteredData;
/**
* Creates a ReadResourceAssemblyHandler that will assemble the response using the contents
* of the given maps.
*
* @param address address of the resource
* @param metrics map of attributes of AccessType.METRIC. Keys are the attribute names, values are the full
* read-attribute response from invoking the attribute's read handler. Will not be {@code null}
* @param otherAttributes map of attributes not of AccessType.METRIC that have a read handler registered. Keys
* are the attribute names, values are the full read-attribute response from invoking the
* attribute's read handler. Will not be {@code null}
* @param directChildren Children names read directly from the parent resource where we didn't call read-resource
* to gather data. We wouldn't call read-resource if the recursive=false
* @param childResources read-resource response from child resources, where the key is the PathAddress
* relative to the address of the operation this handler is handling and the
* value is the full read-resource response. Will not be {@code null}
* @param nonExistentChildTypes names of child types where no data is available
* @param filteredData information about resources and attributes that were filtered
*/
private ReadResourceAssemblyHandler(final PathAddress address,
final Map<String, ModelNode> metrics,
final Map<String, ModelNode> otherAttributes, final Map<String, ModelNode> directChildren,
final Map<PathElement, ModelNode> childResources, final Set<String> nonExistentChildTypes, FilteredData filteredData) {
this.address = address;
this.metrics = metrics;
this.otherAttributes = otherAttributes;
this.directChildren = directChildren;
this.childResources = childResources;
this.nonExistentChildTypes = nonExistentChildTypes;
this.filteredData = filteredData;
}
@Override
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
Map<String, ModelNode> sortedAttributes = new TreeMap<String, ModelNode>();
Map<String, ModelNode> sortedChildren = new TreeMap<String, ModelNode>();
boolean failed = false;
for (Map.Entry<String, ModelNode> entry : otherAttributes.entrySet()) {
ModelNode value = entry.getValue();
if (!value.has(FAILURE_DESCRIPTION)) {
sortedAttributes.put(entry.getKey(), value.get(RESULT));
} else if (value.hasDefined(FAILURE_DESCRIPTION)) {
context.getFailureDescription().set(value.get(FAILURE_DESCRIPTION));
failed = true;
break;
}
}
if (!failed) {
for (Map.Entry<PathElement, ModelNode> entry : childResources.entrySet()) {
PathElement path = entry.getKey();
ModelNode value = entry.getValue();
if (!value.has(FAILURE_DESCRIPTION)) {
ModelNode childTypeNode = sortedChildren.get(path.getKey());
if (childTypeNode == null) {
childTypeNode = new ModelNode();
sortedChildren.put(path.getKey(), childTypeNode);
}
childTypeNode.get(path.getValue()).set(value.get(RESULT));
} else if (!failed && value.hasDefined(FAILURE_DESCRIPTION)) {
context.getFailureDescription().set(value.get(FAILURE_DESCRIPTION));
failed = true;
}
}
}
if (!failed) {
for (Map.Entry<String, ModelNode> directChild : directChildren.entrySet()) {
sortedChildren.put(directChild.getKey(), directChild.getValue());
}
for (String nonExistentChildType : nonExistentChildTypes) {
sortedChildren.put(nonExistentChildType, new ModelNode());
}
for (Map.Entry<String, ModelNode> metric : metrics.entrySet()) {
ModelNode value = metric.getValue();
if (!value.has(FAILURE_DESCRIPTION)) {
sortedAttributes.put(metric.getKey(), value.get(RESULT));
}
// we ignore metric failures
// TODO how to prevent the metric failure screwing up the overall context?
}
final ModelNode result = context.getResult();
result.setEmptyObject();
for (Map.Entry<String, ModelNode> entry : sortedAttributes.entrySet()) {
result.get(entry.getKey()).set(entry.getValue());
}
for (Map.Entry<String, ModelNode> entry : sortedChildren.entrySet()) {
if (!entry.getValue().isDefined()) {
result.get(entry.getKey()).set(entry.getValue());
} else {
ModelNode childTypeNode = new ModelNode();
for (Property property : entry.getValue().asPropertyList()) {
PathElement pe = PathElement.pathElement(entry.getKey(), property.getName());
if (!filteredData.isFilteredResource(address, pe)) {
childTypeNode.get(property.getName()).set(property.getValue());
}
}
result.get(entry.getKey()).set(childTypeNode);
}
}
if (filteredData.hasFilteredData()) {
context.getResponseHeaders().get(ACCESS_CONTROL).set(filteredData.toModelNode());
}
}
context.stepCompleted();
}
}
} |
package it.unibz.inf.ontop.constraints;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import it.unibz.inf.ontop.model.atom.DataAtom;
import it.unibz.inf.ontop.model.term.*;
import java.util.*;
public class ImmutableHomomorphismUtilities {
public static boolean extendHomomorphism(Map<Variable, VariableOrGroundTerm> map, ImmutableList<? extends VariableOrGroundTerm> from, ImmutableList<? extends VariableOrGroundTerm> to) {
int arity = from.size();
if (arity != to.size())
return false;
for (int i = 0; i < arity; i++) {
// if we cannot find a match, terminate the process and return false
if (!extendHomomorphism(map, from.get(i), to.get(i)))
return false;
}
return true;
}
private static boolean extendHomomorphism(Map<Variable, VariableOrGroundTerm> map, VariableOrGroundTerm from, VariableOrGroundTerm to) {
if (from instanceof Variable) {
VariableOrGroundTerm t = map.put((Variable) from, to);
if (t != null && !t.equals(to)) {
// if there was a different value there
return false;
}
}
else if (from instanceof Constant) {
// constants must match
if (!from.equals(to))
return false;
}
else /*if (from instanceof GroundFunctionalTerm)*/ {
// the to term must also be a function
if (!(to instanceof GroundFunctionalTerm))
return false;
GroundFunctionalTerm fromF = (GroundFunctionalTerm)from;
GroundFunctionalTerm toF = (GroundFunctionalTerm)to;
if (!fromF.getFunctionSymbol().equals(toF.getFunctionSymbol()))
return false;
return extendHomomorphism(map, fromF.getTerms(), toF.getTerms());
}
return true;
}
private static Map<Variable, VariableOrGroundTerm> getSomeHomomorphicExtension(Map<Variable, VariableOrGroundTerm> map, DataAtom from, DataAtom to) {
if (!from.getPredicate().equals(to.getPredicate()))
return null;
Map<Variable, VariableOrGroundTerm> extension = new HashMap<>(map);
return extendHomomorphism(extension, from.getArguments(), to.getArguments())
? extension
: null;
}
private static final class State {
final Map<Variable, VariableOrGroundTerm> homomorphism;
final Queue<DataAtom> remainingAtomChoices;
final DataAtom currentAtom;
State(DataAtom currentAtom, Map<Variable, VariableOrGroundTerm> homomorphism, Collection<DataAtom> choices) {
this.currentAtom = currentAtom;
this.homomorphism = homomorphism;
this.remainingAtomChoices = new ArrayDeque<>(choices);
}
}
/**
* Extends a given substitution that maps each atom in {@code from} to match at least one atom in {@code to}
*
* @param map
* @param from
* @param to
* @return
*/
public static boolean hasSomeHomomorphism(Map<Variable, VariableOrGroundTerm> map, ImmutableList<DataAtom> from, ImmutableSet<DataAtom> to) {
ListIterator<DataAtom> iterator = from.listIterator();
if (!iterator.hasNext())
return true;
State state = new State(iterator.next(), map, to);
Stack<State> stack = new Stack<>();
while (true) {
DataAtom candidate = state.remainingAtomChoices.poll();
if (candidate != null) {
Map<Variable, VariableOrGroundTerm> ext = getSomeHomomorphicExtension(state.homomorphism, state.currentAtom, candidate);
if (ext != null) {
if (!iterator.hasNext()) // reached the last atom
return true;
// save the partial homomorphism for the next iteration
stack.push(state);
state = new State(iterator.next(), ext, to);
}
}
else {
if (stack.empty()) // checked all possible substitutions and found no match
return false;
// backtracking: restore the state and move back
state = stack.pop();
iterator.previous();
}
}
}
} |
package org.csstudio.platform.internal.data;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import org.csstudio.platform.data.IDoubleValue;
import org.csstudio.platform.data.INumericMetaData;
import org.csstudio.platform.data.ITimestamp;
import org.csstudio.platform.data.ISeverity;
/** Implementation of {@link IDoubleValue}.
* @author Kay Kasemir
*/
public class DoubleValue extends Value implements IDoubleValue
{
/** The values. */
final private double values[];
/** Constructor from pieces. */
public DoubleValue(final ITimestamp time, final ISeverity severity,
final String status, final INumericMetaData meta_data,
final Quality quality,
final double values[])
{
super(time, severity, status, meta_data, quality);
this.values = values;
}
/** {@inheritDoc} */
final public double[] getValues()
{ return values; }
/** {@inheritDoc} */
final public double getValue()
{ return values[0]; }
/** {@inheritDoc} */
@Override
public String format(Format how, int precision)
{
StringBuffer buf = new StringBuffer();
if (getSeverity().hasValue())
{
NumberFormat fmt;
if (how == Format.Exponential)
{ // Is there a better way to get this silly format?
StringBuffer pattern = new StringBuffer(10);
pattern.append("0."); //$NON-NLS-1$
for (int i=0; i<precision; ++i)
pattern.append('0');
pattern.append("E0"); //$NON-NLS-1$
fmt = new DecimalFormat(pattern.toString());
}
else
{
fmt = NumberFormat.getNumberInstance();
if (how == Format.Default)
{
final INumericMetaData num_meta = (INumericMetaData)getMetaData();
// Should have numeric meta data, but in case of errors
// that might be null.
if (num_meta != null)
precision = num_meta.getPrecision();
}
fmt.setMinimumFractionDigits(precision);
fmt.setMaximumFractionDigits(precision);
}
buf.append(formatDouble(fmt, values[0]));
for (int i = 1; i < values.length; i++)
{
buf.append(Messages.ArrayElementSeparator);
buf.append(formatDouble(fmt, values[i]));
}
}
else
buf.append(Messages.NoValue);
return buf.toString();
}
private String formatDouble(final NumberFormat fmt, double d)
{
if (Double.isInfinite(d))
return Messages.Infinite;
if (Double.isNaN(d))
return Messages.NaN;
return fmt.format(d);
}
/** {@inheritDoc} */
@Override
public boolean equals(final Object obj)
{
if (! (obj instanceof DoubleValue))
return false;
final DoubleValue rhs = (DoubleValue) obj;
if (rhs.values.length != values.length)
return false;
// Compare individual values, using the hint from
// page 33 of the "Effective Java" book to handle
// NaN and Infinity
for (int i=0; i<values.length; ++i)
if (Double.doubleToLongBits(values[i]) !=
Double.doubleToLongBits(rhs.values[i]))
return false;
return super.equals(obj);
}
/** {@inheritDoc} */
@Override
public int hashCode()
{
int h = super.hashCode();
for (int i=0; i<values.length; ++i)
h += values[i];
return h;
}
} |
package com.censoredsoftware.Demigods.Engine.PlayerCharacter;
import java.util.Set;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import redis.clients.johm.*;
import com.censoredsoftware.Demigods.API.CharacterAPI;
import com.censoredsoftware.Demigods.Engine.Demigods;
import com.censoredsoftware.Demigods.Engine.DemigodsData;
import com.censoredsoftware.Demigods.Engine.Tracked.TrackedItemStack;
import com.censoredsoftware.Demigods.Engine.Tracked.TrackedModelFactory;
/**
* Creates a saved version of a PlayerInventory.
*/
@Model
public class PlayerCharacterInventory
{
@Id
private Long id;
@Attribute
@Indexed
private long owner;
@Reference
private TrackedItemStack helmet;
@Reference
private TrackedItemStack chestplate;
@Reference
private TrackedItemStack leggings;
@Reference
private TrackedItemStack boots;
@Array(of = TrackedItemStack.class, length = 36)
private TrackedItemStack[] items;
void setOwner(Long id)
{
this.owner = id;
}
void setHelmet(ItemStack helmet)
{
this.helmet = TrackedModelFactory.createTrackedItemStack(helmet);
}
void setChestplate(ItemStack chestplate)
{
this.chestplate = TrackedModelFactory.createTrackedItemStack(chestplate);
}
void setLeggings(ItemStack leggings)
{
this.leggings = TrackedModelFactory.createTrackedItemStack(leggings);
}
void setBoots(ItemStack boots)
{
this.boots = TrackedModelFactory.createTrackedItemStack(boots);
}
void setItems(Inventory inventory)
{
if(this.items == null) this.items = new TrackedItemStack[36];
for(int i = 0; i < 35; i++)
{
if(inventory.getItem(i) == null)
{
this.items[i] = TrackedModelFactory.createTrackedItemStack(new ItemStack(Material.AIR));
}
else
{
this.items[i] = TrackedModelFactory.createTrackedItemStack(inventory.getItem(i));
}
}
}
public Long getId()
{
return this.id;
}
public PlayerCharacter getOwner()
{
return CharacterAPI.getChar(this.owner);
}
public static void save(PlayerCharacterInventory inventory)
{
try
{
DemigodsData.jOhm.save(inventory);
}
catch(Exception e)
{
Demigods.message.severe("Could not save inventory: " + inventory.getId());
}
}
public static PlayerCharacterInventory load(long id)
{
return DemigodsData.jOhm.get(PlayerCharacterInventory.class, id);
}
public static Set<PlayerCharacterInventory> loadAll()
{
return DemigodsData.jOhm.getAll(PlayerCharacterInventory.class);
}
/**
* Applies this inventory to the given <code>player</code>.
*
* @param player the player for whom apply the inventory.
*/
public void setToPlayer(Player player)
{
// Define the inventory
PlayerInventory inventory = player.getInventory();
// Clear it all first
inventory.clear();
inventory.setHelmet(new ItemStack(Material.AIR));
inventory.setChestplate(new ItemStack(Material.AIR));
inventory.setLeggings(new ItemStack(Material.AIR));
inventory.setBoots(new ItemStack(Material.AIR));
// Set the armor contents
if(this.helmet != null) inventory.setHelmet(this.helmet.toItemStack());
if(this.chestplate != null) inventory.setChestplate(this.chestplate.toItemStack());
if(this.leggings != null) inventory.setLeggings(this.leggings.toItemStack());
if(this.boots != null) inventory.setBoots(this.boots.toItemStack());
// Set items
for(int i = 0; i < 35; i++)
{
if(this.items[i] != null) inventory.setItem(i, this.items[i].toItemStack());
}
// Delete
DemigodsData.jOhm.delete(PlayerCharacterInventory.class, id);
}
} |
package org.hisp.dhis.android.core.program;
import org.hisp.dhis.android.core.arch.db.stores.internal.IdentifiableObjectStore;
import org.hisp.dhis.android.core.arch.repositories.children.internal.ChildrenAppender;
import org.hisp.dhis.android.core.arch.repositories.collection.internal.ReadOnlyIdentifiableCollectionRepositoryImpl;
import org.hisp.dhis.android.core.arch.repositories.filters.internal.BooleanFilterConnector;
import org.hisp.dhis.android.core.arch.repositories.filters.internal.EnumFilterConnector;
import org.hisp.dhis.android.core.arch.repositories.filters.internal.FilterConnectorFactory;
import org.hisp.dhis.android.core.arch.repositories.filters.internal.IntegerFilterConnector;
import org.hisp.dhis.android.core.arch.repositories.filters.internal.StringFilterConnector;
import org.hisp.dhis.android.core.arch.repositories.scope.RepositoryScope;
import org.hisp.dhis.android.core.common.FormType;
import org.hisp.dhis.android.core.period.FeatureType;
import org.hisp.dhis.android.core.period.PeriodType;
import org.hisp.dhis.android.core.program.internal.ProgramStageFields;
import java.util.Map;
import javax.inject.Inject;
import dagger.Reusable;
@Reusable
public final class ProgramStageCollectionRepository
extends ReadOnlyIdentifiableCollectionRepositoryImpl<ProgramStage, ProgramStageCollectionRepository> {
@Inject
ProgramStageCollectionRepository(final IdentifiableObjectStore<ProgramStage> store,
final Map<String, ChildrenAppender<ProgramStage>> childrenAppenders,
final RepositoryScope scope) {
super(store, childrenAppenders, scope, new FilterConnectorFactory<>(scope,
s -> new ProgramStageCollectionRepository(store, childrenAppenders, s)));
}
public StringFilterConnector<ProgramStageCollectionRepository> byDescription() {
return cf.string(ProgramStageFields.DESCRIPTION);
}
public StringFilterConnector<ProgramStageCollectionRepository> byDisplayDescription() {
return cf.string(ProgramStageFields.DISPLAY_DESCRIPTION);
}
public StringFilterConnector<ProgramStageCollectionRepository> byExecutionDateLabel() {
return cf.string(ProgramStageFields.EXECUTION_DATE_LABEL);
}
public BooleanFilterConnector<ProgramStageCollectionRepository> byAllowGenerateNextVisit() {
return cf.bool(ProgramStageFields.ALLOW_GENERATE_NEXT_VISIT);
}
public BooleanFilterConnector<ProgramStageCollectionRepository> byValidCompleteOnly() {
return cf.bool(ProgramStageFields.VALID_COMPLETE_ONLY);
}
public StringFilterConnector<ProgramStageCollectionRepository> byReportDateToUse() {
return cf.string(ProgramStageFields.REPORT_DATE_TO_USE);
}
public BooleanFilterConnector<ProgramStageCollectionRepository> byOpenAfterEnrollment() {
return cf.bool(ProgramStageFields.OPEN_AFTER_ENROLLMENT);
}
public BooleanFilterConnector<ProgramStageCollectionRepository> byRepeatable() {
return cf.bool(ProgramStageFields.REPEATABLE);
}
public EnumFilterConnector<ProgramStageCollectionRepository, FeatureType> byFeatureType() {
return cf.enumC(ProgramStageFields.FEATURE_TYPE);
}
public EnumFilterConnector<ProgramStageCollectionRepository, FormType> byFormType() {
return cf.enumC(ProgramStageFields.FORM_TYPE);
}
public BooleanFilterConnector<ProgramStageCollectionRepository> byDisplayGenerateEventBox() {
return cf.bool(ProgramStageFields.DISPLAY_GENERATE_EVENT_BOX);
}
public BooleanFilterConnector<ProgramStageCollectionRepository> byGeneratedByEnrollmentDate() {
return cf.bool(ProgramStageFields.GENERATED_BY_ENROLMENT_DATE);
}
public BooleanFilterConnector<ProgramStageCollectionRepository> byAutoGenerateEvent() {
return cf.bool(ProgramStageFields.AUTO_GENERATE_EVENT);
}
public IntegerFilterConnector<ProgramStageCollectionRepository> bySortOrder() {
return cf.integer(ProgramStageFields.SORT_ORDER);
}
public BooleanFilterConnector<ProgramStageCollectionRepository> byHideDueDate() {
return cf.bool(ProgramStageFields.HIDE_DUE_DATE);
}
public BooleanFilterConnector<ProgramStageCollectionRepository> byBlockEntryForm() {
return cf.bool(ProgramStageFields.BLOCK_ENTRY_FORM);
}
public IntegerFilterConnector<ProgramStageCollectionRepository> byMinDaysFromStart() {
return cf.integer(ProgramStageFields.MIN_DAYS_FROM_START);
}
public IntegerFilterConnector<ProgramStageCollectionRepository> byStandardInterval() {
return cf.integer(ProgramStageFields.STANDARD_INTERVAL);
}
public EnumFilterConnector<ProgramStageCollectionRepository, PeriodType> byPeriodType() {
return cf.enumC(ProgramStageFields.PERIOD_TYPE);
}
public StringFilterConnector<ProgramStageCollectionRepository> byProgramUid() {
return cf.string(ProgramStageFields.PROGRAM);
}
public BooleanFilterConnector<ProgramStageCollectionRepository> byAccessDataWrite() {
return cf.bool(ProgramStageTableInfo.Columns.ACCESS_DATA_WRITE);
}
public BooleanFilterConnector<ProgramStageCollectionRepository> byRemindCompleted() {
return cf.bool(ProgramStageFields.REMIND_COMPLETED);
}
public ProgramStageCollectionRepository withStyle() {
return cf.withChild(ProgramStageFields.STYLE);
}
public ProgramStageCollectionRepository withProgramStageDataElements() {
return cf.withChild(ProgramStageFields.PROGRAM_STAGE_DATA_ELEMENTS);
}
public ProgramStageCollectionRepository withProgramStageSections() {
return cf.withChild(ProgramStageFields.PROGRAM_STAGE_SECTIONS);
}
} |
package org.hisp.dhis.client.sdk.core.program;
import org.hisp.dhis.client.sdk.core.common.Fields;
import org.hisp.dhis.client.sdk.core.common.controllers.AbsSyncStrategyController;
import org.hisp.dhis.client.sdk.core.common.controllers.SyncStrategy;
import org.hisp.dhis.client.sdk.core.common.persistence.DbUtils;
import org.hisp.dhis.client.sdk.core.common.persistence.IDbOperation;
import org.hisp.dhis.client.sdk.core.common.persistence.ITransactionManager;
import org.hisp.dhis.client.sdk.core.common.preferences.DateType;
import org.hisp.dhis.client.sdk.core.common.preferences.ILastUpdatedPreferences;
import org.hisp.dhis.client.sdk.core.common.preferences.ResourceType;
import org.hisp.dhis.client.sdk.core.systeminfo.ISystemInfoController;
import org.hisp.dhis.client.sdk.models.program.ProgramStageSection;
import org.hisp.dhis.client.sdk.models.utils.ModelUtils;
import org.joda.time.DateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class ProgramStageSectionController extends AbsSyncStrategyController<ProgramStageSection>
implements IProgramStageSectionController {
/* Api clients */
private final IProgramStageSectionApiClient programStageSectionApiClient;
/* Controllers */
private final ISystemInfoController systemInfoController;
private final IProgramStageController programStageController;
/* Utilities */
private final ITransactionManager transactionManager;
public ProgramStageSectionController(IProgramStageSectionApiClient programStageSectionApiClient,
IProgramStageSectionStore programStageSectionStore,
IProgramStageController programStageController,
ISystemInfoController systemInfoController,
ITransactionManager transactionManager,
ILastUpdatedPreferences lastUpdatedPreferences) {
super(ResourceType.PROGRAM_STAGE_SECTIONS,
programStageSectionStore, lastUpdatedPreferences);
this.programStageSectionApiClient = programStageSectionApiClient;
this.systemInfoController = systemInfoController;
this.programStageController = programStageController;
this.transactionManager = transactionManager;
}
@Override
protected void synchronize(SyncStrategy strategy, Set<String> uids) {
DateTime serverTime = systemInfoController.getSystemInfo().getServerDate();
DateTime lastUpdated = lastUpdatedPreferences.get(
ResourceType.PROGRAM_STAGE_SECTIONS, DateType.SERVER);
List<ProgramStageSection> persistedProgramStageSections =
identifiableObjectStore.queryAll();
// we have to download all ids from server in order to
// find out what was removed on the server side
List<ProgramStageSection> allExistingProgramStageSections = programStageSectionApiClient
.getProgramStageSections(Fields.BASIC, null);
String[] uidArray = null;
if (uids != null) {
// here we want to get list of ids of program stage sections which are
// stored locally and list of program stage sections which we want to download
Set<String> persistedProgramStageSectionIds = ModelUtils
.toUidSet(persistedProgramStageSections);
persistedProgramStageSectionIds.addAll(uids);
uidArray = persistedProgramStageSectionIds
.toArray(new String[persistedProgramStageSectionIds.size()]);
}
List<ProgramStageSection> updatedProgramStageSections = programStageSectionApiClient
.getProgramStageSections(Fields.ALL, lastUpdated, uidArray);
// Retrieving program stage uids from program stages sections
Set<String> programStageSectionUids = new HashSet<>();
List<ProgramStageSection> mergedProgramStageSections = ModelUtils.merge(
allExistingProgramStageSections, updatedProgramStageSections,
persistedProgramStageSections);
for (ProgramStageSection programStageSection : mergedProgramStageSections) {
programStageSectionUids.add(programStageSection.getProgramStage().getUId());
}
// Syncing programs before saving program stages (since
// program stages are referencing them directly)
programStageController.sync(strategy, programStageSectionUids);
// we will have to perform something similar to what happens in AbsController
List<IDbOperation> dbOperations = DbUtils.createOperations(
allExistingProgramStageSections, updatedProgramStageSections,
persistedProgramStageSections, identifiableObjectStore);
transactionManager.transact(dbOperations);
lastUpdatedPreferences.save(ResourceType.PROGRAM_STAGE_SECTIONS,
DateType.SERVER, serverTime);
}
} |
package org.mskcc.cbio.portal.oncoPrintSpecLanguage;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.mskcc.cbio.portal.oncoPrintSpecLanguage.DataTypeSpecEnumerations.DataTypeCategory;
import org.mskcc.cbio.portal.util.EqualsUtil;
import org.mskcc.cbio.portal.util.HashCodeUtil;
/**
* Represent a discrete dataTypeSpec, like CNA or mutation.
* The specified values are given by an EnumSet, so any subset can be specified.
*
* TODO: replace DiscreteDataTypeSpec with this
* @author Arthur Goldberg
*/
public class DiscreteDataTypeSetSpec extends DataTypeSpec{
private final Set<GeneticTypeLevel> specifiedValues;
private final Set<String> mutationPatterns;
public DiscreteDataTypeSetSpec(GeneticDataTypes theGeneticDataType){
this.theGeneticDataType = theGeneticDataType;
specifiedValues = EnumSet.noneOf(GeneticTypeLevel.class);
mutationPatterns = new HashSet<String>();
}
/**
* create a DiscreteDataTypeSetSpec from a datatype name and a data type level
* @param theGeneticDataType
* @param validValues1
*/
public DiscreteDataTypeSetSpec(GeneticDataTypes theGeneticDataType,
GeneticTypeLevel validValues1) throws IllegalArgumentException{
// verify that validValues1 is a level for theGeneticDataType
if( validValues1.getTheGeneticDataType().equals(theGeneticDataType)){
this.theGeneticDataType = theGeneticDataType;
this.specifiedValues = EnumSet.of(validValues1);
mutationPatterns = new HashSet<String>();
}else{
throw new IllegalArgumentException( validValues1 + " is not a level for " + theGeneticDataType );
}
}
/**
* create a DiscreteDataTypeSetSpec from a datatype name and a numerical level code.
*
* @param theGeneticDataTypeName
* @param levelCode
*/
public DiscreteDataTypeSetSpec(String theGeneticDataTypeName,
int levelCode) {
//System.out.format( "DiscreteDataTypeSetSpec: constructed with '%s' and '%d'%n", theGeneticDataTypeName, levelCode );
theGeneticDataType = DiscreteDataTypeSpec.findDataType( theGeneticDataTypeName );
// convertCode throws an exception if levelCode is not a level for theGeneticDataTypeName
specifiedValues = EnumSet.of( GeneticTypeLevel.convertCode( this.theGeneticDataType, levelCode ));
mutationPatterns = new HashSet<String>();
}
/**
* create a DiscreteDataTypeSetSpec from a datatype name and a set of levels.
*
* @param theGeneticDataType
* @param validValues
*/
public DiscreteDataTypeSetSpec(GeneticDataTypes theGeneticDataType,
GeneticTypeLevel... validValues) {
this.theGeneticDataType = theGeneticDataType;
this.specifiedValues = EnumSet.noneOf(GeneticTypeLevel.class);
// TODO: perhaps make it an error to provide no validValues
for( GeneticTypeLevel c : validValues){
this.specifiedValues.add(c);
}
mutationPatterns = new HashSet<String>();
}
/**
*
* @param theGeneticDataTypeNameString
* @param levelCodeString
* @return
*/
public static DiscreteDataTypeSetSpec discreteDataTypeSetSpecGeneratorByLevelCode(String theGeneticDataTypeNameString,
String levelCodeString ){
try {
return new DiscreteDataTypeSetSpec( theGeneticDataTypeNameString, Integer.parseInt(levelCodeString) );
} catch (NumberFormatException e) {
return null;
} catch (IllegalArgumentException e) {
return null;
}
}
/**
*
* @param levelName
* @return
*/
public static DiscreteDataTypeSetSpec discreteDataTypeSetSpecGeneratorByLevelName(String levelName){
if (levelName==null) {
return null;
}
GeneticTypeLevel theGeneticTypeLevel = GeneticTypeLevel.findDataTypeLevel(levelName);
// verify that levelName maps to a level within a discrete datatype
if( theGeneticTypeLevel!=null
&& theGeneticTypeLevel.getTheGeneticDataType().getTheDataTypeCategory()
.equals(DataTypeCategory.Discrete) ){
return new DiscreteDataTypeSetSpec(theGeneticTypeLevel.getTheGeneticDataType(),
theGeneticTypeLevel);
}else{
return null;
}
}
/**
*
* @param specificMutation
* @return
*/
public static DiscreteDataTypeSetSpec specificMutationDataTypeSetSpecGenerator(String specificMutation){
DiscreteDataTypeSetSpec ret = new DiscreteDataTypeSetSpec(GeneticDataTypes.Mutation);
ret.addLevel(specificMutation);
return ret;
}
public static GeneticDataTypes findDataType( String name )
throws IllegalArgumentException{
return DataTypeSpec.genericFindDataType( name, DataTypeCategory.Discrete );
}
/**
* Alternative style for a copy constructor, using a static newInstance
* method.
*/
public static DiscreteDataTypeSetSpec newInstance( DiscreteDataTypeSetSpec aDiscreteDataTypeSetSpec ) {
if( null == aDiscreteDataTypeSetSpec ){
return null;
}
DiscreteDataTypeSetSpec theNewDiscreteDataTypeSetSpec =
new DiscreteDataTypeSetSpec( aDiscreteDataTypeSetSpec.getTheGeneticDataType() );
theNewDiscreteDataTypeSetSpec.combine(aDiscreteDataTypeSetSpec);
return theNewDiscreteDataTypeSetSpec;
}
/**
* indicate whether value satisfies this DiscreteDataTypeSetSpec
* @param value
* @return true if value satisfies this DiscreteDataTypeSetSpec
*/
public boolean satisfy( Object value ) {
if (value instanceof GeneticTypeLevel) {
return this.specifiedValues.contains((GeneticTypeLevel)value);
} else if (theGeneticDataType == GeneticDataTypes.Mutation) {
if (value instanceof String) {
return satisfySpecificMutation((String)value);
}
}
return false;
}
private static Pattern SPECIFIC_POSITION_MUTATION_PATTERN = Pattern.compile("[^0-9]*([0-9]+)");
private static Pattern SPECIFIC_RANGE_DELETION_PATTERN = Pattern.compile("[^0-9]*([0-9]+)[^0-9]+([0-9]+)[^0-9]*");
private boolean satisfySpecificMutation( String specificMutations ) {
String specificMutationsUpper = specificMutations.toUpperCase();
for (String specificMutationUpper : specificMutationsUpper.split(",")) {
if (specificMutationUpper.startsWith("P.")) {
specificMutationUpper = specificMutationUpper.substring(2);
}
specificMutationUpper = specificMutationUpper.replaceAll(" ","_");
if (mutationPatterns.contains(specificMutationUpper)) {
// complete match, including specific mutation to an amino acid such V600E, D200fs
return true;
}
for ( String mutationPattern : mutationPatterns ) {
Matcher spm = SPECIFIC_POSITION_MUTATION_PATTERN.matcher(mutationPattern);
if (spm.matches()) {// all mutations for a specific amino acid
String strPos = spm.group(1);
if (specificMutationUpper.matches(".*[^0-9]+"+strPos+"[^0-9\\+\\-]*")
|| specificMutationUpper.matches(strPos+"[^0-9]+.*")) {
// To deal with cases that the query position appears in the mutation string
// e.g., S634*, S479_splice, *691S, 278in_frame_del, 1002_1003_del,
// YQQQQQ263in_frame_del*, A1060fs, A277_splice
// Note: "S30" will not match "S300"
// Note: "S30" will not match "e30+1"
return true;
}
Matcher delm = SPECIFIC_RANGE_DELETION_PATTERN.matcher(specificMutationUpper);
if (delm.matches()) {
// To deal with deletions
// e.g. query 1020 matches 1018_1023DNPPVL>V
int start = Integer.parseInt(delm.group(1));
int end = Integer.parseInt(delm.group(2));
int pos = Integer.parseInt(strPos);
if (start<pos && pos<end) {
return true;
}
}
}
// The follow types are matched according the the mutaiton string,
// which may not be correct. A more accurate solution would be using
// the mutation_type from database directly
else if (mutationPattern.equals("MS") || mutationPattern.equals("MISSENSE")) {
if (specificMutationUpper.matches("[A-Z][0-9]+[A-Z]")) {
if (specificMutationUpper.charAt(0) !=
specificMutationUpper.charAt(specificMutationUpper.length()-1)) { //not silent
return true;
}
}
} else if (mutationPattern.equals("NS") || mutationPattern.equals("NONSENSE")) {
if (specificMutationUpper.matches("[A-Z][0-9]+\\*")) {
return true;
}
} else if (mutationPattern.equals("NONSTART")) {
if (specificMutationUpper.matches("M1[^0-9]+[^M]")) {
return true;
}
} else if (mutationPattern.equals("NONSTOP")) {
if (specificMutationUpper.matches(".*\\*[0-9]+.+")) {
return true;
}
} else if (mutationPattern.equals("FS") || mutationPattern.equals("FRAMESHIFT")) {
if (specificMutationUpper.matches("[A-Z\\*][0-9]+FS")) {
return true;
}
} else if (mutationPattern.equals("IF") || mutationPattern.equals("INFRAME")) {
if (specificMutationUpper.matches(".+IN_FRAME_((INS)|(DEL)).*") ||
specificMutationUpper.matches(".*[0-9]+((INS)|(DEL))[A-Z]*")) {
return true;
}
} else if (mutationPattern.equals("SP") || mutationPattern.equals("SPLICE")) {
if (specificMutationUpper.matches("[A-Z][0-9]+_SPLICE") ||
specificMutationUpper.matches("E[0-9]+[\\+\\-][0-9]+")) {
return true;
}
} else if (mutationPattern.equals("TRUNC")) {
//NONSENSE
if (specificMutationUpper.matches("[A-Z][0-9]+\\*")) {
return true;
}
// insert *
if (specificMutationUpper.matches(".*[0-9]+INS[A-Z]*\\*[A-Z]*")) {
return true;
}
//NONSTART
if (specificMutationUpper.matches("M1[^0-9]+")) {
return true;
}
//NONSTOP
if (specificMutationUpper.matches(".*\\*[0-9]+.+")) {
return true;
}
//FRAMESHIFT
if (specificMutationUpper.matches("[A-Z\\*][0-9]+FS")) {
return true;
}
//SPLICE
if (specificMutationUpper.matches("[A-Z][0-9]+_SPLICE") ||
specificMutationUpper.matches("E[0-9]+[\\+\\-][0-9]+")) {
return true;
}
} else if (mutationPattern.equals("FUSION")) {
if (specificMutationUpper.endsWith("FUSION")) {
return true;
}
}
}
}
return false;
}
/**
* add the level aGeneticTypeLevel to this instance's accepted levels;
* if aGeneticTypeLevel is already accepted no change occurs.
* @param aGeneticTypeLevel
*/
public void addLevel( Object value ){
if (value instanceof GeneticTypeLevel) {
specifiedValues.add((GeneticTypeLevel) value);
} else if (theGeneticDataType == GeneticDataTypes.Mutation && value instanceof String) {
mutationPatterns.add(((String)value).toUpperCase());
} else {
throw new java.lang.IllegalArgumentException("Wrong level");
}
}
/**
* combine the aDiscreteDataTypeSetSpec's accepted levels into this class's levels
* @param aDiscreteDataTypeSetSpec
*/
public void combine(DiscreteDataTypeSetSpec aDiscreteDataTypeSetSpec) {
this.specifiedValues.addAll(aDiscreteDataTypeSetSpec.getSpecifiedValues());
this.mutationPatterns.addAll(aDiscreteDataTypeSetSpec.getMutationPatterns());
}
@Override
public String toString() {
//return theGeneticDataType.toString() + " in " + specifiedValues.toString();
StringBuilder sb = new StringBuilder();
for (GeneticTypeLevel value : specifiedValues){
sb.append( value.toString() ).append(" ");
}
for (String str : mutationPatterns) {
sb.append( str ).append( " " );
}
return sb.toString();
}
@Override
public boolean equals( Object aThat) {
if( this == aThat ) return true;
if ( !(aThat instanceof DiscreteDataTypeSetSpec) ) return false;
DiscreteDataTypeSetSpec that = (DiscreteDataTypeSetSpec) aThat;
return
EqualsUtil.areEqual(this.theGeneticDataType, that.theGeneticDataType) &&
EqualsUtil.areEqual(this.specifiedValues, that.specifiedValues) &&
EqualsUtil.areEqual(this.mutationPatterns, that.mutationPatterns);
}
// TODO: TEST
@Override
public int hashCode( ) {
int result = HashCodeUtil.SEED;
result = HashCodeUtil.hash( result, theGeneticDataType );
result = HashCodeUtil.hash( result, specifiedValues );
result = HashCodeUtil.hash( result, mutationPatterns);
return result;
}
public Set<GeneticTypeLevel> getSpecifiedValues() {
return specifiedValues;
}
public Set<String> getMutationPatterns() {
return mutationPatterns;
}
@Override public final Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
} |
package io.debezium.connector.oracle;
import static io.debezium.connector.oracle.util.TestHelper.TYPE_LENGTH_PARAMETER_KEY;
import static io.debezium.connector.oracle.util.TestHelper.TYPE_NAME_PARAMETER_KEY;
import static io.debezium.connector.oracle.util.TestHelper.TYPE_SCALE_PARAMETER_KEY;
import static io.debezium.connector.oracle.util.TestHelper.defaultConfig;
import static io.debezium.data.Envelope.FieldName.AFTER;
import static junit.framework.Assert.fail;
import static junit.framework.TestCase.assertEquals;
import static org.fest.assertions.Assertions.assertThat;
import static org.fest.assertions.MapAssert.entry;
import java.lang.management.ManagementFactory;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.file.Path;
import java.sql.SQLException;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import javax.management.JMException;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import org.apache.kafka.connect.data.Field;
import org.apache.kafka.connect.data.Schema;
import org.apache.kafka.connect.data.Struct;
import org.apache.kafka.connect.source.SourceRecord;
import org.apache.kafka.connect.storage.FileOffsetBackingStore;
import org.apache.kafka.connect.storage.MemoryOffsetBackingStore;
import org.awaitility.Awaitility;
import org.awaitility.Durations;
import org.awaitility.core.ConditionTimeoutException;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.debezium.DebeziumException;
import io.debezium.config.Configuration;
import io.debezium.connector.oracle.OracleConnectorConfig.LogMiningStrategy;
import io.debezium.connector.oracle.OracleConnectorConfig.SnapshotMode;
import io.debezium.connector.oracle.junit.RequireDatabaseOption;
import io.debezium.connector.oracle.junit.SkipTestDependingOnAdapterNameRule;
import io.debezium.connector.oracle.junit.SkipTestDependingOnDatabaseOptionRule;
import io.debezium.connector.oracle.junit.SkipWhenAdapterNameIsNot;
import io.debezium.connector.oracle.logminer.LogMinerStreamingChangeEventSource;
import io.debezium.connector.oracle.util.TestHelper;
import io.debezium.converters.CloudEventsConverterTest;
import io.debezium.converters.spi.CloudEventsMaker;
import io.debezium.data.Envelope;
import io.debezium.data.Envelope.FieldName;
import io.debezium.data.SchemaAndValueField;
import io.debezium.data.VariableScaleDecimal;
import io.debezium.data.VerifyRecord;
import io.debezium.doc.FixFor;
import io.debezium.embedded.AbstractConnectorTest;
import io.debezium.embedded.EmbeddedEngine;
import io.debezium.heartbeat.Heartbeat;
import io.debezium.junit.logging.LogInterceptor;
import io.debezium.relational.RelationalDatabaseConnectorConfig;
import io.debezium.relational.history.FileDatabaseHistory;
import io.debezium.relational.history.MemoryDatabaseHistory;
import io.debezium.util.Testing;
/**
* Integration test for the Debezium Oracle connector.
*
* @author Gunnar Morling
*/
public class OracleConnectorIT extends AbstractConnectorTest {
private static final Logger LOGGER = LoggerFactory.getLogger(OracleConnectorIT.class);
private static final long MICROS_PER_SECOND = TimeUnit.SECONDS.toMicros(1);
private static final String SNAPSHOT_COMPLETED_KEY = "snapshot_completed";
@Rule
public final TestRule skipAdapterRule = new SkipTestDependingOnAdapterNameRule();
@Rule
public final TestRule skipOptionRule = new SkipTestDependingOnDatabaseOptionRule();
private static OracleConnection connection;
@BeforeClass
public static void beforeClass() throws SQLException {
connection = TestHelper.testConnection();
TestHelper.dropTable(connection, "debezium.customer");
TestHelper.dropTable(connection, "debezium.masked_hashed_column_table");
TestHelper.dropTable(connection, "debezium.truncated_column_table");
TestHelper.dropTable(connection, "debezium.dt_table");
String ddl = "create table debezium.customer (" +
" id numeric(9,0) not null, " +
" name varchar2(1000), " +
" score decimal(6, 2), " +
" registered timestamp, " +
" primary key (id)" +
")";
connection.execute(ddl);
connection.execute("GRANT SELECT ON debezium.customer to " + TestHelper.getConnectorUserName());
connection.execute("ALTER TABLE debezium.customer ADD SUPPLEMENTAL LOG DATA (ALL) COLUMNS");
String ddl2 = "create table debezium.masked_hashed_column_table (" +
" id numeric(9,0) not null, " +
" name varchar2(255), " +
" name2 varchar2(255), " +
" name3 varchar2(20)," +
" primary key (id)" +
")";
connection.execute(ddl2);
connection.execute("GRANT SELECT ON debezium.masked_hashed_column_table to " + TestHelper.getConnectorUserName());
connection.execute("ALTER TABLE debezium.masked_hashed_column_table ADD SUPPLEMENTAL LOG DATA (ALL) COLUMNS");
String ddl3 = "create table debezium.truncated_column_table (" +
" id numeric(9,0) not null, " +
" name varchar2(20), " +
" primary key (id)" +
")";
connection.execute(ddl3);
connection.execute("GRANT SELECT ON debezium.truncated_column_table to " + TestHelper.getConnectorUserName());
connection.execute("ALTER TABLE debezium.truncated_column_table ADD SUPPLEMENTAL LOG DATA (ALL) COLUMNS");
String ddl4 = "create table dt_table (" +
" id numeric(9,0) not null, " +
" c1 int, " +
" c2 int, " +
" c3a numeric(5,2), " +
" c3b varchar(128), " +
" f1 float(10), " +
" f2 decimal(8,4), " +
" primary key (id)" +
")";
connection.execute(ddl4);
connection.execute("GRANT SELECT ON debezium.dt_table to " + TestHelper.getConnectorUserName());
connection.execute("ALTER TABLE debezium.dt_table ADD SUPPLEMENTAL LOG DATA (ALL) COLUMNS");
}
@AfterClass
public static void closeConnection() throws SQLException {
if (connection != null) {
TestHelper.dropTable(connection, "debezium.customer2");
TestHelper.dropTable(connection, "customer");
TestHelper.dropTable(connection, "masked_hashed_column_table");
TestHelper.dropTable(connection, "truncated_column_table");
TestHelper.dropTable(connection, "dt_table");
connection.close();
}
}
@Before
public void before() throws SQLException {
TestHelper.dropTable(connection, "debezium.dbz800a");
TestHelper.dropTable(connection, "debezium.dbz800b");
connection.execute("delete from debezium.customer");
connection.execute("delete from debezium.masked_hashed_column_table");
connection.execute("delete from debezium.truncated_column_table");
connection.execute("delete from debezium.dt_table");
setConsumeTimeout(TestHelper.defaultMessageConsumerPollTimeout(), TimeUnit.SECONDS);
initializeConnectorTestFramework();
Testing.Files.delete(TestHelper.DB_HISTORY_PATH);
}
@Test
@FixFor("DBZ-2452")
public void shouldSnapshotAndStreamWithHyphenedTableName() throws Exception {
TestHelper.dropTable(connection, "debezium.\"my-table\"");
try {
String ddl = "create table \"my-table\" (" +
" id numeric(9,0) not null, " +
" c1 int, " +
" c2 varchar(128), " +
" primary key (id))";
connection.execute(ddl);
connection.execute("GRANT SELECT ON debezium.\"my-table\" to " + TestHelper.getConnectorUserName());
connection.execute("ALTER TABLE debezium.\"my-table\" ADD SUPPLEMENTAL LOG DATA (ALL) COLUMNS");
connection.execute("INSERT INTO debezium.\"my-table\" VALUES (1, 25, 'Test')");
connection.execute("COMMIT");
Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM\\.MY-TABLE")
.build();
start(OracleConnector.class, config);
assertConnectorIsRunning();
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
connection.execute("INSERT INTO debezium.\"my-table\" VALUES (2, 50, 'Test2')");
connection.execute("COMMIT");
SourceRecords records = consumeRecordsByTopic(2);
List<SourceRecord> hyphenatedTableRecords = records.recordsForTopic("server1.DEBEZIUM.my-table");
assertThat(hyphenatedTableRecords).hasSize(2);
// read
SourceRecord record1 = hyphenatedTableRecords.get(0);
VerifyRecord.isValidRead(record1, "ID", 1);
Struct after1 = (Struct) ((Struct) record1.value()).get(AFTER);
assertThat(after1.get("ID")).isEqualTo(1);
assertThat(after1.get("C1")).isEqualTo(BigDecimal.valueOf(25L));
assertThat(after1.get("C2")).isEqualTo("Test");
assertThat(record1.sourceOffset().get(SourceInfo.SNAPSHOT_KEY)).isEqualTo(true);
assertThat(record1.sourceOffset().get(SNAPSHOT_COMPLETED_KEY)).isEqualTo(true);
// insert
SourceRecord record2 = hyphenatedTableRecords.get(1);
VerifyRecord.isValidInsert(record2, "ID", 2);
Struct after2 = (Struct) ((Struct) record2.value()).get(AFTER);
assertThat(after2.get("ID")).isEqualTo(2);
assertThat(after2.get("C1")).isEqualTo(BigDecimal.valueOf(50L));
assertThat(after2.get("C2")).isEqualTo("Test2");
}
finally {
TestHelper.dropTable(connection, "debezium.\"my-table\"");
}
}
@Test
public void shouldTakeSnapshot() throws Exception {
Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM\\.CUSTOMER")
.build();
int expectedRecordCount = 0;
connection.execute("INSERT INTO debezium.customer VALUES (1, 'Billie-Bob', 1234.56, TO_DATE('2018-02-22', 'yyyy-mm-dd'))");
connection.execute("INSERT INTO debezium.customer VALUES (2, 'Bruce', 2345.67, null)");
connection.execute("COMMIT");
expectedRecordCount += 2;
start(OracleConnector.class, config);
assertConnectorIsRunning();
SourceRecords records = consumeRecordsByTopic(expectedRecordCount);
List<SourceRecord> testTableRecords = records.recordsForTopic("server1.DEBEZIUM.CUSTOMER");
assertThat(testTableRecords).hasSize(expectedRecordCount);
// read
SourceRecord record1 = testTableRecords.get(0);
VerifyRecord.isValidRead(record1, "ID", 1);
Struct after = (Struct) ((Struct) record1.value()).get("after");
assertThat(after.get("ID")).isEqualTo(1);
assertThat(after.get("NAME")).isEqualTo("Billie-Bob");
assertThat(after.get("SCORE")).isEqualTo(BigDecimal.valueOf(1234.56));
assertThat(after.get("REGISTERED")).isEqualTo(toMicroSecondsSinceEpoch(LocalDateTime.of(2018, 2, 22, 0, 0, 0)));
assertThat(record1.sourceOffset().get(SourceInfo.SNAPSHOT_KEY)).isEqualTo(true);
assertThat(record1.sourceOffset().get(SNAPSHOT_COMPLETED_KEY)).isEqualTo(false);
Struct source = (Struct) ((Struct) record1.value()).get("source");
assertThat(source.get(SourceInfo.SNAPSHOT_KEY)).isEqualTo("true");
SourceRecord record2 = testTableRecords.get(1);
VerifyRecord.isValidRead(record2, "ID", 2);
after = (Struct) ((Struct) record2.value()).get("after");
assertThat(after.get("ID")).isEqualTo(2);
assertThat(after.get("NAME")).isEqualTo("Bruce");
assertThat(after.get("SCORE")).isEqualTo(BigDecimal.valueOf(2345.67));
assertThat(after.get("REGISTERED")).isNull();
assertThat(record2.sourceOffset().get(SourceInfo.SNAPSHOT_KEY)).isEqualTo(true);
assertThat(record2.sourceOffset().get(SNAPSHOT_COMPLETED_KEY)).isEqualTo(true);
source = (Struct) ((Struct) record2.value()).get("source");
assertThat(source.get(SourceInfo.SNAPSHOT_KEY)).isEqualTo("last");
}
@Test
public void shouldContinueWithStreamingAfterSnapshot() throws Exception {
Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM\\.CUSTOMER")
.build();
continueStreamingAfterSnapshot(config);
}
private void continueStreamingAfterSnapshot(Configuration config) throws Exception {
int expectedRecordCount = 0;
connection.execute("INSERT INTO debezium.customer VALUES (1, 'Billie-Bob', 1234.56, TO_DATE('2018-02-22', 'yyyy-mm-dd'))");
connection.execute("INSERT INTO debezium.customer VALUES (2, 'Bruce', 2345.67, null)");
connection.execute("COMMIT");
expectedRecordCount += 2;
start(OracleConnector.class, config);
assertConnectorIsRunning();
SourceRecords records = consumeRecordsByTopic(expectedRecordCount);
List<SourceRecord> testTableRecords = records.recordsForTopic("server1.DEBEZIUM.CUSTOMER");
assertThat(testTableRecords).hasSize(expectedRecordCount);
// read
SourceRecord record1 = testTableRecords.get(0);
VerifyRecord.isValidRead(record1, "ID", 1);
Struct after = (Struct) ((Struct) record1.value()).get("after");
assertThat(after.get("ID")).isEqualTo(1);
Struct source = (Struct) ((Struct) record1.value()).get("source");
assertThat(source.get(SourceInfo.SNAPSHOT_KEY)).isEqualTo("true");
assertThat(source.get(SourceInfo.SCN_KEY)).isNotNull();
assertThat(source.get(SourceInfo.SERVER_NAME_KEY)).isEqualTo("server1");
assertThat(source.get(SourceInfo.DEBEZIUM_VERSION_KEY)).isNotNull();
assertThat(source.get(SourceInfo.TXID_KEY)).isNull();
assertThat(source.get(SourceInfo.TIMESTAMP_KEY)).isNotNull();
assertThat(record1.sourceOffset().get(SourceInfo.SNAPSHOT_KEY)).isEqualTo(true);
assertThat(record1.sourceOffset().get(SNAPSHOT_COMPLETED_KEY)).isEqualTo(false);
SourceRecord record2 = testTableRecords.get(1);
VerifyRecord.isValidRead(record2, "ID", 2);
after = (Struct) ((Struct) record2.value()).get("after");
assertThat(after.get("ID")).isEqualTo(2);
assertThat(record2.sourceOffset().get(SourceInfo.SNAPSHOT_KEY)).isEqualTo(true);
assertThat(record2.sourceOffset().get(SNAPSHOT_COMPLETED_KEY)).isEqualTo(true);
expectedRecordCount = 0;
connection.execute("INSERT INTO debezium.customer VALUES (3, 'Brian', 2345.67, null)");
connection.execute("COMMIT");
expectedRecordCount += 1;
records = consumeRecordsByTopic(expectedRecordCount);
testTableRecords = records.recordsForTopic("server1.DEBEZIUM.CUSTOMER");
assertThat(testTableRecords).hasSize(expectedRecordCount);
SourceRecord record3 = testTableRecords.get(0);
VerifyRecord.isValidInsert(record3, "ID", 3);
after = (Struct) ((Struct) record3.value()).get("after");
assertThat(after.get("ID")).isEqualTo(3);
assertThat(record3.sourceOffset().containsKey(SourceInfo.SNAPSHOT_KEY)).isFalse();
assertThat(record3.sourceOffset().containsKey(SNAPSHOT_COMPLETED_KEY)).isFalse();
source = (Struct) ((Struct) record3.value()).get("source");
assertThat(source.get(SourceInfo.SNAPSHOT_KEY)).isEqualTo("false");
assertThat(source.get(SourceInfo.SCN_KEY)).isNotNull();
assertThat(source.get(SourceInfo.SERVER_NAME_KEY)).isEqualTo("server1");
assertThat(source.get(SourceInfo.DEBEZIUM_VERSION_KEY)).isNotNull();
assertThat(source.get(SourceInfo.TXID_KEY)).isNotNull();
assertThat(source.get(SourceInfo.TIMESTAMP_KEY)).isNotNull();
}
@Test
@FixFor("DBZ-1223")
public void shouldStreamTransaction() throws Exception {
Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM\\.CUSTOMER")
.build();
// Testing.Print.enable();
int expectedRecordCount = 0;
connection.execute("INSERT INTO debezium.customer VALUES (1, 'Billie-Bob', 1234.56, TO_DATE('2018-02-22', 'yyyy-mm-dd'))");
connection.execute("INSERT INTO debezium.customer VALUES (2, 'Bruce', 2345.67, null)");
connection.execute("COMMIT");
expectedRecordCount += 2;
start(OracleConnector.class, config);
assertConnectorIsRunning();
SourceRecords records = consumeRecordsByTopic(expectedRecordCount);
List<SourceRecord> testTableRecords = records.recordsForTopic("server1.DEBEZIUM.CUSTOMER");
assertThat(testTableRecords).hasSize(expectedRecordCount);
// read
SourceRecord record1 = testTableRecords.get(0);
VerifyRecord.isValidRead(record1, "ID", 1);
Struct after = (Struct) ((Struct) record1.value()).get("after");
assertThat(after.get("ID")).isEqualTo(1);
Struct source = (Struct) ((Struct) record1.value()).get("source");
assertThat(source.get(SourceInfo.SNAPSHOT_KEY)).isEqualTo("true");
assertThat(source.get(SourceInfo.SCN_KEY)).isNotNull();
assertThat(source.get(SourceInfo.SERVER_NAME_KEY)).isEqualTo("server1");
assertThat(source.get(SourceInfo.DEBEZIUM_VERSION_KEY)).isNotNull();
assertThat(source.get(SourceInfo.TXID_KEY)).isNull();
assertThat(source.get(SourceInfo.TIMESTAMP_KEY)).isNotNull();
assertThat(record1.sourceOffset().get(SourceInfo.SNAPSHOT_KEY)).isEqualTo(true);
assertThat(record1.sourceOffset().get(SNAPSHOT_COMPLETED_KEY)).isEqualTo(false);
SourceRecord record2 = testTableRecords.get(1);
VerifyRecord.isValidRead(record2, "ID", 2);
after = (Struct) ((Struct) record2.value()).get("after");
assertThat(after.get("ID")).isEqualTo(2);
assertThat(record2.sourceOffset().get(SourceInfo.SNAPSHOT_KEY)).isEqualTo(true);
assertThat(record2.sourceOffset().get(SNAPSHOT_COMPLETED_KEY)).isEqualTo(true);
expectedRecordCount = 30;
connection.setAutoCommit(false);
sendTxBatch(config, expectedRecordCount, 100);
sendTxBatch(config, expectedRecordCount, 200);
}
private void sendTxBatch(Configuration config, int expectedRecordCount, int offset) throws SQLException, InterruptedException {
boolean isAutoCommit = false;
if (connection.connection().getAutoCommit()) {
isAutoCommit = true;
connection.connection().setAutoCommit(false);
}
for (int i = offset; i < expectedRecordCount + offset; i++) {
connection.executeWithoutCommitting(String.format("INSERT INTO debezium.customer VALUES (%s, 'Brian%s', 2345.67, null)", i, i));
}
connection.connection().commit();
if (isAutoCommit) {
connection.connection().setAutoCommit(true);
}
assertTxBatch(config, expectedRecordCount, offset);
}
private void assertTxBatch(Configuration config, int expectedRecordCount, int offset) throws InterruptedException {
SourceRecords records;
List<SourceRecord> testTableRecords;
Struct after;
Struct source;
records = consumeRecordsByTopic(expectedRecordCount);
testTableRecords = records.recordsForTopic("server1.DEBEZIUM.CUSTOMER");
assertThat(testTableRecords).hasSize(expectedRecordCount);
final String adapter = config.getString(OracleConnectorConfig.CONNECTOR_ADAPTER);
for (int i = 0; i < expectedRecordCount; i++) {
SourceRecord record3 = testTableRecords.get(i);
VerifyRecord.isValidInsert(record3, "ID", i + offset);
after = (Struct) ((Struct) record3.value()).get("after");
assertThat(after.get("ID")).isEqualTo(i + offset);
assertThat(record3.sourceOffset().containsKey(SourceInfo.SNAPSHOT_KEY)).isFalse();
assertThat(record3.sourceOffset().containsKey(SNAPSHOT_COMPLETED_KEY)).isFalse();
if (!"LogMiner".equalsIgnoreCase(adapter)) {
assertThat(record3.sourceOffset().containsKey(SourceInfo.LCR_POSITION_KEY)).isTrue();
assertThat(record3.sourceOffset().containsKey(SourceInfo.SCN_KEY)).isFalse();
}
source = (Struct) ((Struct) record3.value()).get("source");
assertThat(source.get(SourceInfo.SNAPSHOT_KEY)).isEqualTo("false");
assertThat(source.get(SourceInfo.SCN_KEY)).isNotNull();
if (!"LogMiner".equalsIgnoreCase(adapter)) {
assertThat(source.get(SourceInfo.LCR_POSITION_KEY)).isNotNull();
}
assertThat(source.get(SourceInfo.SERVER_NAME_KEY)).isEqualTo("server1");
assertThat(source.get(SourceInfo.DEBEZIUM_VERSION_KEY)).isNotNull();
assertThat(source.get(SourceInfo.TXID_KEY)).isNotNull();
assertThat(source.get(SourceInfo.TIMESTAMP_KEY)).isNotNull();
}
}
@Test
public void shouldStreamAfterRestart() throws Exception {
Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM\\.CUSTOMER")
.build();
// Testing.Print.enable();
int expectedRecordCount = 0;
connection.execute("INSERT INTO debezium.customer VALUES (1, 'Billie-Bob', 1234.56, TO_DATE('2018-02-22', 'yyyy-mm-dd'))");
connection.execute("INSERT INTO debezium.customer VALUES (2, 'Bruce', 2345.67, null)");
connection.execute("COMMIT");
expectedRecordCount += 2;
start(OracleConnector.class, config);
assertConnectorIsRunning();
waitForSnapshotToBeCompleted(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
SourceRecords records = consumeRecordsByTopic(expectedRecordCount);
List<SourceRecord> testTableRecords = records.recordsForTopic("server1.DEBEZIUM.CUSTOMER");
assertThat(testTableRecords).hasSize(expectedRecordCount);
expectedRecordCount = 30;
connection.setAutoCommit(false);
sendTxBatch(config, expectedRecordCount, 100);
sendTxBatch(config, expectedRecordCount, 200);
stopConnector();
final int OFFSET = 300;
for (int i = OFFSET; i < expectedRecordCount + OFFSET; i++) {
connection.executeWithoutCommitting(String.format("INSERT INTO debezium.customer VALUES (%s, 'Brian%s', 2345.67, null)", i, i));
}
connection.connection().commit();
start(OracleConnector.class, config);
assertConnectorIsRunning();
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
assertTxBatch(config, expectedRecordCount, 300);
sendTxBatch(config, expectedRecordCount, 400);
sendTxBatch(config, expectedRecordCount, 500);
}
@Test
public void shouldStreamAfterRestartAfterSnapshot() throws Exception {
Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM\\.CUSTOMER")
.build();
// Testing.Print.enable();
int expectedRecordCount = 0;
connection.execute("INSERT INTO debezium.customer VALUES (1, 'Billie-Bob', 1234.56, TO_DATE('2018-02-22', 'yyyy-mm-dd'))");
connection.execute("INSERT INTO debezium.customer VALUES (2, 'Bruce', 2345.67, null)");
connection.execute("COMMIT");
expectedRecordCount += 2;
start(OracleConnector.class, config);
assertConnectorIsRunning();
SourceRecords records = consumeRecordsByTopic(expectedRecordCount);
List<SourceRecord> testTableRecords = records.recordsForTopic("server1.DEBEZIUM.CUSTOMER");
assertThat(testTableRecords).hasSize(expectedRecordCount);
stopConnector();
connection.setAutoCommit(false);
final int OFFSET = 100;
for (int i = OFFSET; i < expectedRecordCount + OFFSET; i++) {
connection.executeWithoutCommitting(String.format("INSERT INTO debezium.customer VALUES (%s, 'Brian%s', 2345.67, null)", i, i));
}
connection.connection().commit();
try {
connection.setAutoCommit(true);
Testing.print("=== Starting connector second time ===");
start(OracleConnector.class, config);
assertConnectorIsRunning();
assertTxBatch(config, expectedRecordCount, 100);
sendTxBatch(config, expectedRecordCount, 200);
}
finally {
connection.setAutoCommit(false);
}
}
@Test
public void shouldReadChangeStreamForExistingTable() throws Exception {
Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM\\.CUSTOMER")
.with(OracleConnectorConfig.SNAPSHOT_MODE, SnapshotMode.SCHEMA_ONLY)
.build();
start(OracleConnector.class, config);
assertConnectorIsRunning();
waitForSnapshotToBeCompleted(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
int expectedRecordCount = 0;
connection.execute("INSERT INTO debezium.customer VALUES (1, 'Billie-Bob', 1234.56, TO_DATE('2018-02-22', 'yyyy-mm-dd'))");
connection.execute("COMMIT");
expectedRecordCount += 1;
connection.execute("UPDATE debezium.customer SET name = 'Bruce', score = 2345.67, registered = TO_DATE('2018-03-23', 'yyyy-mm-dd') WHERE id = 1");
connection.execute("COMMIT");
expectedRecordCount += 1;
connection.execute("UPDATE debezium.customer SET id = 2 WHERE id = 1");
connection.execute("COMMIT");
expectedRecordCount += 3; // deletion + tombstone + insert with new id
connection.execute("DELETE debezium.customer WHERE id = 2");
connection.execute("COMMIT");
expectedRecordCount += 2; // deletion + tombstone
SourceRecords records = consumeRecordsByTopic(expectedRecordCount);
List<SourceRecord> testTableRecords = records.recordsForTopic("server1.DEBEZIUM.CUSTOMER");
assertThat(testTableRecords).hasSize(expectedRecordCount);
// insert
VerifyRecord.isValidInsert(testTableRecords.get(0), "ID", 1);
Struct after = (Struct) ((Struct) testTableRecords.get(0).value()).get("after");
assertThat(after.get("ID")).isEqualTo(1);
assertThat(after.get("NAME")).isEqualTo("Billie-Bob");
assertThat(after.get("SCORE")).isEqualTo(BigDecimal.valueOf(1234.56));
assertThat(after.get("REGISTERED")).isEqualTo(toMicroSecondsSinceEpoch(LocalDateTime.of(2018, 2, 22, 0, 0, 0)));
Map<String, ?> offset = testTableRecords.get(0).sourceOffset();
assertThat(offset.get(SourceInfo.SNAPSHOT_KEY)).isNull();
assertThat(offset.get("snapshot_completed")).isNull();
// update
VerifyRecord.isValidUpdate(testTableRecords.get(1), "ID", 1);
Struct before = (Struct) ((Struct) testTableRecords.get(1).value()).get("before");
assertThat(before.get("ID")).isEqualTo(1);
assertThat(before.get("NAME")).isEqualTo("Billie-Bob");
assertThat(before.get("SCORE")).isEqualTo(BigDecimal.valueOf(1234.56));
assertThat(before.get("REGISTERED")).isEqualTo(toMicroSecondsSinceEpoch(LocalDateTime.of(2018, 2, 22, 0, 0, 0)));
after = (Struct) ((Struct) testTableRecords.get(1).value()).get("after");
assertThat(after.get("ID")).isEqualTo(1);
assertThat(after.get("NAME")).isEqualTo("Bruce");
assertThat(after.get("SCORE")).isEqualTo(BigDecimal.valueOf(2345.67));
assertThat(after.get("REGISTERED")).isEqualTo(toMicroSecondsSinceEpoch(LocalDateTime.of(2018, 3, 23, 0, 0, 0)));
// update of PK
VerifyRecord.isValidDelete(testTableRecords.get(2), "ID", 1);
before = (Struct) ((Struct) testTableRecords.get(2).value()).get("before");
assertThat(before.get("ID")).isEqualTo(1);
assertThat(before.get("NAME")).isEqualTo("Bruce");
assertThat(before.get("SCORE")).isEqualTo(BigDecimal.valueOf(2345.67));
assertThat(before.get("REGISTERED")).isEqualTo(toMicroSecondsSinceEpoch(LocalDateTime.of(2018, 3, 23, 0, 0, 0)));
VerifyRecord.isValidTombstone(testTableRecords.get(3));
VerifyRecord.isValidInsert(testTableRecords.get(4), "ID", 2);
after = (Struct) ((Struct) testTableRecords.get(4).value()).get("after");
assertThat(after.get("ID")).isEqualTo(2);
assertThat(after.get("NAME")).isEqualTo("Bruce");
assertThat(after.get("SCORE")).isEqualTo(BigDecimal.valueOf(2345.67));
assertThat(after.get("REGISTERED")).isEqualTo(toMicroSecondsSinceEpoch(LocalDateTime.of(2018, 3, 23, 0, 0, 0)));
// delete
VerifyRecord.isValidDelete(testTableRecords.get(5), "ID", 2);
before = (Struct) ((Struct) testTableRecords.get(5).value()).get("before");
assertThat(before.get("ID")).isEqualTo(2);
assertThat(before.get("NAME")).isEqualTo("Bruce");
assertThat(before.get("SCORE")).isEqualTo(BigDecimal.valueOf(2345.67));
assertThat(before.get("REGISTERED")).isEqualTo(toMicroSecondsSinceEpoch(LocalDateTime.of(2018, 3, 23, 0, 0, 0)));
VerifyRecord.isValidTombstone(testTableRecords.get(6));
}
@Test
@FixFor("DBZ-835")
public void deleteWithoutTombstone() throws Exception {
Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM\\.CUSTOMER")
.with(OracleConnectorConfig.SNAPSHOT_MODE, SnapshotMode.SCHEMA_ONLY)
.with(OracleConnectorConfig.TOMBSTONES_ON_DELETE, false)
.build();
start(OracleConnector.class, config);
assertConnectorIsRunning();
waitForSnapshotToBeCompleted(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
int expectedRecordCount = 0;
connection.execute("INSERT INTO debezium.customer VALUES (1, 'Billie-Bob', 1234.56, TO_DATE('2018-02-22', 'yyyy-mm-dd'))");
connection.execute("COMMIT");
expectedRecordCount += 1;
connection.execute("DELETE debezium.customer WHERE id = 1");
connection.execute("COMMIT");
expectedRecordCount += 1; // deletion, no tombstone
connection.execute("INSERT INTO debezium.customer VALUES (2, 'Billie-Bob', 1234.56, TO_DATE('2018-02-22', 'yyyy-mm-dd'))");
connection.execute("COMMIT");
expectedRecordCount += 1;
SourceRecords records = consumeRecordsByTopic(expectedRecordCount);
List<SourceRecord> testTableRecords = records.recordsForTopic("server1.DEBEZIUM.CUSTOMER");
assertThat(testTableRecords).hasSize(expectedRecordCount);
// delete
VerifyRecord.isValidDelete(testTableRecords.get(1), "ID", 1);
final Struct before = ((Struct) testTableRecords.get(1).value()).getStruct("before");
assertThat(before.get("ID")).isEqualTo(1);
assertThat(before.get("NAME")).isEqualTo("Billie-Bob");
assertThat(before.get("SCORE")).isEqualTo(BigDecimal.valueOf(1234.56));
assertThat(before.get("REGISTERED")).isEqualTo(toMicroSecondsSinceEpoch(LocalDateTime.of(2018, 2, 22, 0, 0, 0)));
VerifyRecord.isValidInsert(testTableRecords.get(2), "ID", 2);
}
@Test
public void shouldReadChangeStreamForTableCreatedWhileStreaming() throws Exception {
TestHelper.dropTable(connection, "debezium.customer2");
try {
Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM\\.CUSTOMER2")
.build();
start(OracleConnector.class, config);
assertConnectorIsRunning();
waitForSnapshotToBeCompleted(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
String ddl = "create table debezium.customer2 (" +
" id numeric(9,0) not null, " +
" name varchar2(1000), " +
" score decimal(6, 2), " +
" registered timestamp, " +
" primary key (id)" +
")";
connection.execute(ddl);
TestHelper.streamTable(connection, "debezium.customer2");
connection.execute("INSERT INTO debezium.customer2 VALUES (2, 'Billie-Bob', 1234.56, TO_DATE('2018-02-22', 'yyyy-mm-dd'))");
connection.execute("COMMIT");
SourceRecords records = consumeRecordsByTopic(1);
List<SourceRecord> testTableRecords = records.recordsForTopic("server1.DEBEZIUM.CUSTOMER2");
assertThat(testTableRecords).hasSize(1);
VerifyRecord.isValidInsert(testTableRecords.get(0), "ID", 2);
Struct after = (Struct) ((Struct) testTableRecords.get(0).value()).get("after");
assertThat(after.get("ID")).isEqualTo(2);
assertThat(after.get("NAME")).isEqualTo("Billie-Bob");
assertThat(after.get("SCORE")).isEqualTo(BigDecimal.valueOf(1234.56));
assertThat(after.get("REGISTERED")).isEqualTo(toMicroSecondsSinceEpoch(LocalDateTime.of(2018, 2, 22, 0, 0, 0)));
}
finally {
TestHelper.dropTable(connection, "debezium.customer2");
}
}
@Test
@FixFor("DBZ-800")
public void shouldReceiveHeartbeatAlsoWhenChangingTableIncludeListTables() throws Exception {
TestHelper.dropTable(connection, "debezium.dbz800a");
TestHelper.dropTable(connection, "debezium.dbz800b");
// the low heartbeat interval should make sure that a heartbeat message is emitted after each change record
// received from Postgres
Configuration config = TestHelper.defaultConfig()
.with(Heartbeat.HEARTBEAT_INTERVAL, "1")
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM\\.DBZ800B")
.build();
start(OracleConnector.class, config);
assertConnectorIsRunning();
waitForSnapshotToBeCompleted(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
connection.execute("CREATE TABLE debezium.dbz800a (id NUMBER(9) NOT NULL, aaa VARCHAR2(100), PRIMARY KEY (id) )");
connection.execute("CREATE TABLE debezium.dbz800b (id NUMBER(9) NOT NULL, bbb VARCHAR2(100), PRIMARY KEY (id) )");
connection.execute("INSERT INTO debezium.dbz800a VALUES (1, 'AAA')");
connection.execute("INSERT INTO debezium.dbz800b VALUES (2, 'BBB')");
connection.execute("COMMIT");
// The number of heartbeat events may vary depending on how fast the events are seen in
// LogMiner, so to compensate for the varied number of heartbeats that might be emitted
// the following waits until we have seen the DBZ800B event before returning.
final AtomicReference<SourceRecords> records = new AtomicReference<>();
Awaitility.await()
.atMost(Duration.ofSeconds(60))
.until(() -> {
if (records.get() == null) {
records.set(consumeRecordsByTopic(1));
}
else {
consumeRecordsByTopic(1).allRecordsInOrder().forEach(records.get()::add);
}
return records.get().recordsForTopic("server1.DEBEZIUM.DBZ800B") != null;
});
List<SourceRecord> heartbeats = records.get().recordsForTopic("__debezium-heartbeat.server1");
List<SourceRecord> tableA = records.get().recordsForTopic("server1.DEBEZIUM.DBZ800A");
List<SourceRecord> tableB = records.get().recordsForTopic("server1.DEBEZIUM.DBZ800B");
// there should be at least one heartbeat, no events for DBZ800A and one for DBZ800B
assertThat(heartbeats).isNotEmpty();
assertThat(tableA).isNull();
assertThat(tableB).hasSize(1);
VerifyRecord.isValidInsert(tableB.get(0), "ID", 2);
}
@Test
@FixFor("DBZ-775")
public void shouldConsumeEventsWithMaskedAndTruncatedColumnsWithDatabaseName() throws Exception {
shouldConsumeEventsWithMaskedAndTruncatedColumns(true);
}
@Test
@FixFor("DBZ-775")
public void shouldConsumeEventsWithMaskedAndTruncatedColumnsWithoutDatabaseName() throws Exception {
shouldConsumeEventsWithMaskedAndTruncatedColumns(false);
}
public void shouldConsumeEventsWithMaskedAndTruncatedColumns(boolean useDatabaseName) throws Exception {
final Configuration config;
if (useDatabaseName) {
final String dbName = TestHelper.getDatabaseName();
config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.SNAPSHOT_MODE, SnapshotMode.SCHEMA_ONLY)
.with("column.mask.with.12.chars", dbName + ".DEBEZIUM.MASKED_HASHED_COLUMN_TABLE.NAME")
.with("column.mask.hash.SHA-256.with.salt.CzQMA0cB5K",
dbName + ".DEBEZIUM.MASKED_HASHED_COLUMN_TABLE.NAME2," + dbName + ".DEBEZIUM.MASKED_HASHED_COLUMN_TABLE.NAME3")
.with("column.truncate.to.4.chars", dbName + ".DEBEZIUM.TRUNCATED_COLUMN_TABLE.NAME")
.build();
}
else {
config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.SNAPSHOT_MODE, SnapshotMode.SCHEMA_ONLY)
.with("column.mask.with.12.chars", "DEBEZIUM.MASKED_HASHED_COLUMN_TABLE.NAME")
.with("column.mask.hash.SHA-256.with.salt.CzQMA0cB5K", "DEBEZIUM.MASKED_HASHED_COLUMN_TABLE.NAME2,DEBEZIUM.MASKED_HASHED_COLUMN_TABLE.NAME3")
.with("column.truncate.to.4.chars", "DEBEZIUM.TRUNCATED_COLUMN_TABLE.NAME")
.build();
}
start(OracleConnector.class, config);
assertConnectorIsRunning();
waitForSnapshotToBeCompleted(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
connection.execute("INSERT INTO debezium.masked_hashed_column_table (id, name, name2, name3) VALUES (10, 'some_name', 'test', 'test')");
connection.execute("INSERT INTO debezium.truncated_column_table VALUES(11, 'some_name')");
connection.execute("COMMIT");
final SourceRecords records = consumeRecordsByTopic(2);
final List<SourceRecord> tableA = records.recordsForTopic("server1.DEBEZIUM.MASKED_HASHED_COLUMN_TABLE");
final List<SourceRecord> tableB = records.recordsForTopic("server1.DEBEZIUM.TRUNCATED_COLUMN_TABLE");
assertThat(tableA).hasSize(1);
SourceRecord record = tableA.get(0);
VerifyRecord.isValidInsert(record, "ID", 10);
Struct value = (Struct) record.value();
if (value.getStruct("after") != null) {
Struct after = value.getStruct("after");
assertThat(after.getString("NAME")).isEqualTo("************");
assertThat(after.getString("NAME2")).isEqualTo("8e68c68edbbac316dfe2f6ada6b0d2d3e2002b487a985d4b7c7c82dd83b0f4d7");
assertThat(after.getString("NAME3")).isEqualTo("8e68c68edbbac316dfe2");
}
assertThat(tableB).hasSize(1);
record = tableB.get(0);
VerifyRecord.isValidInsert(record, "ID", 11);
value = (Struct) record.value();
if (value.getStruct("after") != null) {
assertThat(value.getStruct("after").getString("NAME")).isEqualTo("some");
}
stopConnector();
}
@Test
@FixFor("DBZ-775")
public void shouldRewriteIdentityKeyWithDatabaseName() throws Exception {
shouldRewriteIdentityKey(true);
}
@Test
@FixFor("DBZ-775")
public void shouldRewriteIdentityKeyWithoutDatabaseName() throws Exception {
shouldRewriteIdentityKey(false);
}
private void shouldRewriteIdentityKey(boolean useDatabaseName) throws Exception {
final Configuration config;
if (useDatabaseName) {
config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.SNAPSHOT_MODE, SnapshotMode.SCHEMA_ONLY)
.with(OracleConnectorConfig.MSG_KEY_COLUMNS, "(.*).debezium.customer:id,name")
.build();
}
else {
config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.SNAPSHOT_MODE, SnapshotMode.SCHEMA_ONLY)
.with(OracleConnectorConfig.MSG_KEY_COLUMNS, "debezium.customer:id,name")
.build();
}
start(OracleConnector.class, config);
assertConnectorIsRunning();
waitForSnapshotToBeCompleted(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
connection.execute("INSERT INTO debezium.customer VALUES (3, 'Nest', 1234.56, TO_DATE('2018-02-22', 'yyyy-mm-dd'))");
connection.execute("COMMIT");
SourceRecords records = consumeRecordsByTopic(1);
List<SourceRecord> recordsForTopic = records.recordsForTopic("server1.DEBEZIUM.CUSTOMER");
assertThat(recordsForTopic.get(0).key()).isNotNull();
Struct key = (Struct) recordsForTopic.get(0).key();
assertThat(key.get("ID")).isNotNull();
assertThat(key.get("NAME")).isNotNull();
stopConnector();
}
@Test
@FixFor({ "DBZ-1916", "DBZ-1830" })
public void shouldPropagateSourceTypeByDatatype() throws Exception {
final Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.SNAPSHOT_MODE, SnapshotMode.SCHEMA_ONLY)
.with("datatype.propagate.source.type", ".+\\.NUMBER,.+\\.VARCHAR2,.+\\.FLOAT")
.build();
start(OracleConnector.class, config);
assertConnectorIsRunning();
waitForSnapshotToBeCompleted(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
connection.execute("INSERT INTO debezium.dt_table (id,c1,c2,c3a,c3b,f1,f2) values (1,123,456,789.01,'test',1.228,234.56)");
connection.execute("COMMIT");
final SourceRecords records = consumeRecordsByTopic(1);
List<SourceRecord> recordsForTopic = records.recordsForTopic("server1.DEBEZIUM.DT_TABLE");
assertThat(recordsForTopic).hasSize(1);
final Field before = recordsForTopic.get(0).valueSchema().field("before");
assertThat(before.schema().field("ID").schema().parameters()).includes(
entry(TYPE_NAME_PARAMETER_KEY, "NUMBER"),
entry(TYPE_LENGTH_PARAMETER_KEY, "9"),
entry(TYPE_SCALE_PARAMETER_KEY, "0"));
assertThat(before.schema().field("C1").schema().parameters()).includes(
entry(TYPE_NAME_PARAMETER_KEY, "NUMBER"),
entry(TYPE_LENGTH_PARAMETER_KEY, "38"),
entry(TYPE_SCALE_PARAMETER_KEY, "0"));
assertThat(before.schema().field("C2").schema().parameters()).includes(
entry(TYPE_NAME_PARAMETER_KEY, "NUMBER"),
entry(TYPE_LENGTH_PARAMETER_KEY, "38"),
entry(TYPE_SCALE_PARAMETER_KEY, "0"));
assertThat(before.schema().field("C3A").schema().parameters()).includes(
entry(TYPE_NAME_PARAMETER_KEY, "NUMBER"),
entry(TYPE_LENGTH_PARAMETER_KEY, "5"),
entry(TYPE_SCALE_PARAMETER_KEY, "2"));
assertThat(before.schema().field("C3B").schema().parameters()).includes(
entry(TYPE_NAME_PARAMETER_KEY, "VARCHAR2"),
entry(TYPE_LENGTH_PARAMETER_KEY, "128"));
assertThat(before.schema().field("F2").schema().parameters()).includes(
entry(TYPE_NAME_PARAMETER_KEY, "NUMBER"),
entry(TYPE_LENGTH_PARAMETER_KEY, "8"),
entry(TYPE_SCALE_PARAMETER_KEY, "4"));
assertThat(before.schema().field("F1").schema().parameters()).includes(
entry(TYPE_NAME_PARAMETER_KEY, "FLOAT"),
entry(TYPE_LENGTH_PARAMETER_KEY, "10"));
}
@Test
@FixFor({ "DBZ-4385" })
public void shouldTruncate() throws Exception {
// Drop table if it exists
TestHelper.dropTable(connection, "debezium.truncate_ddl");
try {
// complex ddl
final String ddl = "create table debezium.truncate_ddl (" +
"id NUMERIC(6), " +
"name VARCHAR(100), " +
"primary key(id))";
// create table
connection.execute(ddl);
TestHelper.streamTable(connection, "debezium.truncate_ddl");
// Insert a snapshot record
connection.execute("INSERT INTO debezium.truncate_ddl (id, name) values (1, 'Acme')");
connection.commit();
final Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM.TRUNCATE_DDL")
.build();
// Perform a basic startup & initial snapshot of data
start(OracleConnector.class, config);
assertConnectorIsRunning();
waitForSnapshotToBeCompleted(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
final SourceRecords snapshotRecords = consumeRecordsByTopic(1);
assertThat(snapshotRecords.recordsForTopic("server1.DEBEZIUM.TRUNCATE_DDL")).hasSize(1);
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
// truncate statement
connection.execute("TRUNCATE TABLE debezium.truncate_ddl");
SourceRecords streamingRecords = consumeRecordsByTopic(1);
List<SourceRecord> records = streamingRecords.recordsForTopic("server1.DEBEZIUM.TRUNCATE_DDL");
assertThat(records).hasSize(1);
String op = ((Struct) records.get(0).value()).getString("op");
assertThat(op).isEqualTo("t");
// verify record after truncate
connection.execute("INSERT INTO debezium.truncate_ddl (id, name) values (2, 'Roadrunner')");
connection.commit();
streamingRecords = consumeRecordsByTopic(1);
records = streamingRecords.recordsForTopic("server1.DEBEZIUM.TRUNCATE_DDL");
assertThat(records).hasSize(1);
op = ((Struct) records.get(0).value()).getString("op");
assertThat(op).isEqualTo("c");
}
finally {
TestHelper.dropTable(connection, "debezium.truncate_ddl");
}
}
@Test
@FixFor({ "DBZ-4385" })
public void shouldNotTruncateWhenSkipped() throws Exception {
// Drop table if it exists
TestHelper.dropTable(connection, "debezium.truncate_ddl");
try {
// complex ddl
final String ddl = "create table debezium.truncate_ddl (" +
"id NUMERIC(6), " +
"name VARCHAR(100), " +
"primary key(id))";
// create table
connection.execute(ddl);
TestHelper.streamTable(connection, "debezium.truncate_ddl");
// Insert a snapshot record
connection.execute("INSERT INTO debezium.truncate_ddl (id, name) values (1, 'Acme')");
connection.commit();
final Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM.TRUNCATE_DDL")
.with(OracleConnectorConfig.SKIPPED_OPERATIONS, "t") // Filter out truncate operations.
.build();
// Perform a basic startup & initial snapshot of data
start(OracleConnector.class, config);
assertConnectorIsRunning();
waitForSnapshotToBeCompleted(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
final SourceRecords snapshotRecords = consumeRecordsByTopic(1);
assertThat(snapshotRecords.recordsForTopic("server1.DEBEZIUM.TRUNCATE_DDL")).hasSize(1);
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
// truncate statement
connection.execute("TRUNCATE TABLE debezium.truncate_ddl");
// Nothing happens, so nothing to verify either.
// verify record after truncate
connection.execute("INSERT INTO debezium.truncate_ddl (id, name) values (2, 'Roadrunner')");
connection.commit();
SourceRecords streamingRecords = consumeRecordsByTopic(1);
List<SourceRecord> records = streamingRecords.recordsForTopic("server1.DEBEZIUM.TRUNCATE_DDL");
assertThat(records).hasSize(1);
String op = ((Struct) records.get(0).value()).getString("op");
assertThat(op).isEqualTo("c");
}
finally {
TestHelper.dropTable(connection, "debezium.truncate_ddl");
}
}
@FixFor("DBZ-1539")
public void shouldHandleIntervalTypesAsInt64() throws Exception {
// Drop table if it exists
TestHelper.dropTable(connection, "debezium.interval");
try {
// complex ddl
final String ddl = "create table debezium.interval (" +
" id numeric(6) constraint interval_id_nn not null, " +
" intYM interval year to month," +
" intYM2 interval year(9) to month," + // max precision
" intDS interval day to second, " +
" intDS2 interval day(9) to second(9), " + // max precision
" constraint interval_pk primary key(id)" +
")";
// create table
connection.execute(ddl);
TestHelper.streamTable(connection, "debezium.interval");
// Insert a snapshot record
connection.execute("INSERT INTO debezium.interval (id, intYM, intYM2, intDS, intDS2) "
+ "values (1, INTERVAL '2' YEAR, INTERVAL '555-4' YEAR(3) TO MONTH, "
+ "INTERVAL '3' DAY, INTERVAL '111 10:09:08.555444333' DAY(3) TO SECOND(9))");
connection.execute("INSERT INTO debezium.interval (id, intYM, intYM2, intDS, intDS2) "
+ "values (2, INTERVAL '0' YEAR, INTERVAL '0' MONTH, "
+ "INTERVAL '0' DAY, INTERVAL '0' SECOND)");
connection.commit();
final Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM.INTERVAL")
.with(OracleConnectorConfig.LOG_MINING_STRATEGY, "online_catalog")
.build();
// Perform a basic startup & initial snapshot of data
start(OracleConnector.class, config);
assertConnectorIsRunning();
waitForSnapshotToBeCompleted(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
// Verify record generated during snapshot
final SourceRecords snapshotRecords = consumeRecordsByTopic(2);
assertThat(snapshotRecords.allRecordsInOrder()).hasSize(2);
assertThat(snapshotRecords.topics()).contains("server1.DEBEZIUM.INTERVAL");
List<SourceRecord> records = snapshotRecords.recordsForTopic("server1.DEBEZIUM.INTERVAL");
assertThat(records).hasSize(2);
Struct after = ((Struct) records.get(0).value()).getStruct(AFTER);
assertThat(after.get("ID")).isEqualTo(1);
assertThat(after.getInt64("INTYM")).isEqualTo(63115200000000L);
assertThat(after.getInt64("INTYM2")).isEqualTo(17524987200000000L);
assertThat(after.getInt64("INTDS")).isEqualTo(259200000000L);
assertThat(after.getInt64("INTDS2")).isEqualTo(9627503444333L);
after = ((Struct) records.get(1).value()).getStruct(AFTER);
assertThat(after.getInt64("INTYM")).isEqualTo(0L);
assertThat(after.getInt64("INTYM2")).isEqualTo(0L);
assertThat(after.getInt64("INTDS")).isEqualTo(0L);
assertThat(after.getInt64("INTDS2")).isEqualTo(0L);
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
connection.execute("INSERT INTO debezium.interval (id, intYM, intYM2, intDS, intDS2) "
+ "values (3, INTERVAL '2' YEAR, INTERVAL '555-4' YEAR(3) TO MONTH, "
+ "INTERVAL '3' DAY, INTERVAL '111 10:09:08.555444333' DAY(3) TO SECOND(9))");
connection.execute("INSERT INTO debezium.interval (id, intYM, intYM2, intDS, intDS2) "
+ "values (4, INTERVAL '0' YEAR, INTERVAL '0' MONTH, "
+ "INTERVAL '0' DAY, INTERVAL '0' SECOND)");
connection.commit();
// Verify record generated during streaming
final SourceRecords streamingRecords = consumeRecordsByTopic(2);
assertThat(streamingRecords.allRecordsInOrder()).hasSize(2);
assertThat(streamingRecords.topics()).contains("server1.DEBEZIUM.INTERVAL");
records = streamingRecords.recordsForTopic("server1.DEBEZIUM.INTERVAL");
assertThat(records).hasSize(2);
after = ((Struct) records.get(0).value()).getStruct(AFTER);
assertThat(after.get("ID")).isEqualTo(3);
assertThat(after.getInt64("INTYM")).isEqualTo(63115200000000L);
assertThat(after.getInt64("INTYM2")).isEqualTo(17524987200000000L);
assertThat(after.getInt64("INTDS")).isEqualTo(259200000000L);
assertThat(after.getInt64("INTDS2")).isEqualTo(9627503444333L);
after = ((Struct) records.get(1).value()).getStruct(AFTER);
assertThat(after.get("ID")).isEqualTo(4);
assertThat(after.getInt64("INTYM")).isEqualTo(0L);
assertThat(after.getInt64("INTYM2")).isEqualTo(0L);
assertThat(after.getInt64("INTDS")).isEqualTo(0L);
assertThat(after.getInt64("INTDS2")).isEqualTo(0L);
assertNoRecordsToConsume();
}
finally {
TestHelper.dropTable(connection, "debezium.interval");
}
}
@Test
@FixFor("DBZ-1539")
public void shouldHandleIntervalTypesAsString() throws Exception {
// Drop table if it exists
TestHelper.dropTable(connection, "debezium.interval");
try {
// complex ddl
final String ddl = "create table debezium.interval (" +
" id numeric(6) constraint interval_id_nn not null, " +
" intYM interval year to month," +
" intYM2 interval year(9) to month," + // max precision
" intDS interval day to second, " +
" intDS2 interval day(9) to second(9), " + // max precision
" constraint interval_pk primary key(id)" +
")";
// create table
connection.execute(ddl);
TestHelper.streamTable(connection, "debezium.interval");
// Insert a snapshot record
connection.execute("INSERT INTO debezium.interval (id, intYM, intYM2, intDS, intDS2) "
+ "values (1, INTERVAL '2' YEAR, INTERVAL '555-4' YEAR(3) TO MONTH, "
+ "INTERVAL '3' DAY, INTERVAL '111 10:09:08.555444333' DAY(3) TO SECOND(9))");
connection.execute("INSERT INTO debezium.interval (id, intYM, intYM2, intDS, intDS2) "
+ "values (2, INTERVAL '0' YEAR, INTERVAL '0' MONTH, "
+ "INTERVAL '0' DAY, INTERVAL '0' SECOND)");
connection.commit();
final Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM.INTERVAL")
.with(OracleConnectorConfig.LOG_MINING_STRATEGY, "online_catalog")
.with(OracleConnectorConfig.INTERVAL_HANDLING_MODE,
OracleConnectorConfig.IntervalHandlingMode.STRING.getValue())
.build();
// Perform a basic startup & initial snapshot of data
start(OracleConnector.class, config);
assertConnectorIsRunning();
waitForSnapshotToBeCompleted(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
// Verify record generated during snapshot
final SourceRecords snapshotRecords = consumeRecordsByTopic(2);
assertThat(snapshotRecords.allRecordsInOrder()).hasSize(2);
assertThat(snapshotRecords.topics()).contains("server1.DEBEZIUM.INTERVAL");
List<SourceRecord> records = snapshotRecords.recordsForTopic("server1.DEBEZIUM.INTERVAL");
assertThat(records).hasSize(2);
Struct after = ((Struct) records.get(0).value()).getStruct(AFTER);
assertThat(after.get("ID")).isEqualTo(1);
assertThat(after.getString("INTYM")).isEqualTo("P2Y0M0DT0H0M0S");
assertThat(after.getString("INTYM2")).isEqualTo("P555Y4M0DT0H0M0S");
assertThat(after.getString("INTDS")).isEqualTo("P0Y0M3DT0H0M0S");
assertThat(after.getString("INTDS2")).isEqualTo("P0Y0M111DT10H9M563.444333S");
after = ((Struct) records.get(1).value()).getStruct(AFTER);
assertThat(after.get("ID")).isEqualTo(2);
assertThat(after.getString("INTYM")).isEqualTo("P0Y0M0DT0H0M0S");
assertThat(after.getString("INTYM2")).isEqualTo("P0Y0M0DT0H0M0S");
assertThat(after.getString("INTDS")).isEqualTo("P0Y0M0DT0H0M0S");
assertThat(after.getString("INTDS2")).isEqualTo("P0Y0M0DT0H0M0S");
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
connection.execute("INSERT INTO debezium.interval (id, intYM, intYM2, intDS, intDS2) "
+ "values (3, INTERVAL '2' YEAR, INTERVAL '555-4' YEAR(3) TO MONTH, "
+ "INTERVAL '3' DAY, INTERVAL '111 10:09:08.555444333' DAY(3) TO SECOND(9))");
connection.execute("INSERT INTO debezium.interval (id, intYM, intYM2, intDS, intDS2) "
+ "values (4, INTERVAL '0' YEAR, INTERVAL '0' MONTH, "
+ "INTERVAL '0' DAY, INTERVAL '0' SECOND)");
connection.commit();
// Verify record generated during streaming
final SourceRecords streamingRecords = consumeRecordsByTopic(2);
assertThat(streamingRecords.allRecordsInOrder()).hasSize(2);
assertThat(streamingRecords.topics()).contains("server1.DEBEZIUM.INTERVAL");
records = streamingRecords.recordsForTopic("server1.DEBEZIUM.INTERVAL");
assertThat(records).hasSize(2);
after = ((Struct) records.get(0).value()).getStruct(AFTER);
assertThat(after.get("ID")).isEqualTo(3);
assertThat(after.getString("INTYM")).isEqualTo("P2Y0M0DT0H0M0S");
assertThat(after.getString("INTYM2")).isEqualTo("P555Y4M0DT0H0M0S");
assertThat(after.getString("INTDS")).isEqualTo("P0Y0M3DT0H0M0S");
assertThat(after.getString("INTDS2")).isEqualTo("P0Y0M111DT10H9M563.444333S");
after = ((Struct) records.get(1).value()).getStruct(AFTER);
assertThat(after.get("ID")).isEqualTo(4);
assertThat(after.getString("INTYM")).isEqualTo("P0Y0M0DT0H0M0S");
assertThat(after.getString("INTYM2")).isEqualTo("P0Y0M0DT0H0M0S");
assertThat(after.getString("INTDS")).isEqualTo("P0Y0M0DT0H0M0S");
assertThat(after.getString("INTDS2")).isEqualTo("P0Y0M0DT0H0M0S");
assertNoRecordsToConsume();
}
finally {
TestHelper.dropTable(connection, "debezium.interval");
}
}
@Test
@FixFor("DBZ-2624")
public void shouldSnapshotAndStreamChangesFromTableWithNumericDefaultValues() throws Exception {
// Drop table if it exists
TestHelper.dropTable(connection, "debezium.complex_ddl");
try {
// complex ddl
final String ddl = "create table debezium.complex_ddl (" +
" id numeric(6) constraint customers_id_nn not null, " +
" name varchar2(100)," +
" value numeric default 1, " +
" constraint customers_pk primary key(id)" +
")";
// create table
connection.execute(ddl);
connection.execute("GRANT SELECT ON debezium.complex_ddl to " + TestHelper.getConnectorUserName());
connection.execute("ALTER TABLE debezium.complex_ddl ADD SUPPLEMENTAL LOG DATA (ALL) COLUMNS");
// Insert a snapshot record
connection.execute("INSERT INTO debezium.complex_ddl (id, name) values (1, 'Acme')");
connection.commit();
final Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM.COMPLEX_DDL")
.with(OracleConnectorConfig.LOG_MINING_STRATEGY, "online_catalog")
.build();
// Perform a basic startup & initial snapshot of data
start(OracleConnector.class, config);
assertConnectorIsRunning();
waitForSnapshotToBeCompleted(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
// Verify record generated during snapshot
final SourceRecords snapshotRecords = consumeRecordsByTopic(1);
assertThat(snapshotRecords.recordsForTopic("server1.DEBEZIUM.COMPLEX_DDL").size()).isEqualTo(1);
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
connection.execute("INSERT INTO debezium.complex_ddl (id, name)values (2, 'Acme2')");
connection.commit();
// Verify record generated during streaming
final SourceRecords streamingRecords = consumeRecordsByTopic(1);
assertThat(streamingRecords.recordsForTopic("server1.DEBEZIUM.COMPLEX_DDL").size()).isEqualTo(1);
}
finally {
TestHelper.dropTable(connection, "debezium.complex_ddl");
}
}
@Test
@FixFor("DBZ-2683")
@RequireDatabaseOption("Partitioning")
public void shouldSnapshotAndStreamChangesFromPartitionedTable() throws Exception {
TestHelper.dropTable(connection, "players");
try {
final String ddl = "CREATE TABLE players (" +
"id NUMERIC(6), " +
"name VARCHAR(100), " +
"birth_date DATE," +
"primary key(id)) " +
"PARTITION BY RANGE (birth_date) (" +
"PARTITION p2019 VALUES LESS THAN (TO_DATE('2020-01-01', 'yyyy-mm-dd')), " +
"PARTITION p2020 VALUES LESS THAN (TO_DATE('2021-01-01', 'yyyy-mm-dd'))" +
")";
connection.execute(ddl);
connection.execute("GRANT SELECT ON debezium.players to " + TestHelper.getConnectorUserName());
connection.execute("ALTER TABLE debezium.players ADD SUPPLEMENTAL LOG DATA (ALL) COLUMNS");
// Insert a record to be captured by snapshot
connection.execute("INSERT INTO debezium.players (id, name, birth_date) VALUES (1, 'Roger Rabbit', TO_DATE('2019-05-01', 'yyyy-mm-dd'))");
connection.commit();
// Start connector
final Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM.PLAYERS")
.build();
start(OracleConnector.class, config);
assertConnectorIsRunning();
waitForSnapshotToBeCompleted(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
final SourceRecords snapshotRecords = consumeRecordsByTopic(1);
assertThat(snapshotRecords.recordsForTopic("server1.DEBEZIUM.PLAYERS").size()).isEqualTo(1);
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
// Insert a record to be captured during streaming
connection.execute("INSERT INTO debezium.players (id, name, birth_date) VALUES (2, 'Bugs Bunny', TO_DATE('2019-06-26', 'yyyy-mm-dd'))");
connection.execute("INSERT INTO debezium.players (id, name, birth_date) VALUES (3, 'Elmer Fud', TO_DATE('2020-11-01', 'yyyy-mm-dd'))");
connection.commit();
final SourceRecords streamRecords = consumeRecordsByTopic(2);
assertThat(streamRecords.recordsForTopic("server1.DEBEZIUM.PLAYERS").size()).isEqualTo(2);
}
finally {
TestHelper.dropTable(connection, "players");
}
}
@Test
@FixFor("DBZ-2849")
public void shouldAvroSerializeColumnsWithSpecialCharacters() throws Exception {
// Setup environment
TestHelper.dropTable(connection, "columns_test");
try {
connection.execute("CREATE TABLE columns_test (id NUMERIC(6), amount$ number not null, primary key(id))");
connection.execute("GRANT SELECT ON debezium.columns_test to " + TestHelper.getConnectorUserName());
connection.execute("ALTER TABLE debezium.columns_test ADD SUPPLEMENTAL LOG DATA (ALL) COLUMNS");
// Insert a record for snapshot
connection.execute("INSERT INTO debezium.columns_test (id, amount$) values (1, 12345.67)");
connection.commit();
// Start connector
final Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM.COLUMNS_TEST")
.with(OracleConnectorConfig.SANITIZE_FIELD_NAMES, "true")
.build();
start(OracleConnector.class, config);
assertConnectorIsRunning();
waitForSnapshotToBeCompleted(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
final SourceRecords snapshots = consumeRecordsByTopic(1);
assertThat(snapshots.recordsForTopic("server1.DEBEZIUM.COLUMNS_TEST").size()).isEqualTo(1);
final SourceRecord snapshot = snapshots.recordsForTopic("server1.DEBEZIUM.COLUMNS_TEST").get(0);
VerifyRecord.isValidRead(snapshot, "ID", 1);
Struct after = ((Struct) snapshot.value()).getStruct(AFTER);
assertThat(after.getInt32("ID")).isEqualTo(1);
assertThat(after.get("AMOUNT_")).isEqualTo(VariableScaleDecimal.fromLogical(after.schema().field("AMOUNT_").schema(), BigDecimal.valueOf(12345.67d)));
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
// Insert a record for streaming
connection.execute("INSERT INTO debezium.columns_test (id, amount$) values (2, 23456.78)");
connection.commit();
final SourceRecords streams = consumeRecordsByTopic(1);
assertThat(streams.recordsForTopic("server1.DEBEZIUM.COLUMNS_TEST").size()).isEqualTo(1);
final SourceRecord stream = streams.recordsForTopic("server1.DEBEZIUM.COLUMNS_TEST").get(0);
VerifyRecord.isValidInsert(stream, "ID", 2);
after = ((Struct) stream.value()).getStruct(AFTER);
assertThat(after.getInt32("ID")).isEqualTo(2);
assertThat(after.get("AMOUNT_")).isEqualTo(VariableScaleDecimal.fromLogical(after.schema().field("AMOUNT_").schema(), BigDecimal.valueOf(23456.78d)));
}
finally {
TestHelper.dropTable(connection, "columns_test");
}
}
@Test
@FixFor("DBZ-2825")
@SkipWhenAdapterNameIsNot(value = SkipWhenAdapterNameIsNot.AdapterName.LOGMINER, reason = "Tests archive log support for LogMiner only")
public void testArchiveLogScnBoundariesAreIncluded() throws Exception {
// Drop table if it exists
TestHelper.dropTable(connection, "alog_test");
try {
final String ddl = "CREATE TABLE alog_test (id numeric, name varchar2(50), primary key(id))";
connection.execute(ddl);
connection.execute("GRANT SELECT ON debezium.alog_test TO " + TestHelper.getConnectorUserName());
connection.execute("ALTER TABLE debezium.alog_test ADD SUPPLEMENTAL LOG DATA (ALL) COLUMNS");
connection.commit();
// Insert a snapshot record
connection.execute("INSERT INTO debezium.alog_test (id, name) VALUES (1, 'Test')");
connection.commit();
// start connector and take snapshot
final Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM.ALOG_TEST")
.build();
start(OracleConnector.class, config);
assertConnectorIsRunning();
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
// Validate snapshot record
final SourceRecords snapshotRecords = consumeRecordsByTopic(1);
assertThat(snapshotRecords.recordsForTopic("server1.DEBEZIUM.ALOG_TEST").size()).isEqualTo(1);
SourceRecord record = snapshotRecords.recordsForTopic("server1.DEBEZIUM.ALOG_TEST").get(0);
Struct after = (Struct) ((Struct) record.value()).get(AFTER);
assertThat(after.get("ID")).isEqualTo(BigDecimal.valueOf(1));
assertThat(after.get("NAME")).isEqualTo("Test");
// stop the connector
stopConnector();
// Force flush of all redo logs to archive logs
TestHelper.forceFlushOfRedoLogsToArchiveLogs();
// Start connector and wait for streaming
start(OracleConnector.class, config);
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
// Insert record for streaming
connection.execute("INSERT INTO debezium.alog_test (id, name) values (2, 'Home')");
connection.execute("COMMIT");
// Validate streaming record
final SourceRecords records = consumeRecordsByTopic(1);
assertThat(records.recordsForTopic("server1.DEBEZIUM.ALOG_TEST").size()).isEqualTo(1);
record = records.recordsForTopic("server1.DEBEZIUM.ALOG_TEST").get(0);
after = (Struct) ((Struct) record.value()).get(AFTER);
assertThat(after.get("ID")).isEqualTo(BigDecimal.valueOf(2));
assertThat(after.get("NAME")).isEqualTo("Home");
}
finally {
TestHelper.dropTable(connection, "alog_test");
}
}
@Test
@FixFor("DBZ-2784")
public void shouldConvertDatesSpecifiedAsStringInSQL() throws Exception {
try {
TestHelper.dropTable(connection, "orders");
final String ddl = "CREATE TABLE orders (" +
"id NUMERIC(6), " +
"order_date date not null," +
"primary key(id))";
connection.execute(ddl);
connection.execute("GRANT SELECT ON debezium.orders TO " + TestHelper.getConnectorUserName());
connection.execute("ALTER TABLE debezium.orders ADD SUPPLEMENTAL LOG DATA (ALL) COLUMNS");
connection.execute("INSERT INTO debezium.orders VALUES (9, '22-FEB-2018')");
connection.execute("COMMIT");
final Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.SNAPSHOT_MODE, SnapshotMode.INITIAL)
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "debezium.orders")
.build();
start(OracleConnector.class, config);
assertNoRecordsToConsume();
waitForSnapshotToBeCompleted(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
final SourceRecords snapshotRecords = consumeRecordsByTopic(1);
final List<SourceRecord> snapshotOrders = snapshotRecords.recordsForTopic("server1.DEBEZIUM.ORDERS");
assertThat(snapshotOrders.size()).isEqualTo(1);
final Struct snapshotAfter = ((Struct) snapshotOrders.get(0).value()).getStruct(AFTER);
assertThat(snapshotAfter.get("ID")).isEqualTo(9);
assertThat(snapshotAfter.get("ORDER_DATE")).isEqualTo(1519257600000L);
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
connection.execute("INSERT INTO debezium.orders VALUES (10, TO_DATE('2018-02-22', 'yyyy-mm-dd'))");
connection.execute("COMMIT");
final SourceRecords streamRecords = consumeRecordsByTopic(1);
final List<SourceRecord> orders = streamRecords.recordsForTopic("server1.DEBEZIUM.ORDERS");
assertThat(orders).hasSize(1);
final Struct after = ((Struct) orders.get(0).value()).getStruct(AFTER);
assertThat(after.get("ID")).isEqualTo(10);
assertThat(after.get("ORDER_DATE")).isEqualTo(1519257600000L);
}
finally {
TestHelper.dropTable(connection, "orders");
}
}
@Test
@FixFor("DBZ-2733")
public void shouldConvertNumericAsStringDecimalHandlingMode() throws Exception {
TestHelper.dropTable(connection, "table_number_pk");
try {
final String ddl = "CREATE TABLE table_number_pk (id NUMBER, name varchar2(255), age number, primary key (id))";
connection.execute(ddl);
connection.execute("GRANT SELECT ON debezium.table_number_pk TO " + TestHelper.getConnectorUserName());
connection.execute("ALTER TABLE debezium.table_number_pk ADD SUPPLEMENTAL LOG DATA (ALL) COLUMNS");
// Insert snapshot record
connection.execute("INSERT INTO debezium.table_number_pk (id, name, age) values (1, 'Bob', 25)");
connection.execute("COMMIT");
final Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.SNAPSHOT_MODE, SnapshotMode.INITIAL)
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "debezium.table_number_pk")
.with(OracleConnectorConfig.DECIMAL_HANDLING_MODE, "string")
.build();
// Start connector
start(OracleConnector.class, config);
assertNoRecordsToConsume();
waitForSnapshotToBeCompleted(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
// Read snapshot record & verify
SourceRecords records = consumeRecordsByTopic(1);
assertThat(records.recordsForTopic("server1.DEBEZIUM.TABLE_NUMBER_PK")).hasSize(1);
SourceRecord record = records.recordsForTopic("server1.DEBEZIUM.TABLE_NUMBER_PK").get(0);
List<SchemaAndValueField> expected = Arrays.asList(
new SchemaAndValueField("ID", Schema.STRING_SCHEMA, "1"),
new SchemaAndValueField("NAME", Schema.OPTIONAL_STRING_SCHEMA, "Bob"),
new SchemaAndValueField("AGE", Schema.OPTIONAL_STRING_SCHEMA, "25"));
assertRecordSchemaAndValues(expected, record, AFTER);
// Wait for streaming to have begun
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
// Insert streaming record
connection.execute("INSERT INTO debezium.table_number_pk (id, name, age) values (2, 'Sue', 30)");
connection.execute("COMMIT");
// Read stream record & verify
records = consumeRecordsByTopic(1);
assertThat(records.recordsForTopic("server1.DEBEZIUM.TABLE_NUMBER_PK")).hasSize(1);
record = records.recordsForTopic("server1.DEBEZIUM.TABLE_NUMBER_PK").get(0);
expected = Arrays.asList(
new SchemaAndValueField("ID", Schema.STRING_SCHEMA, "2"),
new SchemaAndValueField("NAME", Schema.OPTIONAL_STRING_SCHEMA, "Sue"),
new SchemaAndValueField("AGE", Schema.OPTIONAL_STRING_SCHEMA, "30"));
assertRecordSchemaAndValues(expected, record, AFTER);
}
finally {
TestHelper.dropTable(connection, "table_number_pk");
}
}
protected void assertRecordSchemaAndValues(List<SchemaAndValueField> expectedByColumn, SourceRecord record, String envelopeFieldName) {
Struct content = ((Struct) record.value()).getStruct(envelopeFieldName);
if (expectedByColumn == null) {
assertThat(content).isNull();
}
else {
assertThat(content).as("expected there to be content in Envelope under " + envelopeFieldName).isNotNull();
expectedByColumn.forEach(expected -> expected.assertFor(content));
}
}
@Test
@FixFor("DBZ-2920")
public void shouldStreamDdlThatExceeds4000() throws Exception {
TestHelper.dropTable(connection, "large_dml");
// Setup table
final String ddl = "CREATE TABLE large_dml (id NUMERIC(6), value varchar2(4000), value2 varchar2(4000), primary key(id))";
connection.execute(ddl);
connection.execute("GRANT SELECT ON debezium.large_dml TO " + TestHelper.getConnectorUserName());
connection.execute("ALTER TABLE debezium.large_dml ADD SUPPLEMENTAL LOG DATA (ALL) COLUMNS");
// Prepare snapshot record
String largeValue = generateAlphaNumericStringColumn(4000);
String largeValue2 = generateAlphaNumericStringColumn(4000);
connection.execute("INSERT INTO large_dml (id, value, value2) values (1, '" + largeValue + "', '" + largeValue2 + "')");
connection.commit();
// Start connector
final Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "debezium.large_dml")
.with(OracleConnectorConfig.SNAPSHOT_MODE, SnapshotMode.INITIAL)
.build();
start(OracleConnector.class, config);
assertNoRecordsToConsume();
// Verify snapshot
waitForSnapshotToBeCompleted(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
SourceRecords records = consumeRecordsByTopic(1);
assertThat(records.topics()).hasSize(1);
assertThat(records.recordsForTopic("server1.DEBEZIUM.LARGE_DML")).hasSize(1);
Struct after = ((Struct) records.recordsForTopic("server1.DEBEZIUM.LARGE_DML").get(0).value()).getStruct(AFTER);
assertThat(after.get("ID")).isEqualTo(1);
assertThat(after.get("VALUE")).isEqualTo(largeValue);
assertThat(after.get("VALUE2")).isEqualTo(largeValue2);
// Prepare stream records
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
List<String> largeValues = new ArrayList<>();
List<String> largeValues2 = new ArrayList<>();
for (int i = 0; i < 10; ++i) {
largeValues.add(generateAlphaNumericStringColumn(4000));
largeValues2.add(generateAlphaNumericStringColumn(4000));
connection.execute("INSERT INTO large_dml (id, value, value2) values (" + (2 + i) + ", '" + largeValues.get(largeValues.size() - 1) + "', '"
+ largeValues2.get(largeValues2.size() - 1) + "')");
}
connection.commit();
// Verify stream
records = consumeRecordsByTopic(10);
assertThat(records.topics()).hasSize(1);
assertThat(records.recordsForTopic("server1.DEBEZIUM.LARGE_DML")).hasSize(10);
List<SourceRecord> entries = records.recordsForTopic("server1.DEBEZIUM.LARGE_DML");
for (int i = 0; i < 10; ++i) {
SourceRecord record = entries.get(i);
after = ((Struct) record.value()).getStruct(AFTER);
assertThat(after.get("ID")).isEqualTo(2 + i);
assertThat(after.get("VALUE")).isEqualTo(largeValues.get(i));
assertThat(after.get("VALUE2")).isEqualTo(largeValues2.get(i));
}
// Stop connector
stopConnector((r) -> TestHelper.dropTable(connection, "large_dml"));
}
@Test
@FixFor("DBZ-2891")
@SkipWhenAdapterNameIsNot(value = SkipWhenAdapterNameIsNot.AdapterName.XSTREAM, reason = "Only applies to Xstreams")
public void shouldNotObserveDeadlockWhileStreamingWithXstream() throws Exception {
long oldPollTimeInMs = pollTimeoutInMs;
TestHelper.dropTable(connection, "deadlock_test");
try {
final String ddl = "CREATE TABLE deadlock_test (id numeric(9), name varchar2(50), primary key(id))";
connection.execute(ddl);
connection.execute("GRANT SELECT ON debezium.deadlock_test TO " + TestHelper.getConnectorUserName());
connection.execute("ALTER TABLE debezium.deadlock_test ADD SUPPLEMENTAL LOG DATA (ALL) COLUMNS");
// Set connector to poll very slowly
this.pollTimeoutInMs = TimeUnit.SECONDS.toMillis(20);
final Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "debezium.deadlock_test")
.with(OracleConnectorConfig.SNAPSHOT_MODE, SnapshotMode.INITIAL)
.with(OracleConnectorConfig.MAX_QUEUE_SIZE, 2)
.with(RelationalDatabaseConnectorConfig.MAX_BATCH_SIZE, 1)
.build();
start(OracleConnector.class, config);
assertNoRecordsToConsume();
waitForSnapshotToBeCompleted(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
for (int i = 0; i < 10; ++i) {
connection.execute("INSERT INTO deadlock_test (id, name) values (" + i + ", 'Test " + i + "')");
connection.execute("COMMIT");
}
SourceRecords records = consumeRecordsByTopic(10, 24);
assertThat(records.topics()).hasSize(1);
assertThat(records.recordsForTopic("server1.DEBEZIUM.DEADLOCK_TEST")).hasSize(10);
}
finally {
// Reset poll time
this.pollTimeoutInMs = oldPollTimeInMs;
TestHelper.dropTable(connection, "deadlock_test");
}
}
@Test
@FixFor("DBZ-3057")
public void shouldReadTableUniqueIndicesWithCharactersThatRequireExplicitQuotes() throws Exception {
final String TABLE_NAME = "debezium.\"#T70_Sid:582003931_1_ConnConne\"";
try {
TestHelper.dropTable(connection, TABLE_NAME);
final String ddl = "CREATE GLOBAL TEMPORARY TABLE " + TABLE_NAME + " (id number, name varchar2(50))";
connection.execute(ddl);
connection.execute("GRANT SELECT ON " + TABLE_NAME + " TO " + TestHelper.getConnectorUserName());
connection.execute("ALTER TABLE " + TABLE_NAME + " ADD SUPPLEMENTAL LOG DATA (ALL) COLUMNS");
final Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.SNAPSHOT_MODE, OracleConnectorConfig.SnapshotMode.INITIAL)
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM\\.\\#T70_Sid\\:582003931_1_ConnConne")
.build();
start(OracleConnector.class, config);
assertConnectorIsRunning();
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
}
finally {
TestHelper.dropTable(connection, TABLE_NAME);
}
}
@Test
@FixFor("DBZ-3151")
public void testSnapshotCompletesWithSystemGeneratedUniqueIndexOnKeylessTable() throws Exception {
TestHelper.dropTable(connection, "XML_TABLE");
try {
final String ddl = "CREATE TABLE XML_TABLE of XMLTYPE";
connection.execute(ddl);
connection.execute("GRANT SELECT ON DEBEZIUM.XML_TABLE TO " + TestHelper.getConnectorUserName());
connection.execute("ALTER TABLE DEBEZIUM.XML_TABLE ADD SUPPLEMENTAL LOG DATA (ALL) COLUMNS");
connection.execute("INSERT INTO DEBEZIUM.XML_TABLE values (xmltype('<?xml version=\"1.0\"?><tab><name>Hi</name></tab>'))");
connection.execute("COMMIT");
final Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.SNAPSHOT_MODE, SnapshotMode.INITIAL)
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM\\.XML_TABLE")
.build();
start(OracleConnector.class, config);
assertNoRecordsToConsume();
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
}
finally {
TestHelper.dropTable(connection, "XML_TABLE");
}
}
@Test
@FixFor("DBZ-3001")
public void shouldGetOracleDatabaseVersion() throws Exception {
OracleDatabaseVersion version = connection.getOracleVersion();
assertThat(version).isNotNull();
assertThat(version.getMajor()).isGreaterThan(0);
}
@Test
@FixFor("DBZ-3109")
public void shouldStreamChangesForTableWithMultipleLogGroupTypes() throws Exception {
try {
TestHelper.dropTable(connection, "log_group_test");
final String ddl = "CREATE TABLE log_group_test (id numeric(9,0) primary key, name varchar2(50))";
connection.execute(ddl);
connection.execute("GRANT SELECT ON debezium.log_group_test TO " + TestHelper.getConnectorUserName());
connection.execute("ALTER TABLE debezium.log_group_test ADD SUPPLEMENTAL LOG DATA (ALL) COLUMNS");
connection.execute("ALTER TABLE debezium.log_group_test ADD SUPPLEMENTAL LOG DATA (PRIMARY KEY) COLUMNS");
final Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.SNAPSHOT_MODE, SnapshotMode.INITIAL)
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM\\.LOG_GROUP_TEST")
.build();
start(OracleConnector.class, config);
assertConnectorIsRunning();
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
connection.execute("INSERT INTO debezium.log_group_test (id, name) values (1,'Test')");
connection.execute("COMMIT");
SourceRecords records = consumeRecordsByTopic(1);
assertThat(records.recordsForTopic("server1.DEBEZIUM.LOG_GROUP_TEST")).hasSize(1);
}
finally {
TestHelper.dropTable(connection, "log_group_test");
}
}
@Test
@FixFor("DBZ-2875")
public void shouldResumeStreamingAtCorrectScnOffset() throws Exception {
TestHelper.dropTable(connection, "offset_test");
try {
Testing.Debug.enable();
connection.execute("CREATE TABLE offset_test (id numeric(9,0) primary key, name varchar2(50))");
connection.execute("GRANT SELECT ON debezium.offset_test TO " + TestHelper.getConnectorUserName());
connection.execute("ALTER TABLE debezium.offset_test ADD SUPPLEMENTAL LOG DATA (ALL) COLUMNS");
final Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.SNAPSHOT_MODE, SnapshotMode.SCHEMA_ONLY)
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM\\.OFFSET_TEST")
.build();
start(OracleConnector.class, config);
assertNoRecordsToConsume();
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
connection.execute("INSERT INTO debezium.offset_test (id, name) values (1, 'Bob')");
SourceRecords records1 = consumeRecordsByTopic(1);
assertThat(records1.recordsForTopic("server1.DEBEZIUM.OFFSET_TEST")).hasSize(1);
Struct after = (Struct) ((Struct) records1.allRecordsInOrder().get(0).value()).get("after");
Testing.print(after);
assertThat(after.get("ID")).isEqualTo(1);
assertThat(after.get("NAME")).isEqualTo("Bob");
stopConnector();
start(OracleConnector.class, config);
assertNoRecordsToConsume();
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
connection.execute("INSERT INTO debezium.offset_test (id, name) values (2, 'Bill')");
SourceRecords records2 = consumeRecordsByTopic(1);
assertThat(records2.recordsForTopic("server1.DEBEZIUM.OFFSET_TEST")).hasSize(1);
after = (Struct) ((Struct) records2.allRecordsInOrder().get(0).value()).get("after");
Testing.print(after);
assertThat(after.get("ID")).isEqualTo(2);
assertThat(after.get("NAME")).isEqualTo("Bill");
}
finally {
TestHelper.dropTable(connection, "offset_test");
}
}
@Test
@FixFor("DBZ-3036")
public void shouldHandleParentChildIndexOrganizedTables() throws Exception {
TestHelper.dropTable(connection, "test_iot");
try {
String ddl = "CREATE TABLE test_iot (" +
"id numeric(9,0), " +
"description varchar2(50) not null, " +
"primary key(id)) " +
"ORGANIZATION INDEX " +
"INCLUDING description " +
"OVERFLOW";
connection.execute(ddl);
TestHelper.streamTable(connection, "debezium.test_iot");
// Insert data for snapshot
connection.executeWithoutCommitting("INSERT INTO debezium.test_iot VALUES ('1', 'Hello World')");
connection.execute("COMMIT");
Configuration config = defaultConfig()
.with(OracleConnectorConfig.SCHEMA_INCLUDE_LIST, "DEBEZIUM")
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "(.)*IOT(.)*")
.build();
start(OracleConnector.class, config);
assertNoRecordsToConsume();
waitForSnapshotToBeCompleted(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
SourceRecords records = consumeRecordsByTopic(1);
assertThat(records.recordsForTopic("server1.DEBEZIUM.TEST_IOT")).hasSize(1);
SourceRecord record = records.recordsForTopic("server1.DEBEZIUM.TEST_IOT").get(0);
Struct after = (Struct) ((Struct) record.value()).get(FieldName.AFTER);
VerifyRecord.isValidRead(record, "ID", 1);
assertThat(after.get("DESCRIPTION")).isEqualTo("Hello World");
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
// Insert data for streaming
connection.executeWithoutCommitting("INSERT INTO debezium.test_iot VALUES ('2', 'Goodbye')");
connection.execute("COMMIT");
records = consumeRecordsByTopic(1);
assertThat(records.recordsForTopic("server1.DEBEZIUM.TEST_IOT")).hasSize(1);
record = records.recordsForTopic("server1.DEBEZIUM.TEST_IOT").get(0);
after = (Struct) ((Struct) record.value()).get(FieldName.AFTER);
VerifyRecord.isValidInsert(record, "ID", 2);
assertThat(after.get("DESCRIPTION")).isEqualTo("Goodbye");
}
finally {
TestHelper.dropTable(connection, "test_iot");
// This makes sure all index-organized tables are cleared after dropping parent table
TestHelper.purgeRecycleBin(connection);
}
}
// todo: should this test be removed since its now covered in OracleClobDataTypesIT?
@Test
@FixFor("DBZ-3257")
public void shouldSnapshotAndStreamClobDataTypes() throws Exception {
TestHelper.dropTable(connection, "clob_test");
try {
String ddl = "CREATE TABLE clob_test(id numeric(9,0) primary key, val_clob clob, val_nclob nclob)";
connection.execute(ddl);
TestHelper.streamTable(connection, "clob_test");
connection.execute("INSERT INTO clob_test values (1, 'TestClob', 'TestNClob')");
Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM\\.CLOB_TEST")
.with(OracleConnectorConfig.LOB_ENABLED, true)
.build();
start(OracleConnector.class, config);
assertConnectorIsRunning();
waitForSnapshotToBeCompleted(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
SourceRecords sourceRecords = consumeRecordsByTopic(1);
assertThat(sourceRecords.recordsForTopic("server1.DEBEZIUM.CLOB_TEST")).hasSize(1);
List<SourceRecord> records = sourceRecords.recordsForTopic("server1.DEBEZIUM.CLOB_TEST");
VerifyRecord.isValidRead(records.get(0), "ID", 1);
Struct after = (Struct) ((Struct) records.get(0).value()).get(Envelope.FieldName.AFTER);
assertThat(after.get("VAL_CLOB")).isEqualTo("TestClob");
assertThat(after.get("VAL_NCLOB")).isEqualTo("TestNClob");
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
connection.execute("UPDATE clob_test SET val_clob = 'TestClob2', val_nclob = 'TestNClob2' WHERE ID = 1");
sourceRecords = consumeRecordsByTopic(1);
assertThat(sourceRecords.recordsForTopic("server1.DEBEZIUM.CLOB_TEST")).hasSize(1);
records = sourceRecords.recordsForTopic("server1.DEBEZIUM.CLOB_TEST");
VerifyRecord.isValidUpdate(records.get(0), "ID", 1);
after = (Struct) ((Struct) records.get(0).value()).get(Envelope.FieldName.AFTER);
assertThat(after.get("VAL_CLOB")).isEqualTo("TestClob2");
assertThat(after.get("VAL_NCLOB")).isEqualTo("TestNClob2");
}
finally {
TestHelper.dropTable(connection, "clob_test");
}
}
@Test
@FixFor("DBZ-3347")
public void shouldContainPartitionInSchemaChangeEvent() throws Exception {
TestHelper.dropTable(connection, "dbz3347");
try {
connection.execute("create table dbz3347 (id number primary key, data varchar2(50))");
TestHelper.streamTable(connection, "dbz3347");
Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM\\.DBZ3347")
.with(OracleConnectorConfig.LOG_MINING_STRATEGY, "online_catalog")
.with(OracleConnectorConfig.INCLUDE_SCHEMA_CHANGES, true)
.build();
start(OracleConnector.class, config);
assertConnectorIsRunning();
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
SourceRecords schemaChanges = consumeRecordsByTopic(1);
SourceRecord change = schemaChanges.recordsForTopic(TestHelper.SERVER_NAME).get(0);
assertThat(change.sourcePartition()).isEqualTo(Collections.singletonMap("server", TestHelper.SERVER_NAME));
}
finally {
TestHelper.dropTable(connection, "dbz3347");
}
}
@Test
@FixFor("DBZ-832")
public void shouldSnapshotAndStreamTablesWithNoPrimaryKey() throws Exception {
TestHelper.dropTable(connection, "dbz832");
try {
connection.execute("create table dbz832 (id numeric(9,0), data varchar2(50))");
TestHelper.streamTable(connection, "dbz832");
connection.execute("INSERT INTO dbz832 values (1, 'Test')");
Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM\\.DBZ832")
.build();
start(OracleConnector.class, config);
assertConnectorIsRunning();
waitForSnapshotToBeCompleted(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
SourceRecords records = consumeRecordsByTopic(1);
assertThat(records.recordsForTopic("server1.DEBEZIUM.DBZ832")).hasSize(1);
SourceRecord record = records.recordsForTopic("server1.DEBEZIUM.DBZ832").get(0);
assertThat(record.key()).isNull();
Struct after = ((Struct) record.value()).getStruct(Envelope.FieldName.AFTER);
assertThat(after.get("ID")).isEqualTo(1);
assertThat(after.get("DATA")).isEqualTo("Test");
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
connection.execute("INSERT INTO dbz832 values (2, 'Test2')");
records = consumeRecordsByTopic(1);
assertThat(records.recordsForTopic("server1.DEBEZIUM.DBZ832")).hasSize(1);
record = records.recordsForTopic("server1.DEBEZIUM.DBZ832").get(0);
assertThat(record.key()).isNull();
after = ((Struct) record.value()).getStruct(Envelope.FieldName.AFTER);
assertThat(after.get("ID")).isEqualTo(2);
assertThat(after.get("DATA")).isEqualTo("Test2");
}
finally {
TestHelper.dropTable(connection, "dbz832");
}
}
@Test
@FixFor("DBZ-1211")
public void shouldSnapshotAndStreamTablesWithUniqueIndexPrimaryKey() throws Exception {
TestHelper.dropTables(connection, "dbz1211_child", "dbz1211");
try {
connection.execute("create table dbz1211 (id numeric(9,0), data varchar2(50), constraint pkdbz1211 primary key (id) using index)");
connection.execute("alter table dbz1211 add constraint xdbz1211 unique (id,data) using index");
connection
.execute("create table dbz1211_child (id numeric(9,0), data varchar2(50), constraint fk1211 foreign key (id) references dbz1211 on delete cascade)");
connection.execute("alter table dbz1211_child add constraint ydbz1211 unique (id,data) using index");
TestHelper.streamTable(connection, "dbz1211");
TestHelper.streamTable(connection, "dbz1211_child");
connection.executeWithoutCommitting("INSERT INTO dbz1211 values (1, 'Test')");
connection.executeWithoutCommitting("INSERT INTO dbz1211_child values (1, 'Child')");
connection.commit();
Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM\\.DBZ1211,DEBEZIUM\\.DBZ1211\\_CHILD")
.build();
start(OracleConnector.class, config);
assertConnectorIsRunning();
waitForSnapshotToBeCompleted(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
SourceRecords records = consumeRecordsByTopic(2);
assertThat(records.recordsForTopic("server1.DEBEZIUM.DBZ1211")).hasSize(1);
assertThat(records.recordsForTopic("server1.DEBEZIUM.DBZ1211_CHILD")).hasSize(1);
SourceRecord record = records.recordsForTopic("server1.DEBEZIUM.DBZ1211").get(0);
Struct key = (Struct) record.key();
assertThat(key).isNotNull();
assertThat(key.get("ID")).isEqualTo(1);
assertThat(key.schema().field("DATA")).isNull();
Struct after = ((Struct) record.value()).getStruct(Envelope.FieldName.AFTER);
assertThat(after.get("ID")).isEqualTo(1);
assertThat(after.get("DATA")).isEqualTo("Test");
record = records.recordsForTopic("server1.DEBEZIUM.DBZ1211_CHILD").get(0);
key = (Struct) record.key();
assertThat(key).isNotNull();
assertThat(key.get("ID")).isEqualTo(1);
assertThat(key.get("DATA")).isEqualTo("Child");
after = ((Struct) record.value()).getStruct(Envelope.FieldName.AFTER);
assertThat(after.get("ID")).isEqualTo(1);
assertThat(after.get("DATA")).isEqualTo("Child");
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
connection.execute("INSERT INTO dbz1211 values (2, 'Test2')");
connection.executeWithoutCommitting("INSERT INTO dbz1211_child values (1, 'Child1-2')");
connection.executeWithoutCommitting("INSERT INTO dbz1211_child values (2, 'Child2-1')");
connection.commit();
records = consumeRecordsByTopic(3);
assertThat(records.recordsForTopic("server1.DEBEZIUM.DBZ1211")).hasSize(1);
assertThat(records.recordsForTopic("server1.DEBEZIUM.DBZ1211_CHILD")).hasSize(2);
record = records.recordsForTopic("server1.DEBEZIUM.DBZ1211").get(0);
key = (Struct) record.key();
assertThat(key).isNotNull();
assertThat(key.get("ID")).isEqualTo(2);
assertThat(key.schema().field("DATA")).isNull();
after = ((Struct) record.value()).getStruct(Envelope.FieldName.AFTER);
assertThat(after.get("ID")).isEqualTo(2);
assertThat(after.get("DATA")).isEqualTo("Test2");
record = records.recordsForTopic("server1.DEBEZIUM.DBZ1211_CHILD").get(0);
key = (Struct) record.key();
assertThat(key).isNotNull();
assertThat(key.get("ID")).isEqualTo(1);
assertThat(key.get("DATA")).isEqualTo("Child1-2");
after = ((Struct) record.value()).getStruct(Envelope.FieldName.AFTER);
assertThat(after.get("ID")).isEqualTo(1);
assertThat(after.get("DATA")).isEqualTo("Child1-2");
record = records.recordsForTopic("server1.DEBEZIUM.DBZ1211_CHILD").get(1);
key = (Struct) record.key();
assertThat(key).isNotNull();
assertThat(key.get("ID")).isEqualTo(2);
assertThat(key.get("DATA")).isEqualTo("Child2-1");
after = ((Struct) record.value()).getStruct(Envelope.FieldName.AFTER);
assertThat(after.get("ID")).isEqualTo(2);
assertThat(after.get("DATA")).isEqualTo("Child2-1");
}
finally {
TestHelper.dropTables(connection, "dbz1211_child", "dbz1211");
}
}
@Test
@FixFor("DBZ-3322")
public void shouldNotEmitEventsOnConstraintViolations() throws Exception {
TestHelper.dropTable(connection, "dbz3322");
try {
connection.execute("CREATE TABLE dbz3322 (id number(9,0), data varchar2(50))");
connection.execute("CREATE UNIQUE INDEX uk_dbz3322 ON dbz3322 (id)");
TestHelper.streamTable(connection, "dbz3322");
Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM\\.DBZ3322")
.build();
start(OracleConnector.class, config);
assertConnectorIsRunning();
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
try {
connection.executeWithoutCommitting("INSERT INTO dbz3322 (id,data) values (1, 'Test1')");
connection.executeWithoutCommitting("INSERT INTO dbz3322 (id,data) values (1, 'Test2')");
}
catch (SQLException e) {
// ignore unique constraint violation
if (!e.getMessage().startsWith("ORA-00001")) {
throw e;
}
}
finally {
connection.executeWithoutCommitting("COMMIT");
}
SourceRecords records = consumeRecordsByTopic(1);
assertThat(records.recordsForTopic("server1.DEBEZIUM.DBZ3322")).hasSize(1);
final Struct after = (((Struct) records.recordsForTopic("server1.DEBEZIUM.DBZ3322").get(0).value()).getStruct("after"));
assertThat(after.get("ID")).isEqualTo(1);
assertThat(after.get("DATA")).isEqualTo("Test1");
assertNoRecordsToConsume();
}
finally {
TestHelper.dropTable(connection, "dbz3322");
}
}
@Test
@FixFor("DBZ-5090")
public void shouldNotEmitEventsOnConstraintViolationsAcrossSessions() throws Exception {
TestHelper.dropTable(connection, "dbz5090");
try {
connection.execute("CREATE TABLE dbz5090 (id number(9,0), data varchar2(50))");
connection.execute("CREATE UNIQUE INDEX uk_dbz5090 ON dbz5090 (id)");
TestHelper.streamTable(connection, "dbz5090");
Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM\\.DBZ5090")
.build();
start(OracleConnector.class, config);
assertConnectorIsRunning();
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
// We require the use of an executor here so that the multiple threads cooperate with one
// another in a way that does not block the test moving forward in the various stages.
ExecutorService executorService = Executors.newFixedThreadPool(2);
try (OracleConnection connection2 = TestHelper.testConnection(); OracleConnection connection3 = TestHelper.testConnection()) {
connection.executeWithoutCommitting("INSERT INTO dbz5090 (id,data) values (1,'Test1')");
// Task that creates in-progress transaction with second connection
final CountDownLatch latchA = new CountDownLatch(2);
final CountDownLatch latchB = new CountDownLatch(1);
final List<Future<Boolean>> futures = new ArrayList<>();
// Task that creates in-progress transaction with second connection
futures.add(executorService.submit(() -> {
try {
connection2.executeWithoutCommitting("INSERT INTO dbz5090 (id,data) values (2,'Test2')");
latchA.countDown();
try {
connection2.executeWithoutCommitting("INSERT INTO dbz5090 (id,data) values (1,'Test2')");
}
catch (SQLException e) {
// Test that transaction state isn't tainted if user retries multiple times per session
// and gets repeated SQL exceptions such as constraint violations for duplicate PKs.
latchB.await();
connection2.executeWithoutCommitting("INSERT INTO dbz5090 (id,data) values (1,'Test2')");
}
return true;
}
catch (SQLException e) {
return false;
}
}));
// Task that creates in-progress transaction with third connection
futures.add(executorService.submit(() -> {
try {
connection3.executeWithoutCommitting("INSERT INTO dbz5090 (id,data) values (3,'Test3')");
latchA.countDown();
try {
connection3.executeWithoutCommitting("INSERT INTO dbz5090 (id,data) values (1,'Test3')");
}
catch (SQLException e) {
// Test that transaction state isn't tainted if user retries multiple times per session
// and gets repeated SQL exceptions such as constraint violations for duplicate PKs.
latchB.await();
connection3.executeWithoutCommitting("INSERT INTO dbz5090 (id,data) values (1,'Test3b')");
}
return true;
}
catch (SQLException e) {
return false;
}
}));
// We wait until the latch has been triggered by the callable task
latchA.await();
// Explicitly wait 5 seconds to guarantee that the thread has executed the SQL
Thread.sleep(5000);
connection.commit();
// toggle each thread's second attempt
latchB.countDown();
// Get thread state, should return false due to constraint violation
assertThat(futures.get(0).get()).isFalse();
assertThat(futures.get(1).get()).isFalse();
// Each connection inserts one new row and attempts a duplicate insert of an existing PK
// so the connection needs to be committed to guarantee that we test the scenario where
// we get a transaction commit & need to filter out roll-back rows rather than the
// transaction being rolled back entirely.
connection2.commit();
connection3.commit();
}
final SourceRecords sourceRecords = consumeRecordsByTopic(3);
List<SourceRecord> records = sourceRecords.recordsForTopic("server1.DEBEZIUM.DBZ5090");
assertThat(records).hasSize(3);
VerifyRecord.isValidInsert(records.get(0), "ID", 1);
final Struct after = (((Struct) records.get(0).value()).getStruct("after"));
assertThat(after.get("ID")).isEqualTo(1);
assertThat(after.get("DATA")).isEqualTo("Test1");
assertNoRecordsToConsume();
}
finally {
TestHelper.dropTable(connection, "dbz5090");
}
}
@Test
@FixFor("DBZ-3322")
public void shouldNotEmitEventsInRollbackTransaction() throws Exception {
TestHelper.dropTable(connection, "dbz3322");
try {
connection.execute("CREATE TABLE dbz3322 (id number(9,0), data varchar2(50))");
connection.execute("CREATE UNIQUE INDEX uk_dbz3322 ON dbz3322 (id)");
TestHelper.streamTable(connection, "dbz3322");
Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM\\.DBZ3322")
.build();
start(OracleConnector.class, config);
assertConnectorIsRunning();
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
connection.executeWithoutCommitting("INSERT INTO dbz3322 (id,data) values (1, 'Test')");
connection.executeWithoutCommitting("INSERT INTO dbz3322 (id,data) values (2, 'Test')");
connection.executeWithoutCommitting("ROLLBACK");
connection.executeWithoutCommitting("INSERT INTO dbz3322 (id,data) values (3, 'Test')");
connection.executeWithoutCommitting("COMMIT");
SourceRecords records = consumeRecordsByTopic(1);
assertThat(records.recordsForTopic("server1.DEBEZIUM.DBZ3322")).hasSize(1);
Struct value = (Struct) records.recordsForTopic("server1.DEBEZIUM.DBZ3322").get(0).value();
assertThat(value.getStruct(Envelope.FieldName.AFTER).get("ID")).isEqualTo(3);
assertNoRecordsToConsume();
}
finally {
TestHelper.dropTable(connection, "dbz3322");
}
}
@Test
@FixFor("DBZ-3062")
public void shouldSelectivelySnapshotTables() throws Exception {
TestHelper.dropTables(connection, "dbz3062a", "dbz3062b");
try {
connection.execute("CREATE TABLE dbz3062a (id number(9,0), data varchar2(50))");
connection.execute("CREATE TABLE dbz3062b (id number(9,0), data varchar2(50))");
TestHelper.streamTable(connection, "dbz3062a");
TestHelper.streamTable(connection, "dbz3062b");
connection.execute("INSERT INTO dbz3062a VALUES (1, 'Test1')");
connection.execute("INSERT INTO dbz3062b VALUES (2, 'Test2')");
Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.SNAPSHOT_MODE, SnapshotMode.INITIAL)
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM\\.DBZ3062.*")
.with(OracleConnectorConfig.SNAPSHOT_MODE_TABLES, "[A-z].*DEBEZIUM\\.DBZ3062A")
.build();
start(OracleConnector.class, config);
assertConnectorIsRunning();
waitForSnapshotToBeCompleted(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
SourceRecords records = consumeRecordsByTopic(1);
List<SourceRecord> tableA = records.recordsForTopic("server1.DEBEZIUM.DBZ3062A");
List<SourceRecord> tableB = records.recordsForTopic("server1.DEBEZIUM.DBZ3062B");
assertThat(tableA).hasSize(1);
assertThat(tableB).isNull();
Struct after = ((Struct) tableA.get(0).value()).getStruct(AFTER);
assertThat(after.get("ID")).isEqualTo(1);
assertThat(after.get("DATA")).isEqualTo("Test1");
assertNoRecordsToConsume();
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
connection.executeWithoutCommitting("INSERT INTO dbz3062a VALUES (3, 'Test3')");
connection.executeWithoutCommitting("INSERT INTO dbz3062b VALUES (4, 'Test4')");
connection.commit();
records = consumeRecordsByTopic(2);
tableA = records.recordsForTopic("server1.DEBEZIUM.DBZ3062A");
tableB = records.recordsForTopic("server1.DEBEZIUM.DBZ3062B");
assertThat(tableA).hasSize(1);
assertThat(tableB).hasSize(1);
after = ((Struct) tableA.get(0).value()).getStruct(AFTER);
assertThat(after.get("ID")).isEqualTo(3);
assertThat(after.get("DATA")).isEqualTo("Test3");
after = ((Struct) tableB.get(0).value()).getStruct(AFTER);
assertThat(after.get("ID")).isEqualTo(4);
assertThat(after.get("DATA")).isEqualTo("Test4");
}
finally {
TestHelper.dropTables(connection, "dbz3062a", "dbz3062b");
}
}
@Test
@FixFor("DBZ-3616")
public void shouldNotLogWarningsAboutCommittedTransactionsWhileStreamingNormally() throws Exception {
TestHelper.dropTables(connection, "dbz3616", "dbz3616");
try {
connection.execute("CREATE TABLE dbz3616 (id number(9,0), data varchar2(50))");
TestHelper.streamTable(connection, "dbz3616");
connection.commit();
Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.SNAPSHOT_MODE, SnapshotMode.INITIAL)
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM\\.DBZ3616.*")
// use online_catalog mode explicitly due to Awaitility timer below.
.with(OracleConnectorConfig.LOG_MINING_STRATEGY, "online_catalog")
.build();
// Start connector
start(OracleConnector.class, config);
assertConnectorIsRunning();
// Wait for streaming
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
// Start second connection and write an insert, without commit.
OracleConnection connection2 = TestHelper.testConnection();
connection2.executeWithoutCommitting("INSERT INTO dbz3616 (id,data) values (1,'Conn2')");
// One first connection write an insert without commit, then explicitly commit it.
connection.executeWithoutCommitting("INSERT INTO dbz3616 (id,data) values (2,'Conn1')");
connection.commit();
// Connector should continually re-mine the first transaction until committed.
// During this time, there should not be these extra log messages that we
// will assert against later via LogInterceptor.
Awaitility.await()
.pollDelay(Durations.ONE_MINUTE)
.timeout(Durations.TWO_MINUTES)
.until(() -> true);
// Now commit connection2, this means we should get 2 inserts.
connection2.commit();
// Now get the 2 records, two inserts from both transactions
SourceRecords records = consumeRecordsByTopic(2);
assertThat(records.recordsForTopic("server1.DEBEZIUM.DBZ3616")).hasSize(2);
List<SourceRecord> tableRecords = records.recordsForTopic("server1.DEBEZIUM.DBZ3616");
assertThat(((Struct) tableRecords.get(0).value()).getStruct("after").get("ID")).isEqualTo(2);
assertThat(((Struct) tableRecords.get(1).value()).getStruct("after").get("ID")).isEqualTo(1);
}
finally {
TestHelper.dropTables(connection, "dbz3616", "dbz3616");
}
}
@Test
@FixFor("DBZ-3668")
public void shouldOutputRecordsInCloudEventsFormat() throws Exception {
final Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM\\.CUSTOMER")
.build();
connection.execute("INSERT INTO customer (id,name,score) values (1001, 'DBZ3668', 100)");
start(OracleConnector.class, config);
assertConnectorIsRunning();
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
SourceRecords records = consumeRecordsByTopic(1);
List<SourceRecord> customers = records.recordsForTopic("server1.DEBEZIUM.CUSTOMER");
assertThat(customers).hasSize(1);
for (SourceRecord customer : customers) {
CloudEventsConverterTest.shouldConvertToCloudEventsInJson(customer, false);
CloudEventsConverterTest.shouldConvertToCloudEventsInJsonWithDataAsAvro(customer, false);
CloudEventsConverterTest.shouldConvertToCloudEventsInAvro(customer, "oracle", "server1", false);
}
connection.execute("INSERT INTO customer (id,name,score) values (1002, 'DBZ3668', 95)");
records = consumeRecordsByTopic(1);
customers = records.recordsForTopic("server1.DEBEZIUM.CUSTOMER");
assertThat(customers).hasSize(1);
for (SourceRecord customer : customers) {
CloudEventsConverterTest.shouldConvertToCloudEventsInJson(customer, false, jsonNode -> {
assertThat(jsonNode.get(CloudEventsMaker.FieldName.ID).asText()).contains("scn:");
});
CloudEventsConverterTest.shouldConvertToCloudEventsInJsonWithDataAsAvro(customer, false);
CloudEventsConverterTest.shouldConvertToCloudEventsInAvro(customer, "oracle", "server1", false);
}
}
@Test
@FixFor("DBZ-3896")
public void shouldCaptureTableMetadataWithMultipleStatements() throws Exception {
try {
Configuration config = TestHelper.defaultConfig().with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM\\.DBZ3896").build();
start(OracleConnector.class, config);
assertConnectorIsRunning();
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
connection.execute("CREATE TABLE dbz3896 (id number(9,0), name varchar2(50), data varchar2(50))",
"CREATE UNIQUE INDEX dbz3896_pk ON dbz3896 (\"ID\", \"NAME\")",
"ALTER TABLE dbz3896 ADD CONSTRAINT idx_dbz3896 PRIMARY KEY (\"ID\", \"NAME\") USING INDEX \"DBZ3896_PK\"");
TestHelper.streamTable(connection, "dbz3896");
connection.execute("INSERT INTO dbz3896 (id,name,data) values (1,'First','Test')");
SourceRecords records = consumeRecordsByTopic(1);
assertThat(records.recordsForTopic("server1.DEBEZIUM.DBZ3896")).hasSize(1);
SourceRecord record = records.recordsForTopic("server1.DEBEZIUM.DBZ3896").get(0);
assertThat(record.key()).isNotNull();
assertThat(record.keySchema().field("ID")).isNotNull();
assertThat(record.keySchema().field("NAME")).isNotNull();
assertThat(((Struct) record.key()).get("ID")).isEqualTo(1);
assertThat(((Struct) record.key()).get("NAME")).isEqualTo("First");
}
finally {
TestHelper.dropTable(connection, "dbz3896");
}
}
@Test
@FixFor("DBZ-3898")
public void shouldIgnoreAllTablesInExcludedSchemas() throws Exception {
try {
TestHelper.dropTable(connection, "dbz3898");
connection.execute("CREATE TABLE dbz3898 (id number(9,0), data varchar2(50))");
TestHelper.streamTable(connection, "dbz3898");
// Explicitly uses CATALOG_IN_REDO mining strategy
// This strategy makes changes to several LOGMNR tables as DDL tracking gets enabled
Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.LOG_MINING_STRATEGY, LogMiningStrategy.CATALOG_IN_REDO)
.build();
start(OracleConnector.class, config);
assertConnectorIsRunning();
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
connection.execute("INSERT INTO dbz3898 (id,data) values (1,'Test')");
SourceRecords records = consumeRecordsByTopic(1);
assertThat(records.recordsForTopic("server1.DEBEZIUM.DBZ3898")).hasSize(1);
// Wait 2 minutes to let the connector run a few cycles
// Then check that there is absolutely nothing to consume and that no exceptions are thrown
Awaitility.await().atMost(Duration.ofMinutes(3)).pollDelay(Duration.ofMinutes(2)).until(() -> true);
assertNoRecordsToConsume();
}
finally {
TestHelper.dropTable(connection, "dbz3898");
}
}
@Test
@FixFor({ "DBZ-3712", "DBZ-4879" })
@SkipWhenAdapterNameIsNot(value = SkipWhenAdapterNameIsNot.AdapterName.LOGMINER, reason = "Tests archive log support for LogMiner only")
public void shouldStartWithArchiveLogOnlyModeAndStreamWhenRecordsBecomeAvailable() throws Exception {
TestHelper.dropTable(connection, "dbz3712");
try {
connection.execute("CREATE TABLE dbz3712 (id number(9,0), data varchar2(50))");
TestHelper.streamTable(connection, "dbz3712");
Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.LOG_MINING_ARCHIVE_LOG_ONLY_MODE, true)
.with(OracleConnectorConfig.LOG_MINING_ARCHIVE_LOG_ONLY_SCN_POLL_INTERVAL_MS, 2000)
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM\\.DBZ3712")
.build();
start(OracleConnector.class, config);
assertConnectorIsRunning();
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
// At this point the connector is new and should not emit any records as the SCN offset
// obtained from the snapshot is in the redo logs.
waitForAvailableRecords(waitTimeForRecords(), TimeUnit.SECONDS);
assertNoRecordsToConsume();
// We will insert a new record but this record won't be emitted right away and will
// require that a log switch happen so that it can be emitted.
connection.execute("INSERT INTO dbz3712 (id,data) values (1, 'Test')");
waitForLogSwitchOrForceOneAfterTimeout();
// We should now be able to consume a record
SourceRecords records = consumeRecordsByTopic(1);
assertThat(records.recordsForTopic("server1.DEBEZIUM.DBZ3712")).hasSize(1);
// Now insert a new record but this record won't be emitted because it will require
// a log switch to happen so it can be emitted.
connection.execute("INSERT INTO dbz3712 (id,data) values (2, 'Test2')");
waitForLogSwitchOrForceOneAfterTimeout();
// We should now be able to consume a record
records = consumeRecordsByTopic(1);
assertThat(records.recordsForTopic("server1.DEBEZIUM.DBZ3712")).hasSize(1);
}
finally {
TestHelper.dropTable(connection, "dbz3712");
}
}
@Test
@FixFor("DBZ-3712")
@SkipWhenAdapterNameIsNot(value = SkipWhenAdapterNameIsNot.AdapterName.LOGMINER, reason = "Tests archive log support for LogMiner only")
public void shouldPermitChangingToArchiveLogOnlyModeOnExistingConnector() throws Exception {
TestHelper.dropTable(connection, "dbz3712");
try {
connection.execute("CREATE TABLE dbz3712 (id number(9,0), data varchar2(50))");
TestHelper.streamTable(connection, "dbz3712");
Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.LOG_MINING_ARCHIVE_LOG_ONLY_SCN_POLL_INTERVAL_MS, 2000)
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM\\.DBZ3712")
.build();
start(OracleConnector.class, config);
assertConnectorIsRunning();
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
// The connector was started with archive.log.only.mode disabled so this record should
// be emitted immediately once its written to the redo logs.
connection.execute("INSERT INTO dbz3712 (id,data) values (1, 'Test1')");
// We should now be able to consume a record
SourceRecords records = consumeRecordsByTopic(1);
assertThat(records.recordsForTopic("server1.DEBEZIUM.DBZ3712")).hasSize(1);
// Restart connector using the same offsets but with archive log only mode
stopConnector();
config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.LOG_MINING_ARCHIVE_LOG_ONLY_MODE, true)
.with(OracleConnectorConfig.LOG_MINING_ARCHIVE_LOG_ONLY_SCN_POLL_INTERVAL_MS, 2000)
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM\\.DBZ3712")
.build();
start(OracleConnector.class, config);
assertConnectorIsRunning();
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
// At this point the connector was restarted with archive log only mode. The SCN offset
// was previously in the redo logs and may likely not be in the archive logs on start so
// we'll give the connector a moment and verify it has no records to consume.
waitForAvailableRecords(waitTimeForRecords(), TimeUnit.SECONDS);
assertNoRecordsToConsume();
// Insert a new record
// This should not be picked up until after a log switch
connection.execute("INSERT INTO dbz3712 (id,data) values (2, 'Test2')");
waitForLogSwitchOrForceOneAfterTimeout();
// We should now be able to consume a record
records = consumeRecordsByTopic(1);
assertThat(records.recordsForTopic("server1.DEBEZIUM.DBZ3712")).hasSize(1);
// Insert a new record
// This should not be picked up until after a log switch
connection.execute("INSERT INTO dbz3712 (id,data) values (3, 'Test2')");
waitForLogSwitchOrForceOneAfterTimeout();
// We should now be able to consume a record
records = consumeRecordsByTopic(1);
assertThat(records.recordsForTopic("server1.DEBEZIUM.DBZ3712")).hasSize(1);
}
finally {
TestHelper.dropTable(connection, "dbz3712");
}
}
private void waitForLogSwitchOrForceOneAfterTimeout() throws SQLException {
List<BigInteger> sequences = TestHelper.getCurrentRedoLogSequences();
try {
Awaitility.await()
.pollInterval(Duration.of(5, ChronoUnit.SECONDS))
.atMost(Duration.of(20, ChronoUnit.SECONDS))
.until(() -> {
if (TestHelper.getCurrentRedoLogSequences().equals(sequences)) {
assertNoRecordsToConsume();
return false;
}
// Oracle triggered its on log switch
return true;
});
// In this use case Oracle triggered its own log switch
// We don't need to trigger one on our own.
}
catch (ConditionTimeoutException e) {
// expected if Oracle doesn't trigger its own log switch
TestHelper.forceLogfileSwitch();
}
}
@Test
@FixFor("DBZ-3978")
@SkipWhenAdapterNameIsNot(value = SkipWhenAdapterNameIsNot.AdapterName.LOGMINER, reason = "Specific to only LogMiner")
public void shouldFilterUser() throws Exception {
try {
TestHelper.dropTable(connection, "dbz3978");
connection.execute("CREATE TABLE dbz3978 (id number(9,0), data varchar2(50), primary key (id))");
TestHelper.streamTable(connection, "dbz3978");
Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM\\.DBZ3978")
.with(OracleConnectorConfig.SNAPSHOT_MODE, SnapshotMode.SCHEMA_ONLY)
.with(OracleConnectorConfig.LOG_MINING_USERNAME_EXCLUDE_LIST, "DEBEZIUM")
.build();
start(OracleConnector.class, config);
assertConnectorIsRunning();
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
connection.executeWithoutCommitting("INSERT INTO debezium.dbz3978 VALUES (1, 'Test1')");
connection.executeWithoutCommitting("INSERT INTO debezium.dbz3978 VALUES (2, 'Test2')");
connection.execute("COMMIT");
// all messages are filtered out
assertThat(waitForAvailableRecords(10, TimeUnit.SECONDS)).isFalse();
// There should be at least 2 DML events captured but ignored
Long totalDmlCount = getStreamingMetric("TotalCapturedDmlCount");
assertThat(totalDmlCount).isGreaterThanOrEqualTo(2L);
}
finally {
TestHelper.dropTable(connection, "dbz3978");
}
}
@SuppressWarnings("unchecked")
private <T> T getStreamingMetric(String metricName) throws JMException {
final MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
final ObjectName objectName = getStreamingMetricsObjectName(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
return (T) mbeanServer.getAttribute(objectName, metricName);
}
private String generateAlphaNumericStringColumn(int size) {
final String alphaNumericString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
final StringBuilder sb = new StringBuilder(size);
for (int i = 0; i < size; ++i) {
int index = (int) (alphaNumericString.length() * Math.random());
sb.append(alphaNumericString.charAt(index));
}
return sb.toString();
}
private void verifyHeartbeatRecord(SourceRecord heartbeat) {
assertEquals("__debezium-heartbeat.server1", heartbeat.topic());
Struct key = (Struct) heartbeat.key();
assertThat(key.get("serverName")).isEqualTo("server1");
}
private long toMicroSecondsSinceEpoch(LocalDateTime localDateTime) {
return localDateTime.toEpochSecond(ZoneOffset.UTC) * MICROS_PER_SECOND;
}
@Test(expected = DebeziumException.class)
@FixFor("DBZ-3986")
public void shouldCreateSnapshotSchemaOnlyRecoveryExceptionWithoutOffset() {
final Path path = Testing.Files.createTestingPath("missing-history.txt").toAbsolutePath();
Configuration config = defaultConfig()
.with(OracleConnectorConfig.SNAPSHOT_MODE, SnapshotMode.SCHEMA_ONLY_RECOVERY)
.with(FileDatabaseHistory.FILE_PATH, path)
.build();
// Start the connector ...
AtomicReference<Throwable> exception = new AtomicReference<>();
start(OracleConnector.class, config, (success, message, error) -> exception.set(error));
Testing.Files.delete(path);
throw (RuntimeException) exception.get();
}
@Test
@FixFor("DBZ-3986")
public void shouldCreateSnapshotSchemaOnlyRecovery() throws Exception {
try {
Configuration.Builder builder = defaultConfig()
.with(OracleConnectorConfig.SNAPSHOT_MODE, SnapshotMode.SCHEMA_ONLY)
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM\\.DBZ3986")
.with(OracleConnectorConfig.DATABASE_HISTORY, MemoryDatabaseHistory.class.getName())
.with(EmbeddedEngine.OFFSET_STORAGE, FileOffsetBackingStore.class.getName());
Configuration config = builder.build();
consumeRecords(config);
// Insert a row of data in advance
connection.execute("INSERT INTO DBZ3986 (ID, DATA) values (3, 'asuka')");
builder.with(OracleConnectorConfig.SNAPSHOT_MODE, SnapshotMode.SCHEMA_ONLY_RECOVERY);
config = builder.build();
start(OracleConnector.class, config);
int recordCount = 1;
SourceRecords sourceRecords = consumeRecordsByTopic(recordCount);
// Compare data
assertThat(sourceRecords.allRecordsInOrder()).hasSize(recordCount);
Struct struct = (Struct) ((Struct) sourceRecords.allRecordsInOrder().get(0).value()).get(AFTER);
assertEquals(3, struct.get("ID"));
assertEquals("asuka", struct.get("DATA"));
}
finally {
TestHelper.dropTable(connection, "DBZ3986");
}
}
@Test(expected = DebeziumException.class)
@FixFor("DBZ-3986")
public void shouldCreateSnapshotSchemaOnlyExceptionWithoutHistory() throws Exception {
try {
Configuration.Builder builder = defaultConfig()
.with(OracleConnectorConfig.SNAPSHOT_MODE, SnapshotMode.SCHEMA_ONLY)
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM\\.DBZ3986")
.with(OracleConnectorConfig.DATABASE_HISTORY, MemoryDatabaseHistory.class.getName())
.with(EmbeddedEngine.OFFSET_STORAGE, FileOffsetBackingStore.class.getName());
Configuration config = builder.build();
consumeRecords(config);
AtomicReference<Throwable> exception = new AtomicReference<>();
start(OracleConnector.class, config, (success, message, error) -> exception.set(error));
throw (RuntimeException) exception.get();
}
finally {
TestHelper.dropTable(connection, "DBZ3986");
}
}
@Test
@FixFor("DBZ-3986")
public void shouldSkipDataOnSnapshotSchemaOnly() throws Exception {
try {
Configuration.Builder builder = defaultConfig()
.with(OracleConnectorConfig.SNAPSHOT_MODE, SnapshotMode.SCHEMA_ONLY)
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM\\.DBZ3986")
.with(OracleConnectorConfig.DATABASE_HISTORY, MemoryDatabaseHistory.class.getName())
.with(EmbeddedEngine.OFFSET_STORAGE, MemoryOffsetBackingStore.class.getName());
Configuration config = builder.build();
consumeRecords(config);
// Insert a row of data in advance. And should skip the data
connection.execute("INSERT INTO DBZ3986 (ID, DATA) values (3, 'asuka')");
start(OracleConnector.class, config);
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
connection.execute("INSERT INTO DBZ3986 (ID, DATA) values (4, 'debezium')");
int recordCount = 1;
SourceRecords sourceRecords = consumeRecordsByTopic(recordCount);
// Compare data
assertThat(sourceRecords.allRecordsInOrder()).hasSize(recordCount);
Struct struct = (Struct) ((Struct) sourceRecords.allRecordsInOrder().get(0).value()).get(AFTER);
assertEquals(4, struct.get("ID"));
assertEquals("debezium", struct.get("DATA"));
}
finally {
TestHelper.dropTable(connection, "DBZ3986");
}
}
@Test
@FixFor("DBZ-4161")
@SkipWhenAdapterNameIsNot(value = SkipWhenAdapterNameIsNot.AdapterName.LOGMINER, reason = "Applies to LogMiner only")
public void shouldWarnAboutTableNameLengthExceeded() throws Exception {
try {
TestHelper.dropTable(connection, "dbz4161_with_a_name_that_is_greater_than_30");
connection.execute("CREATE TABLE dbz4161_with_a_name_that_is_greater_than_30 (id numeric(9,0), data varchar2(30))");
TestHelper.streamTable(connection, "dbz4161_with_a_name_that_is_greater_than_30");
connection.execute("INSERT INTO dbz4161_with_a_name_that_is_greater_than_30 values (1, 'snapshot')");
Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM\\.DBZ4161_WITH_A_NAME_THAT_IS_GREATER_THAN_30")
.build();
LogInterceptor logInterceptor = new LogInterceptor(LogMinerStreamingChangeEventSource.class);
start(OracleConnector.class, config);
assertConnectorIsRunning();
waitForSnapshotToBeCompleted(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
SourceRecords records = consumeRecordsByTopic(1);
assertThat(records.recordsForTopic("server1.DEBEZIUM.DBZ4161_WITH_A_NAME_THAT_IS_GREATER_THAN_30")).hasSize(1);
SourceRecord record = records.recordsForTopic("server1.DEBEZIUM.DBZ4161_WITH_A_NAME_THAT_IS_GREATER_THAN_30").get(0);
Struct after = ((Struct) record.value()).getStruct(AFTER);
assertThat(after.get("ID")).isEqualTo(1);
assertThat(after.get("DATA")).isEqualTo("snapshot");
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
connection.execute("INSERT INTO dbz4161_with_a_name_that_is_greater_than_30 values (2, 'streaming')");
waitForCurrentScnToHaveBeenSeenByConnector();
assertNoRecordsToConsume();
assertThat(logInterceptor.containsWarnMessage("Table 'DBZ4161_WITH_A_NAME_THAT_IS_GREATER_THAN_30' won't be captured by Oracle LogMiner")).isTrue();
}
finally {
TestHelper.dropTable(connection, "dbz4161_with_a_name_that_is_greater_than_30");
}
}
@Test
@FixFor("DBZ-4161")
@SkipWhenAdapterNameIsNot(value = SkipWhenAdapterNameIsNot.AdapterName.LOGMINER, reason = "Applies to LogMiner only")
public void shouldWarnAboutColumnNameLengthExceeded() throws Exception {
try {
TestHelper.dropTable(connection, "dbz4161");
connection.execute("CREATE TABLE dbz4161 (id numeric(9,0), a_very_long_column_name_that_is_greater_than_30 varchar2(30))");
TestHelper.streamTable(connection, "dbz4161");
connection.execute("INSERT INTO dbz4161 values (1, 'snapshot')");
Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM\\.DBZ4161")
.build();
LogInterceptor logInterceptor = new LogInterceptor(LogMinerStreamingChangeEventSource.class);
start(OracleConnector.class, config);
assertConnectorIsRunning();
waitForSnapshotToBeCompleted(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
SourceRecords records = consumeRecordsByTopic(1);
assertThat(records.recordsForTopic("server1.DEBEZIUM.DBZ4161")).hasSize(1);
SourceRecord record = records.recordsForTopic("server1.DEBEZIUM.DBZ4161").get(0);
Struct after = ((Struct) record.value()).getStruct(AFTER);
assertThat(after.get("ID")).isEqualTo(1);
assertThat(after.get("A_VERY_LONG_COLUMN_NAME_THAT_IS_GREATER_THAN_30")).isEqualTo("snapshot");
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
connection.execute("INSERT INTO dbz4161 values (2, 'streaming')");
waitForCurrentScnToHaveBeenSeenByConnector();
assertNoRecordsToConsume();
assertThat(logInterceptor.containsWarnMessage("Table 'DBZ4161' won't be captured by Oracle LogMiner")).isTrue();
}
finally {
TestHelper.dropTable(connection, "dbz4161");
}
}
@Test
@FixFor("DBZ-3611")
public void shouldSafelySnapshotAndStreamWithDatabaseIncludeList() throws Exception {
try {
TestHelper.dropTable(connection, "dbz3611");
connection.execute("CREATE TABLE dbz3611 (id numeric(9,0), data varchar2(30))");
TestHelper.streamTable(connection, "dbz3611");
connection.execute("INSERT INTO dbz3611 values (1, 'snapshot')");
Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.DATABASE_INCLUDE_LIST, "ORCLPDB1")
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM\\.dbz3611")
.build();
start(OracleConnector.class, config);
assertConnectorIsRunning();
waitForSnapshotToBeCompleted(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
SourceRecords records = consumeRecordsByTopic(1);
assertThat(records.recordsForTopic("server1.DEBEZIUM.DBZ3611")).hasSize(1);
SourceRecord record = records.recordsForTopic("server1.DEBEZIUM.DBZ3611").get(0);
Struct after = ((Struct) record.value()).getStruct(AFTER);
assertThat(after.get("ID")).isEqualTo(1);
assertThat(after.get("DATA")).isEqualTo("snapshot");
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
connection.execute("INSERT INTO dbz3611 values (2, 'streaming')");
records = consumeRecordsByTopic(1);
assertThat(records.recordsForTopic("server1.DEBEZIUM.DBZ3611")).hasSize(1);
assertNoRecordsToConsume();
}
finally {
TestHelper.dropTable(connection, "dbz3611");
}
}
/**
* database include/exclude list are not support (yet) for the Oracle connector; this test is just there to make
* sure that the presence of these (functionally ignored) properties doesn't cause any problems.
*/
@Test
@FixFor("DBZ-3611")
public void shouldSafelySnapshotAndStreamWithDatabaseExcludeList() throws Exception {
try {
TestHelper.dropTable(connection, "dbz3611");
connection.execute("CREATE TABLE dbz3611 (id numeric(9,0), data varchar2(30))");
TestHelper.streamTable(connection, "dbz3611");
connection.execute("INSERT INTO dbz3611 values (1, 'snapshot')");
Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.DATABASE_EXCLUDE_LIST, "ORCLPDB2")
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM\\.dbz3611")
.build();
start(OracleConnector.class, config);
assertConnectorIsRunning();
waitForSnapshotToBeCompleted(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
SourceRecords records = consumeRecordsByTopic(1);
assertThat(records.recordsForTopic("server1.DEBEZIUM.DBZ3611")).hasSize(1);
SourceRecord record = records.recordsForTopic("server1.DEBEZIUM.DBZ3611").get(0);
Struct after = ((Struct) record.value()).getStruct(AFTER);
assertThat(after.get("ID")).isEqualTo(1);
assertThat(after.get("DATA")).isEqualTo("snapshot");
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
connection.execute("INSERT INTO dbz3611 values (2, 'streaming')");
records = consumeRecordsByTopic(1);
assertThat(records.recordsForTopic("server1.DEBEZIUM.DBZ3611")).hasSize(1);
assertNoRecordsToConsume();
}
finally {
TestHelper.dropTable(connection, "dbz3611");
}
}
@Test
@FixFor("DBZ-4376")
public void shouldNotRaiseNullPointerExceptionWithNonUppercaseDatabaseName() throws Exception {
// the snapshot process would throw a NPE due to a lowercase PDB or DBNAME setup
Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.PDB_NAME, TestHelper.getDatabaseName().toLowerCase())
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM\\.CUSTOMER")
.build();
connection.execute("INSERT INTO debezium.customer (id,name) values (1, 'Bugs Bunny')");
start(OracleConnector.class, config);
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
List<SourceRecord> records = consumeRecordsByTopic(1).recordsForTopic("server1.DEBEZIUM.CUSTOMER");
assertThat(((Struct) records.get(0).value()).getStruct(AFTER).get("ID")).isEqualTo(1);
}
@FixFor("DBZ-3986")
private void consumeRecords(Configuration config) throws SQLException, InterruptedException {
// Poll for records ...
TestHelper.dropTable(connection, "DBZ3986");
connection.execute("CREATE TABLE DBZ3986 (ID number(9,0), DATA varchar2(50))");
TestHelper.streamTable(connection, "DBZ3986");
// Start the connector ...
start(OracleConnector.class, config);
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
connection.execute("INSERT INTO DBZ3986 (ID, DATA) values (1, 'Test')");
connection.execute("INSERT INTO DBZ3986 (ID, DATA) values (2, 'ashlin')");
int recordCount = 2;
SourceRecords sourceRecords = consumeRecordsByTopic(recordCount);
assertThat(sourceRecords.allRecordsInOrder()).hasSize(recordCount);
stopConnector();
}
@Test
@FixFor("DBZ-4367")
public void shouldCaptureChangesForTransactionsAcrossSnapshotBoundary() throws Exception {
TestHelper.dropTable(connection, "DBZ4367");
try {
connection.execute("CREATE TABLE DBZ4367 (ID number(9, 0), DATA varchar2(50))");
TestHelper.streamTable(connection, "DBZ4367");
connection.execute("INSERT INTO DBZ4367 (ID, DATA) VALUES (1, 'pre-snapshot pre TX')");
connection.executeWithoutCommitting("INSERT INTO DBZ4367 (ID, DATA) VALUES (2, 'pre-snapshot in TX')");
Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM\\.DBZ4367")
.build();
start(OracleConnector.class, config);
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
connection.executeWithoutCommitting("INSERT INTO DBZ4367 (ID, DATA) VALUES (3, 'post-snapshot in TX')");
connection.executeWithoutCommitting("COMMIT");
connection.execute("INSERT INTO DBZ4367 (ID, DATA) VALUES (4, 'post snapshot post TX')");
SourceRecords records = consumeRecordsByTopic(4);
List<Integer> ids = records.recordsForTopic("server1.DEBEZIUM.DBZ4367").stream()
.map(r -> getAfter(r).getInt32("ID"))
.collect(Collectors.toList());
assertThat(ids).containsOnly(1, 2, 3, 4);
assertThat(ids).doesNotHaveDuplicates();
assertThat(ids).hasSize(4);
}
finally {
stopConnector();
TestHelper.dropTable(connection, "DBZ4367");
}
}
@Test
@FixFor("DBZ-4367")
public void shouldCaptureChangesForTransactionsAcrossSnapshotBoundaryWithoutDuplicatingSnapshottedChanges() throws Exception {
OracleConnection secondConnection = TestHelper.testConnection();
TestHelper.dropTable(connection, "DBZ4367");
try {
connection.execute("CREATE TABLE DBZ4367 (ID number(9, 0), DATA varchar2(50))");
TestHelper.streamTable(connection, "DBZ4367");
connection.execute("INSERT INTO DBZ4367 (ID, DATA) VALUES (1, 'pre-snapshot pre TX')");
connection.executeWithoutCommitting("INSERT INTO DBZ4367 (ID, DATA) VALUES (2, 'pre-snapshot in TX')");
secondConnection.execute("INSERT INTO DBZ4367 (ID, DATA) VALUES (3, 'pre-snapshot in another TX')");
Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM\\.DBZ4367")
.build();
start(OracleConnector.class, config);
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
SourceRecords records = consumeRecordsByTopic(2);
List<Integer> ids = records.recordsForTopic("server1.DEBEZIUM.DBZ4367").stream()
.map(r -> getAfter(r).getInt32("ID"))
.collect(Collectors.toList());
assertThat(ids).containsOnly(1, 3);
assertThat(ids).doesNotHaveDuplicates();
assertThat(ids).hasSize(2);
connection.executeWithoutCommitting("INSERT INTO DBZ4367 (ID, DATA) VALUES (4, 'post-snapshot in TX')");
connection.executeWithoutCommitting("COMMIT");
connection.execute("INSERT INTO DBZ4367 (ID, DATA) VALUES (5, 'post snapshot post TX')");
records = consumeRecordsByTopic(3);
ids = records.recordsForTopic("server1.DEBEZIUM.DBZ4367").stream()
.map(r -> getAfter(r).getInt32("ID"))
.collect(Collectors.toList());
assertThat(ids).containsOnly(2, 4, 5);
assertThat(ids).doesNotHaveDuplicates();
assertThat(ids).hasSize(3);
}
finally {
stopConnector();
TestHelper.dropTable(connection, "DBZ4367");
secondConnection.close();
}
}
@Test
@FixFor("DBZ-4367")
public void shouldCaptureChangesForTransactionsAcrossSnapshotBoundaryWithoutReemittingDDLChanges() throws Exception {
OracleConnection secondConnection = TestHelper.testConnection();
TestHelper.dropTable(connection, "DBZ4367");
TestHelper.dropTable(connection, "DBZ4367_EXTRA");
try {
connection.execute("CREATE TABLE DBZ4367 (ID number(9, 0), DATA varchar2(50))");
TestHelper.streamTable(connection, "DBZ4367");
connection.execute("CREATE TABLE DBZ4367_EXTRA (ID number(9, 0), DATA varchar2(50))");
TestHelper.streamTable(connection, "DBZ4367_EXTRA");
// some transactions that are complete pre-snapshot
connection.execute("INSERT INTO DBZ4367 (ID, DATA) VALUES (1, 'pre-snapshot pre TX')");
connection.execute("INSERT INTO DBZ4367_EXTRA (ID, DATA) VALUES (100, 'second table, pre-snapshot pre TX')");
// this is a transaction that spans the snapshot boundary, changes should be streamed
connection.executeWithoutCommitting("INSERT INTO DBZ4367 (ID, DATA) VALUES (2, 'pre-snapshot in TX')");
// pre-snapshot DDL, should not be emitted in the streaming phase
secondConnection.execute("ALTER TABLE DBZ4367_EXTRA ADD DATA2 VARCHAR2(50) DEFAULT 'default2'");
secondConnection.execute("ALTER TABLE DBZ4367_EXTRA ADD DATA3 VARCHAR2(50) DEFAULT 'default3'");
secondConnection.execute("INSERT INTO DBZ4367_EXTRA (ID, DATA, DATA2, DATA3) VALUES (150, 'second table, with outdated schema', 'something', 'something')");
secondConnection.execute("ALTER TABLE DBZ4367_EXTRA DROP COLUMN DATA3");
connection.executeWithoutCommitting("INSERT INTO DBZ4367_EXTRA (ID, DATA, DATA2) VALUES (200, 'second table, pre-snapshot in TX', 'something')");
Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM\\.DBZ4367,DEBEZIUM\\.DBZ4367_EXTRA")
.with(OracleConnectorConfig.INCLUDE_SCHEMA_CHANGES, true)
.build();
start(OracleConnector.class, config);
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
SourceRecords records;
List<SourceRecord> ddls;
List<Integer> ids;
// we expect two DDL records (synthetic CREATEs for the final table structure) and three DML records (one for each insert)
records = consumeRecordsByTopic(5);
ddls = records.ddlRecordsForDatabase("ORCLPDB1");
ddls.forEach(r -> assertThat(((Struct) r.value()).getString("ddl")).contains("CREATE TABLE"));
assertThat(ddls).hasSize(2);
ids = records.recordsForTopic("server1.DEBEZIUM.DBZ4367").stream()
.map(r -> getAfter(r).getInt32("ID"))
.collect(Collectors.toList());
assertThat(ids).containsExactly(1);
ids = records.recordsForTopic("server1.DEBEZIUM.DBZ4367_EXTRA").stream()
.map(r -> getAfter(r).getInt32("ID"))
.collect(Collectors.toList());
assertThat(ids).containsOnly(100, 150);
assertThat(ids).doesNotHaveDuplicates();
assertThat(ids).hasSize(2);
connection.executeWithoutCommitting("INSERT INTO DBZ4367 (ID, DATA) VALUES (3, 'post-snapshot in TX')");
connection.executeWithoutCommitting("INSERT INTO DBZ4367_EXTRA (ID, DATA, DATA2) VALUES (300, 'second table, post-snapshot in TX', 'something')");
connection.executeWithoutCommitting("COMMIT");
// snapshot-spanning transaction ends here
// post-snapshot transaction, changes should be streamed
connection.execute("INSERT INTO DBZ4367 (ID, DATA) VALUES (4, 'post snapshot post TX')");
connection.execute("INSERT INTO DBZ4367_EXTRA (ID, DATA, DATA2) VALUES (400, 'second table, post-snapshot post TX', 'something')");
records = consumeRecordsByTopic(6);
ddls = records.ddlRecordsForDatabase("ORCLPDB1");
if (ddls != null) {
assertThat(ddls).isEmpty();
}
ids = records.recordsForTopic("server1.DEBEZIUM.DBZ4367").stream()
.map(r -> getAfter(r).getInt32("ID"))
.collect(Collectors.toList());
assertThat(ids).containsOnly(2, 3, 4);
assertThat(ids).doesNotHaveDuplicates();
assertThat(ids).hasSize(3);
ids = records.recordsForTopic("server1.DEBEZIUM.DBZ4367_EXTRA").stream()
.map(r -> getAfter(r).getInt32("ID"))
.collect(Collectors.toList());
assertThat(ids).containsOnly(200, 300, 400);
assertThat(ids).doesNotHaveDuplicates();
assertThat(ids).hasSize(3);
}
finally {
stopConnector();
TestHelper.dropTable(connection, "DBZ4367");
TestHelper.dropTable(connection, "DBZ4367_EXTRA");
secondConnection.close();
}
}
@Test
@FixFor("DBZ-4842")
public void shouldRestartAfterCapturedTableIsDroppedWhileConnectorDown() throws Exception {
TestHelper.dropTable(connection, "dbz4842");
try {
connection.execute("CREATE TABLE dbz4842 (id numeric(9,0) primary key, name varchar2(50))");
TestHelper.streamTable(connection, "dbz4842");
Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM\\.DBZ4842")
.build();
start(OracleConnector.class, config);
assertConnectorIsRunning();
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
connection.execute("INSERT INTO dbz4842 (id,name) values (1,'Test')");
SourceRecords records = consumeRecordsByTopic(1);
assertThat(records.recordsForTopic("server1.DEBEZIUM.DBZ4842")).hasSize(1);
stopConnector((running) -> assertThat(running).isFalse());
connection.execute("INSERT INTO dbz4842 (id,name) values (2,'Test')");
TestHelper.dropTable(connection, "dbz4842");
start(OracleConnector.class, config);
assertConnectorIsRunning();
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
// there won't be any records because the drop of the table will cause LogMiner to register
// the final insert with table-name OBJ#xxxxx since the object no longer exists.
Awaitility.await().pollDelay(10, TimeUnit.SECONDS).timeout(11, TimeUnit.SECONDS).until(() -> {
assertNoRecordsToConsume();
return true;
});
}
finally {
TestHelper.dropTable(connection, "dbz4842");
}
}
@Test
@FixFor("DBZ-4852")
@SkipWhenAdapterNameIsNot(value = SkipWhenAdapterNameIsNot.AdapterName.LOGMINER, reason = "User-defined types not supported")
public void shouldCaptureChangeForTableWithUnsupportedColumnType() throws Exception {
TestHelper.dropTable(connection, "dbz4852");
try {
// Setup a special directory reference used by the BFILENAME arguments
try (OracleConnection admin = TestHelper.adminConnection()) {
admin.execute("CREATE OR REPLACE DIRECTORY DIR_DBZ4852 AS '/home/oracle'");
}
Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM\\.DBZ4852")
.build();
start(OracleConnector.class, config);
assertConnectorIsRunning();
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
// Setup table with an unsupported column type, i.e. BFILE
connection.execute("CREATE TABLE dbz4852 (id numeric(9,0) primary key, filename bfile)");
TestHelper.streamTable(connection, "dbz4852");
// Perform DML operations
connection.execute("INSERT INTO dbz4852 (id,filename) values (1,bfilename('DIR_DBZ4852','test.txt'))");
connection.execute("UPDATE dbz4852 set filename = bfilename('DIR_DBZ4852','test2.txt') WHERE id = 1");
connection.execute("DELETE FROM dbz4852 where id = 1");
SourceRecords records = consumeRecordsByTopic(3);
assertThat(records.recordsForTopic("server1.DEBEZIUM.DBZ4852")).hasSize(3);
SourceRecord insert = records.recordsForTopic("server1.DEBEZIUM.DBZ4852").get(0);
VerifyRecord.isValidInsert(insert, "ID", 1);
Struct after = ((Struct) insert.value()).getStruct(Envelope.FieldName.AFTER);
assertThat(after.schema().field("FILENAME")).isNull();
SourceRecord update = records.recordsForTopic("server1.DEBEZIUM.DBZ4852").get(1);
VerifyRecord.isValidUpdate(update, "ID", 1);
Struct before = ((Struct) update.value()).getStruct(Envelope.FieldName.BEFORE);
assertThat(before.schema().field("FILENAME")).isNull();
after = ((Struct) update.value()).getStruct(Envelope.FieldName.AFTER);
assertThat(after.schema().field("FILENAME")).isNull();
SourceRecord delete = records.recordsForTopic("server1.DEBEZIUM.DBZ4852").get(2);
VerifyRecord.isValidDelete(delete, "ID", 1);
before = ((Struct) delete.value()).getStruct(Envelope.FieldName.BEFORE);
assertThat(before.schema().field("FILENAME")).isNull();
}
finally {
TestHelper.dropTable(connection, "dbz4852");
}
}
@Test
@FixFor("DBZ-4853")
public void shouldCaptureChangeForTableWithUnsupportedColumnTypeLong() throws Exception {
TestHelper.dropTable(connection, "dbz4853");
try {
Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM\\.DBZ4853")
.build();
start(OracleConnector.class, config);
assertConnectorIsRunning();
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
// Setup table with an unsupported column type, i.e. BFILE
connection.execute("CREATE TABLE dbz4853 (id numeric(9,0) primary key, long_val long)");
TestHelper.streamTable(connection, "dbz4853");
// Perform DML operations
connection.execute("INSERT INTO dbz4853 (id,long_val) values (1,'test.txt')");
connection.execute("UPDATE dbz4853 set long_val = 'test2.txt' WHERE id = 1");
connection.execute("DELETE FROM dbz4853 where id = 1");
SourceRecords records = consumeRecordsByTopic(3);
assertThat(records.recordsForTopic("server1.DEBEZIUM.DBZ4853")).hasSize(3);
SourceRecord insert = records.recordsForTopic("server1.DEBEZIUM.DBZ4853").get(0);
VerifyRecord.isValidInsert(insert, "ID", 1);
Struct after = ((Struct) insert.value()).getStruct(Envelope.FieldName.AFTER);
assertThat(after.schema().field("LONG_VAL")).isNull();
SourceRecord update = records.recordsForTopic("server1.DEBEZIUM.DBZ4853").get(1);
VerifyRecord.isValidUpdate(update, "ID", 1);
Struct before = ((Struct) update.value()).getStruct(Envelope.FieldName.BEFORE);
assertThat(before.schema().field("LONG_VAL")).isNull();
after = ((Struct) update.value()).getStruct(Envelope.FieldName.AFTER);
assertThat(after.schema().field("LONG_VAL")).isNull();
SourceRecord delete = records.recordsForTopic("server1.DEBEZIUM.DBZ4853").get(2);
VerifyRecord.isValidDelete(delete, "ID", 1);
before = ((Struct) delete.value()).getStruct(Envelope.FieldName.BEFORE);
assertThat(before.schema().field("LONG_VAL")).isNull();
}
finally {
TestHelper.dropTable(connection, "dbz4853");
}
}
@Test
@FixFor("DBZ-4907")
@SkipWhenAdapterNameIsNot(value = SkipWhenAdapterNameIsNot.AdapterName.LOGMINER, reason = "Only LogMiner performs flushes")
public void shouldContinueToUpdateOffsetsEvenWhenTableIsNotChanged() throws Exception {
TestHelper.dropTable(connection, "dbz4907");
try {
connection.execute("CREATE TABLE dbz4907 (id numeric(9,0) primary key, state varchar2(50))");
connection.execute("INSERT INTO dbz4907 (id,state) values (1, 'snapshot')");
TestHelper.streamTable(connection, "dbz4907");
Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM\\.DBZ4907")
.build();
start(OracleConnector.class, config);
assertConnectorIsRunning();
waitForSnapshotToBeCompleted(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
SourceRecords records = consumeRecordsByTopic(1);
List<SourceRecord> table = records.recordsForTopic("server1.DEBEZIUM.DBZ4907");
assertThat(table).hasSize(1);
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
// There should at least be a commit by the flush policy that triggers the advancement
// of the SCN values in the offsets within a few seconds of the polling mechanism.
final String offsetScn = getStreamingMetric("OffsetScn");
final String committedScn = getStreamingMetric("CommittedScn");
Awaitility.await().atMost(60, TimeUnit.SECONDS).until(() -> {
final String newOffsetScn = getStreamingMetric("OffsetScn");
final String newCommittedScn = getStreamingMetric("CommittedScn");
return !newOffsetScn.equals(offsetScn) && !newCommittedScn.equals(committedScn);
});
}
finally {
TestHelper.dropTable(connection, "dbz4907");
}
}
@Test
@FixFor("DBZ-4936")
public void shouldNotEmitLastCommittedTransactionEventsUponRestart() throws Exception {
TestHelper.dropTable(connection, "dbz4936");
try {
connection.execute("CREATE TABLE dbz4936 (id numeric(9,0) primary key, name varchar2(100))");
TestHelper.streamTable(connection, "dbz4936");
Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM\\.DBZ4936")
// this explicitly only applies when memory buffer is being used
.with(OracleConnectorConfig.LOG_MINING_BUFFER_TYPE, "memory")
.build();
start(OracleConnector.class, config);
assertConnectorIsRunning();
// Initiate a second connection with an open transaction
try (OracleConnection activeTransaction = TestHelper.testConnection()) {
// Wait for snapshot phase to conclude
waitForSnapshotToBeCompleted(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
// Initiate in-progress transaction on separate connection
activeTransaction.setAutoCommit(false);
activeTransaction.executeWithoutCommitting("INSERT INTO dbz4936 (id,name) values (1,'In-Progress')");
// Wait for streaming to begin
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
// Perform a DML on main connection & commit
connection.execute("INSERT INTO dbz4936 (id,name) values (2, 'committed')");
// Get the DML
SourceRecords records = consumeRecordsByTopic(1);
List<SourceRecord> tableRecords = records.recordsForTopic("server1.DEBEZIUM.DBZ4936");
assertThat(tableRecords).hasSize(1);
VerifyRecord.isValidInsert(tableRecords.get(0), "ID", 2);
// Now update the inserted entry
connection.execute("UPDATE dbz4936 set name = 'updated' WHERE id = 2");
// Get the DML
records = consumeRecordsByTopic(1);
tableRecords = records.recordsForTopic("server1.DEBEZIUM.DBZ4936");
assertThat(tableRecords).hasSize(1);
VerifyRecord.isValidUpdate(tableRecords.get(0), "ID", 2);
// Stop the connector
// This should flush commit_scn but leave scn as a value that comes before the in-progress transaction
stopConnector();
// Restart connector
start(OracleConnector.class, config);
assertConnectorIsRunning();
// Wait for streaming & then commit in-progress transaction
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
activeTransaction.commit();
// Get the DML
records = consumeRecordsByTopic(1);
tableRecords = records.recordsForTopic("server1.DEBEZIUM.DBZ4936");
assertThat(tableRecords).hasSize(1);
VerifyRecord.isValidInsert(tableRecords.get(0), "ID", 1);
// There should be no more records to consume
assertNoRecordsToConsume();
}
}
finally {
TestHelper.dropTable(connection, "dbz4936");
}
}
@Test
@FixFor("DbZ-3318")
@SkipWhenAdapterNameIsNot(value = SkipWhenAdapterNameIsNot.AdapterName.LOGMINER, reason = "Applies only to LogMiner")
public void shouldSuccessfullyConnectAndStreamWithDatabaseUrl() throws Exception {
connection.execute("INSERT INTO customer (id,name,score) values (1001, 'DBZ3668', 100)");
// Use the default configuration as a baseline.
// The default configuration automatically adds the `database.hostname` property, but we want to
// use `database.url` instead. So we'll generate a map, remove the hostname key and then add
// the url key instead before creating a new configuration object for the connector.
final Map<String, String> defaultConfig = TestHelper.defaultConfig().build().asMap();
defaultConfig.remove(OracleConnectorConfig.HOSTNAME.name());
defaultConfig.put(OracleConnectorConfig.URL.name(), TestHelper.getOracleConnectionUrlDescriptor());
Configuration.Builder builder = Configuration.create();
for (Map.Entry<String, String> entry : defaultConfig.entrySet()) {
builder.with(entry.getKey(), entry.getValue());
}
start(OracleConnector.class, builder.build());
assertConnectorIsRunning();
waitForSnapshotToBeCompleted(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
// Read snapshot record
SourceRecords records = consumeRecordsByTopic(1);
List<SourceRecord> tableRecords = records.recordsForTopic("server1.DEBEZIUM.CUSTOMER");
assertThat(tableRecords).hasSize(1);
VerifyRecord.isValidRead(tableRecords.get(0), "ID", 1001);
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
}
@Test
@FixFor("DBZ-4953")
public void shouldStreamTruncateEventWhenLobIsEnabled() throws Exception {
TestHelper.dropTable(connection, "dbz4953");
try {
connection.execute("CREATE TABLE dbz4953 (id numeric(9,0) primary key, col2 varchar2(100))");
TestHelper.streamTable(connection, "dbz4953");
connection.execute("INSERT INTO dbz4953 (id,col2) values (1, 'Daffy Duck')");
Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM\\.DBZ4953")
.with(OracleConnectorConfig.LOB_ENABLED, true)
.build();
start(OracleConnector.class, config);
assertConnectorIsRunning();
waitForSnapshotToBeCompleted(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
SourceRecords records = consumeRecordsByTopic(1);
List<SourceRecord> tableRecords = records.recordsForTopic("server1.DEBEZIUM.DBZ4953");
assertThat(tableRecords).hasSize(1);
VerifyRecord.isValidRead(tableRecords.get(0), "ID", 1);
// truncate
connection.execute("TRUNCATE TABLE dbz4953");
records = consumeRecordsByTopic(1);
tableRecords = records.recordsForTopic("server1.DEBEZIUM.DBZ4953");
assertThat(tableRecords).hasSize(1);
VerifyRecord.isValidTruncate(tableRecords.get(0));
assertNoRecordsToConsume();
}
finally {
TestHelper.dropTable(connection, "dbz4953");
}
}
@Test
@FixFor("DBZ-4963")
@SkipWhenAdapterNameIsNot(value = SkipWhenAdapterNameIsNot.AdapterName.LOGMINER, reason = "Applies only to LogMiner")
public void shouldRestartLogMiningSessionAfterMaxSessionElapses() throws Exception {
TestHelper.dropTable(connection, "dbz4963");
try {
connection.execute("CREATE TABLE dbz4963 (id numeric(9,0) primary key, data varchar2(50))");
TestHelper.streamTable(connection, "dbz4963");
Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM\\.DBZ4963")
.with(OracleConnectorConfig.LOG_MINING_SESSION_MAX_MS, 10_000L)
.build();
LogInterceptor logInterceptor = new LogInterceptor(LogMinerStreamingChangeEventSource.class);
start(OracleConnector.class, config);
assertConnectorIsRunning();
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
// Wait at most 60 seconds until we get notified in the logs that maximum session had exceeded.
Awaitility.await()
.atMost(60, TimeUnit.SECONDS)
.until(() -> logInterceptor.containsMessage("LogMiner session has exceeded maximum session time"));
stopConnector();
}
finally {
TestHelper.dropTable(connection, "dbz4963");
}
}
@Test
@FixFor("DBZ-4963")
@Ignore("Waits 60 seconds by default, so disabled by default")
public void shouldNotRestartLogMiningSessionWithMaxSessionZero() throws Exception {
TestHelper.dropTable(connection, "dbz4963");
try {
connection.execute("CREATE TABLE dbz4963 (id numeric(9,0) primary key, data varchar2(50))");
TestHelper.streamTable(connection, "dbz4963");
// default max session is 0L
Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM\\.DBZ4963")
.build();
LogInterceptor logInterceptor = new LogInterceptor(LogMinerStreamingChangeEventSource.class);
start(OracleConnector.class, config);
assertConnectorIsRunning();
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
try {
// Wait at most 60 seconds for potential message
// The message should never be written here and so a ConditionTimeoutException should be thrown.
Awaitility.await()
.atMost(60, TimeUnit.SECONDS)
.until(() -> logInterceptor.containsMessage("LogMiner session has exceeded maximum session time"));
}
catch (ConditionTimeoutException e) {
// expected
stopConnector();
return;
}
fail("Expected a ConditionTimeoutException, LogMiner session max session message should not have been written.");
}
finally {
TestHelper.dropTable(connection, "dbz4963");
}
}
@Test
@FixFor("DBZ-5006")
public void shouldSupportTablesWithForwardSlashes() throws Exception {
// Different forward-slash scenarios
testTableWithForwardSlashes("/dbz5006", "_dbz5006");
testTableWithForwardSlashes("dbz/5006", "dbz_5006");
testTableWithForwardSlashes("dbz5006/", "dbz5006_");
testTableWithForwardSlashes("db/z50/06", "db_z50_06");
testTableWithForwardSlashes("dbz//5006", "dbz__5006");
}
private void testTableWithForwardSlashes(String tableName, String topicTableName) throws Exception {
final String quotedTableName = "\"" + tableName + "\"";
TestHelper.dropTable(connection, quotedTableName);
try {
// Always want to make sure the offsets are cleared for each invocation of this sub-test
Testing.Files.delete(OFFSET_STORE_PATH);
Testing.Files.delete(TestHelper.DB_HISTORY_PATH);
connection.execute("CREATE TABLE " + quotedTableName + " (id numeric(9,0) primary key, data varchar2(50))");
connection.execute("INSERT INTO " + quotedTableName + " (id,data) values (1, 'Record1')");
TestHelper.streamTable(connection, quotedTableName);
Configuration config = TestHelper.defaultConfig()
.with(OracleConnectorConfig.TABLE_INCLUDE_LIST, "DEBEZIUM\\." + tableName)
.build();
start(OracleConnector.class, config);
assertConnectorIsRunning();
waitForSnapshotToBeCompleted(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
// NOTE: Forward slashes are not valid in topic names, will be converted to underscore.
// The following takes this into account.
SourceRecords records = consumeRecordsByTopic(1);
List<SourceRecord> tableRecords = records.recordsForTopic("server1.DEBEZIUM." + topicTableName);
assertThat(tableRecords).hasSize(1);
VerifyRecord.isValidRead(tableRecords.get(0), "ID", 1);
waitForStreamingRunning(TestHelper.CONNECTOR_NAME, TestHelper.SERVER_NAME);
assertNoRecordsToConsume();
connection.execute("INSERT INTO " + quotedTableName + " (id,data) values (2,'Record2')");
records = consumeRecordsByTopic(1);
tableRecords = records.recordsForTopic("server1.DEBEZIUM." + topicTableName);
assertThat(tableRecords).hasSize(1);
VerifyRecord.isValidInsert(tableRecords.get(0), "ID", 2);
connection.execute("UPDATE " + quotedTableName + " SET data = 'Record2u' WHERE id = 2");
records = consumeRecordsByTopic(1);
tableRecords = records.recordsForTopic("server1.DEBEZIUM." + topicTableName);
assertThat(tableRecords).hasSize(1);
VerifyRecord.isValidUpdate(tableRecords.get(0), "ID", 2);
connection.execute("DELETE " + quotedTableName + " WHERE id = 1");
records = consumeRecordsByTopic(2);
tableRecords = records.recordsForTopic("server1.DEBEZIUM." + topicTableName);
assertThat(tableRecords).hasSize(2);
VerifyRecord.isValidDelete(tableRecords.get(0), "ID", 1);
VerifyRecord.isValidTombstone(tableRecords.get(1));
assertNoRecordsToConsume();
}
catch (Exception e) {
throw new RuntimeException("Forward-slash test failed for table: " + tableName, e);
}
finally {
stopConnector();
TestHelper.dropTable(connection, quotedTableName);
}
}
private void waitForCurrentScnToHaveBeenSeenByConnector() throws SQLException {
try (OracleConnection admin = TestHelper.adminConnection()) {
admin.resetSessionToCdb();
final Scn scn = admin.getCurrentScn();
Awaitility.await()
.atMost(TestHelper.defaultMessageConsumerPollTimeout(), TimeUnit.SECONDS)
.until(() -> {
final String scnValue = getStreamingMetric("CurrentScn");
if (scnValue == null) {
return false;
}
return Scn.valueOf(scnValue).compareTo(scn) > 0;
});
}
}
private Struct getAfter(SourceRecord record) {
return ((Struct) record.value()).getStruct(Envelope.FieldName.AFTER);
}
} |
package org.incode.module.document.dom.impl.docs;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.Optional;
import java.util.SortedSet;
import java.util.TreeSet;
import javax.inject.Inject;
import javax.jdo.JDOHelper;
import javax.jdo.annotations.Column;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.Index;
import javax.jdo.annotations.Indices;
import javax.jdo.annotations.Inheritance;
import javax.jdo.annotations.InheritanceStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Queries;
import javax.jdo.annotations.Unique;
import javax.jdo.annotations.Uniques;
import com.google.common.collect.Lists;
import com.google.common.eventbus.Subscribe;
import org.apache.commons.lang3.StringUtils;
import org.axonframework.eventhandling.annotation.EventHandler;
import org.joda.time.LocalDate;
import org.apache.isis.applib.AbstractSubscriber;
import org.apache.isis.applib.ApplicationException;
import org.apache.isis.applib.annotation.Action;
import org.apache.isis.applib.annotation.ActionLayout;
import org.apache.isis.applib.annotation.BookmarkPolicy;
import org.apache.isis.applib.annotation.Collection;
import org.apache.isis.applib.annotation.Contributed;
import org.apache.isis.applib.annotation.DomainObject;
import org.apache.isis.applib.annotation.DomainObjectLayout;
import org.apache.isis.applib.annotation.DomainService;
import org.apache.isis.applib.annotation.Editing;
import org.apache.isis.applib.annotation.MemberOrder;
import org.apache.isis.applib.annotation.Mixin;
import org.apache.isis.applib.annotation.NatureOfService;
import org.apache.isis.applib.annotation.Parameter;
import org.apache.isis.applib.annotation.ParameterLayout;
import org.apache.isis.applib.annotation.Programmatic;
import org.apache.isis.applib.annotation.Property;
import org.apache.isis.applib.annotation.SemanticsOf;
import org.apache.isis.applib.annotation.Where;
import org.apache.isis.applib.services.background.BackgroundService2;
import org.apache.isis.applib.services.factory.FactoryService;
import org.apache.isis.applib.services.i18n.TranslatableString;
import org.apache.isis.applib.services.registry.ServiceRegistry2;
import org.apache.isis.applib.services.title.TitleService;
import org.apache.isis.applib.services.xactn.TransactionService;
import org.apache.isis.applib.value.Blob;
import org.apache.isis.applib.value.Clob;
import org.incode.module.document.DocumentModule;
import org.incode.module.document.dom.impl.applicability.Applicability;
import org.incode.module.document.dom.impl.applicability.ApplicabilityRepository;
import org.incode.module.document.dom.impl.applicability.AttachmentAdvisor;
import org.incode.module.document.dom.impl.applicability.AttachmentAdvisorAttachToNone;
import org.incode.module.document.dom.impl.applicability.RendererModelFactory;
import org.incode.module.document.dom.impl.renderers.Renderer;
import org.incode.module.document.dom.impl.renderers.RendererFromBytesToBytes;
import org.incode.module.document.dom.impl.renderers.RendererFromBytesToBytesWithPreviewToUrl;
import org.incode.module.document.dom.impl.renderers.RendererFromBytesToChars;
import org.incode.module.document.dom.impl.renderers.RendererFromBytesToCharsWithPreviewToUrl;
import org.incode.module.document.dom.impl.renderers.RendererFromCharsToBytes;
import org.incode.module.document.dom.impl.renderers.RendererFromCharsToBytesWithPreviewToUrl;
import org.incode.module.document.dom.impl.renderers.RendererFromCharsToChars;
import org.incode.module.document.dom.impl.renderers.RendererFromCharsToCharsWithPreviewToUrl;
import org.incode.module.document.dom.impl.rendering.RenderingStrategy;
import org.incode.module.document.dom.impl.types.DocumentType;
import org.incode.module.document.dom.services.ClassNameViewModel;
import org.incode.module.document.dom.services.ClassService;
import org.incode.module.document.dom.spi.AttachmentAdvisorClassNameService;
import org.incode.module.document.dom.spi.RendererModelFactoryClassNameService;
import org.incode.module.document.dom.types.AtPathType;
import org.incode.module.document.dom.types.FqcnType;
import org.estatio.module.invoice.dom.DocumentTemplateApi;
import org.estatio.module.invoice.dom.DocumentTemplateData;
import org.estatio.module.invoice.dom.DocumentTypeApi;
import org.estatio.module.invoice.dom.DocumentTypeData;
import org.estatio.module.invoice.dom.RenderingStrategyApi;
import org.estatio.module.invoice.dom.RenderingStrategyData;
import lombok.Getter;
import lombok.Setter;
@PersistenceCapable(
identityType= IdentityType.DATASTORE,
schema = "incodeDocuments"
)
@Inheritance(strategy = InheritanceStrategy.NEW_TABLE)
@Queries({
@javax.jdo.annotations.Query(
name = "findByTypeAndAtPath", language = "JDOQL",
value = "SELECT "
+ "FROM org.incode.module.document.dom.impl.docs.DocumentTemplate "
+ "WHERE typeCopy == :type "
+ " && atPathCopy == :atPath "
+ "ORDER BY date DESC"
),
@javax.jdo.annotations.Query(
name = "findByTypeAndAtPathAndDate", language = "JDOQL",
value = "SELECT "
+ "FROM org.incode.module.document.dom.impl.docs.DocumentTemplate "
+ "WHERE typeCopy == :type "
+ " && atPathCopy == :atPath "
+ " && date == :date "
),
@javax.jdo.annotations.Query(
name = "findByTypeAndApplicableToAtPath", language = "JDOQL",
value = "SELECT "
+ "FROM org.incode.module.document.dom.impl.docs.DocumentTemplate "
+ "WHERE typeCopy == :type "
+ " && :atPath.startsWith(atPathCopy) "
+ "ORDER BY atPathCopy DESC, date DESC "
),
@javax.jdo.annotations.Query(
name = "findByApplicableToAtPath", language = "JDOQL",
value = "SELECT "
+ "FROM org.incode.module.document.dom.impl.docs.DocumentTemplate "
+ "WHERE :atPath.startsWith(atPathCopy) "
+ "ORDER BY typeCopy ASC, atPathCopy DESC, date DESC "
),
@javax.jdo.annotations.Query(
name = "findByTypeAndApplicableToAtPathAndCurrent", language = "JDOQL",
value = "SELECT "
+ "FROM org.incode.module.document.dom.impl.docs.DocumentTemplate "
+ "WHERE typeCopy == :type "
+ " && :atPath.startsWith(atPathCopy) "
+ " && (date == null || date <= :now) "
+ "ORDER BY atPathCopy DESC, date DESC "
),
@javax.jdo.annotations.Query(
name = "findByType", language = "JDOQL",
value = "SELECT "
+ "FROM org.incode.module.document.dom.impl.docs.DocumentTemplate "
+ "WHERE typeCopy == :type "
+ "ORDER BY atPathCopy DESC, date DESC "
),
@javax.jdo.annotations.Query(
name = "findByApplicableToAtPathAndCurrent", language = "JDOQL",
value = "SELECT "
+ "FROM org.incode.module.document.dom.impl.docs.DocumentTemplate "
+ " && :atPath.startsWith(atPathCopy) "
+ " && (date == null || date <= :now) "
+ "ORDER BY atPathCopy DESC, typeCopy, date DESC "
)
})
@Uniques({
@Unique(
name = "DocumentTemplate_type_atPath_date_IDX",
members = { "typeCopy", "atPathCopy", "date" }
),
})
@Indices({
@Index(
name = "DocumentTemplate_atPath_date_IDX",
members = { "atPathCopy", "date" }
),
@Index(
name = "DocumentTemplate_type_date_IDX",
members = { "typeCopy", "date" }
),
})
@DomainObject(
objectType = "incodeDocuments.DocumentTemplate",
editing = Editing.DISABLED
)
@DomainObjectLayout(
titleUiEvent = DocumentTemplate.TitleUiEvent.class,
iconUiEvent = DocumentTemplate.IconUiEvent.class,
cssClassUiEvent = DocumentTemplate.CssClassUiEvent.class,
bookmarking = BookmarkPolicy.AS_ROOT
)
public class DocumentTemplate
extends DocumentAbstract<DocumentTemplate>
implements DocumentTemplateApi {
enum Toggle {
ENTITIES {
@Override public DocumentTemplateApi getTemplateApi(final DocumentTemplate documentTemplate) {
return documentTemplate;
}
@Override public DocumentTypeApi getTypeApi(final DocumentTemplate documentTemplate) {
return documentTemplate.getType();
}
@Override public RenderingStrategyApi getContentRenderingStrategyApi(final DocumentTemplate documentTemplate) {
return documentTemplate.getContentRenderingStrategy();
}
@Override public RenderingStrategyApi getNameRenderingStrategyApi(final DocumentTemplate documentTemplate) {
return documentTemplate.getNameRenderingStrategy();
}
},
DATA {
@Override public DocumentTemplateApi getTemplateApi(final DocumentTemplate documentTemplate) {
return documentTemplate.getTemplateData();
}
@Override public DocumentTypeApi getTypeApi(final DocumentTemplate documentTemplate) {
return documentTemplate.getTypeData();
}
@Override public RenderingStrategyApi getContentRenderingStrategyApi(final DocumentTemplate documentTemplate) {
return documentTemplate.getContentRenderingStrategyData();
}
@Override public RenderingStrategyApi getNameRenderingStrategyApi(final DocumentTemplate documentTemplate) {
return documentTemplate.getNameRenderingStrategyData();
}
};
public abstract DocumentTemplateApi getTemplateApi(final DocumentTemplate documentTemplate);
public abstract DocumentTypeApi getTypeApi(final DocumentTemplate documentTemplate);
public abstract RenderingStrategyApi getContentRenderingStrategyApi(final DocumentTemplate documentTemplate);
public abstract RenderingStrategyApi getNameRenderingStrategyApi(final DocumentTemplate documentTemplate);
}
static Toggle toggle = Toggle.DATA;
//region > ui event classes
public static class TitleUiEvent extends DocumentModule.TitleUiEvent<DocumentTemplate>{}
public static class IconUiEvent extends DocumentModule.IconUiEvent<DocumentTemplate>{}
public static class CssClassUiEvent extends DocumentModule.CssClassUiEvent<DocumentTemplate>{}
//endregion
//region > title, icon, cssClass
/**
* Implemented as a subscriber so can be overridden by consuming application if required.
*/
@DomainService(nature = NatureOfService.DOMAIN)
public static class TitleSubscriber extends AbstractSubscriber {
public String getId() {
return "incodeDocuments.DocumentTemplate$TitleSubscriber";
}
@EventHandler
@Subscribe
public void on(DocumentTemplate.TitleUiEvent ev) {
if(ev.getTitle() != null) {
return;
}
ev.setTranslatableTitle(titleOf(ev.getSource()));
}
private TranslatableString titleOf(final DocumentTemplate template) {
if(template.getDate() != null) {
return TranslatableString.tr("[{type}] ({date})",
"type", template.getType().getReference(),
"date", template.getDate());
} else {
return TranslatableString.tr("[{type}] {name}",
"name", template.getName(),
"type", template.getType().getReference());
}
}
@Inject
TitleService titleService;
}
/**
* Implemented as a subscriber so can be overridden by consuming application if required.
*/
@DomainService(nature = NatureOfService.DOMAIN)
public static class IconSubscriber extends AbstractSubscriber {
public String getId() {
return "incodeDocuments.DocumentTemplate$IconSubscriber";
}
@EventHandler
@Subscribe
public void on(DocumentTemplate.IconUiEvent ev) {
if(ev.getIconName() != null) {
return;
}
ev.setIconName("");
}
}
/**
* Implemented as a subscriber so can be overridden by consuming application if required.
*/
@DomainService(nature = NatureOfService.DOMAIN)
public static class CssClassSubscriber extends AbstractSubscriber {
public String getId() {
return "incodeDocuments.DocumentTemplate$CssClassSubscriber";
}
@EventHandler
@Subscribe
public void on(DocumentTemplate.CssClassUiEvent ev) {
if(ev.getCssClass() != null) {
return;
}
ev.setCssClass("");
}
}
//endregion
//region > constructor
DocumentTemplate() {
// for unit testing only
}
public DocumentTemplate(
final DocumentType type,
final LocalDate date,
final String atPath,
final String fileSuffix,
final boolean previewOnly,
final Blob blob,
final RenderingStrategy contentRenderingStrategy,
final String subjectText,
final RenderingStrategy subjectRenderingStrategy) {
super(type, atPath);
modifyBlob(blob);
init(type, date, atPath, fileSuffix, previewOnly, contentRenderingStrategy, subjectText, subjectRenderingStrategy);
}
public DocumentTemplate(
final DocumentType type,
final LocalDate date,
final String atPath,
final String fileSuffix,
final boolean previewOnly,
final String name, final String mimeType, final String text,
final RenderingStrategy contentRenderingStrategy,
final String subjectText,
final RenderingStrategy subjectRenderingStrategy) {
super(type, atPath);
setTextData(name, mimeType, text);
init(type, date, atPath, fileSuffix, previewOnly, contentRenderingStrategy, subjectText, subjectRenderingStrategy);
}
public DocumentTemplate(
final DocumentType type,
final LocalDate date,
final String atPath,
final String fileSuffix,
final boolean previewOnly,
final Clob clob,
final RenderingStrategy contentRenderingStrategy,
final String subjectText,
final RenderingStrategy subjectRenderingStrategy) {
super(type, atPath);
modifyClob(clob);
init(type, date, atPath, fileSuffix, previewOnly, contentRenderingStrategy, subjectText, subjectRenderingStrategy);
}
private void init(
final DocumentType type,
final LocalDate date,
final String atPath,
final String fileSuffix,
final boolean previewOnly,
final RenderingStrategy contentRenderingStrategy,
final String nameText,
final RenderingStrategy nameRenderingStrategy) {
this.typeCopy = type;
this.atPathCopy = atPath;
this.date = date;
this.fileSuffix = stripLeadingDotAndLowerCase(fileSuffix);
this.previewOnly = previewOnly;
this.contentRenderingStrategy = contentRenderingStrategy;
this.nameText = nameText;
this.nameRenderingStrategy = nameRenderingStrategy;
}
static String stripLeadingDotAndLowerCase(final String fileSuffix) {
final int lastDot = fileSuffix.lastIndexOf(".");
final String stripLeadingDot = fileSuffix.substring(lastDot+1);
return stripLeadingDot.toLowerCase();
}
//endregion
//region > typeCopy (derived property, persisted)
/**
* Copy of {@link #getType()}, for query purposes only.
*/
@Getter @Setter
@Column(allowsNull = "false", name = "typeId")
@Property(
notPersisted = true, // ignore for auditing
hidden = Where.EVERYWHERE
)
private DocumentType typeCopy;
public DocumentType getTypeCopy() {
return typeCopy;
}
//endregion
//region > atPathCopy (derived property, persisted)
/**
* Copy of {@link #getAtPath()}, for query purposes only.
*/
@Getter @Setter
@Column(allowsNull = "false", length = AtPathType.Meta.MAX_LEN)
@Property(
notPersisted = true, // ignore for auditing
hidden = Where.EVERYWHERE
)
private String atPathCopy;
//endregion
private DocumentTemplateData templateData;
@Programmatic
public DocumentTemplateData getTemplateData() {
return templateData != null
? templateData
: (templateData = getTypeData().lookup(getAtPathCopy()));
}
@Programmatic
public DocumentTemplateApi getTemplateApi() {
return toggle.getTemplateApi(this);
}
private DocumentTypeData typeData;
@Programmatic
public DocumentTypeData getTypeData() {
return typeData != null
? typeData
: (typeData = DocumentTypeData.reverseLookup(getTypeCopy()));
}
@Programmatic
public DocumentTypeApi getTypeApi() {
return toggle.getTypeApi(this);
}
@Programmatic
public RenderingStrategyData getContentRenderingStrategyData() {
return getTemplateData().getContentRenderingStrategy();
}
public RenderingStrategyApi getContentRenderingStrategyApi() {
return toggle.getContentRenderingStrategyApi(this);
}
@Programmatic
public RenderingStrategyData getNameRenderingStrategyData() {
return getTemplateData().getNameRenderingStrategy();
}
public RenderingStrategyApi getNameRenderingStrategyApi() {
return toggle.getNameRenderingStrategyApi(this);
}
//region > date (property)
public static class DateDomainEvent extends DocumentTemplate.PropertyDomainEvent<LocalDate> { }
@Getter @Setter
@Column(allowsNull = "false")
@Property(
domainEvent = DateDomainEvent.class,
editing = Editing.DISABLED
)
private LocalDate date;
//endregion
//region > contentRenderingStrategy (property)
public static class RenderingStrategyDomainEvent extends PropertyDomainEvent<RenderingStrategy> { }
@Getter @Setter
@Column(allowsNull = "false", name = "contentRenderStrategyId")
@Property(
domainEvent = RenderingStrategyDomainEvent.class,
editing = Editing.DISABLED
)
private RenderingStrategy contentRenderingStrategy;
public RenderingStrategy getContentRenderingStrategy() {
return contentRenderingStrategy;
}
//endregion
//region > fileSuffix (property)
public static class FileSuffixDomainEvent extends PropertyDomainEvent<String> { }
@Getter @Setter
@Column(allowsNull = "false", length = FileSuffixType.Meta.MAX_LEN)
@Property(
domainEvent = FileSuffixDomainEvent.class,
editing = Editing.DISABLED
)
private String fileSuffix;
//endregion
//region > nameText (persisted property)
public static class NameTextDomainEvent extends PropertyDomainEvent<Clob> { }
/**
* Used to determine the name of the {@link Document#getName() name} of the rendered {@link Document}.
*/
@Getter @Setter
@javax.jdo.annotations.Column(allowsNull = "false", length = NameTextType.Meta.MAX_LEN)
@Property(
notPersisted = true, // exclude from auditing
domainEvent = NameTextDomainEvent.class,
editing = Editing.DISABLED
)
private String nameText;
//endregion
//region > nameRenderingStrategy (property)
public static class NameRenderingStrategyDomainEvent extends PropertyDomainEvent<RenderingStrategy> { }
@Getter @Setter
@Column(allowsNull = "false", name = "nameRenderStrategyId")
@Property(
domainEvent = NameRenderingStrategyDomainEvent.class,
editing = Editing.DISABLED
)
private RenderingStrategy nameRenderingStrategy;
public RenderingStrategy getNameRenderingStrategy() {
return nameRenderingStrategy;
}
//endregion
//region > PreviewOnly (property)
public static class PreviewOnlyDomainEvent extends RenderingStrategy.PropertyDomainEvent<Boolean> { }
/**
* Whether this template can only be previewed (not used to also create a document).
*/
@Getter @Setter
@Column(allowsNull = "false")
@Property(
domainEvent = PreviewOnlyDomainEvent.class,
editing = Editing.DISABLED
)
private boolean previewOnly;
//endregion
//region > applicabilities (collection)
public static class ApplicabilitiesDomainEvent extends DocumentType.CollectionDomainEvent<Applicability> {
}
@javax.jdo.annotations.Persistent(mappedBy = "documentTemplate", dependentElement = "true")
@Collection(
domainEvent = ApplicabilitiesDomainEvent.class,
editing = Editing.DISABLED
)
@Getter @Setter
private SortedSet<Applicability> appliesTo = new TreeSet<>();
//endregion
//region > applicable (action)
/**
* TODO: remove once moved over to using DocumentTypeData and DocumentTemplateData
*/
@Mixin
public static class _applicable {
private final DocumentTemplate documentTemplate;
public _applicable(final DocumentTemplate documentTemplate) {
this.documentTemplate = documentTemplate;
}
public static class ActionDomainEvent extends DocumentAbstract.ActionDomainEvent { }
@Action(domainEvent = ActionDomainEvent.class, semantics = SemanticsOf.IDEMPOTENT)
@ActionLayout(cssClassFa = "fa-plus", contributed = Contributed.AS_ACTION)
@MemberOrder(name = "appliesTo", sequence = "1")
public DocumentTemplate $$(
@Parameter(maxLength = FqcnType.Meta.MAX_LEN, mustSatisfy = FqcnType.Meta.Specification.class)
@ParameterLayout(named = "Domain type")
final String domainClassName,
@Parameter(maxLength = FqcnType.Meta.MAX_LEN, mustSatisfy = FqcnType.Meta.Specification.class)
@ParameterLayout(named = "Renderer Model Factory")
final ClassNameViewModel rendererModelFactoryClassNameViewModel,
@Parameter(maxLength = FqcnType.Meta.MAX_LEN, mustSatisfy = FqcnType.Meta.Specification.class)
@ParameterLayout(named = "Attachment Advisor")
final ClassNameViewModel attachmentAdvisorClassNameViewModel) {
applicable(
domainClassName, rendererModelFactoryClassNameViewModel.getFullyQualifiedClassName(), attachmentAdvisorClassNameViewModel.getFullyQualifiedClassName());
return this.documentTemplate;
}
public TranslatableString disable$$() {
if (rendererModelFactoryClassNameService == null) {
return TranslatableString.tr(
"No RendererModelFactoryClassNameService registered to locate implementations of RendererModelFactory");
}
if (attachmentAdvisorClassNameService == null) {
return TranslatableString.tr(
"No AttachmentAdvisorClassNameService registered to locate implementations of AttachmentAdvisor");
}
return null;
}
public List<ClassNameViewModel> choices1$$() {
return rendererModelFactoryClassNameService.rendererModelFactoryClassNames();
}
public List<ClassNameViewModel> choices2$$() {
return attachmentAdvisorClassNameService.attachmentAdvisorClassNames();
}
public TranslatableString validate0$$(final String domainTypeName) {
return isApplicable(domainTypeName) ?
TranslatableString.tr(
"Already applicable for '{domainTypeName}'",
"domainTypeName", domainTypeName)
: null;
}
@Programmatic
public Applicability applicable(
final Class<?> domainClass,
final Class<? extends RendererModelFactory> renderModelFactoryClass,
final Class<? extends AttachmentAdvisor> attachmentAdvisorClass) {
return applicable(
domainClass.getName(),
renderModelFactoryClass,
attachmentAdvisorClass != null
? attachmentAdvisorClass
: AttachmentAdvisorAttachToNone.class
);
}
@Programmatic
public Applicability applicable(
final String domainClassName,
final Class<? extends RendererModelFactory> renderModelFactoryClass,
final Class<? extends AttachmentAdvisor> attachmentAdvisorClass) {
return applicable(domainClassName, renderModelFactoryClass.getName(), attachmentAdvisorClass.getName() );
}
@Programmatic
public Applicability applicable(
final String domainClassName,
final String renderModelFactoryClassName,
final String attachmentAdvisorClassName) {
Applicability applicability = existingApplicability(domainClassName);
if(applicability == null) {
applicability = applicabilityRepository.create(documentTemplate, domainClassName, renderModelFactoryClassName, attachmentAdvisorClassName);
} else {
applicability.setRendererModelFactoryClassName(renderModelFactoryClassName);
applicability.setAttachmentAdvisorClassName(attachmentAdvisorClassName);
}
return applicability;
}
private boolean isApplicable(final String domainClassName) {
return existingApplicability(domainClassName) != null;
}
private Applicability existingApplicability(final String domainClassName) {
SortedSet<Applicability> applicabilities = documentTemplate.getAppliesTo();
for (Applicability applicability : applicabilities) {
if (applicability.getDomainClassName().equals(domainClassName)) {
return applicability;
}
}
return null;
}
@Inject
RendererModelFactoryClassNameService rendererModelFactoryClassNameService;
@Inject
AttachmentAdvisorClassNameService attachmentAdvisorClassNameService;
@Inject
ApplicabilityRepository applicabilityRepository;
}
//endregion
//region > notApplicable (action)
/**
* TODO: remove once moved over to using DocumentTypeData and DocumentTemplateData
*/
@Mixin
public static class _notApplicable {
private final DocumentTemplate documentTemplate;
public _notApplicable(final DocumentTemplate documentTemplate) {
this.documentTemplate = documentTemplate;
}
public static class NotApplicableDomainEvent extends DocumentTemplate.ActionDomainEvent {
}
@Action(
domainEvent = NotApplicableDomainEvent.class,
semantics = SemanticsOf.IDEMPOTENT_ARE_YOU_SURE
)
@ActionLayout(
cssClassFa = "fa-minus"
)
@MemberOrder(name = "appliesTo", sequence = "2")
public DocumentTemplate $$(final Applicability applicability) {
applicabilityRepository.delete(applicability);
return this.documentTemplate;
}
public TranslatableString disable$$() {
final TranslatableString tr = factoryService.mixin(_applicable.class, documentTemplate).disable$$();
if(tr != null) {
return tr;
}
return choices0$$().isEmpty() ? TranslatableString.tr("No applicabilities to remove") : null;
}
public SortedSet<Applicability> choices0$$() {
return documentTemplate.getAppliesTo();
}
@Inject
ApplicabilityRepository applicabilityRepository;
@Inject
FactoryService factoryService;
}
//endregion
//region > appliesTo, newRendererModelFactory + newRendererModel, newAttachmentAdvisor + newAttachmentAdvice
/**
* TODO: only called by DocumentTemplateEquivalenceIntegTest, so eventually should be able to delete (along with Applicable etc).
*/
@Programmatic
public Optional<Applicability> applicableTo(final Class<?> domainObjectClass) {
return Lists.newArrayList(getAppliesTo()).stream()
.filter(applicability -> applies(applicability, domainObjectClass)).findFirst();
}
/**
* TODO: only called indirectly by {@link #applicableTo(Class)}, itself called only by test code, so should be able to delete.
*/
private boolean applies(
final Applicability applicability,
final Class<?> domainObjectClass) {
final Class<?> load = classService.load(applicability.getDomainClassName());
return load.isAssignableFrom(domainObjectClass);
}
private RendererModelFactory newRendererModelFactory(final Object domainObject) {
final Class<?> domainClass = domainObject.getClass();
return getTemplateApi().newRenderModelFactory(domainClass, classService, serviceRegistry2);
}
@Override
public RendererModelFactory newRenderModelFactory(
final Class<?> domainClass,
final ClassService classService,
final ServiceRegistry2 serviceRegistry2) {
final Optional<Applicability> applicability = applicableTo(domainClass);
return applicability.map(Applicability::getRendererModelFactoryClassName)
.map(classService::instantiate)
.map(RendererModelFactory.class::cast)
.map(serviceRegistry2::injectServicesInto)
.orElse(null);
}
@Programmatic
public AttachmentAdvisor newAttachmentAdvisor(final Object domainObject) {
final Class<?> domainClass = domainObject.getClass();
return getTemplateApi().newAttachmentAdvisor(domainClass, classService, serviceRegistry2);
}
@Programmatic
public AttachmentAdvisor newAttachmentAdvisor(
final Class<?> domainClass,
final ClassService classService,
final ServiceRegistry2 serviceRegistry2) {
final Optional<Applicability> applicability = applicableTo(domainClass);
return applicability.map(Applicability::getAttachmentAdvisorClassName)
.map(classService::instantiate)
.map(AttachmentAdvisor.class::cast)
.map(serviceRegistry2::injectServicesInto)
.orElse(null);
}
@Programmatic
public Object newRendererModel(final Object domainObject) {
final RendererModelFactory rendererModelFactory = newRendererModelFactory(domainObject);
if(rendererModelFactory == null) {
throw new IllegalStateException(String.format(
"For domain template %s, could not locate Applicability for domain object: %s",
getName(), domainObject.getClass().getName()));
}
final Object rendererModel = rendererModelFactory.newRendererModel(this, domainObject);
serviceRegistry2.injectServicesInto(rendererModel);
return rendererModel;
}
@Programmatic
public List<AttachmentAdvisor.PaperclipSpec> newAttachmentAdvice(final Document document, final Object domainObject) {
final AttachmentAdvisor attachmentAdvisor = newAttachmentAdvisor(domainObject);
if(attachmentAdvisor == null) {
throw new IllegalStateException(String.format(
"For domain template %s, could not locate Applicability for domain object: %s",
getName(), domainObject.getClass().getName()));
}
final List<AttachmentAdvisor.PaperclipSpec> paperclipSpecs = attachmentAdvisor.advise(this, domainObject,
document);
return paperclipSpecs;
}
//endregion
//region > preview, previewUrl (programmatic)
@Programmatic
public URL previewUrl(final Object rendererModel) throws IOException {
serviceRegistry2.injectServicesInto(rendererModel);
if(!getTemplateData().getContentRenderingStrategy().isPreviewsToUrl()) {
throw new IllegalStateException(String.format("RenderingStrategy '%s' does not support previewing to URL",
getTemplateData().getContentRenderingStrategy().getReference()));
}
final DocumentNature inputNature = getTemplateData().getContentRenderingStrategy().getInputNature();
final DocumentNature outputNature = getTemplateData().getContentRenderingStrategy().getOutputNature();
final Renderer renderer = getContentRenderingStrategyApi().newRenderer(
classService, serviceRegistry2);
switch (inputNature){
case BYTES:
switch (outputNature) {
case BYTES:
return ((RendererFromBytesToBytesWithPreviewToUrl) renderer).previewBytesToBytes(
getType(), getAtPath(), getVersion(),
asBytes(), rendererModel);
case CHARACTERS:
return ((RendererFromBytesToCharsWithPreviewToUrl) renderer).previewBytesToChars(
getType(), getAtPath(), getVersion(),
asBytes(), rendererModel);
default:
// shouldn't happen, above switch statement is complete
throw new IllegalArgumentException(String.format("Unknown output DocumentNature '%s'", outputNature));
}
case CHARACTERS:
switch (outputNature) {
case BYTES:
return ((RendererFromCharsToBytesWithPreviewToUrl) renderer).previewCharsToBytes(
getType(), getAtPath(), getVersion(),
asChars(), rendererModel);
case CHARACTERS:
return ((RendererFromCharsToCharsWithPreviewToUrl) renderer).previewCharsToChars(
getType(), getAtPath(), getVersion(),
asChars(), rendererModel);
default:
// shouldn't happen, above switch statement is complete
throw new IllegalArgumentException(String.format("Unknown output DocumentNature '%s'", outputNature));
}
default:
// shouldn't happen, above switch statement is complete
throw new IllegalArgumentException(String.format("Unknown input DocumentNature '%s'", inputNature));
}
}
//endregion
//region > create, createAndRender, createAndScheduleRender (programmatic)
@Programmatic
public Document create(final Object domainObject) {
final Document document = createDocumentUsingRendererModel(domainObject);
transactionService.flushTransaction();
return document;
}
@Programmatic
public Document createAndScheduleRender(final Object domainObject) {
final Document document = create(domainObject);
backgroundService2.execute(document).render(this, domainObject);
return document;
}
@Programmatic
public Document createAndRender(final Object domainObject) {
final Document document = create(domainObject);
document.render(this, domainObject);
return document;
}
//endregion
//region > createDocument (programmatic)
@Programmatic
public Document createDocumentUsingRendererModel(
final Object domainObject) {
final Object rendererModel = newRendererModel(domainObject);
final String documentName = determineDocumentName(rendererModel);
return createDocument(documentName);
}
private String determineDocumentName(final Object contentDataModel) {
serviceRegistry2.injectServicesInto(contentDataModel);
// subject
final RendererFromCharsToChars nameRenderer =
(RendererFromCharsToChars) getNameRenderingStrategyApi().newRenderer(
classService, serviceRegistry2);
String renderedDocumentName;
try {
renderedDocumentName = nameRenderer.renderCharsToChars(
getType(), "name", getAtPath(), getVersion(),
getNameText(), contentDataModel);
} catch (IOException e) {
renderedDocumentName = getName();
}
return withFileSuffix(renderedDocumentName);
}
private Document createDocument(String documentName) {
return documentRepository.create(getType(), getAtPath(), documentName, getMimeType());
}
//endregion
//region > renderContent (programmatic)
@Programmatic
public void renderContent(
final Document document,
final Object contentDataModel) {
renderContent((DocumentLike)document, contentDataModel);
}
@Programmatic
public void renderContent(
final DocumentLike document,
final Object contentDataModel) {
final String documentName = determineDocumentName(contentDataModel);
document.setName(documentName);
final RenderingStrategyApi renderingStrategy = getContentRenderingStrategyApi();
final String variant = "content";
try {
final DocumentNature inputNature = renderingStrategy.getInputNature();
final DocumentNature outputNature = renderingStrategy.getOutputNature();
final Renderer renderer = renderingStrategy.newRenderer(classService, serviceRegistry2);
switch (inputNature){
case BYTES:
switch (outputNature) {
case BYTES:
final byte[] renderedBytes = ((RendererFromBytesToBytes) renderer).renderBytesToBytes(
getType(), variant, getAtPath(), getVersion(),
asBytes(), contentDataModel);
final Blob blob = new Blob (documentName, getMimeType(), renderedBytes);
document.modifyBlob(blob);
return;
case CHARACTERS:
final String renderedChars = ((RendererFromBytesToChars) renderer).renderBytesToChars(
getType(), variant, getAtPath(), getVersion(),
asBytes(), contentDataModel);
if(renderedChars.length() <= TextType.Meta.MAX_LEN) {
document.setTextData(getName(), getMimeType(), renderedChars);
} else {
final Clob clob = new Clob (documentName, getMimeType(), renderedChars);
document.modifyClob(clob);
}
return;
default:
// shouldn't happen, above switch statement is complete
throw new IllegalArgumentException(String.format("Unknown output DocumentNature '%s'", outputNature));
}
case CHARACTERS:
switch (outputNature) {
case BYTES:
final byte[] renderedBytes = ((RendererFromCharsToBytes) renderer).renderCharsToBytes(
getType(), variant, getAtPath(), getVersion(),
asChars(), contentDataModel);
final Blob blob = new Blob (documentName, getMimeType(), renderedBytes);
document.modifyBlob(blob);
return;
case CHARACTERS:
final String renderedChars = ((RendererFromCharsToChars) renderer).renderCharsToChars(
getType(), variant, getAtPath(), getVersion(),
asChars(), contentDataModel);
if(renderedChars.length() <= TextType.Meta.MAX_LEN) {
document.setTextData(getName(), getMimeType(), renderedChars);
} else {
final Clob clob = new Clob (documentName, getMimeType(), renderedChars);
document.modifyClob(clob);
}
return;
default:
// shouldn't happen, above switch statement is complete
throw new IllegalArgumentException(String.format("Unknown output DocumentNature '%s'", outputNature));
}
default:
// shouldn't happen, above switch statement is complete
throw new IllegalArgumentException(String.format("Unknown input DocumentNature '%s'", inputNature));
}
} catch (IOException e) {
throw new ApplicationException("Unable to render document template", e);
}
}
//endregion
//region > withFileSuffix (programmatic)
@Programmatic
public String withFileSuffix(final String documentName) {
final String suffix = getFileSuffix();
final int lastPeriod = suffix.lastIndexOf(".");
final String suffixNoDot = suffix.substring(lastPeriod + 1);
final String suffixWithDot = "." + suffixNoDot;
if (documentName.endsWith(suffixWithDot)) {
return trim(documentName, NameType.Meta.MAX_LEN);
}
else {
return StringUtils.stripEnd(trim(documentName, NameType.Meta.MAX_LEN - suffixWithDot.length()),".") + suffixWithDot;
}
}
private static String trim(final String name, final int length) {
return name.length() > length ? name.substring(0, length) : name;
}
//endregion
//region > getVersion (programmatic)
@Programmatic
private long getVersion() {
return (Long)JDOHelper.getVersion(this);
}
//endregion
//region > injected services
@Inject
ClassService classService;
@Inject
ServiceRegistry2 serviceRegistry2;
@Inject
TransactionService transactionService;
@Inject
BackgroundService2 backgroundService2;
//endregion
//region > types
public static class FileSuffixType {
private FileSuffixType() {}
public static class Meta {
public static final int MAX_LEN = 12;
private Meta() {}
}
}
public static class NameTextType {
private NameTextType() {}
public static class Meta {
public static final int MAX_LEN = 255;
private Meta() {}
}
}
//endregion
} |
package org.protobee.examples.broadcast.modules;
import java.net.SocketAddress;
import org.jboss.netty.handler.codec.http.HttpMethod;
import org.protobee.annotation.InjectLogger;
import org.protobee.compatability.Headers;
import org.protobee.events.BasicMessageReceivedEvent;
import org.protobee.examples.protos.BroadcasterProtos.BroadcastMessage;
import org.protobee.guice.scopes.SessionScope;
import org.protobee.identity.NetworkIdentityManager;
import org.protobee.modules.ProtocolModule;
import org.protobee.network.ConnectionCreator;
import org.protobee.protocol.Protocol;
import org.protobee.protocol.ProtocolModel;
import org.protobee.util.SocketAddressUtils;
import org.slf4j.Logger;
import com.google.common.base.Preconditions;
import com.google.common.eventbus.Subscribe;
import com.google.inject.Inject;
@SessionScope
@Headers(required = {})
public class FeelingsInitiatorModule extends ProtocolModule {
@InjectLogger
private Logger log;
private final NetworkIdentityManager identityManager;
private final Protocol feelingsProtocol;
private final ConnectionCreator creator;
private final ProtocolModel feelingsModel;
private final SocketAddressUtils addressUtils;
@Inject
public FeelingsInitiatorModule(ConnectionCreator creator,
Protocol feelings, ProtocolModel feelingsModel, SocketAddressUtils addressUtils,
NetworkIdentityManager manager) {
this.creator = creator;
this.feelingsProtocol = feelings;
this.feelingsModel = feelingsModel;
this.addressUtils = addressUtils;
this.identityManager = manager;
}
@Subscribe
public void messageReceived(BasicMessageReceivedEvent event) {
Preconditions.checkArgument(event.getMessage() instanceof BroadcastMessage,
"Not a broadcast message");
BroadcastMessage message = (BroadcastMessage) event.getMessage();
SocketAddress address =
addressUtils.getAddress(message.getListeningAddress(), message.getListeningPort());
if (message.getMessage().equals("feelings!")
&& (!identityManager.hasNetworkIdentity(address) || !identityManager.getNewtorkIdentity(
address).hasCurrentSession(feelingsProtocol))) {
log.info("Connecting to address " + address + " with feelings protocol");
creator.connect(feelingsModel, address, HttpMethod.valueOf("SAY"), "/");
}
}
} |
package br.net.mirante.singular.form.wicket.panel;
import org.apache.wicket.Application;
import org.apache.wicket.Component;
import org.apache.wicket.IInitializer;
import org.apache.wicket.MarkupContainer;
import org.apache.wicket.extensions.ajax.markup.html.form.upload.UploadProgressBar;
import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow;
import org.apache.wicket.markup.head.CssHeaderItem;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.head.JavaScriptHeaderItem;
import org.apache.wicket.markup.head.OnDomReadyHeaderItem;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.upload.FileUploadField;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.StringResourceModel;
import org.apache.wicket.protocol.http.servlet.MultipartServletWebRequestImpl;
import org.apache.wicket.protocol.http.servlet.UploadInfo;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.request.resource.*;
import org.apache.wicket.resource.CoreLibrariesContributor;
import org.apache.wicket.util.lang.Args;
import org.apache.wicket.util.time.Duration;
import org.apache.wicket.util.visit.IVisit;
import org.apache.wicket.util.visit.IVisitor;
import javax.servlet.http.HttpServletRequest;
import java.util.Formatter;
public abstract class SUploadProgressBar extends Panel {
public static final String RESOURCE_STARTING = "UploadProgressBar.starting";
/**
* Initializer for this component; binds static resources.
*/
public final static class ComponentInitializer implements IInitializer
{
@Override
public void init(final Application application)
{
// register the upload status resource
application.getSharedResources().add(RESOURCE_NAME, new UploadStatusResource());
}
@Override
public String toString()
{
return "UploadProgressBar initializer";
}
@Override
public void destroy(final Application application)
{
}
}
private static final ResourceReference JS = new JavaScriptResourceReference(
UploadProgressBar.class, "progressbar.js");
private static final ResourceReference CSS = new CssResourceReference(
UploadProgressBar.class, "UploadProgressBar.css");
private static final String RESOURCE_NAME = UploadProgressBar.class.getName();
private static final long serialVersionUID = 1L;
private MarkupContainer statusDiv;
private MarkupContainer barDiv;
private final FileUploadField uploadField;
public SUploadProgressBar(final String id, final FileUploadField uploadField)
{
super(id);
this.uploadField = uploadField;
if (uploadField != null)
{
uploadField.setOutputMarkupId(true);
}
setRenderBodyOnly(true);
}
@Override
protected void onInitialize()
{
super.onInitialize();
getCallbackForm().setOutputMarkupId(true);
barDiv = newBarComponent("bar");
add(barDiv);
statusDiv = newStatusComponent("status");
add(statusDiv);
}
/**
* Creates a component for the status text
*
* @param id
* The component id
* @return the status component
*/
protected MarkupContainer newStatusComponent(String id)
{
WebMarkupContainer status = new WebMarkupContainer(id);
status.setOutputMarkupId(true);
return status;
}
/**
* Creates a component for the bar
*
* @param id
* The component id
* @return the bar component
*/
protected MarkupContainer newBarComponent(String id)
{
WebMarkupContainer bar = new WebMarkupContainer(id);
bar.setOutputMarkupId(true);
return bar;
}
/**
* Override this to provide your own CSS, or return null to avoid including the default.
*
* @return ResourceReference for your CSS.
*/
protected ResourceReference getCss()
{
return CSS;
}
/**
* {@inheritDoc}
*/
@Override
public void renderHead(final IHeaderResponse response)
{
super.renderHead(response);
CoreLibrariesContributor.contributeAjax(getApplication(), response);
response.render(JavaScriptHeaderItem.forReference(JS));
ResourceReference css = getCss();
if (css != null)
{
response.render(CssHeaderItem.forReference(css));
}
ResourceReference ref = new SharedResourceReference(RESOURCE_NAME);
final String uploadFieldId = (uploadField == null) ? "" : uploadField.getMarkupId();
final String status = new StringResourceModel(RESOURCE_STARTING, this, (IModel<?>)null).getString();
CharSequence url = urlFor(ref, UploadStatusResource.newParameter(getPage().getId()));
StringBuilder builder = new StringBuilder(128);
Formatter formatter = new Formatter(builder);
formatter.format(
"new Wicket.WUPB('%s', '%s', '%s', '%s', '%s', '%s');",
getCallbackForm().getMarkupId(), statusDiv.getMarkupId(), barDiv.getMarkupId(), url, uploadFieldId,
status);
formatter.close();
response.render(OnDomReadyHeaderItem.forScript(builder.toString()));
}
/**
* Form on where will be installed the JavaScript callback to present the progress bar.
* {@link ModalWindow} is designed to hold nested forms and the progress bar callback JavaScript
* needs to be add at the form inside the {@link ModalWindow} if one is used.
*
* @return form
*/
private Form<?> getCallbackForm()
{
Boolean insideModal = getForm().visitParents(ModalWindow.class,
new IVisitor<ModalWindow, Boolean>()
{
@Override
public void component(final ModalWindow object, final IVisit<Boolean> visit)
{
visit.stop(true);
}
});
if ((insideModal != null) && insideModal)
{
return getForm();
}
else
{
return getForm().getRootForm();
}
}
protected abstract Form<?> getForm();
}
class UploadStatusResource extends AbstractResource
{
private static final long serialVersionUID = 1L;
private static final String UPLOAD_PARAMETER = "upload";
/**
* Resource key used to retrieve status message for.
*
* Example: UploadStatusResource.status=${percentageComplete}% finished, ${bytesUploadedString}
* of ${totalBytesString} at ${transferRateString}; ${remainingTimeString}
*/
public static final String RESOURCE_STATUS = "UploadStatusResource.status";
@Override
protected ResourceResponse newResourceResponse(final Attributes attributes)
{
// Determine encoding
final String encoding = Application.get()
.getRequestCycleSettings()
.getResponseRequestEncoding();
ResourceResponse response = new ResourceResponse();
response.setContentType("text/html; charset=" + encoding);
response.setCacheDuration(Duration.NONE);
final String status = getStatus(attributes);
response.setWriteCallback(new WriteCallback()
{
@Override
public void writeData(final Attributes attributes)
{
attributes.getResponse().write("<html><body>|");
attributes.getResponse().write(status);
attributes.getResponse().write("|</body></html>");
}
});
return response;
}
/**
* @param attributes
* @return status string with progress data that will feed the progressbar.js variables on
* browser to update the progress bar
*/
private String getStatus(final Attributes attributes)
{
final String upload = attributes.getParameters().get(UPLOAD_PARAMETER).toString();
final HttpServletRequest req = (HttpServletRequest)attributes.getRequest()
.getContainerRequest();
UploadInfo info = MultipartServletWebRequestImpl.getUploadInfo(req, upload);
String status;
if ((info == null) || (info.getTotalBytes() < 1))
{
status = "100|";
}
else
{
status = info.getPercentageComplete() +
"|" +
new StringResourceModel(RESOURCE_STATUS, (Component)null, Model.of(info)).getString();
}
return status;
}
/**
* Create a new parameter for the given identifier of a {@link UploadInfo}.
*
* @param upload
* identifier
* @return page parameter suitable for URLs to this resource
*/
public static PageParameters newParameter(String upload)
{
return new PageParameters().add(UPLOAD_PARAMETER, upload);
}
} |
package org.eclipse.che.ide.part.editor;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.dom.client.Style;
import com.google.gwt.event.dom.client.MouseDownEvent;
import com.google.gwt.event.dom.client.MouseDownHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.google.gwt.user.client.ui.DeckLayoutPanel;
import com.google.gwt.user.client.ui.DockLayoutPanel;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.ResizeComposite;
import com.google.gwt.user.client.ui.Widget;
import org.eclipse.che.ide.api.editor.texteditor.TextEditor;
import org.eclipse.che.ide.api.parts.PartPresenter;
import org.eclipse.che.ide.api.parts.PartStackView;
import org.eclipse.che.ide.part.widgets.panemenu.EditorPaneMenu;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import static com.google.gwt.dom.client.Style.Display.BLOCK;
import static com.google.gwt.dom.client.Style.Display.NONE;
import static com.google.gwt.dom.client.Style.Unit.PCT;
/**
* @author Evgen Vidolob
* @author Dmitry Shnurenko
* @author Vitaliy Guliy
*/
public class EditorPartStackView extends ResizeComposite implements PartStackView, MouseDownHandler {
interface PartStackUiBinder extends UiBinder<Widget, EditorPartStackView> {
}
private static final PartStackUiBinder UI_BINDER = GWT.create(PartStackUiBinder.class);
@UiField
DockLayoutPanel parent;
@UiField
FlowPanel tabsPanel;
@UiField
DeckLayoutPanel contentPanel;
private final Map<PartPresenter, TabItem> tabs;
private final AcceptsOneWidget partViewContainer;
private final LinkedList<PartPresenter> contents;
private ActionDelegate delegate;
private EditorPaneMenu editorPaneMenu;
private TabItem activeTab;
public EditorPartStackView() {
this.tabs = new HashMap<>();
this.contents = new LinkedList<>();
initWidget(UI_BINDER.createAndBindUi(this));
partViewContainer = new AcceptsOneWidget() {
@Override
public void setWidget(IsWidget widget) {
contentPanel.add(widget);
}
};
addDomHandler(this, MouseDownEvent.getType());
setMaximized(false);
}
/** {@inheritDoc} */
@Override
protected void onAttach() {
super.onAttach();
Style style = getElement().getParentElement().getStyle();
style.setHeight(100, PCT);
style.setWidth(100, PCT);
}
/**
* Adds editor pane menu button in special place on view.
*
* @param editorPaneMenu
* button which will be added
*/
public void addPaneMenuButton(@NotNull EditorPaneMenu editorPaneMenu) {
this.editorPaneMenu = editorPaneMenu;
tabsPanel.add(editorPaneMenu);
}
/** {@inheritDoc} */
@Override
public void onMouseDown(@NotNull MouseDownEvent event) {
delegate.onRequestFocus();
}
/** {@inheritDoc} */
@Override
public void setDelegate(ActionDelegate delegate) {
this.delegate = delegate;
}
/** {@inheritDoc} */
@Override
public void addTab(@NotNull TabItem tabItem, @NotNull PartPresenter partPresenter) {
/** Show editor area if it is empty and hidden */
if (contents.isEmpty()) {
getElement().getParentElement().getStyle().setDisplay(BLOCK);
}
/** Add editor tab to tab panel */
tabsPanel.add(tabItem.getView());
/** Process added editor tab */
tabs.put(partPresenter, tabItem);
contents.add(partPresenter);
partPresenter.go(partViewContainer);
}
/**
* Makes active tab visible.
*/
private void ensureActiveTabVisible() {
if (activeTab == null) {
return;
}
for (int i = 0; i < tabsPanel.getWidgetCount(); i++) {
if (editorPaneMenu != null && editorPaneMenu != tabsPanel.getWidget(i)) {
tabsPanel.getWidget(i).setVisible(true);
}
}
for (int i = 0; i < tabsPanel.getWidgetCount(); i++) {
Widget currentWidget = tabsPanel.getWidget(i);
Widget activeTabWidget = activeTab.getView().asWidget();
if (editorPaneMenu != null && editorPaneMenu == currentWidget) {
continue;
}
if (activeTabWidget.getAbsoluteTop() > tabsPanel.getAbsoluteTop() && activeTabWidget != currentWidget) {
currentWidget.setVisible(false);
}
}
}
/** {@inheritDoc} */
@Override
public void removeTab(@NotNull PartPresenter presenter) {
TabItem tab = tabs.get(presenter);
tabsPanel.remove(tab.getView());
contentPanel.remove(presenter.getView());
tabs.remove(presenter);
contents.remove(presenter);
if (!contents.isEmpty()) {
selectTab(contents.getLast());
}
//this hack need to force redraw dom element to apply correct styles
tabsPanel.getElement().getStyle().setDisplay(NONE);
tabsPanel.getElement().getOffsetHeight();
tabsPanel.getElement().getStyle().setDisplay(BLOCK);
}
/** {@inheritDoc} */
@Override
public void selectTab(@NotNull PartPresenter partPresenter) {
IsWidget view = partPresenter.getView();
// set/remove attribute 'active' for Selenium tests
for (int i = 0; i < contentPanel.getWidgetCount(); i++) {
contentPanel.getWidget(i).getElement().removeAttribute("active");
}
view.asWidget().getElement().setAttribute("active", "");
int viewIndex = contentPanel.getWidgetIndex(view);
if (viewIndex < 0) {
partPresenter.go(partViewContainer);
viewIndex = contentPanel.getWidgetIndex(view);
}
contentPanel.showWidget(viewIndex);
setActiveTab(partPresenter);
if (partPresenter instanceof TextEditor) {
((TextEditor)partPresenter).activate();
}
}
/**
* Switches to specified tab.
*
* @param part tab part
*/
private void setActiveTab(@NotNull PartPresenter part) {
for (TabItem tab : tabs.values()) {
tab.unSelect();
tab.getView().asWidget().getElement().removeAttribute("active");
}
activeTab = tabs.get(part);
activeTab.select();
activeTab.getView().asWidget().getElement().setAttribute("active", "");
delegate.onRequestFocus();
Scheduler.get().scheduleDeferred(this::ensureActiveTabVisible);
}
/** {@inheritDoc} */
@Override
public void setTabPositions(List<PartPresenter> partPositions) {
throw new UnsupportedOperationException("The method doesn't allowed in this class " + getClass());
}
/** {@inheritDoc} */
@Override
public void setFocus(boolean focused) {
if (activeTab == null) {
return;
}
if (focused) {
activeTab.select();
} else {
activeTab.unSelect();
}
}
@Override
public void setMaximized(boolean maximized) {
getElement().setAttribute("maximized", Boolean.toString(maximized));
}
/** {@inheritDoc} */
@Override
public void updateTabItem(@NotNull PartPresenter partPresenter) {
TabItem tab = tabs.get(partPresenter);
tab.update(partPresenter);
}
@Override
public void onResize() {
super.onResize();
Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() {
@Override
public void execute() {
ensureActiveTabVisible();
}
});
}
} |
package bisq.core.btc.nodes;
import bisq.common.config.Config;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkArgument;
@Slf4j
public class BtcNodes {
public enum BitcoinNodesOption {
PROVIDED,
CUSTOM,
PUBLIC
}
// For other base currencies or testnet we ignore provided nodes
public List<BtcNode> getProvidedBtcNodes() {
return useProvidedBtcNodes() ?
Arrays.asList(
// emzy
new BtcNode("kirsche.emzy.de", "fz6nsij6jiyuwlsc.onion", "78.47.61.83", BtcNode.DEFAULT_PORT, "@emzy"),
new BtcNode("node2.emzy.de", "c6ac4jdfyeiakex2.onion", "62.75.210.81", BtcNode.DEFAULT_PORT, "@emzy"),
new BtcNode("node1.emzy.de", "sjyzmwwu6diiit3r.onion", "167.86.90.239", BtcNode.DEFAULT_PORT, "@emzy"),
new BtcNode(null, "3xucqntxp5ddoaz5.onion", null, BtcNode.DEFAULT_PORT, "@emzy"), // cannot provide IP because no static IP
// ripcurlx
new BtcNode("bitcoin.christophatteneder.com", "lgkvbvro67jomosw.onion", "174.138.35.229", BtcNode.DEFAULT_PORT, "@Christoph"),
// mrosseel
new BtcNode("btc.vante.me", "4jyh6llqj264oggs.onion", "94.23.21.80", BtcNode.DEFAULT_PORT, "@miker"),
new BtcNode("btc2.vante.me", "mxdtrjhe2yfsx3pg.onion", "94.23.205.110", BtcNode.DEFAULT_PORT, "@miker"),
// sqrrm
new BtcNode("btc1.sqrrm.net", "3r44ddzjitznyahw.onion", "185.25.48.184", BtcNode.DEFAULT_PORT, "@sqrrm"),
new BtcNode("btc2.sqrrm.net", "i3a5xtzfm4xwtybd.onion", "81.171.22.143", BtcNode.DEFAULT_PORT, "@sqrrm"),
// KanoczTomas
new BtcNode("btc.ispol.sk", "mbm6ffx6j5ygi2ck.onion", "193.58.196.212", BtcNode.DEFAULT_PORT, "@KanoczTomas"),
// Devin Bileck
new BtcNode("btc1.dnsalias.net", "lva54pnbq2nsmjyr.onion", "165.227.34.198", BtcNode.DEFAULT_PORT, "@devinbileck"),
// m52go
new BtcNode("btc.bisq.cc", "4nnuyxm5k5tlyjq3.onion", "167.71.168.194", BtcNode.DEFAULT_PORT, "@m52go"),
// wiz
new BtcNode("node100.wiz.network", "m3yqzythryowgedc.onion", "103.99.168.100", BtcNode.DEFAULT_PORT, "@wiz"),
new BtcNode("node130.wiz.network", "22tg6ufbwz6o3l2u.onion", "103.99.168.130", BtcNode.DEFAULT_PORT, "@wiz"),
new BtcNode("node140.wiz.network", "jiuuuislm7ooesic.onion", "103.99.168.140", BtcNode.DEFAULT_PORT, "@wiz"),
new BtcNode("node150.wiz.network", "zyhtr2ffbzn5yeg3.onion", "103.99.168.150", BtcNode.DEFAULT_PORT, "@wiz")
) :
new ArrayList<>();
}
public boolean useProvidedBtcNodes() {
return Config.baseCurrencyNetwork().isMainnet();
}
public static List<BtcNodes.BtcNode> toBtcNodesList(Collection<String> nodes) {
return nodes.stream()
.filter(e -> !e.isEmpty())
.map(BtcNodes.BtcNode::fromFullAddress)
.collect(Collectors.toList());
}
@EqualsAndHashCode
@Getter
public static class BtcNode {
private static final int DEFAULT_PORT = Config.baseCurrencyNetworkParameters().getPort(); //8333
@Nullable
private final String onionAddress;
@Nullable
private final String hostName;
@Nullable
private final String operator; // null in case the user provides a list of custom btc nodes
@Nullable
private final String address; // IPv4 address
private int port = DEFAULT_PORT;
/**
* @param fullAddress [IPv4 address:port or onion:port]
* @return BtcNode instance
*/
public static BtcNode fromFullAddress(String fullAddress) {
String[] parts = fullAddress.split(":");
checkArgument(parts.length > 0);
final String host = parts[0];
int port = DEFAULT_PORT;
if (parts.length == 2)
port = Integer.valueOf(parts[1]);
return host.contains(".onion") ? new BtcNode(null, host, null, port, null) : new BtcNode(null, null, host, port, null);
}
public BtcNode(@Nullable String hostName, @Nullable String onionAddress, @Nullable String address, int port, @Nullable String operator) {
this.hostName = hostName;
this.onionAddress = onionAddress;
this.address = address;
this.port = port;
this.operator = operator;
}
public boolean hasOnionAddress() {
return onionAddress != null;
}
public String getHostNameOrAddress() {
if (hostName != null)
return hostName;
else
return address;
}
public boolean hasClearNetAddress() {
return hostName != null || address != null;
}
@Override
public String toString() {
return "onionAddress='" + onionAddress + '\'' +
", hostName='" + hostName + '\'' +
", address='" + address + '\'' +
", port='" + port + '\'' +
", operator='" + operator;
}
}
} |
package hudson;
import static org.apache.commons.io.FilenameUtils.getBaseName;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.Plugin.DummyImpl;
import hudson.PluginWrapper.Dependency;
import hudson.model.Hudson;
import hudson.util.CyclicGraphDetector;
import hudson.util.CyclicGraphDetector.CycleDetectedException;
import hudson.util.IOUtils;
import hudson.util.MaskingClassLoader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.logging.Level;
import java.util.logging.Logger;
import jenkins.ClassLoaderReflectionToolkit;
import jenkins.ExtensionFilter;
import jenkins.plugins.DetachedPluginsUtil;
import jenkins.util.AntClassLoader;
import jenkins.util.SystemProperties;
import jenkins.util.URLClassLoader2;
import org.apache.commons.io.output.NullOutputStream;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Expand;
import org.apache.tools.ant.taskdefs.Zip;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.ant.types.PatternSet;
import org.apache.tools.ant.types.Resource;
import org.apache.tools.ant.types.ZipFileSet;
import org.apache.tools.ant.types.resources.MappedResourceCollection;
import org.apache.tools.ant.util.GlobPatternMapper;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipExtraField;
import org.apache.tools.zip.ZipOutputStream;
public class ClassicPluginStrategy implements PluginStrategy {
private static final Logger LOGGER = Logger.getLogger(ClassicPluginStrategy.class.getName());
/**
* Filter for jar files.
*/
private static final FilenameFilter JAR_FILTER = (dir, name) -> name.endsWith(".jar");
private final PluginManager pluginManager;
/**
* All the plugins eventually delegate this classloader to load core, servlet APIs, and SE runtime.
*/
private final MaskingClassLoader coreClassLoader = new MaskingClassLoader(getClass().getClassLoader());
public ClassicPluginStrategy(PluginManager pluginManager) {
this.pluginManager = pluginManager;
}
@Override public String getShortName(File archive) throws IOException {
Manifest manifest;
if (!archive.exists()) {
throw new FileNotFoundException("Failed to load " + archive + ". The file does not exist");
} else if (!archive.isFile()) {
throw new FileNotFoundException("Failed to load " + archive + ". It is not a file");
}
if (isLinked(archive)) {
manifest = loadLinkedManifest(archive);
} else {
try (JarFile jf = new JarFile(archive, false)) {
manifest = jf.getManifest();
} catch (IOException ex) {
// Mention file name in the exception
throw new IOException("Failed to load " + archive, ex);
}
}
return PluginWrapper.computeShortName(manifest, archive.getName());
}
private static boolean isLinked(File archive) {
return archive.getName().endsWith(".hpl") || archive.getName().endsWith(".jpl");
}
private static Manifest loadLinkedManifest(File archive) throws IOException {
// resolve the .hpl file to the location of the manifest file
try {
// Locate the manifest
String firstLine;
try (InputStream manifestHeaderInput = Files.newInputStream(archive.toPath())) {
firstLine = IOUtils.readFirstLine(manifestHeaderInput, "UTF-8");
} catch (InvalidPathException e) {
throw new IOException(e);
}
//noinspection StatementWithEmptyBody
if (firstLine.startsWith("Manifest-Version:")) {
// this is the manifest already
} else {
// indirection
archive = resolve(archive, firstLine);
}
// Read the manifest
try (InputStream manifestInput = Files.newInputStream(archive.toPath())) {
return new Manifest(manifestInput);
} catch (InvalidPathException e) {
throw new IOException(e);
}
} catch (IOException e) {
throw new IOException("Failed to load " + archive, e);
}
}
@Override public PluginWrapper createPluginWrapper(File archive) throws IOException {
final Manifest manifest;
URL baseResourceURL;
File expandDir = null;
// if .hpi, this is the directory where war is expanded
boolean isLinked = isLinked(archive);
if (isLinked) {
manifest = loadLinkedManifest(archive);
} else {
if (archive.isDirectory()) {// already expanded
expandDir = archive;
} else {
File f = pluginManager.getWorkDir();
expandDir = new File(f == null ? archive.getParentFile() : f, getBaseName(archive.getName()));
explode(archive, expandDir);
}
File manifestFile = new File(expandDir, PluginWrapper.MANIFEST_FILENAME);
if (!manifestFile.exists()) {
throw new IOException(
"Plugin installation failed. No manifest at "
+ manifestFile);
}
try (InputStream fin = Files.newInputStream(manifestFile.toPath())) {
manifest = new Manifest(fin);
} catch (InvalidPathException e) {
throw new IOException(e);
}
String canonicalName = manifest.getMainAttributes().getValue("Short-Name") + ".jpi";
if (!archive.getName().equals(canonicalName)) {
LOGGER.warning(() -> "encountered " + archive + " under a nonstandard name; expected " + canonicalName);
}
}
final Attributes atts = manifest.getMainAttributes();
// TODO: define a mechanism to hide classes
// String export = manifest.getMainAttributes().getValue("Export");
List<File> paths = new ArrayList<>();
if (isLinked) {
parseClassPath(manifest, archive, paths, "Libraries", ",");
parseClassPath(manifest, archive, paths, "Class-Path", " +"); // backward compatibility
baseResourceURL = resolve(archive,atts.getValue("Resource-Path")).toURI().toURL();
} else {
File classes = new File(expandDir, "WEB-INF/classes");
if (classes.exists()) { // should not normally happen, due to createClassJarFromWebInfClasses
LOGGER.log(Level.WARNING, "Deprecated unpacked classes directory found in {0}", classes);
paths.add(classes);
}
File lib = new File(expandDir, "WEB-INF/lib");
File[] libs = lib.listFiles(JAR_FILTER);
if (libs != null)
paths.addAll(Arrays.asList(libs));
baseResourceURL = expandDir.toPath().toUri().toURL();
}
File disableFile = new File(archive.getPath() + ".disabled");
if (disableFile.exists()) {
LOGGER.info("Plugin " + archive.getName() + " is disabled");
}
if (paths.isEmpty()) {
LOGGER.info("No classpaths found for plugin " + archive.getName());
}
// compute dependencies
List<PluginWrapper.Dependency> dependencies = new ArrayList<>();
List<PluginWrapper.Dependency> optionalDependencies = new ArrayList<>();
String v = atts.getValue("Plugin-Dependencies");
if (v != null) {
for (String s : v.split(",")) {
PluginWrapper.Dependency d = new PluginWrapper.Dependency(s);
if (d.optional) {
optionalDependencies.add(d);
} else {
dependencies.add(d);
}
}
}
fix(atts,optionalDependencies);
// Register global classpath mask. This is useful for hiding JavaEE APIs that you might see from the container,
// such as database plugin for JPA support. The Mask-Classes attribute is insufficient because those classes
// also need to be masked by all the other plugins that depend on the database plugin.
String masked = atts.getValue("Global-Mask-Classes");
if(masked!=null) {
for (String pkg : masked.trim().split("[ \t\r\n]+"))
coreClassLoader.add(pkg);
}
ClassLoader dependencyLoader = new DependencyClassLoader(coreClassLoader, archive, Util.join(dependencies,optionalDependencies), pluginManager);
dependencyLoader = getBaseClassLoader(atts, dependencyLoader);
return new PluginWrapper(pluginManager, archive, manifest, baseResourceURL,
createClassLoader(paths, dependencyLoader, atts), disableFile, dependencies, optionalDependencies);
}
private void fix(Attributes atts, List<PluginWrapper.Dependency> optionalDependencies) {
String pluginName = atts.getValue("Short-Name");
String jenkinsVersion = atts.getValue("Jenkins-Version");
if (jenkinsVersion==null)
jenkinsVersion = atts.getValue("Hudson-Version");
for (Dependency d : DetachedPluginsUtil.getImpliedDependencies(pluginName, jenkinsVersion)) {
LOGGER.fine(() -> "implied dep " + pluginName + " → " + d.shortName);
pluginManager.considerDetachedPlugin(d.shortName);
optionalDependencies.add(d);
}
}
/**
* @see DetachedPluginsUtil#getImpliedDependencies(String, String)
*
* @deprecated since 2.163
*/
@Deprecated
@NonNull
public static List<PluginWrapper.Dependency> getImpliedDependencies(String pluginName, String jenkinsVersion) {
return DetachedPluginsUtil.getImpliedDependencies(pluginName, jenkinsVersion);
}
@Deprecated
protected ClassLoader createClassLoader(List<File> paths, ClassLoader parent) throws IOException {
return createClassLoader( paths, parent, null );
}
/**
* Creates the classloader that can load all the specified jar files and delegate to the given parent.
*/
protected ClassLoader createClassLoader(List<File> paths, ClassLoader parent, Attributes atts) throws IOException {
if (atts != null) {
String usePluginFirstClassLoader = atts.getValue( "PluginFirstClassLoader" );
if (Boolean.parseBoolean( usePluginFirstClassLoader )) {
PluginFirstClassLoader classLoader = new PluginFirstClassLoader();
classLoader.setParentFirst( false );
classLoader.setParent( parent );
classLoader.addPathFiles( paths );
return classLoader;
}
}
if (useAntClassLoader) {
AntClassLoader classLoader = new AntClassLoader(parent, true);
classLoader.addPathFiles(paths);
return classLoader;
} else {
List<URL> urls = new ArrayList<>();
for (File path : paths) {
urls.add(path.toURI().toURL());
}
return new URLClassLoader2(urls.toArray(new URL[0]), parent);
}
}
/**
* Computes the classloader that takes the class masking into account.
*
* <p>
* This mechanism allows plugins to have their own versions for libraries that core bundles.
*/
private ClassLoader getBaseClassLoader(Attributes atts, ClassLoader base) {
String masked = atts.getValue("Mask-Classes");
if(masked!=null)
base = new MaskingClassLoader(base, masked.trim().split("[ \t\r\n]+"));
return base;
}
@Override
public void initializeComponents(PluginWrapper plugin) {
}
@Override
public <T> List<ExtensionComponent<T>> findComponents(Class<T> type, Hudson hudson) {
List<ExtensionFinder> finders;
if (type==ExtensionFinder.class) {
// Avoid infinite recursion of using ExtensionFinders to find ExtensionFinders
finders = Collections.singletonList(new ExtensionFinder.Sezpoz());
} else {
finders = hudson.getExtensionList(ExtensionFinder.class);
}
/*
* See ExtensionFinder#scout(Class, Hudson) for the dead lock issue and what this does.
*/
if (LOGGER.isLoggable(Level.FINER))
LOGGER.log(Level.FINER, "Scout-loading ExtensionList: "+type, new Throwable());
for (ExtensionFinder finder : finders) {
finder.scout(type, hudson);
}
List<ExtensionComponent<T>> r = new ArrayList<>();
for (ExtensionFinder finder : finders) {
try {
r.addAll(finder.find(type, hudson));
} catch (AbstractMethodError e) {
// backward compatibility
for (T t : finder.findExtensions(type, hudson))
r.add(new ExtensionComponent<>(t));
}
}
List<ExtensionComponent<T>> filtered = new ArrayList<>();
for (ExtensionComponent<T> e : r) {
if (ExtensionFilter.isAllowed(type,e))
filtered.add(e);
}
return filtered;
}
@Override
public void load(PluginWrapper wrapper) throws IOException {
// override the context classloader. This no longer makes sense,
// but it is left for the backward compatibility
ClassLoader old = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(wrapper.classLoader);
try {
String className = wrapper.getPluginClass();
if(className==null) {
// use the default dummy instance
wrapper.setPlugin(new DummyImpl());
} else {
try {
Class<?> clazz = wrapper.classLoader.loadClass(className);
Object o = clazz.getDeclaredConstructor().newInstance();
if(!(o instanceof Plugin)) {
throw new IOException(className+" doesn't extend from hudson.Plugin");
}
wrapper.setPlugin((Plugin) o);
} catch (LinkageError | ClassNotFoundException e) {
throw new IOException("Unable to load " + className + " from " + wrapper.getShortName(),e);
} catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
throw new IOException("Unable to create instance of " + className + " from " + wrapper.getShortName(),e);
}
}
// initialize plugin
try {
Plugin plugin = wrapper.getPluginOrFail();
plugin.setServletContext(pluginManager.context);
startPlugin(wrapper);
} catch(Throwable t) {
// gracefully handle any error in plugin.
throw new IOException("Failed to initialize",t);
}
} finally {
Thread.currentThread().setContextClassLoader(old);
}
}
public void startPlugin(PluginWrapper plugin) throws Exception {
plugin.getPluginOrFail().start();
}
@Override
public void updateDependency(PluginWrapper depender, PluginWrapper dependee) {
DependencyClassLoader classLoader = findAncestorDependencyClassLoader(depender.classLoader);
if (classLoader != null) {
classLoader.updateTransitiveDependencies();
LOGGER.log(Level.INFO, "Updated dependency of {0}", depender.getShortName());
}
}
private DependencyClassLoader findAncestorDependencyClassLoader(ClassLoader classLoader)
{
for (; classLoader != null; classLoader = classLoader.getParent()) {
if (classLoader instanceof DependencyClassLoader) {
return (DependencyClassLoader)classLoader;
}
if (classLoader instanceof AntClassLoader) {
// AntClassLoaders hold parents not only as AntClassLoader#getParent()
// but also as AntClassLoader#getConfiguredParent()
DependencyClassLoader ret = findAncestorDependencyClassLoader(
((AntClassLoader)classLoader).getConfiguredParent()
);
if (ret != null) {
return ret;
}
}
}
return null;
}
@SuppressFBWarnings(value = "PATH_TRAVERSAL_IN", justification = "Administrator action installing a plugin, which could do far worse.")
private static File resolve(File base, String relative) {
File rel = new File(relative);
if(rel.isAbsolute())
return rel;
else
return new File(base.getParentFile(),relative);
}
private static void parseClassPath(Manifest manifest, File archive, List<File> paths, String attributeName, String separator) throws IOException {
String classPath = manifest.getMainAttributes().getValue(attributeName);
if(classPath==null) return; // attribute not found
for (String s : classPath.split(separator)) {
File file = resolve(archive, s);
if(file.getName().contains("*")) {
// handle wildcard
FileSet fs = new FileSet();
File dir = file.getParentFile();
fs.setDir(dir);
fs.setIncludes(file.getName());
for( String included : fs.getDirectoryScanner(new Project()).getIncludedFiles() ) {
paths.add(new File(dir,included));
}
} else {
if(!file.exists())
throw new IOException("No such file: "+file);
paths.add(file);
}
}
}
/**
* Explodes the plugin into a directory, if necessary.
*/
private static void explode(File archive, File destDir) throws IOException {
destDir.mkdirs();
// timestamp check
File explodeTime = new File(destDir,".timestamp2");
if(explodeTime.exists() && explodeTime.lastModified()==archive.lastModified())
return; // no need to expand
// delete the contents so that old files won't interfere with new files
Util.deleteRecursive(destDir);
try {
Project prj = new Project();
unzipExceptClasses(archive, destDir, prj);
createClassJarFromWebInfClasses(archive, destDir, prj);
} catch (BuildException x) {
throw new IOException("Failed to expand " + archive,x);
}
try {
new FilePath(explodeTime).touch(archive.lastModified());
} catch (InterruptedException e) {
throw new AssertionError(e); // impossible
}
}
/**
* Repackage classes directory into a jar file to make it remoting friendly.
* The remoting layer can cache jar files but not class files.
*/
private static void createClassJarFromWebInfClasses(File archive, File destDir, Project prj) throws IOException {
File classesJar = new File(destDir, "WEB-INF/lib/classes.jar");
ZipFileSet zfs = new ZipFileSet();
zfs.setProject(prj);
zfs.setSrc(archive);
zfs.setIncludes("WEB-INF/classes/");
MappedResourceCollection mapper = new MappedResourceCollection();
mapper.add(zfs);
GlobPatternMapper gm = new GlobPatternMapper();
/**
* Forces the fixed timestamp for directories to make sure
* classes.jar always get a consistent checksum.
*/
@Override
protected void zipDir(Resource dir, ZipOutputStream zOut, String vPath,
int mode, ZipExtraField[] extra)
throws IOException {
// use wrappedZOut instead of zOut
super.zipDir(dir,wrappedZOut,vPath,mode,extra);
}
};
z.setProject(prj);
z.setTaskType("zip");
classesJar.getParentFile().mkdirs();
z.setDestFile(classesJar);
z.add(mapper);
z.execute();
}
if (classesJar.isFile()) {
LOGGER.log(Level.WARNING, "Created {0}; update plugin to a version created with a newer harness", classesJar);
}
}
private static void unzipExceptClasses(File archive, File destDir, Project prj) {
Expand e = new Expand();
e.setProject(prj);
e.setTaskType("unzip");
e.setSrc(archive);
e.setDest(destDir);
PatternSet p = new PatternSet();
p.setExcludes("WEB-INF/classes/");
e.addPatternset(p);
e.execute();
}
/**
* Used to load classes from dependency plugins.
*/
static final class DependencyClassLoader extends ClassLoader {
/**
* This classloader is created for this plugin. Useful during debugging.
*/
private final File _for;
private List<Dependency> dependencies;
private final PluginManager pluginManager;
/**
* Topologically sorted list of transitive dependencies. Lazily initialized via double-checked locking.
*/
private volatile List<PluginWrapper> transitiveDependencies;
static {
registerAsParallelCapable();
}
DependencyClassLoader(ClassLoader parent, File archive, List<Dependency> dependencies, PluginManager pluginManager) {
super(parent);
this._for = archive;
this.dependencies = Collections.unmodifiableList(new ArrayList<>(dependencies));
this.pluginManager = pluginManager;
}
private void updateTransitiveDependencies() {
// This will be recalculated at the next time.
transitiveDependencies = null;
}
private List<PluginWrapper> getTransitiveDependencies() {
List<PluginWrapper> localTransitiveDependencies = transitiveDependencies;
if (localTransitiveDependencies == null) {
synchronized (this) {
localTransitiveDependencies = transitiveDependencies;
if (localTransitiveDependencies == null) {
CyclicGraphDetector<PluginWrapper> cgd = new CyclicGraphDetector<PluginWrapper>() {
@Override
protected List<PluginWrapper> getEdges(PluginWrapper pw) {
List<PluginWrapper> dep = new ArrayList<>();
for (Dependency d : pw.getDependencies()) {
PluginWrapper p = pluginManager.getPlugin(d.shortName);
if (p!=null && p.isActive())
dep.add(p);
}
return dep;
}
};
try {
for (Dependency d : dependencies) {
PluginWrapper p = pluginManager.getPlugin(d.shortName);
if (p!=null && p.isActive())
cgd.run(Collections.singleton(p));
}
} catch (CycleDetectedException e) {
throw new AssertionError(e); // such error should have been reported earlier
}
transitiveDependencies = localTransitiveDependencies = cgd.getSorted();
}
}
}
return localTransitiveDependencies;
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
if (PluginManager.FAST_LOOKUP) {
for (PluginWrapper pw : getTransitiveDependencies()) {
try {
Class<?> c = ClassLoaderReflectionToolkit._findLoadedClass(pw.classLoader, name);
if (c!=null) return c;
return ClassLoaderReflectionToolkit._findClass(pw.classLoader, name);
} catch (ClassNotFoundException ignored) {
//not found. try next
}
}
} else {
for (Dependency dep : dependencies) {
PluginWrapper p = pluginManager.getPlugin(dep.shortName);
if(p!=null) {
try {
return p.classLoader.loadClass(name);
} catch (ClassNotFoundException ignored) {
// OK, try next
}
}
}
}
throw new ClassNotFoundException(name);
}
@Override
@SuppressFBWarnings(value = "DMI_COLLECTION_OF_URLS",
justification = "Should not produce network overheads since the URL is local. JENKINS-53793 is a follow-up")
protected Enumeration<URL> findResources(String name) throws IOException {
HashSet<URL> result = new HashSet<>();
if (PluginManager.FAST_LOOKUP) {
for (PluginWrapper pw : getTransitiveDependencies()) {
Enumeration<URL> urls = ClassLoaderReflectionToolkit._findResources(pw.classLoader, name);
while (urls != null && urls.hasMoreElements())
result.add(urls.nextElement());
}
} else {
for (Dependency dep : dependencies) {
PluginWrapper p = pluginManager.getPlugin(dep.shortName);
if (p!=null) {
Enumeration<URL> urls = p.classLoader.getResources(name);
while (urls != null && urls.hasMoreElements())
result.add(urls.nextElement());
}
}
}
return Collections.enumeration(result);
}
@Override
protected URL findResource(String name) {
if (PluginManager.FAST_LOOKUP) {
for (PluginWrapper pw : getTransitiveDependencies()) {
URL url = ClassLoaderReflectionToolkit._findResource(pw.classLoader, name);
if (url!=null) return url;
}
} else {
for (Dependency dep : dependencies) {
PluginWrapper p = pluginManager.getPlugin(dep.shortName);
if(p!=null) {
URL url = p.classLoader.getResource(name);
if (url!=null)
return url;
}
}
}
return null;
}
}
@SuppressFBWarnings(value = "MS_SHOULD_BE_FINAL", justification = "Accessible via System Groovy Scripts")
public static /* not final */ boolean useAntClassLoader = SystemProperties.getBoolean(ClassicPluginStrategy.class.getName() + ".useAntClassLoader", true);
} |
package org.languagetool.tagging.nl;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.languagetool.AnalyzedToken;
import org.languagetool.AnalyzedTokenReadings;
import org.languagetool.tagging.BaseTagger;
import org.languagetool.tools.StringTools;
/**
* Dutch tagger.
*
* @author Marcin Milkowski
*/
public class DutchTagger extends BaseTagger {
@Override
public String getManualAdditionsFileName() {
return "/nl/added.txt";
}
@Override
public String getManualRemovalsFileName() {
return "/nl/removed.txt";
}
public DutchTagger() {
super("/nl/dutch.dict", new Locale("nl"));
}
// custom code to deal with words carrying optional accents
@Override
public List<AnalyzedTokenReadings> tag(final List<String> sentenceTokens) {
final List<AnalyzedTokenReadings> tokenReadings = new ArrayList<>();
int pos = 0;
for (String word : sentenceTokens) {
boolean ignoreSpelling = false;
final List<AnalyzedToken> l = new ArrayList<>();
final String lowerWord = word.toLowerCase(conversionLocale);
final boolean isLowercase = word.equals(lowerWord);
final boolean isMixedCase = StringTools.isMixedCase(word);
final boolean isAllUpper = StringTools.isAllUppercase(word);
List<AnalyzedToken> taggerTokens = asAnalyzedTokenListForTaggedWords(word, getWordTagger().tag(word));
// normal case:
addTokens(taggerTokens, l);
// tag non-lowercase (alluppercase or startuppercase), but not mixedcase
// word with lowercase word tags:
if (!isLowercase && !isMixedCase) {
List<AnalyzedToken> lowerTaggerTokens = asAnalyzedTokenListForTaggedWords(word, getWordTagger().tag(lowerWord));
addTokens(lowerTaggerTokens, l);
}
// tag all-uppercase proper nouns
if (l.isEmpty() && isAllUpper) {
final String firstUpper = StringTools.uppercaseFirstChar(lowerWord);
List<AnalyzedToken> firstupperTaggerTokens = asAnalyzedTokenListForTaggedWords(word,
getWordTagger().tag(firstUpper));
addTokens(firstupperTaggerTokens, l);
}
if (l.isEmpty()) {
String word2 = lowerWord;
// remove single accented characterd
word2 = word2.replace("á", "a").replace("é", "e").replace("í", "i").replace("ó", "o").replace("ú", "u");
// TODO: remove optional hyphens one at a time; for now just all will be removed
// best would be to check the parts as well (uncompound)
word2 = word2.replaceAll("([a-z])-([a-z])", "$1$2");
if (!word2.equals(word)) {
List<AnalyzedToken> l2 = asAnalyzedTokenListForTaggedWords(word, getWordTagger().tag(word2));
if (l2 != null) {
addTokens(l2, l);
String word3 = word;
word3 = word.replaceAll("([a-z])-([a-z])", "$1$2");
// remove allowed accented characterd
word3 = word3.replace("áá", "aa");
word3 = word3.replace("áé", "ae");
word3 = word3.replace("áí", "ai");
word3 = word3.replace("áú", "au");
word3 = word3.replace("éé", "ee");
word3 = word3.replace("éí", "ei");
word3 = word3.replace("éú", "eu");
word3 = word3.replace("íé", "ie");
word3 = word3.replace("óé", "oe");
word3 = word3.replace("óí", "oi");
word3 = word3.replace("óó", "oo");
word3 = word3.replace("óú", "ou");
word3 = word3.replace("úí", "ui");
word3 = word3.replace("úú", "uu");
word3 = word3.replace("íj", "ij");
word3 = word3.replaceAll("(^|[^aeiou])á([^aeiou]|$)", "$1a$2");
word3 = word3.replaceAll("(^|[^aeiou])é([^aeiou]|$)", "$1e$2");
word3 = word3.replaceAll("(^|[^aeiou])í([^aeiou]|$)", "$1i$2");
word3 = word3.replaceAll("(^|[^aeiou])ó([^aeiou]|$)", "$1o$2");
word3 = word3.replaceAll("(^|[^aeiou])ú([^aeiou]|$)", "$1u$2");
if (word3.equals(word2)) {
ignoreSpelling = true;
}
}
}
}
if (l.isEmpty()) {
l.add(new AnalyzedToken(word, null, null));
}
AnalyzedTokenReadings atr = new AnalyzedTokenReadings(l, pos);
if (ignoreSpelling) {
atr.ignoreSpelling();
}
tokenReadings.add(atr);
pos += word.length();
}
return tokenReadings;
}
private void addTokens(final List<AnalyzedToken> taggedTokens, final List<AnalyzedToken> l) {
if (taggedTokens != null) {
l.addAll(taggedTokens);
}
}
} |
package hudson;
import com.google.common.collect.Lists;
import hudson.Plugin.DummyImpl;
import hudson.PluginWrapper.Dependency;
import hudson.model.Hudson;
import hudson.util.CyclicGraphDetector;
import hudson.util.CyclicGraphDetector.CycleDetectedException;
import hudson.util.IOUtils;
import hudson.util.MaskingClassLoader;
import hudson.util.VersionNumber;
import jenkins.ClassLoaderReflectionToolkit;
import jenkins.ExtensionFilter;
import org.apache.commons.io.output.NullOutputStream;
import org.apache.tools.ant.AntClassLoader;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Expand;
import org.apache.tools.ant.taskdefs.Zip;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.ant.types.PatternSet;
import org.apache.tools.ant.types.Resource;
import org.apache.tools.ant.types.ZipFileSet;
import org.apache.tools.ant.types.resources.MappedResourceCollection;
import org.apache.tools.ant.util.GlobPatternMapper;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipExtraField;
import org.apache.tools.zip.ZipOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Vector;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ClassicPluginStrategy implements PluginStrategy {
/**
* Filter for jar files.
*/
private static final FilenameFilter JAR_FILTER = new FilenameFilter() {
public boolean accept(File dir,String name) {
return name.endsWith(".jar");
}
};
private PluginManager pluginManager;
/**
* All the plugins eventually delegate this classloader to load core, servlet APIs, and SE runtime.
*/
private final MaskingClassLoader coreClassLoader = new MaskingClassLoader(getClass().getClassLoader());
public ClassicPluginStrategy(PluginManager pluginManager) {
this.pluginManager = pluginManager;
}
public PluginWrapper createPluginWrapper(File archive) throws IOException {
final Manifest manifest;
URL baseResourceURL;
File expandDir = null;
// if .hpi, this is the directory where war is expanded
boolean isLinked = archive.getName().endsWith(".hpl") || archive.getName().endsWith(".jpl");
if (isLinked) {
// resolve the .hpl file to the location of the manifest file
final String firstLine = IOUtils.readFirstLine(new FileInputStream(archive), "UTF-8");
if (firstLine.startsWith("Manifest-Version:")) {
// this is the manifest already
} else {
// indirection
archive = resolve(archive, firstLine);
}
// then parse manifest
FileInputStream in = new FileInputStream(archive);
try {
manifest = new Manifest(in);
} catch (IOException e) {
throw new IOException("Failed to load " + archive, e);
} finally {
in.close();
}
} else {
if (archive.isDirectory()) {// already expanded
expandDir = archive;
} else {
expandDir = new File(archive.getParentFile(), PluginWrapper.getBaseName(archive));
explode(archive, expandDir);
}
File manifestFile = new File(expandDir, "META-INF/MANIFEST.MF");
if (!manifestFile.exists()) {
throw new IOException(
"Plugin installation failed. No manifest at "
+ manifestFile);
}
FileInputStream fin = new FileInputStream(manifestFile);
try {
manifest = new Manifest(fin);
} finally {
fin.close();
}
}
final Attributes atts = manifest.getMainAttributes();
// TODO: define a mechanism to hide classes
// String export = manifest.getMainAttributes().getValue("Export");
List<File> paths = new ArrayList<File>();
if (isLinked) {
parseClassPath(manifest, archive, paths, "Libraries", ",");
parseClassPath(manifest, archive, paths, "Class-Path", " +"); // backward compatibility
baseResourceURL = resolve(archive,atts.getValue("Resource-Path")).toURI().toURL();
} else {
File classes = new File(expandDir, "WEB-INF/classes");
if (classes.exists())
paths.add(classes);
File lib = new File(expandDir, "WEB-INF/lib");
File[] libs = lib.listFiles(JAR_FILTER);
if (libs != null)
paths.addAll(Arrays.asList(libs));
baseResourceURL = expandDir.toURI().toURL();
}
File disableFile = new File(archive.getPath() + ".disabled");
if (disableFile.exists()) {
LOGGER.info("Plugin " + archive.getName() + " is disabled");
}
// compute dependencies
List<PluginWrapper.Dependency> dependencies = new ArrayList<PluginWrapper.Dependency>();
List<PluginWrapper.Dependency> optionalDependencies = new ArrayList<PluginWrapper.Dependency>();
String v = atts.getValue("Plugin-Dependencies");
if (v != null) {
for (String s : v.split(",")) {
PluginWrapper.Dependency d = new PluginWrapper.Dependency(s);
if (d.optional) {
optionalDependencies.add(d);
} else {
dependencies.add(d);
}
}
}
for (DetachedPlugin detached : DETACHED_LIST)
detached.fix(atts,optionalDependencies);
// Register global classpath mask. This is useful for hiding JavaEE APIs that you might see from the container,
// such as database plugin for JPA support. The Mask-Classes attribute is insufficient because those classes
// also need to be masked by all the other plugins that depend on the database plugin.
String masked = atts.getValue("Global-Mask-Classes");
if(masked!=null) {
for (String pkg : masked.trim().split("[ \t\r\n]+"))
coreClassLoader.add(pkg);
}
ClassLoader dependencyLoader = new DependencyClassLoader(coreClassLoader, archive, Util.join(dependencies,optionalDependencies));
dependencyLoader = getBaseClassLoader(atts, dependencyLoader);
return new PluginWrapper(pluginManager, archive, manifest, baseResourceURL,
createClassLoader(paths, dependencyLoader, atts), disableFile, dependencies, optionalDependencies);
}
@Deprecated
protected ClassLoader createClassLoader(List<File> paths, ClassLoader parent) throws IOException {
return createClassLoader( paths, parent, null );
}
/**
* Creates the classloader that can load all the specified jar files and delegate to the given parent.
*/
protected ClassLoader createClassLoader(List<File> paths, ClassLoader parent, Attributes atts) throws IOException {
if (atts != null) {
String usePluginFirstClassLoader = atts.getValue( "PluginFirstClassLoader" );
if (Boolean.valueOf( usePluginFirstClassLoader )) {
PluginFirstClassLoader classLoader = new PluginFirstClassLoader();
classLoader.setParentFirst( false );
classLoader.setParent( parent );
classLoader.addPathFiles( paths );
return classLoader;
}
}
AntClassLoader2 classLoader = new AntClassLoader2(parent);
classLoader.addPathFiles(paths);
return classLoader;
}
/**
* Information about plugins that were originally in the core.
*/
private static final class DetachedPlugin {
private final String shortName;
/**
* Plugins built for this Jenkins version (and earlier) will automatically be assumed to have
* this plugin in its dependency.
*
* When core/pom.xml version is 1.123-SNAPSHOT when the code is removed, then this value should
* be "1.123.*" (because 1.124 will be the first version that doesn't include the removed code.)
*/
private final VersionNumber splitWhen;
private final String requireVersion;
private DetachedPlugin(String shortName, String splitWhen, String requireVersion) {
this.shortName = shortName;
this.splitWhen = new VersionNumber(splitWhen);
this.requireVersion = requireVersion;
}
private void fix(Attributes atts, List<PluginWrapper.Dependency> optionalDependencies) {
// don't fix the dependency for yourself, or else we'll have a cycle
String yourName = atts.getValue("Short-Name");
if (shortName.equals(yourName)) return;
// some earlier versions of maven-hpi-plugin apparently puts "null" as a literal in Hudson-Version. watch out for them.
String jenkinsVersion = atts.getValue("Jenkins-Version");
if (jenkinsVersion==null)
jenkinsVersion = atts.getValue("Hudson-Version");
if (jenkinsVersion == null || jenkinsVersion.equals("null") || new VersionNumber(jenkinsVersion).compareTo(splitWhen) <= 0)
optionalDependencies.add(new PluginWrapper.Dependency(shortName+':'+requireVersion));
}
}
private static final List<DetachedPlugin> DETACHED_LIST = Arrays.asList(
new DetachedPlugin("maven-plugin","1.296","1.296"),
new DetachedPlugin("subversion","1.310","1.0"),
new DetachedPlugin("cvs","1.340","0.1"),
new DetachedPlugin("ant","1.430.*","1.0"),
new DetachedPlugin("javadoc","1.430.*","1.0"),
new DetachedPlugin("external-monitor-job","1.467.*","1.0"),
new DetachedPlugin("ldap","1.467.*","1.0"),
new DetachedPlugin("pam-auth","1.467.*","1.0"),
new DetachedPlugin("mailer","1.493.*","1.2"),
new DetachedPlugin("matrix-auth","1.535.*","1.0.2"),
new DetachedPlugin("windows-slaves","1.547.*","1.0"),
new DetachedPlugin("antisamy-markup-formatter","1.553.*","1.0"),
new DetachedPlugin("matrix-project","1.561.*","1.0")
);
/**
* Computes the classloader that takes the class masking into account.
*
* <p>
* This mechanism allows plugins to have their own versions for libraries that core bundles.
*/
private ClassLoader getBaseClassLoader(Attributes atts, ClassLoader base) {
String masked = atts.getValue("Mask-Classes");
if(masked!=null)
base = new MaskingClassLoader(base, masked.trim().split("[ \t\r\n]+"));
return base;
}
public void initializeComponents(PluginWrapper plugin) {
}
public <T> List<ExtensionComponent<T>> findComponents(Class<T> type, Hudson hudson) {
List<ExtensionFinder> finders;
if (type==ExtensionFinder.class) {
// Avoid infinite recursion of using ExtensionFinders to find ExtensionFinders
finders = Collections.<ExtensionFinder>singletonList(new ExtensionFinder.Sezpoz());
} else {
finders = hudson.getExtensionList(ExtensionFinder.class);
}
/**
* See {@link ExtensionFinder#scout(Class, Hudson)} for the dead lock issue and what this does.
*/
if (LOGGER.isLoggable(Level.FINER))
LOGGER.log(Level.FINER,"Scout-loading ExtensionList: "+type, new Throwable());
for (ExtensionFinder finder : finders) {
finder.scout(type, hudson);
}
List<ExtensionComponent<T>> r = Lists.newArrayList();
for (ExtensionFinder finder : finders) {
try {
r.addAll(finder._find(type, hudson));
} catch (AbstractMethodError e) {
// backward compatibility
for (T t : finder.findExtensions(type, hudson))
r.add(new ExtensionComponent<T>(t));
}
}
List<ExtensionComponent<T>> filtered = Lists.newArrayList();
for (ExtensionComponent<T> e : r) {
if (ExtensionFilter.isAllowed(type,e))
filtered.add(e);
}
return filtered;
}
public void load(PluginWrapper wrapper) throws IOException {
// override the context classloader. This no longer makes sense,
// but it is left for the backward compatibility
ClassLoader old = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(wrapper.classLoader);
try {
String className = wrapper.getPluginClass();
if(className==null) {
// use the default dummy instance
wrapper.setPlugin(new DummyImpl());
} else {
try {
Class<?> clazz = wrapper.classLoader.loadClass(className);
Object o = clazz.newInstance();
if(!(o instanceof Plugin)) {
throw new IOException(className+" doesn't extend from hudson.Plugin");
}
wrapper.setPlugin((Plugin) o);
} catch (LinkageError e) {
throw new IOException("Unable to load " + className + " from " + wrapper.getShortName(),e);
} catch (ClassNotFoundException e) {
throw new IOException("Unable to load " + className + " from " + wrapper.getShortName(),e);
} catch (IllegalAccessException e) {
throw new IOException("Unable to create instance of " + className + " from " + wrapper.getShortName(),e);
} catch (InstantiationException e) {
throw new IOException("Unable to create instance of " + className + " from " + wrapper.getShortName(),e);
}
}
// initialize plugin
try {
Plugin plugin = wrapper.getPlugin();
plugin.setServletContext(pluginManager.context);
startPlugin(wrapper);
} catch(Throwable t) {
// gracefully handle any error in plugin.
throw new IOException("Failed to initialize",t);
}
} finally {
Thread.currentThread().setContextClassLoader(old);
}
}
public void startPlugin(PluginWrapper plugin) throws Exception {
plugin.getPlugin().start();
}
private static File resolve(File base, String relative) {
File rel = new File(relative);
if(rel.isAbsolute())
return rel;
else
return new File(base.getParentFile(),relative);
}
private static void parseClassPath(Manifest manifest, File archive, List<File> paths, String attributeName, String separator) throws IOException {
String classPath = manifest.getMainAttributes().getValue(attributeName);
if(classPath==null) return; // attribute not found
for (String s : classPath.split(separator)) {
File file = resolve(archive, s);
if(file.getName().contains("*")) {
// handle wildcard
FileSet fs = new FileSet();
File dir = file.getParentFile();
fs.setDir(dir);
fs.setIncludes(file.getName());
for( String included : fs.getDirectoryScanner(new Project()).getIncludedFiles() ) {
paths.add(new File(dir,included));
}
} else {
if(!file.exists())
throw new IOException("No such file: "+file);
paths.add(file);
}
}
}
/**
* Explodes the plugin into a directory, if necessary.
*/
private static void explode(File archive, File destDir) throws IOException {
destDir.mkdirs();
// timestamp check
File explodeTime = new File(destDir,".timestamp2");
if(explodeTime.exists() && explodeTime.lastModified()==archive.lastModified())
return; // no need to expand
// delete the contents so that old files won't interfere with new files
Util.deleteRecursive(destDir);
try {
Project prj = new Project();
unzipExceptClasses(archive, destDir, prj);
createClassJarFromWebInfClasses(archive, destDir, prj);
} catch (BuildException x) {
throw new IOException("Failed to expand " + archive,x);
}
try {
new FilePath(explodeTime).touch(archive.lastModified());
} catch (InterruptedException e) {
throw new AssertionError(e); // impossible
}
}
/**
* Repackage classes directory into a jar file to make it remoting friendly.
* The remoting layer can cache jar files but not class files.
*/
private static void createClassJarFromWebInfClasses(File archive, File destDir, Project prj) throws IOException {
File classesJar = new File(destDir, "WEB-INF/lib/classes.jar");
ZipFileSet zfs = new ZipFileSet();
zfs.setProject(prj);
zfs.setSrc(archive);
zfs.setIncludes("WEB-INF/classes/");
MappedResourceCollection mapper = new MappedResourceCollection();
mapper.add(zfs);
GlobPatternMapper gm = new GlobPatternMapper();
/**
* Forces the fixed timestamp for directories to make sure
* classes.jar always get a consistent checksum.
*/
protected void zipDir(Resource dir, ZipOutputStream zOut, String vPath,
int mode, ZipExtraField[] extra)
throws IOException {
// use wrappedZOut instead of zOut
super.zipDir(dir,wrappedZOut,vPath,mode,extra);
}
};
z.setProject(prj);
z.setTaskType("zip");
classesJar.getParentFile().mkdirs();
z.setDestFile(classesJar);
z.add(mapper);
z.execute();
} finally {
wrappedZOut.close();
}
}
private static void unzipExceptClasses(File archive, File destDir, Project prj) {
Expand e = new Expand();
e.setProject(prj);
e.setTaskType("unzip");
e.setSrc(archive);
e.setDest(destDir);
PatternSet p = new PatternSet();
p.setExcludes("WEB-INF/classes/");
e.addPatternset(p);
e.execute();
}
/**
* Used to load classes from dependency plugins.
*/
final class DependencyClassLoader extends ClassLoader {
/**
* This classloader is created for this plugin. Useful during debugging.
*/
private final File _for;
private List<Dependency> dependencies;
/**
* Topologically sorted list of transient dependencies.
*/
private volatile List<PluginWrapper> transientDependencies;
public DependencyClassLoader(ClassLoader parent, File archive, List<Dependency> dependencies) {
super(parent);
this._for = archive;
this.dependencies = dependencies;
}
private List<PluginWrapper> getTransitiveDependencies() {
if (transientDependencies==null) {
CyclicGraphDetector<PluginWrapper> cgd = new CyclicGraphDetector<PluginWrapper>() {
@Override
protected List<PluginWrapper> getEdges(PluginWrapper pw) {
List<PluginWrapper> dep = new ArrayList<PluginWrapper>();
for (Dependency d : pw.getDependencies()) {
PluginWrapper p = pluginManager.getPlugin(d.shortName);
if (p!=null && p.isActive())
dep.add(p);
}
return dep;
}
};
try {
for (Dependency d : dependencies) {
PluginWrapper p = pluginManager.getPlugin(d.shortName);
if (p!=null && p.isActive())
cgd.run(Collections.singleton(p));
}
} catch (CycleDetectedException e) {
throw new AssertionError(e); // such error should have been reported earlier
}
transientDependencies = cgd.getSorted();
}
return transientDependencies;
}
// public List<PluginWrapper> getDependencyPluginWrappers() {
// List<PluginWrapper> r = new ArrayList<PluginWrapper>();
// for (Dependency d : dependencies) {
// PluginWrapper w = pluginManager.getPlugin(d.shortName);
// if (w!=null) r.add(w);
// return r;
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
if (PluginManager.FAST_LOOKUP) {
for (PluginWrapper pw : getTransitiveDependencies()) {
try {
Class<?> c = ClassLoaderReflectionToolkit._findLoadedClass(pw.classLoader, name);
if (c!=null) return c;
return ClassLoaderReflectionToolkit._findClass(pw.classLoader, name);
} catch (ClassNotFoundException e) {
//not found. try next
}
}
} else {
for (Dependency dep : dependencies) {
PluginWrapper p = pluginManager.getPlugin(dep.shortName);
if(p!=null)
try {
return p.classLoader.loadClass(name);
} catch (ClassNotFoundException _) {
// try next
}
}
}
throw new ClassNotFoundException(name);
}
@Override
protected Enumeration<URL> findResources(String name) throws IOException {
HashSet<URL> result = new HashSet<URL>();
if (PluginManager.FAST_LOOKUP) {
for (PluginWrapper pw : getTransitiveDependencies()) {
Enumeration<URL> urls = ClassLoaderReflectionToolkit._findResources(pw.classLoader, name);
while (urls != null && urls.hasMoreElements())
result.add(urls.nextElement());
}
} else {
for (Dependency dep : dependencies) {
PluginWrapper p = pluginManager.getPlugin(dep.shortName);
if (p!=null) {
Enumeration<URL> urls = p.classLoader.getResources(name);
while (urls != null && urls.hasMoreElements())
result.add(urls.nextElement());
}
}
}
return Collections.enumeration(result);
}
@Override
protected URL findResource(String name) {
if (PluginManager.FAST_LOOKUP) {
for (PluginWrapper pw : getTransitiveDependencies()) {
URL url = ClassLoaderReflectionToolkit._findResource(pw.classLoader, name);
if (url!=null) return url;
}
} else {
for (Dependency dep : dependencies) {
PluginWrapper p = pluginManager.getPlugin(dep.shortName);
if(p!=null) {
URL url = p.classLoader.getResource(name);
if (url!=null)
return url;
}
}
}
return null;
}
}
/**
* {@link AntClassLoader} with a few methods exposed and {@link Closeable} support.
* Deprecated as of Java 7, retained only for Java 6.
*/
private final class AntClassLoader2 extends AntClassLoader implements Closeable {
private final Vector pathComponents;
private AntClassLoader2(ClassLoader parent) {
super(parent,true);
try {
Field $pathComponents = AntClassLoader.class.getDeclaredField("pathComponents");
$pathComponents.setAccessible(true);
pathComponents = (Vector)$pathComponents.get(this);
} catch (NoSuchFieldException e) {
throw new Error(e);
} catch (IllegalAccessException e) {
throw new Error(e);
}
}
public void addPathFiles(Collection<File> paths) throws IOException {
for (File f : paths)
addPathFile(f);
}
public void close() throws IOException {
cleanup();
}
/**
* As of 1.8.0, {@link AntClassLoader} doesn't implement {@link #findResource(String)}
* in any meaningful way, which breaks fast lookup. Implement it properly.
*/
@Override
protected URL findResource(String name) {
URL url = null;
// try and load from this loader if the parent either didn't find
// it or wasn't consulted.
Enumeration e = pathComponents.elements();
while (e.hasMoreElements() && url == null) {
File pathComponent = (File) e.nextElement();
url = getResourceURL(pathComponent, name);
if (url != null) {
log("Resource " + name + " loaded from ant loader", Project.MSG_DEBUG);
}
}
return url;
}
@Override
protected Class defineClassFromData(File container, byte[] classData, String classname) throws IOException {
if (!DISABLE_TRANSFORMER)
classData = pluginManager.getCompatibilityTransformer().transform(classname, classData);
return super.defineClassFromData(container, classData, classname);
}
}
public static boolean useAntClassLoader = Boolean.getBoolean(ClassicPluginStrategy.class.getName()+".useAntClassLoader");
private static final Logger LOGGER = Logger.getLogger(ClassicPluginStrategy.class.getName());
public static boolean DISABLE_TRANSFORMER = Boolean.getBoolean(ClassicPluginStrategy.class.getName()+".noBytecodeTransformer");
} |
package net.mgsx.game.plugins.btree;
import com.badlogic.ashley.core.Component;
import com.badlogic.ashley.core.ComponentMapper;
import com.badlogic.ashley.core.Engine;
import com.badlogic.gdx.ai.btree.BehaviorTree;
import com.badlogic.gdx.utils.Pool.Poolable;
import net.mgsx.game.core.annotations.EditableComponent;
import net.mgsx.game.core.annotations.Storable;
import net.mgsx.game.core.components.Duplicable;
@Storable("btree")
@EditableComponent(autoTool=false)
public class BTreeModel implements Component, Duplicable, Poolable
{
public final static ComponentMapper<BTreeModel> components = ComponentMapper.getFor(BTreeModel.class);
public String libraryName;
public BehaviorTree<EntityBlackboard> tree;
public boolean enabled = false; // XXX should be enabled by default ? or use a command in normal game mode ?
public boolean remove = false;
@Override
public Component duplicate(Engine engine) {
BTreeModel clone = engine.createComponent(BTreeModel.class);
clone.tree = engine.getSystem(BTreeSystem.class).createBehaviorTree(libraryName);
clone.libraryName = libraryName;
clone.remove = remove;
clone.enabled = enabled;
return clone;
}
@Override
public void reset() {
// TODO release tree ?
enabled = false;
}
} |
package com.ctrip.xpipe;
import com.ctrip.xpipe.api.codec.Codec;
import com.ctrip.xpipe.api.command.RequestResponseCommand;
import com.ctrip.xpipe.api.lifecycle.ComponentRegistry;
import com.ctrip.xpipe.command.AbstractCommand;
import com.ctrip.xpipe.endpoint.DefaultEndPoint;
import com.ctrip.xpipe.endpoint.HostPort;
import com.ctrip.xpipe.exception.DefaultExceptionHandler;
import com.ctrip.xpipe.lifecycle.CreatedComponentRedistry;
import com.ctrip.xpipe.lifecycle.DefaultRegistry;
import com.ctrip.xpipe.lifecycle.LifecycleHelper;
import com.ctrip.xpipe.lifecycle.SpringComponentRegistry;
import com.ctrip.xpipe.monitor.CatConfig;
import com.ctrip.xpipe.pool.XpipeNettyClientKeyedObjectPool;
import com.ctrip.xpipe.simpleserver.AbstractIoAction;
import com.ctrip.xpipe.simpleserver.IoAction;
import com.ctrip.xpipe.simpleserver.IoActionFactory;
import com.ctrip.xpipe.simpleserver.Server;
import com.ctrip.xpipe.spring.AbstractProfile;
import com.ctrip.xpipe.testutils.ByteBufReleaseWrapper;
import com.ctrip.xpipe.utils.OsUtils;
import com.ctrip.xpipe.utils.XpipeThreadFactory;
import com.ctrip.xpipe.zk.ZkTestServer;
import com.google.common.collect.Lists;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.util.ResourceLeakDetector;
import org.apache.commons.io.FileUtils;
import org.junit.*;
import org.junit.rules.TestName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ConfigurableApplicationContext;
import java.io.*;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.nio.charset.Charset;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BooleanSupplier;
import java.util.function.Function;
/**
* @author wenchao.meng
* <p>
* 2016328 5:44:47
*/
public class AbstractTest {
protected Logger logger = LoggerFactory.getLogger(getClass());
protected ByteBufAllocator allocator = ByteBufAllocator.DEFAULT;
public static String KEY_INCRMENTAL_ZK_PORT = "INCRMENTAL_ZK_PORT";
protected ExecutorService executors;
protected ScheduledExecutorService scheduled;
private ComponentRegistry componentRegistry;
public static final String LOCAL_HOST = "127.0.0.1";
@Rule
public TestName name = new TestName();
private static Properties properties = new Properties();
private Properties orginProperties;
private ComponentRegistry startedComponentRegistry;
protected void doBeforeAbstractTest() throws Exception {
}
@BeforeClass
public static void beforeAbstractTestClass() {
if (System.getProperty(CatConfig.CAT_ENABLED_KEY) == null) {
System.setProperty(CatConfig.CAT_ENABLED_KEY, "false");
}
System.setProperty(AbstractProfile.PROFILE_KEY, AbstractProfile.PROFILE_NAME_TEST);
}
@Before
public void beforeAbstractTest() throws Exception {
ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.PARANOID);
Thread.interrupted();//clear interrupt
executors = Executors.newCachedThreadPool(XpipeThreadFactory.create(getTestName()));
scheduled = Executors.newScheduledThreadPool(OsUtils.getCpuCount(), XpipeThreadFactory.create(getTestName()));
orginProperties = (Properties) System.getProperties().clone();
doBeforeAbstractTest();
logger.info(remarkableMessage("[begin test][{}]"), name.getMethodName());
componentRegistry = new DefaultRegistry(new CreatedComponentRedistry(), getSpringRegistry());
startedComponentRegistry = new CreatedComponentRedistry();
startedComponentRegistry.initialize();
startedComponentRegistry.start();
Thread.setDefaultUncaughtExceptionHandler(new DefaultExceptionHandler());
InputStream fins = getClass().getClassLoader().getResourceAsStream("xpipe-test.properties");
try {
properties.load(fins);
} finally {
if (fins != null) {
fins.close();
}
}
File file = new File(getTestFileDir());
if (file.exists() && deleteTestDirBeforeTest()) {
deleteTestDir();
}
if (!file.exists()) {
boolean testSucceed = file.mkdirs();
if (!testSucceed) {
throw new IllegalStateException("test dir make failed!" + file);
}
}
}
protected ByteBuf directByteBuf() {
return directByteBuf(1 << 10);
}
protected ByteBuf directByteBuf(int size) {
ByteBuf byteBuf = allocator.directBuffer(size);
addReleasable(byteBuf);
return byteBuf;
}
protected void addReleasable(Object object) {
if (object instanceof ByteBuf) {
try {
add(new ByteBufReleaseWrapper((ByteBuf) object));
} catch (Exception e) {
throw new IllegalStateException("add " + object, e);
}
return;
}
throw new IllegalArgumentException("unknown:" + object);
}
protected String getTestName() {
return name.getMethodName();
}
protected void shouldThrowException(Runnable runnable) {
try{
runnable.run();
Assert.fail();
}catch (Exception e){
logger.info("shouldThrowException: {}", e.getMessage());
}
}
protected void waitConditionUntilTimeOut(BooleanSupplier booleanSupplier) throws TimeoutException {
waitConditionUntilTimeOut(booleanSupplier, 5000, 2);
}
protected void waitConditionUntilTimeOut(BooleanSupplier booleanSupplier, int waitTimeMilli) throws TimeoutException {
waitConditionUntilTimeOut(booleanSupplier, waitTimeMilli, 2);
}
protected void waitConditionUntilTimeOut(BooleanSupplier booleanSupplier, int waitTimeMilli, int intervalMilli) throws TimeoutException {
long maxTime = System.currentTimeMillis() + waitTimeMilli;
while (true) {
boolean result = booleanSupplier.getAsBoolean();
if (result) {
return;
}
if (System.currentTimeMillis() >= maxTime) {
throw new TimeoutException("timeout still false:" + waitTimeMilli);
}
sleep(intervalMilli);
}
}
protected boolean deleteTestDirBeforeTest() {
return true;
}
private ComponentRegistry getSpringRegistry() {
ConfigurableApplicationContext applicationContext = createSpringContext();
if (applicationContext != null) {
return new SpringComponentRegistry(applicationContext);
}
return null;
}
protected XpipeNettyClientKeyedObjectPool getXpipeNettyClientKeyedObjectPool() throws Exception {
XpipeNettyClientKeyedObjectPool result;
try {
result = getBean(XpipeNettyClientKeyedObjectPool.class);
} catch (Exception e) {
result = new XpipeNettyClientKeyedObjectPool();
add(result);
}
LifecycleHelper.initializeIfPossible(result);
LifecycleHelper.startIfPossible(result);
return result;
}
/**
* to be overriden by subclasses
*
* @return
*/
protected ConfigurableApplicationContext createSpringContext() {
return null;
}
protected <T> T getBean(Class<T> clazz) {
return getRegistry().getComponent(clazz);
}
protected void initRegistry() throws Exception {
componentRegistry.initialize();
}
protected void startRegistry() throws Exception {
componentRegistry.start();
}
public static String randomString() {
return randomString(1 << 10);
}
public static String randomString(int length) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
sb.append((char) ('a' + (int) (26 * Math.random())));
}
return sb.toString();
}
protected String getRealDir(final String dir) {
String userHome = getUserHome();
String newDir = dir;
if (dir != null) {
newDir = dir.replace("~", userHome);
}
return newDir;
}
protected String getTestFileDir() {
String result = getUserHome() + "/test";
String testDir = properties.getProperty("test.file.dir");
if (testDir != null) {
result = getRealDir(testDir);
}
return result + "/" + getClass().getSimpleName() + "-" + currentTestName();
}
public static String getUserHome() {
return System.getProperty("user.home");
}
protected void sleepSeconds(int seconds) {
sleep(seconds * 1000);
}
protected void sleepIgnoreInterrupt(int time) {
long future = System.currentTimeMillis() + time;
while (true) {
long left = future - System.currentTimeMillis();
if (left <= 0) {
break;
}
if (left > 0) {
try {
TimeUnit.MILLISECONDS.sleep(left);
} catch (InterruptedException e) {
}
}
}
}
protected void sleep(int miliSeconds) {
try {
TimeUnit.MILLISECONDS.sleep(miliSeconds);
} catch (InterruptedException e) {
}
}
protected String readFileAsString(String fileName) {
return readFileAsString(fileName, Codec.defaultCharset);
}
protected String readFileAsString(String fileName, Charset charset) {
FileInputStream fins = null;
try {
byte[] data = new byte[2048];
ByteArrayOutputStream baous = new ByteArrayOutputStream();
fins = new FileInputStream(new File(fileName));
while (true) {
int size = fins.read(data);
if (size > 0) {
baous.write(data, 0, size);
}
if (size == -1) {
break;
}
}
return new String(baous.toByteArray(), charset);
} catch (FileNotFoundException e) {
logger.error("[readFileAsString]" + fileName, e);
} catch (IOException e) {
logger.error("[readFileAsString]" + fileName, e);
} finally {
if (fins != null) {
try {
fins.close();
} catch (IOException e) {
logger.error("[readFileAsString]", e);
}
}
}
return null;
}
protected void add(Object lifecycle) throws Exception {
this.componentRegistry.add(lifecycle);
}
protected void remove(Object lifecycle) throws Exception {
this.componentRegistry.remove(lifecycle);
}
public ComponentRegistry getRegistry() {
return componentRegistry;
}
protected String currentTestName() {
return name.getMethodName();
}
public static int portUsable(int fromPort) {
for (int i = fromPort; i < fromPort + 100; i++) {
if (isUsable(i)) {
return i;
}
}
throw new IllegalStateException("unfonud usable port from %d" + fromPort);
}
public static int randomPort() {
return randomPort(10000, 30000, null);
}
public static Set<Integer> usedPorts = new HashSet<>();
public static Set<Integer> randomPorts(int count) {
Set<Integer> result = new HashSet<>();
for (int i = 0; i < count; i++) {
result.add(randomPort(result));
}
return result;
}
public static int randomPort(Set<Integer> different) {
return randomPort(10000, 30000, different);
}
/**
* find an available port from min to max
*
* @param min
* @param max
* @return
*/
public static int randomPort(int min, int max) {
return randomPort(min, max, null);
}
public static synchronized int randomPort(int min, int max, Set<Integer> different) {
Random random = new Random();
for (int i = min; i <= max; i++) {
int port = min + random.nextInt(max - min + 1);
if ((different == null || !different.contains(new Integer(port))) && isUsable(port) && !usedPorts.contains(port) ) {
usedPorts.add(port);
return port;
}
}
throw new IllegalStateException(String.format("random port not found:(%d, %d)", min, max));
}
protected static boolean isUsable(int port) {
try (ServerSocket s = new ServerSocket()) {
s.bind(new InetSocketAddress(port));
return true;
} catch (IOException e) {
}
return false;
}
protected static int incrementalPort(int begin) {
return incrementalPort(begin, Integer.MAX_VALUE);
}
protected static int incrementalPort(int begin, int end) {
for (int i = begin; i <= end; i++) {
if (isUsable(i)) {
return i;
}
}
throw new IllegalArgumentException(String.format("can not find usable port [%d, %d]", begin, end));
}
protected int randomInt() {
Random random = new Random();
return random.nextInt();
}
protected int randomInt(int start, int end) {
Random random = new Random();
return start + random.nextInt(end - start + 1);
}
protected String remarkableMessage(String msg) {
return String.format("
}
protected void waitForAnyKeyToExit() throws IOException {
System.out.println("type any key to exit..................");
waitForAnyKey();
}
protected void waitForAnyKey() throws IOException {
System.in.read();
}
protected ZkTestServer startRandomZk() {
int zkPort = incrementalPort(2181, 2281);
return startZk(zkPort);
}
protected ZkTestServer startZk(int zkPort) {
try {
logger.info(remarkableMessage("[startZK]{}"), zkPort);
ZkTestServer zkTestServer = new ZkTestServer(zkPort);
zkTestServer.initialize();
zkTestServer.start();
add(zkTestServer);
return zkTestServer;
} catch (Exception e) {
logger.error("[startZk]", e);
throw new IllegalStateException("[startZk]" + zkPort, e);
}
}
protected int getTestZkPort() {
boolean incremental = Boolean.parseBoolean(System.getProperty(KEY_INCRMENTAL_ZK_PORT, "false"));
if (incremental) {
return incrementalPort(defaultZkPort());
}
return randomPort();
}
public static int defaultZkPort() {
return 2181;
}
public static int defaultMetaServerPort() {
return 9747;
}
protected DefaultEndPoint localhostEndpoint(int port) {
return new DefaultEndPoint("localhost", port);
}
protected InetSocketAddress localhostInetAdress(int port) {
return new InetSocketAddress("localhost", port);
}
protected DefaultEndPoint localHostEndpoint(int port) {
return new DefaultEndPoint("localhost", port);
}
protected HostPort localHostport(int port) {
return new HostPort("localhost", port);
}
protected Server startEmptyServer() throws Exception {
return startServer(new IoActionFactory() {
@Override
public IoAction createIoAction(Socket socket) {
return new AbstractIoAction(socket) {
@Override
protected void doWrite(OutputStream ous, Object readResult) throws IOException {
}
@Override
protected Object doRead(InputStream ins) throws IOException {
while (true) {
int data = ins.read();
if (data == -1) {
break;
}
System.out.print((char) data);
}
return null;
}
};
}
});
}
protected Server startEchoServer() throws Exception {
return startEchoServer(randomPort(), null);
}
protected Server startEchoPrefixServer(String prefix) throws Exception {
return startEchoServer(randomPort(), prefix);
}
protected Server startEchoServer(int port) throws Exception {
return startEchoServer(port, null);
}
protected Server startEchoServer(int port, String prefix) throws Exception {
return startServer(port, new IoActionFactory() {
@Override
public IoAction createIoAction(Socket socket) {
return new AbstractIoAction(socket) {
private String line;
@Override
protected Object doRead(InputStream ins) throws IOException {
line = readLine(ins);
logger.debug("[doRead]{}", line);
logger.info("[doRead]{}", line == null ? null : line.length());
return line;
}
@Override
protected void doWrite(OutputStream ous, Object readResult) throws IOException {
String[] sp = line.split("\\s+");
if (sp.length >= 1) {
if (sp[0].equalsIgnoreCase("sleep")) {
int sleep = Integer.parseInt(sp[1]);
logger.info("[sleep]{}", sleep);
sleepIgnoreInterrupt(sleep);
}
}
logger.debug("[doWrite]{}", line.length());
logger.debug("[doWrite]{}", line);
if (prefix != null) {
ous.write(prefix.getBytes());
}
ous.write(line.getBytes());
ous.flush();
}
};
}
});
}
protected Server startServer(int serverPort, IoActionFactory ioActionFactory) throws Exception {
Server server = new Server(serverPort, ioActionFactory);
server.initialize();
server.start();
add(server);
return server;
}
protected Server startServer(IoActionFactory ioActionFactory) throws Exception {
return startServer(randomPort(), ioActionFactory);
}
protected Server startServer(int serverPort, final String expected) throws Exception {
return startServer(serverPort, new Callable<String>() {
@Override
public String call() throws Exception {
return expected;
}
});
}
protected Server startServer(int serverPort, final Callable<String> function) throws Exception {
return startServer(serverPort, new Function<String, String>() {
@Override
public String apply(String s) {
try {
return function.call();
} catch (Exception e) {
logger.error("[startServer]" + function, e);
return e.getMessage();
}
}
});
}
protected Server startServer(int serverPort, final Function<String, String> function) throws Exception {
IoActionFactory ioActionFactory = new IoActionFactory() {
@Override
public IoAction createIoAction(Socket socket) {
return new AbstractIoAction(socket) {
private String readLine = null;
@Override
protected void doWrite(OutputStream ous, Object readResult) throws IOException {
try {
String call = function.apply(readLine == null? null : readLine.trim());
if (call != null) {
ous.write(call.getBytes());
}
} catch (Exception e) {
throw new IllegalStateException("[doWrite]", e);
}
}
@Override
protected Object doRead(InputStream ins) throws IOException {
readLine = readLine(ins);
logger.info("[doRead]{}", readLine == null ? null : readLine.trim());
return readLine;
}
};
}
};
return startServer(serverPort, ioActionFactory);
}
protected Server startServer(final String result) throws Exception {
return startServer(randomPort(), result);
}
protected Server startServerWithFlexibleResult(Callable<String> result) throws Exception {
return startServer(randomPort(), result);
}
@After
public void afterAbstractTest() throws Exception {
try {
logger.info(remarkableMessage("[end test][{}]"), name.getMethodName());
LifecycleHelper.stopIfPossible(componentRegistry);
LifecycleHelper.disposeIfPossible(componentRegistry);
componentRegistry.destroy();
} catch (Exception e) {
logger.error("[afterAbstractTest]", e);
}
try {
if (deleteTestDirAfterTest()) {
deleteTestDir();
}
} catch (Exception e) {
logger.error("[afterAbstractTest][clean test dir]", e);
}
try {
doAfterAbstractTest();
} catch (Exception e) {
logger.error("[afterAbstractTest]", e);
}
System.setProperties(orginProperties);
executors.shutdownNow();
scheduled.shutdownNow();
}
private void deleteTestDir() {
File file = new File(getTestFileDir());
FileUtils.deleteQuietly(file);
}
protected boolean deleteTestDirAfterTest() {
return true;
}
protected void doAfterAbstractTest() throws Exception {
}
public static class BlockingCommand extends AbstractCommand<Void> implements RequestResponseCommand<Void> {
private int sleepTime;
private int timeout;
private volatile boolean processing = false;
public BlockingCommand(int sleepTime) {
this.sleepTime = sleepTime;
}
public boolean isProcessing() {
return processing;
}
@Override
protected void doExecute() throws Exception {
processing = true;
Thread.sleep(sleepTime);
future().setSuccess();
}
@Override
protected void doReset() {
}
@Override
public String getName() {
return getClass().getSimpleName();
}
@Override
public int getCommandTimeoutMilli() {
return timeout;
}
public BlockingCommand setTimeout(int timeout) {
this.timeout = timeout;
return this;
}
}
public static class CountingCommand extends AbstractCommand<Void> implements RequestResponseCommand<Void> {
private AtomicInteger counter;
private int sleepTime;
private int timeout;
public CountingCommand(AtomicInteger counter, int sleepTime) {
this.counter = counter;
this.sleepTime = sleepTime;
}
@Override
protected void doExecute() throws Exception {
Thread.sleep(sleepTime);
counter.incrementAndGet();
future().setSuccess();
}
@Override
protected void doReset() {
counter.decrementAndGet();
}
@Override
public String getName() {
return getClass().getSimpleName();
}
@Override
public int getCommandTimeoutMilli() {
return timeout;
}
public CountingCommand setTimeout(int timeout) {
this.timeout = timeout;
return this;
}
}
protected String getTimeoutIp() {
List<String> ipam = Lists.newArrayList("192.0.0.0", "192.0.0.1", "127.0.0.0", "10.0.0.1", "10.0.0.0");
for(String ip : ipam) {
Socket socket = new Socket();
try {
socket.connect(new InetSocketAddress(ip, 6379), 100);
} catch (IOException e) {
if(e instanceof SocketTimeoutException) {
return ip;
}
} finally {
try {
socket.close();
} catch (IOException e) {
}
}
}
return "127.0.0.2";
}
} |
package cucumber.io;
import java.io.File;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class FileResourceTest {
@Test
public void get_path_should_return_short_path_when_root_same_as_file() {
// setup
FileResource toTest = new FileResource(new File("test1/test.feature"), new File("test1/test.feature"));
// test
assertEquals("test1" + File.separator + "test.feature", toTest.getPath());
}
@Test
public void get_path_should_return_truncated_path_when_absolute_file_paths_are_input() {
// setup
FileResource toTest = new FileResource(new File("/testPath/test1"), new File("/testPath/test1/test.feature"));
// test
assertEquals("test.feature", toTest.getPath());
}
} |
package org.grouplens.lenskit.mf.funksvd;
import org.grouplens.lenskit.ItemRecommender;
import org.grouplens.lenskit.RatingPredictor;
import org.grouplens.lenskit.Recommender;
import org.grouplens.lenskit.RecommenderBuildException;
import org.grouplens.lenskit.baseline.BaselinePredictor;
import org.grouplens.lenskit.baseline.ItemUserMeanPredictor;
import org.grouplens.lenskit.baseline.UserMeanPredictor;
import org.grouplens.lenskit.core.LenskitRecommender;
import org.grouplens.lenskit.core.LenskitRecommenderEngine;
import org.grouplens.lenskit.core.LenskitRecommenderEngineFactory;
import org.grouplens.lenskit.data.dao.DAOFactory;
import org.grouplens.lenskit.data.dao.EventCollectionDAO;
import org.grouplens.lenskit.data.event.Rating;
import org.grouplens.lenskit.data.event.Ratings;
import org.grouplens.lenskit.data.snapshot.PackedPreferenceSnapshot;
import org.grouplens.lenskit.data.snapshot.PreferenceSnapshot;
import org.grouplens.lenskit.iterative.params.IterationCount;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
public class TestFunkSVDRecommenderBuild {
private DAOFactory daoFactory;
@Before
public void setup() throws RecommenderBuildException {
List<Rating> rs = new ArrayList<Rating>();
rs.add(Ratings.make(1, 5, 2));
rs.add(Ratings.make(1, 7, 4));
rs.add(Ratings.make(8, 4, 5));
rs.add(Ratings.make(8, 5, 4));
daoFactory = new EventCollectionDAO.Factory(rs);
}
private LenskitRecommenderEngine makeEngine() throws RecommenderBuildException {
LenskitRecommenderEngineFactory factory = new LenskitRecommenderEngineFactory(daoFactory);
factory.bind(PreferenceSnapshot.class).to(PackedPreferenceSnapshot.class);
factory.bind(RatingPredictor.class).to(FunkSVDRatingPredictor.class);
factory.bind(BaselinePredictor.class).to(UserMeanPredictor.class);
factory.bind(ItemRecommender.class).to(FunkSVDRecommender.class);
factory.bind(Integer.class).withQualifier(IterationCount.class).to(10);
return factory.create();
}
@Test
public void testFunkSVDRecommenderEngineCreate() throws RecommenderBuildException {
LenskitRecommenderEngine engine = makeEngine();
Recommender rec = engine.open();
try {
assertThat(rec.getRatingPredictor(),
instanceOf(FunkSVDRatingPredictor.class));
assertThat(rec.getItemRecommender(),
instanceOf(FunkSVDRecommender.class));
} finally {
rec.close();
}
}
@Test
public void testConfigSeparation() throws RecommenderBuildException {
LenskitRecommenderEngine engine = makeEngine();
LenskitRecommender rec1 = null;
LenskitRecommender rec2 = null;
try {
rec1 = engine.open();
rec2 = engine.open();
assertThat(rec1.getItemScorer(),
not(sameInstance(rec2.getItemScorer())));
assertThat(rec1.get(FunkSVDModel.class),
sameInstance(rec2.get(FunkSVDModel.class)));
} finally {
if (rec2 != null) {
rec2.close();
}
if (rec1 != null) {
rec1.close();
}
}
}
/**
* Test whether we can build a recommender without predict-time updates.
*/
@SuppressWarnings("unchecked")
@Test
public void testNoPredictUpdates() throws RecommenderBuildException {
LenskitRecommenderEngineFactory factory = new LenskitRecommenderEngineFactory(daoFactory);
factory.bind(RatingPredictor.class)
.to(FunkSVDRatingPredictor.class);
factory.bind(BaselinePredictor.class)
.to(ItemUserMeanPredictor.class);
factory.set(IterationCount.class)
.to(10);
factory.at(FunkSVDRatingPredictor.class)
.bind(FunkSVDUpdateRule.class)
.toNull();
LenskitRecommenderEngine engine = factory.create();
LenskitRecommender rec = engine.open();
try {
RatingPredictor pred = rec.getRatingPredictor();
assertThat(pred, instanceOf(FunkSVDRatingPredictor.class));
FunkSVDRatingPredictor fsvd = (FunkSVDRatingPredictor) pred;
assertThat(fsvd.getUpdateRule(),
nullValue());
} finally {
rec.close();
}
}
} |
package smallworld;
import edu.princeton.cs.In;
import edu.princeton.cs.StdIn;
import edu.princeton.cs.StdOut;
import java.util.Stack;
public class PathFinder {
// prev[v] = previous vertex on shortest path from s to v
// dist[v] = length of shortest path from s to v
private ST<String, String> prev = new ST<String, String>();
private ST<String, Integer> dist = new ST<String, Integer>();
// run BFS in graph G from given source vertex s
public PathFinder(Graph G, String s) {
// put source on the queue
Queue<String> q = new Queue<String>();
q.enqueue(s);
dist.put(s, 0);
// repeated remove next vertex v from queue and insert
// all its neighbors, provided they haven't yet been visited
while (!q.isEmpty()) {
String v = q.dequeue();
for (String w : G.adjacentTo(v)) {
if (!dist.contains(w)) {
q.enqueue(w);
dist.put(w, 1 + dist.get(v));
prev.put(w, v);
}
}
}
}
// is v reachable from the source s?
public boolean hasPathTo(String v) {
return dist.contains(v);
} // hasPathTo( String )
public boolean averageDistance(String v){
return dist.contains(v);
} //averageDistance()
// return the length of the shortest path from v to s
public int distanceTo(String v) {
if (!hasPathTo(v)) return Integer.MAX_VALUE;
return dist.get(v);
}
// return the shortest path from v to s as an Iterable
public Iterable<String> pathTo(String v) {
Stack<String> path = new Stack<String>();
while (v != null && dist.contains(v)) {
path.push(v);
v = prev.get(v);
}
return path;
}
public static void main(String[] args) {
String filename = args[0];
String delimiter = args[1];
System.out.println( filename );
System.out.println( ">" + delimiter + "<" );
In in = new In(filename);
Graph G = GraphGenerator.read(in, delimiter);
String s = args[2];
PathFinder pf = new PathFinder(G, s);
pf.report("Amy");
// pf.report( "JFK" );
// pf.report( "MCO" );
} // main( String [] )
private void report( String airport ) {
for (String v : this.pathTo(airport)) {
StdOut.println(" " + v);
}
StdOut.println("distance " + this.distanceTo(airport));
} // report( PathFinder, String )
} // PathFinder |
package com.pylonproducts.wifiwizard;
import org.apache.cordova.*;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiEnterpriseConfig;
import android.content.Context;
import android.util.Log;
public class WifiWizard extends CordovaPlugin {
private static final String ADD_NETWORK = "addNetwork";
private static final String REMOVE_NETWORK = "removeNetwork";
private static final String CONNECT_NETWORK = "connectNetwork";
private static final String DISCONNECT_NETWORK = "disconnectNetwork";
private static final String LIST_NETWORKS = "listNetworks";
private static final String TAG = "WifiWizard";
private WifiManager wifiManager;
private CallbackContext callbackContext;
@Override
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
this.wifiManager = (WifiManager) cordova.getActivity().getSystemService(Context.WIFI_SERVICE);
}
@Override
public boolean execute(String action, JSONArray data, CallbackContext callbackContext)
throws JSONException {
this.callbackContext = callbackContext;
if (!wifiManager.isWifiEnabled()) {
callbackContext.error("Wifi is not enabled.");
return false;
}
if (action.equals(ADD_NETWORK)) {
return this.addNetwork(callbackContext, data);
}
else if (action.equals(REMOVE_NETWORK)) {
return this.removeNetwork(callbackContext, data);
}
else if (action.equals(CONNECT_NETWORK)) {
return this.connectNetwork(callbackContext, data);
}
else if (action.equals(DISCONNECT_NETWORK)) {
return this.disconnectNetwork(callbackContext, data);
}
else if (action.equals(LIST_NETWORKS)) {
return this.listNetworks(callbackContext);
}
callbackContext.error("Incorrect action parameter: " + action);
return false;
}
// Them helper methods!
/**
* This methods adds a network to the list of available WiFi networks.
* If the network already exists, then it updates it.
*
* @params callbackContext A Cordova callback context.
* @params data JSON Array with [0] == SSID, [1] == password
* @return true if add successful, false if add fails
*/
private boolean addNetwork(CallbackContext callbackContext, JSONArray data) {
// Initialize the WifiConfiguration object
WifiConfiguration wifi = new WifiConfiguration();
Log.d(TAG, "WifiWizard: addNetwork entered.");
try {
String authType = data.getString(2);
// TODO: Check if network exists, if so, then do an update instead.
if (authType.equals("WPA")) {
// TODO: connect/configure for WPA
}
else if (authType.equals("WEP")) {
// TODO: connect/configure for WEP
// or not? screw wep
Log.d(TAG, "WEP unsupported.");
callbackContext.error("WEP unsupported");
return false;
}
// TODO: Add more authentications as necessary
else {
Log.d(TAG, "Wifi Authentication Type Not Supported.");
callbackContext.error("Wifi Authentication Type Not Supported: " + authType);
return false;
}
// Currently, just assuming WPA, as that is the only one that is supported.
String newSSID = data.getString(0);
wifi.SSID = newSSID;
String newPass = data.getString(1);
wifi.preSharedKey = newPass;
Log.d(TAG, "SSID: " + newSSID + ", Pass: " + newPass);
wifi.status = WifiConfiguration.Status.ENABLED;
wifi.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
wifi.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
wifi.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
wifi.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
wifi.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
wifi.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
wifiManager.addNetwork(wifi);
wifiManager.saveConfiguration();
return true;
}
catch (Exception e) {
callbackContext.error(e.getMessage());
Log.d(TAG,e.getMessage());
return false;
}
}
/**
* This method removes a network from the list of configured networks.
*
* @param callbackContext A Cordova callback context
* @param data JSON Array, with [0] being SSID to remove
* @return true if network removed, false if failed
*/
private boolean removeNetwork(CallbackContext callbackContext, JSONArray data) {
Log.d(TAG, "WifiWizard: removeNetwork entered.");
if(!validateData(data)) {
callbackContext.error("WifiWizard: removeNetwork data invalid");
Log.d(TAG, "WifiWizard: removeNetwork data invalid");
return false;
}
// TODO: Verify the type of data!
try {
String ssidToDisconnect = data.getString(0);
int networkIdToRemove = ssidToNetworkId(ssidToDisconnect);
if (networkIdToRemove > 0) {
wifiManager.removeNetwork(networkIdToRemove);
wifiManager.saveConfiguration();
callbackContext.success("Network removed.");
return true;
}
else {
callbackContext.error("Network not found.");
Log.d(TAG, "WifiWizard: Network not found, can't remove.");
return false;
}
}
catch (Exception e) {
callbackContext.error(e.getMessage());
Log.d(TAG, e.getMessage());
return false;
}
}
/**
* This method connects a network.
*
* @param callbackContext A Cordova callback context
* @param data JSON Array, with [0] being SSID to connect
* @return true if network connected, false if failed
*/
private boolean connectNetwork(CallbackContext callbackContext, JSONArray data) {
Log.d(TAG, "WifiWizard: connectNetwork entered.");
if(!validateData(data)) {
callbackContext.error("WifiWizard: connectNetwork invalid data");
Log.d(TAG, "WifiWizard: connectNetwork invalid data.");
return false;
}
String ssidToConnect = "";
try {
ssidToConnect = data.getString(0);
}
catch (Exception e) {
callbackContext.error(e.getMessage());
Log.d(TAG, e.getMessage());
return false;
}
int networkIdToConnect = ssidToNetworkId(ssidToConnect);
if (networkIdToConnect > 0) {
wifiManager.enableNetwork(networkIdToConnect, true);
callbackContext.success("Network " + ssidToConnect + " connected!");
return true;
}
else {
callbackContext.error("Network " + ssidToConnect + " not found!");
Log.d(TAG, "WifiWizard: Network not found to connect.");
return false;
}
}
/**
* This method disconnects a network.
*
* @param callbackContext A Cordova callback context
* @param data JSON Array, with [0] being SSID to connect
* @return true if network disconnected, false if failed
*/
private boolean disconnectNetwork(CallbackContext callbackContext, JSONArray data) {
Log.d(TAG, "WifiWizard: disconnectNetwork entered.");
if(!validateData(data)) {
callbackContext.error("WifiWizard: disconnectNetwork invalid data");
Log.d(TAG, "WifiWizard: disconnectNetwork invalid data");
return false;
}
String ssidToDisconnect = "";
// TODO: Verify type of data here!
try {
ssidToDisconnect = data.getString(0);
}
catch (Exception e) {
callbackContext.error(e.getMessage());
Log.d(TAG, e.getMessage());
return false;
}
int networkIdToDisconnect = ssidToNetworkId(ssidToDisconnect);
if (networkIdToDisconnect > 0) {
wifiManager.disableNetwork(networkIdToDisconnect);
callbackContext.success("Network " + ssidToDisconnect + " disconnected!");
return true;
}
else {
callbackContext.error("Network " + ssidToDisconnect + " not found!");
Log.d(TAG, "WifiWizard: Network not found to disconnect.");
return false;
}
}
/**
* This method uses the callbackContext.success method to send a JSONArray
* of the currently configured networks.
*
* @param callbackContext A Cordova callback context
* @param data JSON Array, with [0] being SSID to connect
* @return true if network disconnected, false if failed
*/
private boolean listNetworks(CallbackContext callbackContext) {
Log.d(TAG, "WifiWizard: listNetworks entered.");
List<WifiConfiguration> wifiList = wifiManager.getConfiguredNetworks();
JSONArray returnList = new JSONArray();
for (WifiConfiguration wifi : wifiList) {
returnList.put(wifi.SSID);
}
callbackContext.success(returnList);
return true;
}
/**
* This method takes a given String, searches the current list of configured WiFi
* networks, and returns the networkId for the netowrk if the SSID matches. If not,
* it returns -1.
*/
private int ssidToNetworkId(String ssid) {
List<WifiConfiguration> currentNetworks = wifiManager.getConfiguredNetworks();
int networkId = -1;
// For each network in the list, compare the SSID with the given one
for (WifiConfiguration test : currentNetworks) {
Log.d(TAG, "Looking for: " + ssid + ", found: " + test.SSID);
if (test.SSID.equals(ssid)) {
networkId = test.networkId;
}
}
return networkId;
}
private boolean validateData(JSONArray data) {
try {
if (data == null || data.get(0) == null) {
callbackContext.error("Data is null.");
return false;
}
return true;
}
catch (Exception e) {
callbackContext.error(e.getMessage());
}
return false;
}
} |
package caris.modular.handlers;
import java.util.ArrayList;
import caris.framework.basehandlers.MessageHandler;
import caris.framework.basereactions.Reaction;
import caris.framework.embedbuilders.Builder;
import caris.framework.reactions.ReactionEmbed;
import caris.framework.reactions.ReactionMessage;
import caris.framework.utilities.Logger;
import caris.framework.utilities.StringUtilities;
import caris.framework.utilities.TokenUtilities;
import sx.blah.discord.api.events.Event;
import sx.blah.discord.handle.obj.IGuild;
import sx.blah.discord.handle.obj.IUser;
import sx.blah.discord.util.EmbedBuilder;
public class TitleCardHandler extends MessageHandler {
public TitleCardHandler() {
super("Title Card Handler");
}
@Override
protected boolean isTriggered(Event event) {
return message.startsWith(">im ");
}
@Override
protected Reaction process(Event event) {
Logger.debug("TitleCard detected", 2);
ArrayList<String> tokens = TokenUtilities.parseTokens(message, new char[] {});
IUser subject = null;
for( IUser user : mrEvent.getGuild().getUsers() ) {
if( StringUtilities.equalsAnyOfIgnoreCase(tokens.get(1), user.mention(true), user.mention(false)) ) {
subject = user;
}
}
if( subject == null ) {
Logger.debug("Operation failed because no user specified", 2);
return new ReactionMessage( "**" + mrEvent.getAuthor().getDisplayName(mrEvent.getGuild()) + "**, no one answered to the call and no work found.", mrEvent.getChannel() );
} else {
Logger.debug("Response produced from " + name, 1, true);
return new ReactionEmbed((new TitleCardBuilder(subject, mrEvent.getGuild())).getEmbeds(), mrEvent.getChannel());
}
}
public class TitleCardBuilder extends Builder {
public IUser user;
public IGuild guild;
public TitleCardBuilder(IUser user, IGuild guild) {
super();
this.user = user;
this.guild = guild;
}
@Override
protected void buildEmbeds() {
embeds.add(new EmbedBuilder());
embeds.get(0).withColor(255, 157, 44);
embeds.get(0).withTitle(user.getDisplayName(guild));
embeds.get(0).withDescription(guild.getName());
embeds.get(0).withImage(user.getAvatarURL());
}
}
} |
package io.jxcore.node;
import android.content.Context;
import android.util.Log;
import com.test.thalitest.ThaliTestRunner;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Random;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
public class StreamCopyingThreadTest {
StreamCopyingThread mStreamCopyingThread;
StreamCopyingThread.Listener mListener;
Context mContext;
InputStream mInputStream;
OutputStream mOutputStream;
String mThreadName = "My test thread name";
String mResult;
String mText = "TestingText";
String lastExceptionMessage = "";
int bufferLength = 0;
ByteArrayOutputStream bOutputStream;
ArrayList<Integer> notifications;
boolean doThrowException = false;
String mTag = "StreamCopyingThreadTest";
public Thread createCheckStreamCopyingThreadIsClosed() {
return new Thread(new Runnable() {
int counter = 0;
@Override
public void run() {
boolean mIsClosed = false;
try {
Field fIsClosed = mStreamCopyingThread.getClass().getDeclaredField("mIsClosed");
fIsClosed.setAccessible(true);
mIsClosed = fIsClosed.getBoolean(mStreamCopyingThread);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
while (!mIsClosed && counter < ThaliTestRunner.counterLimit) {
try {
Thread.sleep(ThaliTestRunner.timeoutLimit);
counter++;
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
if (counter >= ThaliTestRunner.counterLimit) Log.e(mTag, "OutgoingSocketThread didn't start after 5s!");
}
});
}
@Rule
public ExpectedException thrown = ExpectedException.none();
@Before
public void setUp() throws Exception {
mResult = "Lorem ipsum dolor sit.";
notifications = new ArrayList<Integer>();
mContext = jxcore.activity.getBaseContext();
mListener = new ListenerMock();
bOutputStream = new ByteArrayOutputStream();
mInputStream = new StreamCopyingThreadInputStream(mResult);
mOutputStream = new StreamCopyingThreadOutputStream();
mStreamCopyingThread = new StreamCopyingThread(mListener, mInputStream, mOutputStream,
mThreadName);
}
@Test
public void testSetBufferSize() throws Exception {
Field mBufferSizeField = mStreamCopyingThread.getClass().getDeclaredField("mBufferSize");
mBufferSizeField.setAccessible(true);
mStreamCopyingThread.setBufferSize(512 * 8);
assertThat("The mBufferSize is properly set",
mBufferSizeField.getInt(mStreamCopyingThread),
is(512 * 8));
thrown.expect(IllegalArgumentException.class);
mStreamCopyingThread.setBufferSize(0);
thrown.expect(IllegalArgumentException.class);
mStreamCopyingThread.setBufferSize(1024 * 8 + 1);
}
@Test
public void testRun() throws Exception {
mResult = "";
bOutputStream = new ByteArrayOutputStream();
mInputStream = new StreamCopyingThreadInputStreamInfinite(mText);
mOutputStream = new StreamCopyingThreadOutputStreamInfinite();
mStreamCopyingThread = new StreamCopyingThread(mListener, mInputStream, mOutputStream,
mThreadName);
mStreamCopyingThread.start();
Thread.sleep(2000);
Thread checkClosed = createCheckStreamCopyingThreadIsClosed();
mStreamCopyingThread.close();
checkClosed.start();
checkClosed.join();
assertThat("The content of the input stream is equal to the output stream",
bOutputStream.toString(),
is(mResult));
}
@Test
public void testRunWithException() throws Exception {
doThrowException = true;
StreamCopyingThread streamCopyingThread = new StreamCopyingThread(mListener, mInputStream, mOutputStream,
mThreadName);
Thread runner = new Thread(streamCopyingThread);
runner.setName("thread test");
runner.start();
runner.join();
doThrowException = false;
assertThat("The exception is properly handled.",
lastExceptionMessage,
is("Failed to write to the output stream: Test exception."));
}
@Test
public void testRunNotify() throws Exception {
mStreamCopyingThread.setNotifyStreamCopyingProgress(true);
Thread runner = new Thread(mStreamCopyingThread);
runner.start();
runner.join();
assertThat("The content of the input stream is equal to the output stream",
bOutputStream.toString(),
is(mResult));
assertThat("The stream copying progress notifications is properly updated",
notifications.size() > 0,
is(true));
notifications.size();
}
class ListenerMock implements StreamCopyingThread.Listener {
@Override
public void onStreamCopyError(StreamCopyingThread who, String errorMessage) {
lastExceptionMessage = errorMessage;
}
@Override
public void onStreamCopySucceeded(StreamCopyingThread who, int numberOfBytes) {
notifications.add(numberOfBytes);
}
@Override
public void onStreamCopyingThreadDone(StreamCopyingThread who){
}
}
class StreamCopyingThreadInputStream extends InputStream {
ByteArrayInputStream inputStream;
StreamCopyingThreadInputStream(String s) {
inputStream = new ByteArrayInputStream(s.getBytes());
}
@Override
public int read() throws IOException {
return inputStream.read();
}
@Override
public int read(byte[] buffer) throws IOException {
return inputStream.read(buffer);
}
}
class StreamCopyingThreadInputStreamInfinite extends InputStream {
ByteArrayInputStream inputStream;
Random random = new Random();
StreamCopyingThreadInputStreamInfinite(String s) {
inputStream = new ByteArrayInputStream(s.getBytes());
bufferLength = s.length();
}
@Override
public int read() throws IOException {
inputStream.reset();
return inputStream.read();
}
@Override
public int read(byte[] buffer) throws IOException {
inputStream.reset();
try {
Thread.sleep((random.nextInt(200) + 50));
} catch (InterruptedException e) {
e.printStackTrace();
}
return inputStream.read(buffer);
}
}
class StreamCopyingThreadOutputStream extends OutputStream {
@Override
public void write(int oneByte) throws IOException {
if (doThrowException) {
throw new IOException("Test exception.");
}
bOutputStream.write(oneByte);
}
}
class StreamCopyingThreadOutputStreamInfinite extends OutputStream {
public int counter = 0;
@Override
public void write(int oneByte) throws IOException {
counter++;
if(counter % bufferLength == 0){
mResult += mText;
}
bOutputStream.write(oneByte);
}
}
} |
package org.apache.maven.doxia;
import org.apache.maven.model.DistributionManagement;
import org.apache.maven.plugin.Plugin;
import org.apache.maven.plugin.PluginExecutionRequest;
import org.apache.maven.plugin.PluginExecutionResponse;
import org.apache.maven.plugin.AbstractPlugin;
import org.apache.maven.plugin.PluginExecutionException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.wagon.ConnectionException;
import org.apache.maven.wagon.WagonUtils;
import org.apache.maven.wagon.observers.Debug;
import org.apache.maven.wagon.providers.ssh.SshCommandExecutor;
import org.apache.maven.wagon.providers.ssh.ScpWagon;
import org.apache.maven.wagon.repository.Repository;
import org.codehaus.plexus.util.FileUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* @author <a href="mailto:michal@codehaus.org">Michal Maczka</a>
* @version $Id$
* @goal deploy
* @description deploys website using scp protocol.
* First website files are packaged into zip archive,
* then archive is transfred to remote host, nextly it is un-archived.
* This method of deployment should normally be much faster
* then making file by file copy.
* @parameter name="inputDirectory"
* type="String"
* required="true"
* validator=""
* expression="#project.build.directory/site"
* description=""
* @parameter name="workingDirectory"
* type="String"
* required="true"
* validator=""
* expression="#project.build.directory"
* description=""
* @parameter name="unzipCommand"
* type="String"
* required="true"
* validator=""
* expression="unzip -o"
* description=""
* @parameter name="project"
* type="org.apache.maven.project.MavenProject"
* required="true"
* validator=""
* expression="#project"
* description=""
*/
public class ScpSiteDeployMojo
extends AbstractPlugin
{
private String inputDirectory;
private String workingDirectory;
private String unzipCommand;
private MavenProject project;
public void execute()
throws PluginExecutionException
{
File baseDir = new File( inputDirectory );
File zipFile = null;
try
{
zipFile = File.createTempFile( "site", ".zip", new File( workingDirectory ) );
}
catch ( IOException e )
{
throw new PluginExecutionException( "Cannot create site archive!", e );
}
SshCommandExecutor commandExecutor = new ScpWagon();
try
{
DistributionManagement distributionManagement = project.getDistributionManagement();
if ( distributionManagement == null )
{
String msg = "distributionManagement element is missing in the POM: "
+ project.getId();
throw new PluginExecutionException( msg );
}
if ( distributionManagement.getSite() == null )
{
String msg = "distributionManagement/repository element is missing in the POM: "
+ project.getId();
throw new PluginExecutionException( msg );
}
String url = distributionManagement.getSite().getUrl();
String id = distributionManagement.getSite().getId();
if ( url == null )
{
String msg = "distributionManagement/site/url element is missing in the POM: "
+ project.getId();
throw new PluginExecutionException( msg );
}
Repository repository = new Repository( id, url );
//@todo dirty hack to make artifact uploading work
commandExecutor.connect( repository, WagonUtils.getAuthInfo() );
String basedir = repository.getBasedir();
List files = FileUtils.getFileNames( baseDir, "**/**", "", false );
createZip( files, zipFile, baseDir );
Debug debug = new Debug();
commandExecutor.addSessionListener( debug );
commandExecutor.addTransferListener( debug );
String cmd = " mkdir -p " + basedir;
commandExecutor.executeCommand( cmd );
commandExecutor.put( zipFile, zipFile.getName() );
cmd = " cd " + basedir + ";" + unzipCommand + " " + zipFile.getName() + "\n";
commandExecutor.executeCommand( cmd );
String rmCommand = "rm " + basedir + "/" + zipFile.getName();
commandExecutor.executeCommand( rmCommand );
}
catch( Exception e )
{
throw new PluginExecutionException( "Error transfering site archive!", e );
}
finally
{
if ( commandExecutor != null )
{
try
{
commandExecutor.disconnect();
}
catch ( ConnectionException e )
{
//what to to here?
}
}
if ( !zipFile.delete() )
{
zipFile.deleteOnExit();
}
}
}
public void createZip( List files, File zipName, File basedir )
throws Exception
{
ZipOutputStream zos = new ZipOutputStream( new FileOutputStream( zipName ) );
try
{
for ( int i = 0; i < files.size(); i++ )
{
String file = (String) files.get( i );
writeZipEntry( zos, new File( basedir, file ), file );
}
}
finally
{
zos.close();
}
}
private void writeZipEntry( ZipOutputStream jar, File source, String entryName )
throws Exception
{
byte[] buffer = new byte[1024];
int bytesRead;
FileInputStream is = new FileInputStream( source );
try
{
ZipEntry entry = new ZipEntry( entryName );
jar.putNextEntry( entry );
while ( ( bytesRead = is.read( buffer ) ) != -1 )
{
jar.write( buffer, 0, bytesRead );
}
}
finally
{
is.close();
}
}
} |
package org.dozer.eclipse.plugin.editorpage.utils;
import org.dozer.eclipse.plugin.DozerMultiPageEditor;
import org.dozer.eclipse.plugin.DozerPlugin;
import org.dozer.eclipse.plugin.editorpage.Messages;
import org.eclipse.core.databinding.observable.list.IObservableList;
import org.eclipse.core.databinding.observable.value.IObservableValue;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider;
import org.eclipse.jdt.ui.IJavaElementSearchConstants;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jface.databinding.swt.SWTObservables;
import org.eclipse.jface.databinding.viewers.ObservableListContentProvider;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.viewers.AbstractListViewer;
import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.dialogs.SelectionDialog;
import org.eclipse.ui.forms.widgets.ExpandableComposite;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Section;
import org.eclipse.ui.forms.widgets.TableWrapData;
import org.eclipse.ui.forms.widgets.TableWrapLayout;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.wst.xml.core.internal.Logger;
import org.eclipse.wst.xml.core.internal.document.ElementImpl;
import org.eclipse.wst.xml.core.internal.provisional.document.IDOMDocument;
import org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel;
import org.springframework.ide.eclipse.beans.ui.editor.Activator;
import org.springframework.ide.eclipse.core.java.JdtUtils;
import org.w3c.dom.Element;
import java.util.List;
public class DozerUiUtils {
private static DozerUiUtils instance;
private IEditorInput editorInput;
private static FormToolkit toolkit;
private Image classImg = DozerPlugin.getDefault().getImageRegistry().getDescriptor(DozerPlugin.IMG_CLASS).createImage();
private Image interfaceImg = DozerPlugin.getDefault().getImageRegistry().getDescriptor(DozerPlugin.IMG_INTERFACE).createImage();
private IProject project;
private IJavaProject javaProject;
private DozerMultiPageEditor dozerEditor;
public static DozerUiUtils getInstance() {
if (instance == null)
instance = new DozerUiUtils();
return instance;
}
public IEditorInput getEditorInput() {
return editorInput;
}
public static void setToolKit(FormToolkit toolkit) {
DozerUiUtils.toolkit = toolkit;
}
public static FormToolkit getToolKit() {
return DozerUiUtils.toolkit;
}
public void setEditorInput(IEditorInput editorInput, FormToolkit toolkit) {
IEditorInput oldInput = this.editorInput;
this.editorInput = editorInput;
DozerUiUtils.setToolKit(toolkit);
if (oldInput != editorInput) {
init();
}
}
public void setMultiEditor(DozerMultiPageEditor dozerEditor) {
this.dozerEditor = dozerEditor;
}
private void init() {
project = getProject();
javaProject = JavaCore.create(project);
}
private IProject getProject() {
IFile file = null;
if (editorInput instanceof IFileEditorInput) {
file = ((IFileEditorInput) editorInput).getFile();
} else
return null; //Error
return file.getProject();
}
public String doOpenClassSelectionDialog(String superType, boolean allowInterfaces) {
IJavaSearchScope searchScope = null;
IProject project = getProject();
try {
IJavaProject javaProject = JavaCore.create(project);
if (superType != null) {
IType superTypeType = javaProject.findType(superType);
if (superTypeType != null) {
searchScope = SearchEngine.createHierarchyScope(superTypeType);
} else
return null; //Error
}
SelectionDialog dialog =
JavaUI.createTypeDialog(
DozerPlugin.getActiveWorkbenchShell(),
PlatformUI.getWorkbench().getProgressService(),
searchScope,
allowInterfaces?IJavaElementSearchConstants.CONSIDER_CLASSES_AND_INTERFACES:IJavaElementSearchConstants.CONSIDER_CLASSES,
false);
dialog.setTitle("Browse...");
if (dialog.open() == Window.OK) {
IType type = (IType) dialog.getResult()[0];
return type.getFullyQualifiedName('$');
}
} catch (Exception e) {
Logger.logException(e);
}
return null;
}
public static String nullSafeTrimString(String value) {
if (value == null)
return "";
else
return value.trim();
}
public Image getImageFromClassName(String className) {
if (className == null)
return null;
try {
IType superTypeType = javaProject.findType(className);
if (superTypeType == null)
return null;
else if (superTypeType.isInterface())
return interfaceImg;
else
return classImg;
} catch (JavaModelException e) {
Logger.logException(e);
}
return null;
}
public static Composite createComposite(Composite parent) {
return toolkit.createComposite(parent);
}
public static Label createLabel(Composite client, String messagePrefix) {
//Controls
Label label = toolkit.createLabel(client, Messages.getString(messagePrefix));
label.setToolTipText(Messages.getString(messagePrefix + "_hint")); //$NON-NLS-1$
//Format
TableWrapData td = new TableWrapData();
label.setLayoutData(td);
return label;
}
public static IObservableValue createText(Composite client, String messagePrefix) {
Text text = toolkit.createText(client, "", SWT.SINGLE); //$NON-NLS-1$
text.setBackground(new Color(Display.getCurrent(), 255,255,255));
text.setToolTipText(Messages.getString(messagePrefix + "_hint")); //$NON-NLS-1$
//Format
TableWrapData td = new TableWrapData(TableWrapData.FILL_GRAB);
text.setLayoutData(td);
return SWTObservables.observeText(text, SWT.Modify);
}
public static IObservableValue createLabelCheckbox(Composite client, String messagePrefix) {
createLabel(client, messagePrefix);
Button checkbox = toolkit.createButton(client, "", SWT.CHECK);
checkbox.setToolTipText(Messages.getString(messagePrefix + "_hint")); //$NON-NLS-1$
checkbox.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
//Format
TableWrapData td = new TableWrapData(TableWrapData.FILL_GRAB);
checkbox.setLayoutData(td);
return SWTObservables.observeSelection(checkbox);
}
public static IObservableValue createLabelText(Composite client, String messagePrefix) {
createLabel(client, messagePrefix);
return createText(client, messagePrefix);
}
public static IObservableValue createLabelCombo(Composite client, String messagePrefix, String[] values) {
createLabel(client, messagePrefix);
return createCombo(client, messagePrefix, values);
}
public static IObservableValue createCombo(Composite client, String messagePrefix, String[] values) {
CCombo combo = new CCombo(client, SWT.DROP_DOWN | SWT.READ_ONLY
| SWT.FLAT | SWT.BORDER);
for (String value : values) {
combo.add(value);
}
toolkit.adapt(combo);
toolkit.paintBordersFor(combo);
combo.setToolTipText(Messages.getString(messagePrefix + "_hint")); //$NON-NLS-1$
//Format
TableWrapData td = new TableWrapData();
combo.setLayoutData(td);
return SWTObservables.observeSelection(combo);
}
public static IObservableValue createLabelClassBrowse(Composite client, String messagePrefix, final String superType, final boolean allowInterfaces) {
createLabel(client, messagePrefix);
Composite tableClient = toolkit.createComposite(client, SWT.WRAP);
TableWrapLayout layout = new TableWrapLayout();
layout.bottomMargin=0;
layout.leftMargin=0;
layout.rightMargin=0;
layout.topMargin=0;
layout.numColumns = 2;
tableClient.setLayout(layout);
final IObservableValue text = DozerUiUtils.createText(tableClient, messagePrefix);
Button browseBtn = toolkit.createButton(tableClient, "Browse...", SWT.PUSH);
browseBtn.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
String className = DozerUiUtils.getInstance().doOpenClassSelectionDialog(superType, allowInterfaces);
if (className != null) {
text.setValue(className);
}
}
});
TableWrapData td = new TableWrapData();
browseBtn.setLayoutData(td);
td = new TableWrapData(TableWrapData.FILL_GRAB);
tableClient.setLayoutData(td);
return text;
}
public static AbstractListViewer createLabelFieldCombobox(Composite client, String messagePrefix) {
createLabel(client, messagePrefix);
final CCombo combo = new CCombo(client, SWT.FLAT | SWT.BORDER);
TableWrapData td = new TableWrapData();
td.grabHorizontal = true;
//td.maxWidth = 400;
combo.setLayoutData(td);
toolkit.adapt(combo);
toolkit.paintBordersFor(combo);
combo.setToolTipText(Messages.getString(messagePrefix + "_hint")); //$NON-NLS-1$
final ComboViewer comboViewer = new ComboViewer(combo);
//Add Focus-Lost Listener so that the entered text gets converted to a IField and gets selected.
//This way the databinding works
combo.addFocusListener(new FocusListener() {
private StringToFieldConverter converter = new StringToFieldConverter(null, comboViewer);
public void focusGained(FocusEvent e) {}
public void focusLost(FocusEvent e) {
//already selected (due to combobox select)
if (!comboViewer.getSelection().isEmpty())
return;
converter.setExistingFields((List<IField>)comboViewer.getInput());
Object convertedText = converter.convert(combo.getText());
comboViewer.setSelection(new StructuredSelection(convertedText));
}
});
comboViewer.setContentProvider(new ObservableListContentProvider());
comboViewer.setLabelProvider(new LabelProvider() {
@Override
public Image getImage(Object element) {
//FIXME never gets invoced, as a CCombo only shows text
IMethod method = (IMethod)element;
Image image = null;
try {
image = Activator.getDefault().getJavaElementLabelProvider().getImageLabel(
method, method.getFlags() | JavaElementImageProvider.SMALL_ICONS);
} catch (Exception e) {
Logger.logException(e);
}
return image;
}
@Override
public String getText(Object element) {
IField field = (IField)element;
StringBuilder buf = new StringBuilder();
//Copied from org.springframework.ide.eclipse.beans.ui.editor.contentassist.MethodContentAssistCalculator
String fieldName = field.getElementName();
// add method name
String replaceText = fieldName;
buf.append(replaceText);
String displayText = buf.toString();
return displayText;
}
});
return comboViewer;
}
public static AbstractListViewer createLabelMethodCombobox(Composite client, String messagePrefix) {
createLabel(client, messagePrefix);
final CCombo combo = new CCombo(client, SWT.FLAT | SWT.BORDER);
TableWrapData td = new TableWrapData();
td.grabHorizontal = true;
//td.maxWidth = 400;
combo.setLayoutData(td);
toolkit.adapt(combo);
toolkit.paintBordersFor(combo);
combo.setToolTipText(Messages.getString(messagePrefix + "_hint")); //$NON-NLS-1$
final ComboViewer comboViewer = new ComboViewer(combo);
//Add Focus-Lost Listener so that the entered text gets converted to a IMethod and gets selected.
//This way the databinding works
combo.addFocusListener(new FocusListener() {
private StringToMethodConverter converter = new StringToMethodConverter(null, comboViewer);
public void focusGained(FocusEvent e) {}
public void focusLost(FocusEvent e) {
//already selected (due to combobox select)
if (!comboViewer.getSelection().isEmpty())
return;
converter.setExistingMethods((List<IMethod>)comboViewer.getInput());
Object convertedText = converter.convert(combo.getText());
comboViewer.setSelection(new StructuredSelection(convertedText));
}
});
comboViewer.setContentProvider(new ObservableListContentProvider());
comboViewer.setLabelProvider(new LabelProvider() {
@Override
public Image getImage(Object element) {
//FIXME never gets invoced, as a CCombo only shows text
IMethod method = (IMethod)element;
Image image = null;
try {
image = Activator.getDefault().getJavaElementLabelProvider().getImageLabel(
method, method.getFlags() | JavaElementImageProvider.SMALL_ICONS);
} catch (Exception e) {
Logger.logException(e);
}
return image;
}
@Override
public String getText(Object element) {
IMethod method = (IMethod)element;
StringBuilder buf = new StringBuilder();
//Copied from org.springframework.ide.eclipse.beans.ui.editor.contentassist.MethodContentAssistCalculator
String methodName = method.getElementName();
// add method name
String replaceText = methodName;
buf.append(replaceText);
String[] parameterNames = new String[]{"?"};
String[] parameterTypes = new String[]{"?"};
String className = "?";
String returnType = "?";
try {
parameterNames = method.getParameterNames();
parameterTypes = JdtUtils.getParameterTypesString(method);
returnType = JdtUtils.getReturnTypeString(method, true);
className = method.getParent().getElementName();
} catch (JavaModelException e) {
//do nothing
}
// add method parameters
if (parameterTypes.length > 0 && parameterNames.length > 0) {
buf.append(" (");
for (int i = 0; i < parameterTypes.length; i++) {
buf.append(parameterTypes[i]);
buf.append(' ');
buf.append(parameterNames[i]);
if (i < (parameterTypes.length - 1)) {
buf.append(", ");
}
}
buf.append(") ");
}
else {
buf.append("() ");
}
// add return type
if (returnType != null) {
buf.append(Signature.getSimpleName(returnType));
buf.append(" - ");
}
else {
buf.append(" void - ");
}
// add class name
buf.append(className);
String displayText = buf.toString();
return displayText;
}
});
return comboViewer;
}
public static TableViewerSelectionListener createAddClassSelectionListener(
IDOMModel model,
final String elementName,
final String lookupClass) {
TableViewerSelectionListener listener = new TableViewerSelectionListener(model) {
@Override
protected void invoceSelected(Object selected) {
final String className = DozerUiUtils.getInstance().doOpenClassSelectionDialog(lookupClass, true);
if (className != null) {
BusyIndicator.showWhile(
Display.getCurrent(),
new Runnable() {
public void run() {
Element element = getModel().getDocument().createElement(elementName);
org.eclipse.core.dom.utils.DOMUtils.setTextContent(element, className);
IObservableList values = (IObservableList)getTableViewer().getInput();
values.add(element);
}
});
}
}
};
return listener;
}
public static TableViewerSelectionListener createDeleteSelectionListener(IDOMModel model) {
TableViewerSelectionListener listener = new TableViewerSelectionListener(model) {
@Override
protected void invoceSelected(Object selected) {
Element selection = (Element)selected;
Element parentNode = (Element)selection.getParentNode();
IObservableList values = (IObservableList)getTableViewer().getInput();
values.remove(selection);
//if last node had been deleted, delete parent
if (DOMUtils.getElements(parentNode).length == 0) {
Element parentParentNode = (Element)parentNode.getParentNode();
parentNode.getParentNode().removeChild(parentNode);
if (DOMUtils.getElements(parentParentNode).length == 0) {
parentParentNode.getParentNode().removeChild(parentParentNode);
}
}
}
};
return listener;
}
public static Section createTwistieSection(
Composite parentClient,
String messagePrefix) {
Section section = toolkit.createSection(parentClient,
ExpandableComposite.TITLE_BAR |
ExpandableComposite.TWISTIE);
section.setText(Messages.getString(messagePrefix));
section.setDescriptionControl(toolkit.createLabel(section, Messages.getString(messagePrefix+"_sdesc")));
section.setExpanded(true);
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
gd.verticalAlignment = SWT.BEGINNING;
section.setLayoutData(gd);
return section;
}
/**
* Highlights the given element in the sourceview of the document
*
* @param element The element that should be highlighted
*/
public void jumpToElement(Element element) {
ElementImpl elementImpl = (ElementImpl)element;
dozerEditor.getSourceEditor().setHighlightRange(elementImpl.getStartOffset()+1, elementImpl.getLength(), true);
dozerEditor.changeToSourcePage();
}
public IDOMDocument getDomDocument(ITextEditor editor) {
IDocument document = editor.getDocumentProvider().getDocument(editorInput);
IDOMModel sModel = (IDOMModel)org.eclipse.wst.sse.core.StructuredModelManager.getModelManager().getExistingModelForRead(document);
return sModel.getDocument();
}
} |
package org.eclipse.mylar.bugzilla.core;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import javax.security.auth.login.LoginException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.mylar.bugzilla.core.internal.BugParser;
import org.eclipse.mylar.bugzilla.core.internal.NewBugParser;
import org.eclipse.mylar.bugzilla.core.internal.ProductParser;
import org.eclipse.mylar.bugzilla.core.offline.OfflineReportsFile;
/**
* Singleton class that creates <code>BugReport</code> objects by fetching
* bug's state and contents from the Bugzilla server.
*
* @author Mik Kersten (hardening of initial prototype)
*/
public class BugzillaRepository
{
/**
* Test method.
*/
public static void main(String[] args) throws Exception {
instance =
new BugzillaRepository(BugzillaPlugin.getDefault().getServerName() + "/long_list.cgi?buglist=");
BugReport bug = instance.getBug(16161);
System.out.println("Bug " + bug.getId() + ": " + bug.getSummary());
for (Iterator<Attribute> it = bug.getAttributes().iterator(); it.hasNext();) {
Attribute attribute = it.next();
System.out.println(attribute.getName() + ": " + attribute.getValue());
}
System.out.println(bug.getDescription());
for (Iterator<Comment> it = bug.getComments().iterator(); it.hasNext();) {
Comment comment = it.next();
System.out.println(comment.getAuthorName() + "<" + comment.getAuthor() + "> (" + comment.getCreated() + ")");
System.out.print(comment.getText());
System.out.println();
}
}
/** URL of the Bugzilla server */
private static String bugzillaUrl;
/** singleton instance */
private static BugzillaRepository instance;
/**
* Constructor
* @param bugzillaUrl - the url of the bugzilla repository
*/
private BugzillaRepository(String bugzillaUrl)
{
BugzillaRepository.bugzillaUrl = bugzillaUrl;
}
/**
* Get the singleton instance of the <code>BugzillaRepository</code>
* @return The instance of the repository
*/
public synchronized static BugzillaRepository getInstance()
{
if (instance == null)
{
// if the instance hasn't been created yet, create one
instance = new BugzillaRepository(
BugzillaPlugin.getDefault().getServerName());
}
// fix bug 58 by updating url if it changes
if(! BugzillaRepository.bugzillaUrl.equals(BugzillaPlugin.getDefault().getServerName()))
{
BugzillaRepository.bugzillaUrl = BugzillaPlugin.getDefault().getServerName();
}
return instance;
}
/**
* Get a bug from the server
* @param id - the id of the bug to get
* @return - a <code>BugReport</code> for the selected bug or null if it doesn't exist
* @throws IOException
*/
public BugReport getBug(int id) throws IOException, MalformedURLException, LoginException
{
BufferedReader in = null;
try {
// create a new input stream for getting the bug
String url = bugzillaUrl + "/show_bug.cgi?id=" + id;
// allow the use to only see the operations that they can do to a bug if they have
// their user name and password in the preferences
if(BugzillaPreferencePage.getUserName() != null && !BugzillaPreferencePage.getUserName().equals("") && BugzillaPreferencePage.getPassword() != null && !BugzillaPreferencePage.getPassword().equals(""))
{
/*
* The UnsupportedEncodingException exception for
* URLEncoder.encode() should not be thrown, since every
* implementation of the Java platform is required to support
* the standard charset "UTF-8"
*/
url += "&GoAheadAndLogIn=1&Bugzilla_login=" + URLEncoder.encode(BugzillaPreferencePage.getUserName(), "UTF-8") + "&Bugzilla_password=" + URLEncoder.encode(BugzillaPreferencePage.getPassword(), "UTF-8");
}
URL bugUrl = new URL(url);
URLConnection cntx = BugzillaPlugin.getDefault().getUrlConnection(bugUrl);
if(cntx != null){
InputStream input = cntx.getInputStream();
if(input != null) {
in = new BufferedReader(new InputStreamReader(input));
// get the actual bug fron the server and return it
BugReport bug = BugParser.parseBug(in, id, BugzillaPlugin.getDefault().getServerName(), BugzillaPlugin.getDefault().isServerCompatability218(), BugzillaPreferencePage.getUserName(), BugzillaPreferencePage.getPassword());
return bug;
}
}
// TODO handle the error
return null;
}
catch (MalformedURLException e) {
throw e;
}
catch (IOException e) {
throw e;
}
catch(LoginException e)
{
throw e;
}
catch(Exception e) {
// throw an exception if there is a problem reading the bug from the server
// e.printStackTrace();
// throw new IOException(e.getMessage());
BugzillaPlugin.log(new Status(
IStatus.ERROR,
IBugzillaConstants.PLUGIN_ID,
IStatus.ERROR,
"Problem getting report",
e));
return null;
} finally {
try {
if(in != null) in.close();
} catch(IOException e) {
BugzillaPlugin.log(new Status(IStatus.ERROR, IBugzillaConstants.PLUGIN_ID,IStatus.ERROR,"Problem closing the stream", e));
}
}
}
/**
* Get a bug from the server.
* If a bug with the given id is saved offline, the offline version is returned instead.
* @param id - the id of the bug to get
* @return - a <code>BugReport</code> for the selected bug or null if it doesn't exist
* @throws IOException, MalformedURLException, LoginException
*/
public BugReport getCurrentBug(int id) throws MalformedURLException, LoginException, IOException {
// Look among the offline reports for a bug with the given id.
OfflineReportsFile reportsFile = BugzillaPlugin.getDefault().getOfflineReports();
int offlineId = reportsFile.find(id);
// If an offline bug was found, return it if possible.
if (offlineId != -1) {
IBugzillaBug bug = reportsFile.elements().get(offlineId);
if (bug instanceof BugReport) {
return (BugReport)bug;
}
}
// If a suitable offline report was not found, try to get one from the server.
return getBug(id);
}
/**
* Get the list of products when creating a new bug
* @return The list of valid products a bug can be logged against
* @throws IOException
*/
public List<String> getProductList() throws IOException, LoginException, Exception
{
BufferedReader in = null;
try
{
// connect to the bugzilla server
String urlText = "";
// use the usename and password to get into bugzilla if we have it
if(BugzillaPreferencePage.getUserName() != null && !BugzillaPreferencePage.getUserName().equals("") && BugzillaPreferencePage.getPassword() != null && !BugzillaPreferencePage.getPassword().equals(""))
{
/*
* The UnsupportedEncodingException exception for
* URLEncoder.encode() should not be thrown, since every
* implementation of the Java platform is required to support
* the standard charset "UTF-8"
*/
urlText += "?GoAheadAndLogIn=1&Bugzilla_login=" + URLEncoder.encode(BugzillaPreferencePage.getUserName(), "UTF-8") + "&Bugzilla_password=" + URLEncoder.encode(BugzillaPreferencePage.getPassword(), "UTF-8");
}
URL url = new URL(bugzillaUrl + "/enter_bug.cgi" + urlText);
URLConnection cntx = BugzillaPlugin.getDefault().getUrlConnection(url);
if(cntx != null){
InputStream input = cntx.getInputStream();
if(input != null) {
// create a new input stream for getting the bug
in = new BufferedReader(new InputStreamReader(input));
return new ProductParser(in).getProducts();
}
}
return null;
}
finally
{
try{
if(in != null)
in.close();
}catch(IOException e)
{
BugzillaPlugin.log(new Status(IStatus.ERROR, IBugzillaConstants.PLUGIN_ID,IStatus.ERROR,"Problem closing the stream", e));
}
}
}
/**
* Get the attribute values for a new bug
* @param nbm A reference to a NewBugModel to store all of the data
* @throws Exception
*/
public void getnewBugAttributes(NewBugModel nbm, boolean getProd) throws Exception
{
BufferedReader in = null;
try
{
// create a new input stream for getting the bug
String prodname = URLEncoder.encode(nbm.getProduct(), "UTF-8");
String url = bugzillaUrl + "/enter_bug.cgi";
// use the proper url if we dont know the product yet
if(!getProd)
url += "?product=" + prodname + "&";
else
url += "?";
// add the password and username to the url so that bugzilla logs us in
/*
* The UnsupportedEncodingException exception for
* URLEncoder.encode() should not be thrown, since every
* implementation of the Java platform is required to support
* the standard charset "UTF-8"
*/
url += "&GoAheadAndLogIn=1&Bugzilla_login=" + URLEncoder.encode(BugzillaPreferencePage.getUserName(), "UTF-8") + "&Bugzilla_password=" + URLEncoder.encode(BugzillaPreferencePage.getPassword(), "UTF-8");
URL bugUrl = new URL(url);
URLConnection cntx = BugzillaPlugin.getDefault().getUrlConnection(bugUrl);
if(cntx != null){
InputStream input = cntx.getInputStream();
if(input != null) {
in = new BufferedReader(new InputStreamReader(input));
new NewBugParser(in).parseBugAttributes(nbm, getProd);
}
}
} catch(Exception e) {
if ( e instanceof KeyManagementException || e instanceof NoSuchAlgorithmException || e instanceof IOException ){
if(MessageDialog.openQuestion(null, "Bugzilla Connect Error", "Unable to connect to Bugzilla server.\n" +
"Bug report will be created offline and saved for submission later.")){
nbm.setConnected(false);
getProdConfigAttributes(nbm);
}
else
throw new Exception("Bug report will not be created.");
}
else
throw e;
}
finally
{
try{
if(in != null)
in.close();
}catch(IOException e)
{
BugzillaPlugin.log(new Status(IStatus.ERROR, IBugzillaConstants.PLUGIN_ID,IStatus.ERROR,"Problem closing the stream", e));
}
}
}
/**
* Get the bugzilla url that the repository is using
* @return A <code>String</code> containing the url of the bugzilla server
*/
public static String getURL()
{
return bugzillaUrl;
}
/** Method to get attributes from ProductConfiguration if unable to connect
* to Bugzilla server
* @param model - the NewBugModel to store the attributes
*/
public void getProdConfigAttributes(NewBugModel model){
HashMap<String, Attribute> attributes = new HashMap<String, Attribute>();
// ATTRIBUTE: Severity
Attribute a = new Attribute("Severity");
a.setParameterName("bug_severity");
// get optionValues from ProductConfiguration
String[] optionValues = BugzillaPlugin.getDefault().getProductConfiguration().getSeverities();
// add option values from ProductConfiguration to Attribute optionValues
for( int i=0; i<optionValues.length; i++ ){
a.addOptionValue(optionValues[i], optionValues[i]);
}
// add Attribute to model
attributes.put("severites", a);
// ATTRIBUTE: OS
a = new Attribute("OS");
a.setParameterName("op_sys");
optionValues = BugzillaPlugin.getDefault().getProductConfiguration().getOSs();
for( int i=0; i<optionValues.length; i++ ){
a.addOptionValue(optionValues[i], optionValues[i]);
}
attributes.put("OSs", a);
// ATTRIBUTE: Platform
a = new Attribute("Platform");
a.setParameterName("rep_platform");
optionValues = BugzillaPlugin.getDefault().getProductConfiguration().getPlatforms();
for( int i=0; i<optionValues.length; i++ ){
a.addOptionValue(optionValues[i], optionValues[i]);
}
attributes.put("platforms",a);
// ATTRIBUTE: Version
a = new Attribute("Version");
a.setParameterName("version");
optionValues = BugzillaPlugin.getDefault().getProductConfiguration().getVersions(model.getProduct());
for( int i=0; i<optionValues.length; i++ ){
a.addOptionValue(optionValues[i], optionValues[i]);
}
attributes.put("versions", a);
// ATTRIBUTE: Component
a = new Attribute("Component");
a.setParameterName("component");
optionValues = BugzillaPlugin.getDefault().getProductConfiguration().getComponents(model.getProduct());
for( int i=0; i<optionValues.length; i++ ){
a.addOptionValue(optionValues[i], optionValues[i]);
}
attributes.put("components", a);
// ATTRIBUTE: Priority
a = new Attribute("Priority");
a.setParameterName("bug_severity");
optionValues = BugzillaPlugin.getDefault().getProductConfiguration().getPriorities();
for( int i=0; i<optionValues.length; i++ ){
a.addOptionValue(optionValues[i], optionValues[i]);
}
// set NBM Attributes (after all Attributes have been created, and added to attributes map)
model.attributes = attributes;
}
public static String getBugUrl(int id) {
String url = BugzillaPlugin.getDefault().getServerName() + "/show_bug.cgi?id=" + id;
try {
if (BugzillaPreferencePage.getUserName() != null
&& !BugzillaPreferencePage.getUserName().equals("")
&& BugzillaPreferencePage.getPassword() != null
&& !BugzillaPreferencePage.getPassword().equals("")) {
url += "&GoAheadAndLogIn=1&Bugzilla_login="
+ URLEncoder.encode(BugzillaPreferencePage.getUserName(), "UTF-8")
+ "&Bugzilla_password="
+ URLEncoder.encode(BugzillaPreferencePage.getPassword(),"UTF-8");
}
} catch (UnsupportedEncodingException e) {
return "";
}
return url;
}
public static String getBugUrlWithoutLogin(int id) {
String url = BugzillaPlugin.getDefault().getServerName() + "/show_bug.cgi?id=" + id;
return url;
}
} |
package org.eclipse.mylar.internal.tasks.ui.util;
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.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.mylar.context.core.MylarStatusHandler;
import org.eclipse.mylar.tasks.core.AbstractRepositoryQuery;
import org.eclipse.mylar.tasks.core.AbstractTaskContainer;
import org.eclipse.mylar.tasks.core.DelegatingTaskExternalizer;
import org.eclipse.mylar.tasks.core.ITask;
import org.eclipse.mylar.tasks.core.ITaskListExternalizer;
import org.eclipse.mylar.tasks.core.TaskExternalizationException;
import org.eclipse.mylar.tasks.core.TaskList;
import org.eclipse.mylar.tasks.ui.TasksUiPlugin;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* @author Mik Kersten
* @author Ken Sueda
*/
public class TaskListWriter {
// Last number given to new local task
public static final String ATTRIBUTE_LAST_NUM = "LastNum";
public static final String ATTRIBUTE_VERSION = "Version";
public static final String ELEMENT_TASK_LIST = "TaskList";
private static final String VALUE_VERSION = "1.0.1";
private static final String VALUE_VERSION_1_0_0 = "1.0.0";
private static final String FILE_SUFFIX_SAVE = "save.xml";
private List<ITaskListExternalizer> externalizers;
private DelegatingTaskExternalizer delagatingExternalizer = new DelegatingTaskExternalizer();
private List<Node> orphanedTaskNodes = new ArrayList<Node>();
private String readVersion = "";
private boolean hasCaughtException = false;
public void setDelegateExternalizers(List<ITaskListExternalizer> externalizers) {
this.externalizers = externalizers;
this.delagatingExternalizer.setDelegateExternalizers(externalizers);
}
public void writeTaskList(TaskList taskList, File outFile) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db;
Document doc = null;
try {
db = dbf.newDocumentBuilder();
doc = db.newDocument();
} catch (ParserConfigurationException e) {
MylarStatusHandler.log(e, "could not create document");
}
Element root = doc.createElement(ELEMENT_TASK_LIST);
root.setAttribute(ATTRIBUTE_VERSION, VALUE_VERSION);
root.setAttribute(ATTRIBUTE_LAST_NUM, "" + taskList.getLastTaskNum());
// create the categories
for (AbstractTaskContainer category : taskList.getCategories()) {
// if (!category.getHandleIdentifier().equals(TaskArchive.HANDLE)) {
delagatingExternalizer.createCategoryElement(category, doc, root);
}
for (AbstractRepositoryQuery query : taskList.getQueries()) {
Element element = null;
try {
for (ITaskListExternalizer externalizer : externalizers) {
if (externalizer.canCreateElementFor(query))
element = externalizer.createQueryElement(query, doc, root);
}
if (element == null && delagatingExternalizer.canCreateElementFor(query)) {
delagatingExternalizer.createQueryElement(query, doc, root);
}
} catch (Throwable t) {
MylarStatusHandler.fail(t, "Did not externalize: " + query.getSummary(), true);
}
if (element == null) {
MylarStatusHandler.log("Did not externalize: " + query, this);
}
}
// Collection<ITask> allTasks =
// Collections.synchronizedCollection(taskList.getAllTasks());
// synchronized (allTasks) {
for (ITask task : new ArrayList<ITask>(taskList.getAllTasks())) {
createTaskElement(doc, root, task);
}
for (Node orphanedTaskNode : orphanedTaskNodes) {
Node tempNode = doc.importNode(orphanedTaskNode, true);
if (tempNode != null) {
root.appendChild(tempNode);
}
}
doc.appendChild(root);
writeDOMtoFile(doc, outFile);
return;
}
private void createTaskElement(Document doc, Element root, ITask task) {
try {
Element element = null;
for (ITaskListExternalizer externalizer : externalizers) {
if (externalizer.canCreateElementFor(task)) {
element = externalizer.createTaskElement(task, doc, root);
break;
}
}
if (element == null) {
// delagatingExternalizer.canCreateElementFor(task))
delagatingExternalizer.createTaskElement(task, doc, root);
} else if (element == null) {
MylarStatusHandler.log("Did not externalize: " + task, this);
}
} catch (Exception e) {
MylarStatusHandler.log(e, e.getMessage());
}
}
/**
* Writes an XML file from a DOM.
*
* doc - the document to write file - the file to be written to
*/
private void writeDOMtoFile(Document doc, File file) {
try {
ZipOutputStream outputStream = new ZipOutputStream(new FileOutputStream(file));
ZipEntry zipEntry = new ZipEntry(TasksUiPlugin.OLD_TASK_LIST_FILE);
outputStream.putNextEntry(zipEntry);
outputStream.setMethod(ZipOutputStream.DEFLATED);
// OutputStream outputStream = new FileOutputStream(file);
writeDOMtoStream(doc, outputStream);
outputStream.flush();
outputStream.closeEntry();
outputStream.close();
} catch (Exception fnfe) {
MylarStatusHandler.log(fnfe, "TaskList could not be found");
}
}
/**
* Writes the provided XML document out to the specified output stream.
*
* doc - the document to be written outputStream - the stream to which the
* document is to be written
*/
private void writeDOMtoStream(Document doc, OutputStream outputStream) {
// Prepare the DOM document for writing
// DOMSource - Acts as a holder for a transformation Source tree in the
// form of a Document Object Model (DOM) tree
Source source = new DOMSource(doc);
// StreamResult - Acts as an holder for a XML transformation result
// Prepare the output stream
Result result = new StreamResult(outputStream);
// An instance of this class can be obtained with the
// TransformerFactory.newTransformer method. This instance may
// then be used to process XML from a variety of sources and write
// the transformation output to a variety of sinks
Transformer xformer = null;
try {
xformer = TransformerFactory.newInstance().newTransformer();
// Transform the XML Source to a Result
xformer.transform(source, result);
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerFactoryConfigurationError e) {
e.printStackTrace();
} catch (TransformerException e1) {
e1.printStackTrace();
}
}
/**
* TODO: fix this old mess
*/
public void readTaskList(TaskList taskList, File inFile) {
hasCaughtException = false;
orphanedTaskNodes.clear();
try {
if (!inFile.exists())
return;
Document doc = openAsDOM(inFile);
if (doc == null) {
handleException(inFile, null, new TaskExternalizationException("TaskList was not well formed XML"));
return;
}
Element root = doc.getDocumentElement();
readVersion = root.getAttribute(ATTRIBUTE_VERSION);
String lastNum = root.getAttribute(ATTRIBUTE_LAST_NUM);
if (lastNum != null && !lastNum.equals("")) {
taskList.setLastTaskNum(Integer.parseInt(lastNum));
}
if (readVersion.equals(VALUE_VERSION_1_0_0)) {
MylarStatusHandler.log("version: " + readVersion + " not supported", this);
} else {
NodeList list = root.getChildNodes();
// NOTE: order is important, first read the categories
for (int i = 0; i < list.getLength(); i++) {
Node child = list.item(i);
try {
if (child.getNodeName().endsWith(DelegatingTaskExternalizer.KEY_CATEGORY)) {
delagatingExternalizer.readCategory(child, taskList);
}
} catch (Exception e) {
handleException(inFile, child, e);
}
}
// then read the tasks
for (int i = 0; i < list.getLength(); i++) {
Node child = list.item(i);
try {
boolean wasRead = false;
if (!child.getNodeName().endsWith(DelegatingTaskExternalizer.KEY_CATEGORY)
&& !child.getNodeName().endsWith(DelegatingTaskExternalizer.KEY_QUERY)) {
for (ITaskListExternalizer externalizer : externalizers) {
if (!wasRead && externalizer.canReadTask(child)) {
externalizer.readTask(child, taskList, null, null);
wasRead = true;
}
}
if (!wasRead && delagatingExternalizer.canReadTask(child)) {
delagatingExternalizer.readTask(child, taskList, null, null);
wasRead = true;
}
if (!wasRead) {
orphanedTaskNodes.add(child);
}
}
} catch (Exception e) {
// TODO: Save orphans here too?
// If data is source of exception then error will just
// repeat
// now that orphans are re-saved upon task list save. So
// for now we
// log the error warning the user and make a copy of the
// bad tasklist.
handleException(inFile, child, e);
}
}
// then query hits hits, which get corresponded to tasks
for (int i = 0; i < list.getLength(); i++) {
Node child = list.item(i);
try {
if (child.getNodeName().endsWith(DelegatingTaskExternalizer.KEY_QUERY)) {
for (ITaskListExternalizer externalizer : externalizers) {
if (externalizer.canReadQuery(child)) {
AbstractRepositoryQuery query = externalizer.readQuery(child, taskList);
if (query != null) {
taskList.internalAddQuery(query);
}
break;
}
}
}
} catch (Exception e) {
handleException(inFile, child, e);
}
}
// Migration 0.7.0.1 -> 0.8.0
// last task number field wasn't in tasklist.xml
if (lastNum == null || lastNum.equals("")) {
int largest = taskList.findLargestTaskHandle();
taskList.setLastTaskNum(largest);
}
}
} catch (Exception e) {
handleException(inFile, null, e);
}
if (hasCaughtException) {
// if exception was caught, write out the new task file, so that it
// doesn't happen again.
// this is OK, since the original (corrupt) tasklist is saved.
// TODO: The problem with this is that if the orignal tasklist has
// tasks and bug reports, but a
// task is corrupted, the new tasklist that is written will not
// include the bug reports (since the
// bugzilla externalizer is not loaded. So there is a potentila that
// we can lose bug reports.
writeTaskList(taskList, inFile);
}
}
/**
* Opens the specified XML file and parses it into a DOM Document.
*
* Filename - the name of the file to open Return - the Document built from
* the XML file Throws - XMLException if the file cannot be parsed as XML -
* IOException if the file cannot be opened
*/
private Document openAsDOM(File inputFile) throws IOException {
// A factory API that enables applications to obtain a parser
// that produces DOM object trees from XML documents
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// Using DocumentBuilder, obtain a Document from XML file.
DocumentBuilder builder = null;
Document document = null;
try {
// create new instance of DocumentBuilder
builder = factory.newDocumentBuilder();
} catch (ParserConfigurationException pce) {
inputFile.renameTo(new File(inputFile.getName() + FILE_SUFFIX_SAVE));
MylarStatusHandler.log(pce, "Failed to load XML file");
}
try {
// Parse the content of the given file as an XML document
// and return a new DOM Document object. Also throws IOException
InputStream inputStream = null;
if (inputFile.getName().endsWith(TasksUiPlugin.DEFAULT_TASK_LIST_FILE)) {
// is zipped context
inputStream = new ZipInputStream(new FileInputStream(inputFile));
((ZipInputStream) inputStream).getNextEntry();
} else {
inputStream = new FileInputStream(inputFile);
}
document = builder.parse(inputStream);
// document = builder.parse(inputFile);
} catch (SAXException se) {
// TODO: Use TaskListBackupManager to attempt restore from backup
MessageDialog
.openWarning(null, "Mylar task list corrupt",
"Unable to read the Mylar task list. Please restore from backup via File > Import > Mylar Task Data");
// String message = "Restoring the tasklist failed. Would you like
// to attempt to restore from the backup?\n\nTasklist XML File
// location: "
// + inputFile.getAbsolutePath()
// + "\n\nBackup tasklist XML file location: "
// + backup.getAbsolutePath();
// if (backup.exists() && MessageDialog.openQuestion(null, "Unable
// to read Restore From Backup", message)) {
// try {
// document = builder.parse(backup);
// TasksUiPlugin.getDefault().getTaskListSaveManager().reverseBackup();
// } catch (SAXException s) {
// inputFile.renameTo(new File(inputFile.getName() +
// FILE_SUFFIX_SAVE));
// MylarStatusHandler.log(s, "Failed to recover from backup
// restore");
}
return document;
}
private void handleException(File inFile, Node child, Exception e) {
hasCaughtException = true;
String name = inFile.getAbsolutePath();
name = name.substring(0, name.lastIndexOf('.')) + "-save.zip";
File save = new File(name);
if (save.exists()) {
if (!save.delete()) {
MylarStatusHandler.log("Unable to delete old backup tasklist file", this);
return;
}
}
if (!copy(inFile, save)) {
inFile.renameTo(new File(name));
}
if (child == null) {
MylarStatusHandler.log(e, TasksUiPlugin.MESSAGE_RESTORE);
} else {
MylarStatusHandler.log(e, "Tasks may have been lost from " + child.getNodeName());
}
}
private boolean copy(File src, File dst) {
try {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
return true;
} catch (IOException ioe) {
return false;
}
}
// private Document openAsDOM(String input) throws IOException {
// // A factory API that enables applications to obtain a parser
// // that produces DOM object trees from XML documents
// DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// // Using DocumentBuilder, obtain a Document from XML file.
// DocumentBuilder builder = null;
// Document document = null;
// try {
// // create new instance of DocumentBuilder
// builder = factory.newDocumentBuilder();
// } catch (ParserConfigurationException pce) {
// MylarStatusHandler.log(pce, "Failed to load XML file");
// try {
// // Parse the content of the given file as an XML document
// // and return a new DOM Document object. Also throws IOException
// StringReader s = new StringReader(input);
// InputSource in = new InputSource(s);
// document = builder.parse(in);
// } catch (SAXException se) {
// MylarStatusHandler.log(se, "Failed to parse XML file");
// return document;
// public void readTaskList(TaskList taskList, String input) {
// try {
// Document doc = openAsDOM(input);
// if (doc == null) {
// return;
// Element root = doc.getDocumentElement();
// readVersion = root.getAttribute(ATTRIBUTE_VERSION);
// if (readVersion.equals(VALUE_VERSION_1_0_0)) {
// this);
// } else {
// NodeList list = root.getChildNodes();
// for (int i = 0; i < list.getLength(); i++) {
// Node child = list.item(i);
// boolean wasRead = false;
// try {
// (child.getNodeName().endsWith(DelegatingTaskExternalizer.KEY_CATEGORY)) {
// // for (ITaskListExternalizer externalizer : externalizers) {
// // if (externalizer.canReadCategory(child)) {
// // externalizer.readCategory(child, taskList);
// // wasRead = true;
// // break;
// if (delagatingExternalizer.canReadCategory(child)) {
// delagatingExternalizer.readCategory(child, taskList);
// } else {
// for (ITaskListExternalizer externalizer : externalizers) {
// if (externalizer.canReadTask(child)) {
// ITask newTask = externalizer.readTask(child, taskList, null, null);
// // externalizer.getRepositoryClient().addTaskToArchive(newTask);
// taskList.addTaskToArchive(newTask);
// taskList.internalAddRootTask(newTask);
// wasRead = true;
// break;
// if (!wasRead && delagatingExternalizer.canReadTask(child)) {
// taskList.internalAddRootTask(delagatingExternalizer.readTask(child,
// taskList, null, null));
// } catch (Exception e) {
// MylarStatusHandler.log(e, "can't read xml string");
// } catch (Exception e) {
// MylarStatusHandler.log(e, "can't read xml string");
// public String getTaskListXml(TaskList tlist) {
// // TODO make this and writeTaskList use the same base code
// DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
// DocumentBuilder db;
// Document doc = null;
// try {
// db = dbf.newDocumentBuilder();
// doc = db.newDocument();
// } catch (ParserConfigurationException e) {
// MylarStatusHandler.log(e, "could not create document");
// e.printStackTrace();
// Element root = doc.createElement(ELEMENT_TASK_LIST);
// root.setAttribute(ATTRIBUTE_VERSION, VALUE_VERSION);
// for (ITaskListExternalizer externalizer : externalizers) {
// externalizer.createRegistry(doc, root);
// for (ITaskContainer category : tlist.getCategories()) {
// Element element = null;
// for (ITaskListExternalizer externalizer : externalizers) {
// if (externalizer.canCreateElementFor(category))
// element = externalizer.createCategoryElement(category, doc, root);
// if (element == null &&
// delagatingExternalizer.canCreateElementFor(category)) {
// delagatingExternalizer.createCategoryElement(category, doc, root);
// } else if (element == null) {
// MylarStatusHandler.log("Did not externalize: " + category, this);
// for (ITask task : tlist.getRootTasks()) {
// try {
// Element element = null;
// for (ITaskListExternalizer externalizer : externalizers) {
// if (externalizer.canCreateElementFor(task))
// element = externalizer.createTaskElement(task, doc, root);
// if (element == null && delagatingExternalizer.canCreateElementFor(task))
// delagatingExternalizer.createTaskElement(task, doc, root);
// } else if (element == null) {
// MylarStatusHandler.log("Did not externalize: " + task, this);
// } catch (Exception e) {
// MylarStatusHandler.log(e, e.getMessage());
// doc.appendChild(root);
// StringWriter sw = new StringWriter();
// Source source = new DOMSource(doc);
// Result result = new StreamResult(sw);
// Transformer xformer = null;
// try {
// xformer = TransformerFactory.newInstance().newTransformer();
// // Transform the XML Source to a Result
// xformer.transform(source, result);
// } catch (Exception e) {
// e.printStackTrace();
// return sw.toString();
public void setDelegatingExternalizer(DelegatingTaskExternalizer delagatingExternalizer) {
this.delagatingExternalizer = delagatingExternalizer;
}
public List<ITaskListExternalizer> getExternalizers() {
return externalizers;
}
} |
package org.lamport.tla.toolbox.tool.tlc.util;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRunnable;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationType;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.debug.core.ILaunchManager;
import org.lamport.tla.toolbox.tool.ToolboxHandle;
import org.lamport.tla.toolbox.tool.tlc.job.ConfigCreationOperation;
import org.lamport.tla.toolbox.tool.tlc.job.ExtendingTLAModuleCreationOperation;
import org.lamport.tla.toolbox.tool.tlc.launch.IModelConfigurationConstants;
import org.lamport.tla.toolbox.tool.tlc.launch.IModelConfigurationDefaults;
import org.lamport.tla.toolbox.tool.tlc.launch.TLCModelLaunchDelegate;
import org.lamport.tla.toolbox.tool.tlc.model.Assignment;
import org.lamport.tla.toolbox.tool.tlc.model.Formula;
import org.lamport.tla.toolbox.util.ResourceHelper;
import tla2sany.semantic.ModuleNode;
import tla2sany.semantic.OpDeclNode;
import tla2sany.semantic.OpDefNode;
import tla2sany.semantic.SymbolNode;
/**
* Provides utility methods for model manipulation
* @author Simon Zambrovski
* @version $Id$
*/
public class ModelHelper implements IModelConfigurationConstants, IModelConfigurationDefaults
{
private static final String LIST_DELIMITER = ";";
private static final String PARAM_DELIMITER = ":";
/**
* Constructs the model called FOO_MC_1 from the SpecName FOO
* if FOO_MC_1 already exists, delivers FOO_MC_2, and so on...
*
* This method tests the existence of the launch configuration AND of the file
*
* @param specProject
* @param specName
* @return
*/
public static String constructModelName(IProject specProject, String specName)
{
return doConstructModelName(specProject, specName + "_MC_1");
}
/**
* Implementation of the {@link ModelHelper#constructModelName(IProject, String)}
* @param specProject
* @param proposition
* @return
*/
private static String doConstructModelName(IProject specProject, String proposition)
{
ILaunchConfiguration existingModel = getModelByName(specProject, proposition);
if (existingModel != null || specProject.getFile(proposition + ".tla").exists())
{
String oldNumber = proposition.substring(proposition.lastIndexOf("_") + 1);
int number = Integer.parseInt(oldNumber) + 1;
proposition = proposition.substring(0, proposition.lastIndexOf("_") + 1);
return doConstructModelName(specProject, proposition + number);
}
return proposition;
}
/**
* Convenience method retrieving the model for the project of the current specification
* @param modelName name of the model
* @return launch configuration or null, if not found
*/
public static ILaunchConfiguration getModelByName(String modelName)
{
return getModelByName(ToolboxHandle.getCurrentSpec().getProject(), modelName);
}
/**
* @param specProject
* @param modelName
* @return
*/
public static ILaunchConfiguration getModelByName(IProject specProject, String modelName)
{
// TODO! add project test
ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager();
ILaunchConfigurationType launchConfigurationType = launchManager
.getLaunchConfigurationType(TLCModelLaunchDelegate.LAUNCH_ID);
try
{
ILaunchConfiguration[] launchConfigurations = launchManager
.getLaunchConfigurations(launchConfigurationType);
for (int i = 0; i < launchConfigurations.length; i++)
{
if (launchConfigurations[i].getName().equals(modelName))
{
return launchConfigurations[i];
}
}
} catch (CoreException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* Convenience method
* @param modelFile file containing the model
* @return ILaunchconfiguration
*/
public static ILaunchConfiguration getModelByFile(IFile modelFile)
{
ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager();
return launchManager.getLaunchConfiguration(modelFile);
}
/**
* Retrieves the the config file
* REFACTOR HACK
*/
public static IFile getConfigFile(IResource rootModule)
{
IPath cfgPath = rootModule.getLocation().removeFileExtension().addFileExtension("cfg");
// create config file
IWorkspaceRunnable configCreateJob = new ConfigCreationOperation(cfgPath);
// create it
try
{
ResourcesPlugin.getWorkspace().run(configCreateJob, null);
} catch (CoreException e)
{
e.printStackTrace();
// exception, no chance to recover
}
IFile cfgFile = ResourceHelper.getLinkedFile(rootModule.getProject(), cfgPath.toOSString(), true);
return cfgFile;
}
/**
* Creates a new model root and retrieves the handle to it
*/
public static IFile getNewModelRootFile(IResource specRootModule, String modelName)
{
// construct new model checking root module name
IPath modelRootPath = specRootModule.getLocation().removeLastSegments(1).append(modelName + ".tla");
// create a module
IWorkspaceRunnable moduleCreateJob = new ExtendingTLAModuleCreationOperation(modelRootPath, ResourceHelper
.getModuleName(specRootModule));
// create it
try
{
ResourcesPlugin.getWorkspace().run(moduleCreateJob, null);
} catch (CoreException e)
{
e.printStackTrace();
// exception, no chance to recover
}
// create a link in the project
IFile modelRootFile = ResourceHelper.getLinkedFile(specRootModule.getProject(), modelRootPath.toOSString(),
true);
return modelRootFile;
}
/**
* Saves the config working copy
* @param config
*/
public static void doSaveConfigurationCopy(ILaunchConfigurationWorkingCopy config)
{
try
{
config.doSave();
} catch (CoreException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Creates a serial version of the assignment list, to be stored in the {@link ILaunchConfiguration}
*
* Any assignment consist of a label, parameter list and the right side
* These parts are serialized as a list with delimiter {@link ModelHelper#LIST_DELIMETER}
* The parameter list is stored as a list with delimiter {@link ModelHelper#PARAM_DELIMITER}
*
* If the assignment is using a model value {@link Assignment#isModelValue()} == <code>true, the right
* side is set to the label resulting in (foo = foo)
*
*
*/
public static List serializeAssignmentList(List assignments)
{
Iterator iter = assignments.iterator();
Vector result = new Vector(assignments.size());
StringBuffer buffer;
while (iter.hasNext())
{
Assignment assign = (Assignment) iter.next();
buffer = new StringBuffer();
// label
buffer.append(assign.getLabel()).append(LIST_DELIMITER);
// parameters if any
for (int j = 0; j < assign.getParams().length; j++)
{
String param = assign.getParams()[j];
if (param != null)
{
buffer.append(param);
}
buffer.append(PARAM_DELIMITER);
}
buffer.append(LIST_DELIMITER);
// right side
// encode the model value usage (if model value is set, the assignment right side is equals to the label)
if (assign.getRight() != null)
{
buffer.append(assign.getRight());
}
// isModelValue
buffer.append(LIST_DELIMITER).append((assign.isModelValue() ? "1" : "0"));
// is symmetrical
buffer.append(LIST_DELIMITER).append((assign.isSymmetricalSet() ? "1" : "0"));
result.add(buffer.toString());
}
return result;
}
/**
* De-serialize assignment list.
* @see ModelHelper#serializeAssignmentList(List)
*/
public static List deserializeAssignmentList(List serializedList)
{
Vector result = new Vector(serializedList.size());
Iterator iter = serializedList.iterator();
String[] fields = new String[] { null, "", "", "0", "0" };
while (iter.hasNext())
{
String[] serFields = ((String) iter.next()).split(LIST_DELIMITER);
System.arraycopy(serFields, 0, fields, 0, serFields.length);
String[] params;
if ("".equals(fields[1]))
{
params = new String[0];
} else
{
params = fields[1].split(PARAM_DELIMITER);
}
// assignment with label as right side are treated as model values
Assignment assign = new Assignment(fields[0], params, fields[2]);
// is Model Value
if (fields.length > 3 && fields[3].equals("1"))
{
assign.setModelValue(true);
// is symmetrical
if (fields.length > 4 && fields[4].equals("1"))
{
assign.setSymmetric(true);
}
}
result.add(assign);
}
return result;
}
/**
* De-serialize formula list, to a list of formulas, that are selected (have a leading "1")
*
* The first character of the formula is used to determine if the formula is enabled in the model
* editor or not. This allows the user to persist formulas, which are not used in the current model
*/
private static List deserializeFormulaList(List serializedList)
{
Vector result = new Vector(serializedList.size());
Iterator serializedIterator = serializedList.iterator();
while (serializedIterator.hasNext())
{
String entry = (String) serializedIterator.next();
Formula formula = new Formula(entry.substring(1));
if ("1".equals(entry.substring(0, 1)))
{
result.add(formula);
}
}
return result;
}
/**
* Create a representation of the behavior formula
* @param config launch configuration
* @return a string array containing two strings: name of the formula, and the formula with the name
* @throws CoreException if something went wrong
*/
public static String[] createSpecificationContent(ILaunchConfiguration config) throws CoreException
{
StringBuffer buffer = new StringBuffer();
String identifier = getValidIdentifier("spec");
String[] result = null;
// the identifier
buffer.append(identifier).append(" ==\n");
int specType = config.getAttribute(MODEL_BEHAVIOR_SPEC_TYPE, MODEL_BEHAVIOR_TYPE_DEFAULT);
switch (specType)
{
case MODEL_BEHAVIOR_TYPE_NO_SPEC:
// no spec - nothing to do
break;
case MODEL_BEHAVIOR_TYPE_SPEC_CLOSED:
// append the closed formula
buffer.append(config.getAttribute(MODEL_BEHAVIOR_CLOSED_SPECIFICATION, EMPTY_STRING));
result = new String[] { identifier, buffer.toString() };
break;
case MODEL_BEHAVIOR_TYPE_SPEC_INIT_NEXT:
// init, next, fairness
String modelInit = config.getAttribute(MODEL_BEHAVIOR_SEPARATE_SPECIFICATION_INIT, EMPTY_STRING);
String modelNext = config.getAttribute(MODEL_BEHAVIOR_SEPARATE_SPECIFICATION_NEXT, EMPTY_STRING);
String vars = config.getAttribute(MODEL_BEHAVIOR_VARS, EMPTY_STRING);
String modelFairness = config.getAttribute(MODEL_BEHAVIOR_SEPARATE_SPECIFICATION_FAIRNESS, EMPTY_STRING);
// append init. next, fairness
buffer.append(modelInit).append(" /\\[][ ").append(modelNext).append(" ]_").append("<<").append(vars)
.append(">> ");
// add fairness condition, if any
if (!EMPTY_STRING.equals(modelFairness))
{
buffer.append(" /\\ ").append(modelFairness);
}
result = new String[] { identifier, buffer.toString() };
break;
default:
break;
}
// specification
// to .cfg : <id>
// to _MC.tla : <id> == <expression>
// : <id> == <init> /\[][<next>]_vars /\ <fairness>
return result;
}
/**
* Create the content for a single source element
* @return a list with at most one String[] element
* @throws CoreException
*/
public static List createSourceContent(String propertyName, String labelingScheme, ILaunchConfiguration config)
throws CoreException
{
Vector result = new Vector();
String constraint = config.getAttribute(propertyName, EMPTY_STRING);
if (EMPTY_STRING.equals(constraint))
{
return result;
}
String identifier = getValidIdentifier(labelingScheme);
StringBuffer buffer = new StringBuffer();
// the identifier
buffer.append(identifier).append(" ==\n");
buffer.append(constraint);
result.add(new String[] { identifier, buffer.toString() });
return result;
}
/**
* Create representation of constants
* @param config launch configuration
* @return a list of string pairs each representing a constant instantiation
* @throws CoreException
*/
public static List createConstantsContent(ILaunchConfiguration config) throws CoreException
{
List constants = ModelHelper.deserializeAssignmentList(config.getAttribute(MODEL_PARAMETER_CONSTANTS,
new Vector()));
Vector constantContent = new Vector(constants.size());
Assignment constant;
String[] content;
String label;
for (int i = 0; i < constants.size(); i++)
{
label = getValidIdentifier("const");
constant = (Assignment) constants.get(i);
if (constant.isModelValue())
{
// model value assignment
// to .cfg : foo = foo
// to _MC.tla : <nothing>
content = new String[] { constant.getLabel() + " = " + constant.getRight(), "" };
} else
{
// constant instantiation
// to .cfg : foo <- <id>
// to _MC.tla : <id> == <expression>
content = new String[] { constant.getLabel() + " <- " + label,
constant.getParametrizedLabel(label) + " ==\n" + constant.getRight() };
}
constantContent.add(content);
}
return constantContent;
}
/**
* Converts formula list to a string representation
* @param serializedFormulaList
* @param labelingScheme
* @return
*/
public static List createListContent(List serializedFormulaList, String labelingScheme)
{
List formulaList = ModelHelper.deserializeFormulaList(serializedFormulaList);
Vector resultContent = new Vector(formulaList.size());
String[] content;
String label;
for (int i = 0; i < formulaList.size(); i++)
{
label = getValidIdentifier(labelingScheme);
// formulas
// to .cfg : <id>
// to _MC.tla : <id> == <expression>
content = new String[] { label, label + " ==\n" + ((Formula) formulaList.get(i)).getFormula() };
resultContent.add(content);
}
return resultContent;
}
/**
* Retrieves new valid (not used) identifier from given schema
* @param schema a naming schema
* @return a valid identifier
* TODO re-implement
*/
public static String getValidIdentifier(String schema)
{
try
{
Thread.sleep(10);
} catch (InterruptedException e)
{
}
return schema + "_" + System.currentTimeMillis();
}
/**
* Extract the constants from module node
* @param moduleNode
* @return a list of assignments
*/
public static List createConstantsList(ModuleNode moduleNode)
{
OpDeclNode[] constantDecls = moduleNode.getConstantDecls();
Vector constants = new Vector(constantDecls.length);
for (int i = 0; i < constantDecls.length; i++)
{
Assignment assign = new Assignment(constantDecls[i].getName().toString(), new String[constantDecls[i]
.getNumberOfArgs()], null);
constants.add(assign);
}
return constants;
}
/**
* Extract the variables from module node
* @param moduleNode
* @return a string representation of the variables
*/
public static String createVariableList(ModuleNode moduleNode)
{
StringBuffer buffer = new StringBuffer();
OpDeclNode[] variableDecls = moduleNode.getVariableDecls();
for (int i = 0; i < variableDecls.length; i++)
{
buffer.append(variableDecls[i].getName().toString());
if (i != variableDecls.length - 1)
{
buffer.append(", ");
}
}
return buffer.toString();
}
public static SymbolNode getSymbol(String name, ModuleNode moduleNode)
{
return moduleNode.getContext().getSymbol(name);
}
/**
* Extract the operator definitions from module node
* @param moduleNode
* @return a list of assignments
*/
public static List createDefinitionList(ModuleNode moduleNode)
{
OpDefNode[] operatorDefinitions = moduleNode.getOpDefs();
Vector operations = new Vector(operatorDefinitions.length);
for (int i = 0; i < operatorDefinitions.length; i++)
{
Assignment assign = new Assignment(operatorDefinitions[i].getName().toString(),
new String[operatorDefinitions[i].getNumberOfArgs()], null);
operations.add(assign);
}
return operations;
}
} |
package org.osgi.test.support.compatibility;
import java.io.InputStream;
import java.net.URL;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import junit.framework.TestCase;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.osgi.framework.Constants;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
/**
* @author <a href="mailto:tdiekman@tibco.com">Tim Diekmann</a>
*
*/
public abstract class DefaultTestBundleControl extends TestCase {
/* @GuardedBy("this") */
private BundleContext context;
private Map serviceRegistry = new HashMap();
Hashtable fetchedServices = new Hashtable();
/**
* THis method is called by the JUnit runner for OSGi, and gives us a Bundle
* Context.
*/
public synchronized void setBundleContext(BundleContext context) {
this.context = context;
}
/**
* Returns the current Bundle Context
*/
public synchronized BundleContext getContext() {
if (context == null)
fail("No valid Bundle context said, are you running in OSGi Test mode?");
return context;
}
/**
* This returned a web server but we will just now, it is mostly used in
* installBundle and there we get the bundle from our resources.
*/
public String getWebServer() {
return "/www/";
}
/**
* Uninstall a bundle.
*
* @param bundle
* @throws BundleException
*/
public void uninstallBundle(Bundle bundle) throws BundleException {
bundle.uninstall();
}
/**
* Install a bundle.
*
* @param bundle
* @throws BundleException
*/
public Bundle installBundle(String url) throws BundleException {
URL resource = getClass().getResource(url);
if ( resource == null )
fail("Can not load bundle " + url);
return getContext().installBundle(resource.toString());
}
public void failException(String message, Class expectedExceptionClass) {
fail(message + " expected:[" + expectedExceptionClass.getName() + "] and got nothing");
}
public void pass(String passMessage) {
System.out.println(passMessage);
}
public void log(String logMessage) {
System.out.println(logMessage);
}
public void trace(String logMessage) {
System.out.println(logMessage);
}
/**
* Method for logging exceptions. The tested code may throw an
* exception that is a subclass of the specified, so the parameter
* <code>want</code> specifies the expected class. If the parameter
* <code>got</code> is of the wanted type (or a subtype of the
* wanted type), the classname of <code>want</code> is logged. If
* <code>got</code> is of an unexpected type, the classname of
* <code>got</code> is logged.
*
* @param message the log description
* @param want the exception that is specified to be thrown
* @param got the exception that was thrown
*/
public void assertException(String message, Class want, Throwable got) {
String formatted = "";
if(message != null) {
formatted = message + " ";
}
if(want.isInstance(got)) {
pass(formatted + want.getName());
}
else {
got.printStackTrace();
fail(formatted + "expected:[" + want.getName()
+ "] but was:[" + got.getClass().getName() + "]");
}
}
/**
* Asserts that two Dictionaries of properties are equal. If they are not
* an AssertionFailedError is thrown.
*/
public void assertEqualProperties(String message, Dictionary expected, Dictionary actual)
{
if (expected == actual)
{
passNotEquals(message, expected, actual);
return;
}
if ((expected == null) || (actual == null))
{
failNotEquals(message, expected, actual);
return;
}
if (expected.size() != actual.size())
{
failNotEquals(message, expected, actual);
return;
}
Enumeration e = expected.keys();
while (e.hasMoreElements())
{
Object key = e.nextElement();
Object expectedValue = expected.get(key);
Object actualValue = actual.get(key);
if (!objectEquals(expectedValue, actualValue))
{
failNotEquals(message, expected, actual);
return;
}
}
passNotEquals(message, expected, actual);
}
/**
* Compare two objects for equality. This method calls Arrays.equals if the object types are arrays.
*
*/
public boolean objectEquals(Object expected, Object actual)
{
return objectEquals(null, expected, actual);
}
/**
* Compare two objects for equality. This method calls Arrays.equals if the object types are arrays.
*
*/
public boolean objectEquals(Comparator comparator, Object expected, Object actual)
{
if (expected == actual)
{
return true;
}
if ((expected == null) || (actual == null))
{
return false;
}
if (expected.equals(actual))
{
return true;
}
if ( expected instanceof List && actual instanceof List )
return objectEquals( comparator, (List)expected, (List)actual );
if ( expected instanceof Dictionary && actual instanceof Dictionary )
return objectEquals( comparator, (Dictionary)expected, (Dictionary)actual );
try
{
Class clazz = expected.getClass();
if (clazz.isArray())
{
Class type = clazz.getComponentType();
if (type.isPrimitive())
{
if (type.equals(Integer.TYPE))
{
return Arrays.equals((int[])expected, (int[])actual);
}
else
if (type.equals(Long.TYPE))
{
return Arrays.equals((long[])expected, (long[])actual);
}
else
if (type.equals(Byte.TYPE))
{
return Arrays.equals((byte[])expected, (byte[])actual);
}
else
if (type.equals(Short.TYPE))
{
return Arrays.equals((short[])expected, (short[])actual);
}
else
if (type.equals(Character.TYPE))
{
return Arrays.equals((char[])expected, (char[])actual);
}
else
if (type.equals(Float.TYPE))
{
return Arrays.equals((float[])expected, (float[])actual);
}
else
if (type.equals(Double.TYPE))
{
return Arrays.equals((double[])expected, (double[])actual);
}
else
if (type.equals(Boolean.TYPE))
{
return Arrays.equals((boolean[])expected, (boolean[])actual);
}
}
else /* non-primitive array object */
{
return Arrays.equals((Object[])expected, (Object[])actual);
}
}
/* well it did not match any of the above types
* do we have a comparator to compare them?
*/
if (comparator != null) {
if (comparator.compare(expected, actual) == 0) {
return true;
}
}
}
catch (ClassCastException e)
{
}
return false;
}
public boolean serviceAvailable(Class clazz) {
return context.getServiceReference(clazz.getName()) != null;
}
public void registerService(String clazz, Object service, Dictionary properties) throws Exception {
ServiceRegistration sr = context.registerService(clazz, service, properties);
serviceRegistry.put(service, sr);
}
public void unregisterService(Object service) {
ServiceRegistration sr = (ServiceRegistration) serviceRegistry.remove(service);
if (sr != null) {
sr.unregister();
}
}
public void unregisterAllServices() {
for (Iterator i = serviceRegistry.values().iterator(); i.hasNext(); ) {
ServiceRegistration sr = (ServiceRegistration) i.next();
sr.unregister();
}
}
private void passNotEquals(String message, Object expected, Object actual) {
String formatted = "";
if(message != null) {
formatted = message + " ";
}
pass(formatted + "expected:[" + expected + "] and correctly got:[" + actual + "]");
}
/**
* Convenience method for getting services from the framework in cases
* when you don't want to keep track of the ServiceReference.
* <p>
* To unregister the service, use the ungetService(Object service) method.
*
* @param clazz the Class object of the service you with to retrieve
* @return a service object
* @throws NullPointerException if the service couldn't be retrieved
* from the framework.
*/
public Object getService(Class clazz) {
Object service = null;
try {
service = getService(clazz, null);
} catch(InvalidSyntaxException e) {
/* null can not give an exception of this type */
}
return service;
}
public Object getService(Class clazz, String filter) throws InvalidSyntaxException {
ServiceReference[] refs = getContext().getServiceReferences(clazz.getName(), filter);
if(refs == null) {
throw new NullPointerException(
"Can't get service reference for " + clazz.getName());
}
ServiceReference chosenRef = pickServiceReference(refs);
Object service = getContext().getService(chosenRef);
if(service == null) {
throw new NullPointerException(
"Can't get service for " + clazz.getName());
}
/* Save the service and its reference */
fetchedServices.put(service, chosenRef);
return service;
}
public void ungetService(Object service) {
ServiceReference ref = (ServiceReference) fetchedServices.get(service);
getContext().ungetService(ref);
fetchedServices.remove(service);
}
public void ungetAllServices() {
Enumeration e = fetchedServices.keys();
while(e.hasMoreElements()) {
Object service = e.nextElement();
ungetService(service);
}
}
/**
* Picks a service from the given array of references. The rules
* the service is picked by are the same as the rules defined in
* BundleContext.getServiceReference() (highest ranking, lowest
* service ID if the ranking is a tie)
*/
private ServiceReference pickServiceReference(ServiceReference[] refs) {
ServiceReference highest = refs[0];
for(int i = 1; i < refs.length; i++) {
ServiceReference challenger = refs[i];
if(ranking(highest) < ranking(challenger)) {
highest = challenger;
}
else if(ranking(highest) == ranking(challenger)) {
if(serviceid(highest) > serviceid(challenger)) {
highest = challenger;
}
}
}
return highest;
}
/**
* Get service ranking from a service reference.
*
* @param s The service reference
* @return Ranking value of service, default value is zero
*/
private int ranking(ServiceReference s) {
Object v = s.getProperty(Constants.SERVICE_RANKING);
if (v != null && v instanceof Integer) {
return ((Integer)v).intValue();
} else {
return 0;
}
}
private long serviceid(ServiceReference s) {
Long sid = (Long) s.getProperty(Constants.SERVICE_RANKING);
return sid.longValue();
}
public Bundle installBundle(String bundleName, boolean start) throws Exception {
try {
URL url = new URL(getWebServer() + bundleName);
InputStream in = url.openStream();
Bundle b = context.installBundle(getWebServer() + bundleName, in);
if (start) {
b.start();
}
return b;
}
catch(BundleException e) {
System.out.println("Not able to install testbundle " + bundleName);
System.out.println("Nested " + e.getNestedException());
e.printStackTrace();
throw e;
}
catch(Exception e) {
System.out.println("Not able to install testbundle " + bundleName);
e.printStackTrace();
throw e;
}
}
} |
package com.intellij.openapi.actionSystem.impl;
import com.intellij.ide.DataManager;
import com.intellij.ide.IdeEventQueue;
import com.intellij.ide.ProhibitAWTEvents;
import com.intellij.ide.impl.DataManagerImpl;
import com.intellij.ide.impl.dataRules.GetDataRule;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.DataKey;
import com.intellij.openapi.actionSystem.DataProvider;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.application.AccessToken;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.keymap.impl.IdeKeyEventDispatcher;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.UserDataHolder;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Map;
import static com.intellij.ide.impl.DataManagerImpl.getDataProviderEx;
import static com.intellij.ide.impl.DataManagerImpl.validateEditor;
/**
* @author gregsh
*/
class PreCachedDataContext implements DataContext, UserDataHolder {
private Map<Key<?>, Object> myUserData;
private final Map<String, Object> myCachedData;
private static int ourPrevMapEventCount;
private static final Map<Component, Map<String, Object>> ourPrevMaps = ContainerUtil.createWeakKeySoftValueMap();
PreCachedDataContext(@NotNull DataContext original) {
if (!(original instanceof DataManagerImpl.MyDataContext)) {
throw new AssertionError(original.getClass().getName());
}
ApplicationManager.getApplication().assertIsDispatchThread();
Component component = original.getData(PlatformDataKeys.CONTEXT_COMPONENT);
try (AccessToken ignored = ProhibitAWTEvents.start("getData")) {
int count = IdeEventQueue.getInstance().getEventCount();
if (ourPrevMapEventCount != count) {
ourPrevMaps.clear();
}
if (component == null) {
myCachedData = ContainerUtil.createConcurrentWeakValueMap();
myCachedData.put(PlatformDataKeys.MODALITY_STATE.getName(), ModalityState.NON_MODAL);
return;
}
Map<String, Object> prevMap = ourPrevMaps.get(component);
if (prevMap != null) {
myCachedData = prevMap;
return;
}
myCachedData = ContainerUtil.createConcurrentWeakValueMap();
preGetAllData(component, myCachedData);
//noinspection AssignmentToStaticFieldFromInstanceMethod
ourPrevMapEventCount = count;
ourPrevMaps.put(component, myCachedData);
}
}
@Override
public Object getData(@NotNull String dataId) {
ProgressManager.checkCanceled();
Object answer = myCachedData.get(dataId);
if (answer != null && answer != NullResult.Initial) {
return answer == NullResult.Final ? null : answer;
}
DataManagerImpl dataManager = (DataManagerImpl)DataManager.getInstance();
GetDataRule rule = dataManager.getDataRule(dataId);
answer = rule == null ? null : dataManager.getDataFromProvider(dataId2 -> {
Object o = myCachedData.get(dataId2);
return o == NullResult.Initial || o == NullResult.Final ? null : o;
}, dataId, null, rule);
myCachedData.put(dataId, answer == null || answer == NullResult.Initial ? NullResult.Final : answer);
return answer;
}
private static void preGetAllData(@NotNull Component component, @NotNull Map<String, Object> cachedData) {
long start = System.currentTimeMillis();
DataManagerImpl dataManager = (DataManagerImpl)DataManager.getInstance();
ArrayList<Object> slowProviders = new ArrayList<>();
cachedData.put(PlatformDataKeys.CONTEXT_COMPONENT.getName(), component);
cachedData.put(PlatformDataKeys.MODALITY_STATE.getName(), ModalityState.stateForComponent(component));
cachedData.put(PlatformDataKeys.IS_MODAL_CONTEXT.getName(), IdeKeyEventDispatcher.isModalContext(component));
cachedData.put(PlatformDataKeys.SLOW_DATA_PROVIDERS.getName(), slowProviders);
// ignore injected data keys, injections are slow,
// and slow parts must be in a slow provider anyway
DataKey<?>[] keys = DataKey.allKeys();
BitSet computed = new BitSet(keys.length);
for (Component c = component; c != null; c = c.getParent()) {
DataProvider dataProvider = getDataProviderEx(c);
if (dataProvider == null) continue;
for (int i = 0; i < keys.length; i++) {
DataKey<?> key = keys[i];
boolean alreadyComputed = computed.get(i);
if (key == PlatformDataKeys.IS_MODAL_CONTEXT ||
key == PlatformDataKeys.CONTEXT_COMPONENT ||
key == PlatformDataKeys.MODALITY_STATE) {
if (!alreadyComputed) computed.set(i, true);
continue;
}
Object data = !alreadyComputed || key == PlatformDataKeys.SLOW_DATA_PROVIDERS ?
dataManager.getDataFromProvider(dataProvider, key.getName(), null, null) : null;
if (data instanceof Editor) data = validateEditor((Editor)data, component);
if (data == null) continue;
computed.set(i, true);
if (key == PlatformDataKeys.SLOW_DATA_PROVIDERS) {
ContainerUtil.addAll(slowProviders, (Iterable<?>)data);
continue;
}
cachedData.put(key.getName(), data);
}
}
for (int i = 0; i < keys.length; i++) {
DataKey<?> key = keys[i];
if (!computed.get(i)) {
cachedData.put(key.getName(), NullResult.Initial);
}
}
long time = System.currentTimeMillis() - start;
if (time > 200) {
// nothing
}
}
@Override
public String toString() {
return "component=" + getData(PlatformDataKeys.CONTEXT_COMPONENT);
}
@Override
public <T> T getUserData(@NotNull Key<T> key) {
//noinspection unchecked
return (T)getOrCreateMap().get(key);
}
@Override
public <T> void putUserData(@NotNull Key<T> key, @Nullable T value) {
getOrCreateMap().put(key, value);
}
private @NotNull Map<Key<?>, Object> getOrCreateMap() {
Map<Key<?>, Object> userData = myUserData;
if (userData == null) {
myUserData = userData = ContainerUtil.createWeakValueMap();
}
return userData;
}
private enum NullResult {
Initial, Final
}
} |
package com.buzzingandroid.content;
import java.util.ArrayList;
import java.util.StringTokenizer;
import android.content.AsyncQueryHandler;
import android.content.ContentProvider;
import android.content.ContentProviderClient;
import android.content.ContentProviderOperation;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.RemoteException;
import android.provider.BaseColumns;
import android.support.v4.content.CursorLoader;
import android.text.TextUtils;
import android.util.Pair;
import android.widget.FilterQueryProvider;
/**
* A class designed to simplify selections in query, update and delete
* operations through a {@link ContentProvider}
* @author Jesper Borgstrup
*
*/
public class QueryBuilder {
public QueryBuilder() {}
private StringBuilder selection = new StringBuilder();
private ArrayList<String> selectionArgs = new ArrayList<String>();
private String[] searchColumns = new String[0];
private String[] searchQueryTokens = new String[0];
private String[] projection;
private String sortOrder;
/**
* Requires the ID column ({@link BaseColumns#_ID}) to be the specified long.<br />
* Similar to the SQL expression <tt>_id=[id]</tt>
* @param id
* @return The QueryBuilder instance for chaining method calls
*/
public QueryBuilder whereId( long id ) {
readySelection();
selection.append( BaseColumns._ID ).append( "=?" );
selectionArgs.add( Long.toString( id ) );
return this;
}
/**
* Requires the ID column ({@link BaseColumns#_ID}) to be the specified integer.<br />
* Similar to the SQL expression <tt>_id=[id]</tt>
* @param id
* @return The QueryBuilder instance for chaining method calls
*/
public QueryBuilder whereId( int id ) {
readySelection();
selection.append( BaseColumns._ID ).append( "=?" );
selectionArgs.add( Integer.toString( id ) );
return this;
}
/**
* Requires the specified column to be null.<br />
* Similar to the SQL expression <tt>[column] IS NULL</tt>
* @param column
* @return The QueryBuilder instance for chaining method calls
*/
public QueryBuilder whereColumnIsNull( String column ) {
readySelection();
selection.append( column ).append( " IS NULL" );
return this;
}
/**
* Requires the specified column to not be null.<br />
* Similar to the SQL expression <tt>[column] IS NOT NULL</tt>
* @param column
* @return The QueryBuilder instance for chaining method calls
*/
public QueryBuilder whereColumnIsNotNull( String column ) {
readySelection();
selection.append( column ).append( " IS NOT NULL" );
return this;
}
/**
* Requires the specified column to be the specified value.<br />
* Similar to the SQL expression <tt>[column]=[value]</tt>
* @param column
* @param value
* @return The QueryBuilder instance for chaining method calls
*/
public QueryBuilder whereColumnEquals( String column, Object value ) {
readySelection();
selection.append( column ).append( "=?" );
selectionArgs.add( value == null ? null : value.toString() );
return this;
}
/**
* Requires the specified column to not be the specified value.<br />
* Similar to the SQL expression <tt>[column]!=[value]</tt>
* @param column
* @param value
* @return The QueryBuilder instance for chaining method calls
*/
public QueryBuilder whereColumnNotEquals( String column, Object value ) {
readySelection();
selection.append( column ).append( "!=?" );
selectionArgs.add( value == null ? null : value.toString() );
return this;
}
/**
* Requires the specified column to be greater than the specified value.<br />
* Similar to the SQL expression <tt>[column]>[value]</tt>
* @param column
* @param value
* @return The QueryBuilder instance for chaining method calls
*/
public QueryBuilder whereColumnGreaterThan( String column, Object value ) {
readySelection();
selection.append( column ).append( ">?" );
selectionArgs.add( value == null ? null : value.toString() );
return this;
}
/**
* Requires the specified column to be greater than or equal to the specified value.<br />
* Similar to the SQL expression <tt>[column]>=[value]</tt>
* @param column
* @param value
* @return The QueryBuilder instance for chaining method calls
*/
public QueryBuilder whereColumnGreaterThanOrEqual( String column, Object value ) {
readySelection();
selection.append( column ).append( ">=?" );
selectionArgs.add( value == null ? null : value.toString() );
return this;
}
/**
* Requires the specified column to be less than the specified value.<br />
* Similar to the SQL expression <tt>[column]<[value]</tt>
* @param column
* @param value
* @return The QueryBuilder instance for chaining method calls
*/
public QueryBuilder whereColumnLessThan( String column, Object value ) {
readySelection();
selection.append( column ).append( "<?" );
selectionArgs.add( value == null ? null : value.toString() );
return this;
}
/**
* Requires the specified column to be less than or equal to the specified value.<br />
* Similar to the SQL expression <tt>[column]<=[value]</tt>
* @param column
* @param value
* @return The QueryBuilder instance for chaining method calls
*/
public QueryBuilder whereColumnLessThanOrEqual( String column, Object value ) {
readySelection();
selection.append( column ).append( "<=?" );
selectionArgs.add( value == null ? null : value.toString() );
return this;
}
/**
* Requires the specified column to be one of the specified values.<br />
* Similar to the SQL expression <tt>[column] IN ([set])</tt>
* @param column
* @param set
* @return The QueryBuilder instance for chaining method calls
*/
public QueryBuilder whereColumnInSet( String column, Object[] set ) {
readySelection();
selection.append( column ).append( " IN (" );
joinInSelection( set );
selection.append( ")" );
return this;
}
/**
* Requires the specified column to be one of the specified longs.<br />
* Similar to the SQL expression <tt>[column] IN ([set])</tt>
* @param column
* @param set
* @return The QueryBuilder instance for chaining method calls
*/
public QueryBuilder whereColumnInSet( String column, long[] set ) {
readySelection();
selection.append( column ).append( " IN (" );
joinInSelection( set );
selection.append( ")" );
return this;
}
/**
* Requires the specified column to be one of the specified integers.<br />
* Similar to the SQL expression <tt>[column] IN ([set])</tt>
* @param column
* @param set
* @return The QueryBuilder instance for chaining method calls
*/
public QueryBuilder whereColumnInSet( String column, int[] set ) {
readySelection();
selection.append( column ).append( " IN (" );
joinInSelection( set );
selection.append( ")" );
return this;
}
/**
* Requires the specified column to not be one of the specified values.<br />
* Similar to the SQL expression <tt>[column] NOT IN ([set])</tt>
* @param column
* @param set
* @return The QueryBuilder instance for chaining method calls
*/
public QueryBuilder whereColumnNotInSet( String column, Object[] set ) {
readySelection();
selection.append( column ).append( " NOT IN (" );
joinInSelection( set );
selection.append( ")" );
return this;
}
/**
* Requires the specified column to not be one of the specified longs.<br />
* Similar to the SQL expression <tt>[column] NOT IN ([set])</tt>
* @param column
* @param set
* @return The QueryBuilder instance for chaining method calls
*/
public QueryBuilder whereColumnNotInSet( String column, long[] set ) {
readySelection();
selection.append( column ).append( " NOT IN (" );
joinInSelection( set );
selection.append( ")" );
return this;
}
/**
* Requires the specified column to not be one of the specified integers.<br />
* Similar to the SQL expression <tt>[column] NOT IN ([set])</tt>
* @param column
* @param set
* @return The QueryBuilder instance for chaining method calls
*/
public QueryBuilder whereColumnNotInSet( String column, int[] set ) {
readySelection();
selection.append( column ).append( " NOT IN (" );
joinInSelection( set );
selection.append( ")" );
return this;
}
/**
* Adds an extra SQL selection string to the where-clause
* @param extraSelection The selection string
* @param extraSelectionArgs One argument for every question mark in the selection string
* @return The QueryBuilder instance for chaining method calls
*/
public QueryBuilder addSelection( String extraSelection, Object... extraSelectionArgs ) {
readySelection();
selection.append( extraSelection );
for ( Object arg: extraSelectionArgs ) {
selectionArgs.add( arg == null ? null : arg.toString() );
}
return this;
}
/**
* Sets one or more columns for free-text searching.<br />
* Note that subsequent calls to this method will overwrite previously set search columns.
* @param columns
* @return
*/
public QueryBuilder setSearchColumns( String... columns ) {
this.searchColumns = columns;
return this;
}
/**
* Sets a query to be searched for in the column(s) defined in {@link #setSearchColumns(String...)}.<br /><br />
*
* The query is broken into tokens separated by whitespace, and each of these tokens has to be occur in at least
* one of the search columns in order for a row to be selected.<br />
* <br />
* Note that subsequent calls to this method will replace any search query set earlier.
* @param query
* @return
*/
public QueryBuilder setSearchQuery( String query ) {
if ( TextUtils.isEmpty( query ) ) {
this.searchQueryTokens = new String[ 0 ];
} else {
StringTokenizer tokenizer = new StringTokenizer( query );
this.searchQueryTokens = new String[ tokenizer.countTokens() ];
for ( int index = 0; tokenizer.hasMoreTokens(); index++ ) {
this.searchQueryTokens[ index ] = tokenizer.nextToken();
}
}
return this;
}
public QueryBuilder select( String... columns ) {
this.projection = columns;
return this;
}
/**
* Sets the row sort order.<br />
* <br />
* This will be put after the ORDER BY keywords in the SQL expression,
* e.g. <tt>SELECT * FROM [table] ORDER BY [sortOrder]</tt>
* @param sortOrder
* @return
*/
public QueryBuilder orderBy( String sortOrder ) {
this.sortOrder = sortOrder;
return this;
}
/**
* Builds a selection string and an array of arguments to be used directly in
* an query, update or delete call
* @return First value of the pair is the selection string, second value is the arguments (both may be null).
* The pair itself will never be null.
*/
public Pair<String, String[]> buildSelection() {
/*
* First build the selection string
*/
StringBuilder sb = new StringBuilder();
sb.append( selection );
if ( searchQueryTokens.length > 0 && searchColumns.length > 0 ) {
readySelection();
/*
* Build single search selection
*/
StringBuilder sb2 = new StringBuilder();
for ( int i = 0; i < searchColumns.length; i++ ) {
sb2.append( searchColumns[i] );
sb2.append( " LIKE ?" );
if ( i < searchColumns.length-1 ) { sb2.append( " OR " ); }
}
/*
* Build search selection for all tokens
*/
final String singleSearchSelection = sb2.toString();
sb2 = new StringBuilder();
for ( int i = 0; i < searchQueryTokens.length; i++ ) {
sb2.append( "(" );
sb2.append( singleSearchSelection );
sb2.append( ")" );
if ( i < searchQueryTokens.length-1 ) { sb2.append( " AND " ); }
}
sb.append( sb2 );
}
String selectionString = sb.length() == 0 ? null : sb.toString();
/*
* Second, build the selection argument array
*/
ArrayList<String> argList = new ArrayList<String>( selectionArgs );
if ( searchQueryTokens.length > 0 && searchColumns.length > 0 ) {
for ( int i = 0; i < searchQueryTokens.length; i++ ) {
String arg = String.format( "%%%s%%", searchQueryTokens[i] );
for ( int j = 0; j < searchColumns.length; j++ ) {
argList.add( arg );
}
}
}
String[] selectionArgsArray = argList.toArray( new String[ argList.size() ] );
return new Pair<String, String[]>( selectionString, selectionArgsArray );
}
/**
* Ensure that we can query, by checking that at least one column is selected for projection.
*/
private void validateForQuery() {
if ( projection == null || projection.length == 0 ) {
throw new IllegalStateException( "No projection defined. Set one with select(String...)" );
}
}
/**
* Queries the defined projection, selection and sort order on the given URI through the ContentResolver
* retrieved from the given context
* @param context
* @param uri
* @return
*/
public Cursor query( Context context, Uri uri ) {
validateForQuery();
Pair<String, String[]> builtSelection = buildSelection();
return context.getContentResolver().query( uri,
projection,
builtSelection.first,
builtSelection.second,
sortOrder );
}
/**
* Queries the defined projection, selection and sort order on the given URI through the ContentProviderClient
* @param provider
* @param uri
* @return
* @throws RemoteException May be thrown from {@link ContentProviderClient#query(Uri, String[], String, String[], String)}
*/
public Cursor query( ContentProviderClient provider, Uri uri ) throws RemoteException {
validateForQuery();
Pair<String, String[]> builtSelection = buildSelection();
return provider.query( uri,
projection,
builtSelection.first,
builtSelection.second,
sortOrder );
}
public interface AsyncQueryCallback {
public void queryCompleted( Cursor c );
}
/**
* Queries the defined projection, selection and sort order on a background thread
* on the given URI through the ContentResolver retrieved from the given context.<br />
* <br />
* The callback is called on the thread that called this method when the query finishes.
* @param context
* @param uri
* @param callback
*/
public void queryAsync( Context context, Uri uri, final AsyncQueryCallback callback ) {
validateForQuery();
AsyncQueryHandler aqh = new AsyncQueryHandler( context.getContentResolver() ) {
@Override
protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
callback.queryCompleted(cursor);
if ( !cursor.isClosed() ) {
cursor.close();
}
}
};
Pair<String, String[]> builtSelection = buildSelection();
aqh.startQuery(0,
null,
uri,
projection,
builtSelection.first,
builtSelection.second,
sortOrder );
}
/**
* Creates a CursorLoader that queries the defined projection, selection and sort order
* with the specified uri.
* @param context
* @param uri
* @return
*/
public CursorLoader createCursorLoader( Context context, Uri uri ) {
validateForQuery();
Pair<String, String[]> builtSelection = buildSelection();
return new CursorLoader(context,
uri,
projection,
builtSelection.first,
builtSelection.second,
sortOrder );
}
/**
* Creates a SearchFilterProvider that searches through the columns set in {@link #setSearchColumns(String...)}.
* @param context
* @return
*/
public FilterQueryProvider createSearchFilterQueryProvider( final Context context, final Uri uri ) {
return new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
setSearchQuery( TextUtils.isEmpty( constraint ) ? null : constraint.toString() );
return query( context, uri );
}
};
}
/**
* Updates any row that matches the defined selection, with the specified values.
* @param context
* @param values
* @param uri
* @return
*/
public int update( Context context, ContentValues values, Uri uri ) {
Pair<String, String[]> builtSelection = buildSelection();
return context.getContentResolver().update( uri,
values,
builtSelection.first,
builtSelection.second );
}
/**
* Updates any row that matches the defined selection, with the specified values.
* @param provider
* @param values
* @param uri
* @return
* @throws RemoteException May be thrown from {@link ContentProviderClient#update(Uri, ContentValues, String, String[])}
*/
public int update( ContentProviderClient provider, ContentValues values, Uri uri ) throws RemoteException {
Pair<String, String[]> builtSelection = buildSelection();
return provider.update( uri,
values,
builtSelection.first,
builtSelection.second );
}
/**
* Creates an update operation that updates any row that matches the defined selection, with the specified values.<br/>
* <br/>
* To be used in batch operations with {@link ContentProvider#applyBatch(ArrayList)}.
* @return
*/
public ContentProviderOperation createUpdateOperation( ContentValues values, Uri uri) {
Pair<String, String[]> builtSelection = buildSelection();
return ContentProviderOperation.newUpdate( uri ).withSelection( builtSelection.first, builtSelection.second ).withValues( values ).build();
}
/**
* Deletes any row that matches the defined selection.
* @param context
* @param uri
* @return
*/
public int delete( Context context, Uri uri ) {
Pair<String, String[]> builtSelection = buildSelection();
return context.getContentResolver().delete( uri,
builtSelection.first,
builtSelection.second );
}
/**
* Deletes any row that matches the defined selection.
* @param provider
* @param uri
* @return
* @throws RemoteException
*/
public int delete( ContentProviderClient provider, Uri uri ) throws RemoteException {
Pair<String, String[]> builtSelection = buildSelection();
return provider.delete( uri,
builtSelection.first,
builtSelection.second );
}
/**
* Creates a delete operation that deletes any row that matches the defined selection.<br/>
* <br/>
* To be used in batch operations with {@link ContentProvider#applyBatch(ArrayList)}.
* @param uri
* @return
*/
public ContentProviderOperation createDeleteOperation( Uri uri ) {
Pair<String, String[]> builtSelection = buildSelection();
return ContentProviderOperation.newDelete( uri ).withSelection( builtSelection.first, builtSelection.second ).build();
}
/**
* Make ready for another expression by appending "<tt> AND </tt>" if the selection
* is non-empty
*/
private void readySelection() {
if ( selection.length() > 0 ) {
selection.append( " AND " );
}
}
/**
* Append the objects in the array to the selection, each separated by a comma
* @param objects
*/
private void joinInSelection( Object[] objects ) {
for ( int i = 0; i < objects.length; i++ ) {
selection.append( objects[i] );
if ( i != objects.length - 1 ) {
selection.append( ',' );
}
}
}
/**
* Append the longs in the array to the selection, each separated by a comma
* @param objects
*/
private void joinInSelection( long[] objects ) {
for ( int i = 0; i < objects.length; i++ ) {
selection.append( objects[i] );
if ( i != objects.length - 1 ) {
selection.append( ',' );
}
}
}
/**
* Append the integers in the array to the selection, each separated by a comma
* @param objects
*/
private void joinInSelection( int[] objects ) {
for ( int i = 0; i < objects.length; i++ ) {
selection.append( objects[i] );
if ( i != objects.length - 1 ) {
selection.append( ',' );
}
}
}
} |
package org.parser.marpa;
import java.io.BufferedReader;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
/**
* Import/export Application
*/
public class AppImportExport implements Runnable {
ESLIFLoggerInterface eslifLogger;
/**
* @param eslifLogger logger interface
*/
public AppImportExport(ESLIFLoggerInterface eslifLogger) {
this.eslifLogger = eslifLogger;
}
public void run() {
ESLIF eslif;
try {
eslif = ESLIF.getInstance(eslifLogger);
} catch (InterruptedException e) {
e.printStackTrace();
return;
}
final String grammar =
"event ^java_input = predicted java_input\n" +
"\n" +
"java_output ::= lua_proxy action => java_proxy\n" +
"lua_proxy ::= java_input action => ::lua->lua_proxy\n" +
"java_input ::= JAVA_INPUT action => java_proxy\n" +
"JAVA_INPUT ~ [^\\s\\S]\n" +
"\n" +
"<luascript>\n" +
" function table_print (tt, indent, done)\n" +
" done = done or {}\n" +
" indent = indent or 0\n" +
" if type(tt) == \"table\" then\n" +
" for key, value in pairs (tt) do\n" +
" io.write(string.rep (\" \", indent)) -- indent it\n" +
" if type (value) == \"table\" and not done [value] then\n" +
" done [value] = true\n" +
" io.write(string.format(\"[%s] => table\\n\", tostring (key)));\n" +
" io.write(string.rep (\" \", indent+4)) -- indent it\n" +
" io.write(\"(\\n\");\n" +
" table_print (value, indent + 7, done)\n" +
" io.write(string.rep (\" \", indent+4)) -- indent it\n" +
" io.write(\")\\n\");\n" +
" else\n" +
" io.write(string.format(\"[%s] => %s\\n\",\n" +
" tostring (key), tostring(value)))\n" +
" end\n" +
" end\n" +
" else\n" +
" io.write(tostring(tt) .. \"\\n\")\n" +
" end\n" +
" end\n" +
" io.stdout:setvbuf('no')\n" +
"\n" +
" function lua_proxy(value)\n" +
" print('lua_proxy received value of type: '..type(value))\n" +
" if type(value) == 'string' then\n" +
" print('lua_proxy value: '..tostring(value)..', encoding: '..tostring(value:encoding()))\n" +
" else\n" +
" print('lua_proxy value: '..tostring(value))\n" +
" if type(value) == 'table' then\n" +
" table_print(value)\n" +
" end\n" +
" end\n" +
" return value\n" +
" end\n" +
"</luascript>\n";
Object[] inputArray = {
'J',
(short) 1,
(int) 1,
(long) 1,
new byte[] { },
new Boolean(true),
new Boolean(false),
null,
new Character('X'),
};
try {
ESLIFGrammar eslifGrammar = new ESLIFGrammar(eslif, grammar);
for (Object input : inputArray) {
ESLIFRecognizerInterface eslifRecognizerInterface = new AppEmptyRecognizer();
ESLIFRecognizer eslifRecognizer = new ESLIFRecognizer(eslifGrammar, eslifRecognizerInterface);
eslifRecognizer.scan(true); // Initial events
eslifRecognizer.lexemeRead("JAVA_INPUT", input, 1, 1);
ESLIFValueInterface eslifValueInterface = new AppValue();
ESLIFValue eslifValue = new ESLIFValue(eslifRecognizer, eslifValueInterface);
eslifValue.value();
Object value = eslifValueInterface.getResult();
if (input == null) {
// Generic object: then ESLIF guarantees it is the same that transit through all layers
if (value != null) {
this.eslifLogger.error("KO for null");
throw new Exception("null != null");
} else {
this.eslifLogger.info("OK for null");
}
} else if (input.getClass().equals(Object.class)) {
// Generic object: then ESLIF guarantees it is the same that transit through all layers
if (! input.equals(value)) {
this.eslifLogger.error("KO for " + input + " (input class " + input.getClass().getName() + ", value class " + value.getClass().getName() + ")");
throw new Exception(input + " != " + value);
} else {
this.eslifLogger.info("OK for " + input + " (input class " + input.getClass().getName() + ", value class " + value.getClass().getName() + ")");
}
} else {
if (! input.toString().equals(value.toString())) {
this.eslifLogger.error("KO for " + input.toString() + " (input class " + input.getClass().getName() + ", value class " + value.getClass().getName() + ")");
throw new Exception(input.toString() + " != " + value.toString());
} else {
this.eslifLogger.info("OK for " + input.toString() + " (input class " + input.getClass().getName() + ", value class " + value.getClass().getName() + ")");
}
}
}
} catch (Exception e) {
e.printStackTrace();
return;
}
String[] strings = {
"(((3 * 4) + 2 * 7) / 2 - 1)/* This is a\n comment \n */** 3",
"5 / (2 * 3)",
"5 / 2 * 3",
"(5 ** 2) ** 3",
"5 * (2 * 3)",
"5 ** (2 ** 3)",
"5 ** (2 / 3)",
"1 + ( 2 + ( 3 + ( 4 + 5) )",
"1 + ( 2 + ( 3 + ( 4 + 50) ) ) /* comment after */",
" 100",
"not scannable at all",
"100\nsecond line not scannable",
"100 * /* incomplete */"
};
}
} |
package org.jkiss.dbeaver.model.impl.jdbc.struct;
import org.jkiss.dbeaver.Log;
import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.model.impl.jdbc.JDBCSQLDialect;
import org.jkiss.dbeaver.model.messages.ModelMessages;
import org.jkiss.dbeaver.model.DBPDataSource;
import org.jkiss.dbeaver.model.DBPSaveableObject;
import org.jkiss.dbeaver.model.DBUtils;
import org.jkiss.dbeaver.model.data.*;
import org.jkiss.dbeaver.model.exec.*;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCStatement;
import org.jkiss.dbeaver.model.impl.DBObjectNameCaseTransformer;
import org.jkiss.dbeaver.model.impl.data.ExecuteBatchImpl;
import org.jkiss.dbeaver.model.impl.jdbc.cache.JDBCStructCache;
import org.jkiss.dbeaver.model.impl.jdbc.exec.JDBCColumnMetaData;
import org.jkiss.dbeaver.model.impl.struct.AbstractTable;
import org.jkiss.dbeaver.model.meta.Property;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.sql.SQLDataSource;
import org.jkiss.dbeaver.model.sql.SQLDialect;
import org.jkiss.dbeaver.model.sql.SQLUtils;
import org.jkiss.dbeaver.model.struct.*;
import org.jkiss.utils.ArrayUtils;
import org.jkiss.utils.CommonUtils;
import java.util.List;
/**
* JDBC abstract table implementation
*/
public abstract class JDBCTable<DATASOURCE extends DBPDataSource, CONTAINER extends DBSObjectContainer>
extends AbstractTable<DATASOURCE, CONTAINER>
implements DBSDataManipulator, DBPSaveableObject
{
private static final Log log = Log.getLog(JDBCTable.class);
public static final String DEFAULT_TABLE_ALIAS = "x";
public static final int DEFAULT_READ_FETCH_SIZE = 10000;
private boolean persisted;
protected JDBCTable(CONTAINER container, boolean persisted)
{
super(container);
this.persisted = persisted;
}
protected JDBCTable(CONTAINER container, @Nullable String tableName, boolean persisted)
{
super(container, tableName);
this.persisted = persisted;
}
public abstract JDBCStructCache<CONTAINER, ? extends DBSEntity, ? extends DBSEntityAttribute> getCache();
@NotNull
@Property(viewable = true, editable = true, valueTransformer = DBObjectNameCaseTransformer.class, order = 1)
@Override
public String getName()
{
return super.getName();
}
@Override
public boolean isPersisted()
{
return persisted;
}
@Override
public void setPersisted(boolean persisted)
{
this.persisted = persisted;
}
@Override
public int getSupportedFeatures()
{
return DATA_COUNT | DATA_FILTER | DATA_SEARCH | DATA_INSERT | DATA_UPDATE | DATA_DELETE;
}
@NotNull
@Override
public DBCStatistics readData(@NotNull DBCExecutionSource source, @NotNull DBCSession session, @NotNull DBDDataReceiver dataReceiver, DBDDataFilter dataFilter, long firstRow, long maxRows, long flags)
throws DBCException
{
DBCStatistics statistics = new DBCStatistics();
boolean hasLimits = firstRow >= 0 && maxRows > 0;
DBPDataSource dataSource = session.getDataSource();
DBRProgressMonitor monitor = session.getProgressMonitor();
try {
readRequiredMeta(monitor);
} catch (DBException e) {
log.warn(e);
}
DBDPseudoAttribute rowIdAttribute = null;
if ((flags & FLAG_READ_PSEUDO) != 0 && this instanceof DBDPseudoAttributeContainer) {
try {
rowIdAttribute = DBDPseudoAttribute.getAttribute(
((DBDPseudoAttributeContainer) this).getPseudoAttributes(),
DBDPseudoAttributeType.ROWID);
} catch (DBException e) {
log.warn("Can't get pseudo attributes for '" + getName() + "'", e);
}
}
// Always use alias if we have criteria or ROWID.
// Some criteria doesn't work without alias
// (e.g. structured attributes in Oracle requires table alias)
String tableAlias = null;
if (dataFilter.hasConditions() || rowIdAttribute != null) {
if (dataSource instanceof SQLDataSource) {
if (((SQLDataSource) dataSource).getSQLDialect().supportsAliasInSelect()) {
tableAlias = DEFAULT_TABLE_ALIAS;
}
}
}
if (rowIdAttribute != null && tableAlias == null) {
log.warn("Can't query ROWID - table alias not supported");
rowIdAttribute = null;
}
StringBuilder query = new StringBuilder(100);
query.append("SELECT ");
appendSelectSource(session.getProgressMonitor(), query, tableAlias, rowIdAttribute);
query.append(" FROM ").append(getFullQualifiedName());
if (tableAlias != null) {
query.append(" ").append(tableAlias); //$NON-NLS-1$
}
appendQueryConditions(query, tableAlias, dataFilter);
appendQueryOrder(query, tableAlias, dataFilter);
String sqlQuery = query.toString();
statistics.setQueryText(sqlQuery);
monitor.subTask(ModelMessages.model_jdbc_fetch_table_data);
try (DBCStatement dbStat = DBUtils.prepareStatement(
source,
session,
DBCStatementType.SCRIPT,
sqlQuery,
firstRow,
maxRows))
{
if (dbStat instanceof JDBCStatement && maxRows > 0) {
try {
((JDBCStatement) dbStat).setFetchSize(
maxRows <= 0 ? DEFAULT_READ_FETCH_SIZE : (int) maxRows);
} catch (Exception e) {
log.warn(e);
}
}
long startTime = System.currentTimeMillis();
boolean executeResult = dbStat.executeStatement();
statistics.setExecuteTime(System.currentTimeMillis() - startTime);
if (executeResult) {
DBCResultSet dbResult = dbStat.openResultSet();
if (dbResult != null) {
try {
if (rowIdAttribute != null) {
String attrId = rowIdAttribute.getAlias();
if (CommonUtils.isEmpty(attrId)) {
attrId = rowIdAttribute.getName();
}
// Annotate last attribute with row id
List<DBCAttributeMetaData> metaAttributes = dbResult.getMeta().getAttributes();
for (int i = metaAttributes.size(); i > 0; i
DBCAttributeMetaData attr = metaAttributes.get(i - 1);
if (attrId.equalsIgnoreCase(attr.getName()) && attr instanceof JDBCColumnMetaData) {
((JDBCColumnMetaData) attr).setPseudoAttribute(rowIdAttribute);
break;
}
}
}
dataReceiver.fetchStart(session, dbResult, firstRow, maxRows);
startTime = System.currentTimeMillis();
long rowCount = 0;
while (dbResult.nextRow()) {
if (monitor.isCanceled() || (hasLimits && rowCount >= maxRows)) {
// Fetch not more than max rows
break;
}
dataReceiver.fetchRow(session, dbResult);
rowCount++;
if (rowCount % 100 == 0) {
monitor.subTask(rowCount + ModelMessages.model_jdbc__rows_fetched);
monitor.worked(100);
}
}
statistics.setFetchTime(System.currentTimeMillis() - startTime);
statistics.setRowsFetched(rowCount);
} finally {
// First - close cursor
try {
dbResult.close();
} catch (Throwable e) {
log.error("Error closing result set", e); //$NON-NLS-1$
}
// Then - signal that fetch was ended
try {
dataReceiver.fetchEnd(session, dbResult);
} catch (Throwable e) {
log.error("Error while finishing result set fetch", e); //$NON-NLS-1$
}
}
}
}
return statistics;
} finally {
dataReceiver.close();
}
}
protected void appendSelectSource(DBRProgressMonitor monitor, StringBuilder query, String tableAlias, DBDPseudoAttribute rowIdAttribute) {
if (rowIdAttribute != null) {
// If we have pseudo attributes then query gonna be more complex
query.append(tableAlias).append(".*"); //$NON-NLS-1$
query.append(",").append(rowIdAttribute.translateExpression(tableAlias));
if (rowIdAttribute.getAlias() != null) {
query.append(" as ").append(rowIdAttribute.getAlias());
}
} else {
if (tableAlias != null) {
query.append(tableAlias).append(".");
}
query.append("*"); //$NON-NLS-1$
}
}
@Override
public long countData(@NotNull DBCExecutionSource source, @NotNull DBCSession session, @Nullable DBDDataFilter dataFilter) throws DBCException
{
DBRProgressMonitor monitor = session.getProgressMonitor();
StringBuilder query = new StringBuilder("SELECT COUNT(*) FROM "); //$NON-NLS-1$
query.append(getFullQualifiedName());
appendQueryConditions(query, null, dataFilter);
monitor.subTask(ModelMessages.model_jdbc_fetch_table_row_count);
try (DBCStatement dbStat = session.prepareStatement(
DBCStatementType.QUERY,
query.toString(),
false, false, false))
{
dbStat.setStatementSource(source);
if (!dbStat.executeStatement()) {
return 0;
}
DBCResultSet dbResult = dbStat.openResultSet();
if (dbResult == null) {
return 0;
}
try {
if (dbResult.nextRow()) {
Object result = dbResult.getAttributeValue(0);
if (result == null) {
return 0;
} else if (result instanceof Number) {
return ((Number) result).longValue();
} else {
return Long.parseLong(result.toString());
}
} else {
return 0;
}
} finally {
dbResult.close();
}
}
}
@NotNull
@Override
public ExecuteBatch insertData(@NotNull DBCSession session, @NotNull final DBSAttributeBase[] attributes, @Nullable DBDDataReceiver keysReceiver, @NotNull final DBCExecutionSource source)
throws DBCException
{
readRequiredMeta(session.getProgressMonitor());
return new ExecuteBatchImpl(attributes, keysReceiver, true) {
@NotNull
@Override
protected DBCStatement prepareStatement(@NotNull DBCSession session, Object[] attributeValues) throws DBCException {
// Make query
StringBuilder query = new StringBuilder(200);
query
.append(useUpsert(session) ? "UPSERT" : "INSERT")
.append(" INTO ").append(getFullQualifiedName()).append(" ("); //$NON-NLS-1$ //$NON-NLS-2$
boolean hasKey = false;
for (int i = 0; i < attributes.length; i++) {
DBSAttributeBase attribute = attributes[i];
if (attribute.isPseudoAttribute() || DBUtils.isNullValue(attributeValues[i])) {
continue;
}
if (hasKey) query.append(","); //$NON-NLS-1$
hasKey = true;
query.append(getAttributeName(attribute));
}
query.append(")\nVALUES ("); //$NON-NLS-1$
hasKey = false;
for (int i = 0; i < attributes.length; i++) {
DBSAttributeBase attribute = attributes[i];
if (attribute.isPseudoAttribute() || DBUtils.isNullValue(attributeValues[i])) {
continue;
}
if (hasKey) query.append(","); //$NON-NLS-1$
hasKey = true;
query.append("?"); //$NON-NLS-1$
}
query.append(")"); //$NON-NLS-1$
// Execute
DBCStatement dbStat = session.prepareStatement(DBCStatementType.QUERY, query.toString(), false, false, keysReceiver != null);
dbStat.setStatementSource(source);
return dbStat;
}
@Override
protected void bindStatement(@NotNull DBDValueHandler[] handlers, @NotNull DBCStatement statement, Object[] attributeValues) throws DBCException {
int paramIndex = 0;
for (int k = 0; k < handlers.length; k++) {
DBSAttributeBase attribute = attributes[k];
if (attribute.isPseudoAttribute() || DBUtils.isNullValue(attributeValues[k])) {
continue;
}
handlers[k].bindValueObject(statement.getSession(), statement, attribute, paramIndex++, attributeValues[k]);
}
}
};
}
@NotNull
@Override
public ExecuteBatch updateData(
@NotNull DBCSession session,
@NotNull final DBSAttributeBase[] updateAttributes,
@NotNull final DBSAttributeBase[] keyAttributes,
@Nullable DBDDataReceiver keysReceiver, @NotNull final DBCExecutionSource source)
throws DBCException
{
if (useUpsert(session)) {
return insertData(
session,
ArrayUtils.concatArrays(updateAttributes, keyAttributes),
keysReceiver,
source);
}
readRequiredMeta(session.getProgressMonitor());
DBSAttributeBase[] attributes = ArrayUtils.concatArrays(updateAttributes, keyAttributes);
return new ExecuteBatchImpl(attributes, keysReceiver, false) {
@NotNull
@Override
protected DBCStatement prepareStatement(@NotNull DBCSession session, Object[] attributeValues) throws DBCException {
String tableAlias = null;
SQLDialect dialect = ((SQLDataSource) session.getDataSource()).getSQLDialect();
if (dialect.supportsAliasInUpdate()) {
tableAlias = DEFAULT_TABLE_ALIAS;
}
// Make query
StringBuilder query = new StringBuilder();
query.append("UPDATE ").append(getFullQualifiedName());
if (tableAlias != null) {
query.append(' ').append(tableAlias);
}
query.append("\nSET "); //$NON-NLS-1$ //$NON-NLS-2$
boolean hasKey = false;
for (DBSAttributeBase attribute : updateAttributes) {
if (hasKey) query.append(","); //$NON-NLS-1$
hasKey = true;
if (tableAlias != null) {
query.append(tableAlias).append(dialect.getStructSeparator());
}
query.append(getAttributeName(attribute)).append("=?"); //$NON-NLS-1$
}
query.append("\nWHERE "); //$NON-NLS-1$
hasKey = false;
for (int i = 0; i < keyAttributes.length; i++) {
DBSAttributeBase attribute = keyAttributes[i];
if (hasKey) query.append(" AND "); //$NON-NLS-1$
hasKey = true;
appendAttributeCriteria(tableAlias, dialect, query, attribute, attributeValues[updateAttributes.length + i]);
}
// Execute
DBCStatement dbStat = session.prepareStatement(DBCStatementType.QUERY, query.toString(), false, false, keysReceiver != null);
dbStat.setStatementSource(source);
return dbStat;
}
@Override
protected void bindStatement(@NotNull DBDValueHandler[] handlers, @NotNull DBCStatement statement, Object[] attributeValues) throws DBCException {
int paramIndex = 0;
for (int k = 0; k < handlers.length; k++) {
DBSAttributeBase attribute = attributes[k];
if (k >= updateAttributes.length && DBUtils.isNullValue(attributeValues[k])) {
// Skip NULL criteria binding
continue;
}
handlers[k].bindValueObject(statement.getSession(), statement, attribute, paramIndex++, attributeValues[k]);
}
}
};
}
@NotNull
@Override
public ExecuteBatch deleteData(@NotNull DBCSession session, @NotNull final DBSAttributeBase[] keyAttributes, @NotNull final DBCExecutionSource source)
throws DBCException
{
readRequiredMeta(session.getProgressMonitor());
return new ExecuteBatchImpl(keyAttributes, null, false) {
@NotNull
@Override
protected DBCStatement prepareStatement(@NotNull DBCSession session, Object[] attributeValues) throws DBCException {
String tableAlias = null;
SQLDialect dialect = ((SQLDataSource) session.getDataSource()).getSQLDialect();
if (dialect.supportsAliasInUpdate()) {
tableAlias = DEFAULT_TABLE_ALIAS;
}
// Make query
StringBuilder query = new StringBuilder();
query.append("DELETE FROM ").append(getFullQualifiedName());
if (tableAlias != null) {
query.append(' ').append(tableAlias);
}
query.append("\nWHERE "); //$NON-NLS-1$ //$NON-NLS-2$
boolean hasKey = false;
for (int i = 0; i < keyAttributes.length; i++) {
if (hasKey) query.append(" AND "); //$NON-NLS-1$
hasKey = true;
appendAttributeCriteria(tableAlias, dialect, query, keyAttributes[i], attributeValues[i]);
}
// Execute
DBCStatement dbStat = session.prepareStatement(DBCStatementType.QUERY, query.toString(), false, false, false);
dbStat.setStatementSource(source);
return dbStat;
}
@Override
protected void bindStatement(@NotNull DBDValueHandler[] handlers, @NotNull DBCStatement statement, Object[] attributeValues) throws DBCException {
int paramIndex = 0;
for (int k = 0; k < handlers.length; k++) {
DBSAttributeBase attribute = attributes[k];
if (DBUtils.isNullValue(attributeValues[k])) {
// Skip NULL criteria binding
continue;
}
handlers[k].bindValueObject(statement.getSession(), statement, attribute, paramIndex++, attributeValues[k]);
}
}
};
}
private boolean useUpsert(@NotNull DBCSession session) {
SQLDialect dialect = session.getDataSource() instanceof SQLDataSource ?
((SQLDataSource) session.getDataSource()).getSQLDialect() : null;
return dialect instanceof JDBCSQLDialect && ((JDBCSQLDialect) dialect).supportsUpsertStatement();
}
private String getAttributeName(@NotNull DBSAttributeBase attribute) {
// Entity attribute obtain commented because it broke complex attributes full name construction
// We can't use entity attr because only particular query metadata contains real structure
// if (attribute instanceof DBDAttributeBinding) {
// DBSEntityAttribute entityAttribute = ((DBDAttributeBinding) attribute).getEntityAttribute();
// if (entityAttribute != null) {
// attribute = entityAttribute;
// Do not quote pseudo attribute name
return attribute.isPseudoAttribute() ? attribute.getName() : DBUtils.getObjectFullName(getDataSource(), attribute);
}
private void appendQueryConditions(@NotNull StringBuilder query, @Nullable String tableAlias, @Nullable DBDDataFilter dataFilter)
{
if (dataFilter != null && dataFilter.hasConditions()) {
query.append("\nWHERE "); //$NON-NLS-1$
SQLUtils.appendConditionString(dataFilter, getDataSource(), tableAlias, query, true);
}
}
private void appendQueryOrder(@NotNull StringBuilder query, @Nullable String tableAlias, @Nullable DBDDataFilter dataFilter)
{
if (dataFilter != null) {
// Construct ORDER BY
if (dataFilter.hasOrdering()) {
query.append("\nORDER BY "); //$NON-NLS-1$
SQLUtils.appendOrderString(dataFilter, getDataSource(), tableAlias, query);
}
}
}
private void appendAttributeCriteria(@Nullable String tableAlias, SQLDialect dialect, StringBuilder query, DBSAttributeBase attribute, Object value) {
DBDPseudoAttribute pseudoAttribute = null;
if (attribute.isPseudoAttribute()) {
if (attribute instanceof DBDAttributeBinding) {
pseudoAttribute = ((DBDAttributeBinding) attribute).getMetaAttribute().getPseudoAttribute();
} else if (attribute instanceof DBCAttributeMetaData) {
pseudoAttribute = ((DBCAttributeMetaData)attribute).getPseudoAttribute();
} else {
log.error("Unsupported attribute argument: " + attribute);
}
}
if (pseudoAttribute != null) {
if (tableAlias == null) {
tableAlias = this.getFullQualifiedName();
}
String criteria = pseudoAttribute.translateExpression(tableAlias);
query.append(criteria);
} else {
if (tableAlias != null) {
query.append(tableAlias).append(dialect.getStructSeparator());
}
query.append(getAttributeName(attribute));
}
if (DBUtils.isNullValue(value)) {
query.append(" IS NULL"); //$NON-NLS-1$
} else {
query.append("=?"); //$NON-NLS-1$
}
}
/**
* Reads and caches metadata which is required for data requests
* @param monitor progress monitor
* @throws DBCException on error
*/
private void readRequiredMeta(DBRProgressMonitor monitor)
throws DBCException
{
try {
getAttributes(monitor);
}
catch (DBException e) {
throw new DBCException("Can't cache table columns", e);
}
}
} |
package com.flashmath.activity;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import com.education.flashmath.R;
import com.flashmath.fragment.ArithmeticQuestionAnswerFragment;
import com.flashmath.fragment.ArithmeticQuestionFragment;
import com.flashmath.fragment.FractionQuestionAnswerFragment;
import com.flashmath.fragment.FractionQuestionFragment;
import com.flashmath.fragment.QuestionFragment;
import com.flashmath.models.ArithmeticQuestion;
import com.flashmath.models.FractionQuestion;
import com.flashmath.models.Question;
import com.flashmath.network.FlashMathClient;
import com.flashmath.util.ColorUtil;
import com.loopj.android.http.JsonHttpResponseHandler;
public class QuestionActivity extends Activity {
public static final String IS_MOCK_QUIZ_INTENT_KEY = "isMockQuiz";
private static final String NEXT_QUESTION_BTN_TITLE = "Next";
private static final String VERIFY_ANSWER_BTN_TITLE = "Answer";
private static final String END_QUIZ_BTN_TITLE = "Finish";
public static final String QUESTIONS_ANSWERED_INTENT_KEY = "QUESTIONS_ANSWERED";
public QuestionFragment qf;
public Fragment qaf;
private int currentQuestionIndex;
private ArrayList<Question> questionList;
private TextView tvQuestionProgress;
private Button btnVerifyAndNextQuestion;
private String subject;
private String backgroundColor;
private boolean isMockQuiz;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//we will use progress wheel when it's needed (e.g. network requests)
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_question);
btnVerifyAndNextQuestion = (Button) findViewById(R.id.btnVerifyAndNextQuestion);
btnVerifyAndNextQuestion.setVisibility(View.VISIBLE);
subject = getIntent().getStringExtra("subject");
isMockQuiz = getIntent().getBooleanExtra(IS_MOCK_QUIZ_INTENT_KEY, true);
btnVerifyAndNextQuestion.setBackground(ColorUtil.getButtonStyle(subject, this));
Button btnClear = (Button) findViewById(R.id.btnClear);
btnClear.setBackground(ColorUtil.getButtonStyle(subject, this));
backgroundColor = ColorUtil.identifySubjectColor(subject);
tvQuestionProgress = (TextView) findViewById(R.id.tvQuestionProgress);
TextView tvQuestionSlash = (TextView) findViewById(R.id.tvQuestionSlash);
TextView tvQuestionTotal = (TextView) findViewById(R.id.tvQuestionTotal);
tvQuestionProgress.setTextColor(ColorUtil.subjectColorInt(subject));
tvQuestionSlash.setTextColor(ColorUtil.subjectColorInt(subject));
tvQuestionTotal.setTextColor(ColorUtil.subjectColorInt(subject));
ActionBar ab = getActionBar();
ab.setIcon(ColorUtil.getBarIcon(subject, this));
String subjectTitle = Character.toUpperCase(subject.charAt(0))+subject.substring(1);
ab.setTitle(subjectTitle + " Questions");
if (subject.equalsIgnoreCase("Fractions")) {
qf = new FractionQuestionFragment();
} else {
qf = new ArithmeticQuestionFragment();
}
//disable the button until we have data loaded...
btnVerifyAndNextQuestion.setEnabled(false);
setupServerQuestions();
qf.setBackgroundColor(backgroundColor);
getFragmentManager().beginTransaction().add(R.id.fragmentForQuestion, qf).commit();
}
private void setupServerQuestions() {
setProgressBarIndeterminateVisibility(true);
currentQuestionIndex = 0;
FlashMathClient client = FlashMathClient.getClient(this);
client.getQuestions(subject, new JsonHttpResponseHandler() {
@Override
public void onSuccess(JSONObject response) {
JSONArray jsonResults = null;
try {
jsonResults = response.getJSONArray("questions");
questionList = new ArrayList<Question>();
if (subject.equalsIgnoreCase("Fractions")) {
questionList.addAll(FractionQuestion.fromJSONArray(jsonResults, subject));
} else {
questionList.addAll(ArithmeticQuestion.fromJSONArray(jsonResults, subject));
}
} catch (JSONException e) {
e.printStackTrace();
}
qf.setQuestion(questionList.get(currentQuestionIndex));
if (subject.equalsIgnoreCase("Fractions")) {
((FractionQuestionFragment) qf).setupFractionQuestion();
qaf = new FractionQuestionAnswerFragment();
((FractionQuestionAnswerFragment) qaf).setQuestion(questionList.get(currentQuestionIndex));
} else {
((ArithmeticQuestionFragment) qf).setupArithmeticQuestion();
qaf = new ArithmeticQuestionAnswerFragment();
((ArithmeticQuestionAnswerFragment) qaf).setQuestion(questionList.get(currentQuestionIndex));
}
tvQuestionProgress.setText(String.valueOf(currentQuestionIndex + 1));
//data is loaded, we can enable the button
btnVerifyAndNextQuestion.setEnabled(true);
setProgressBarIndeterminateVisibility(false);
}
@Override
public void onFailure(Throwable arg0, JSONObject errorResponse) {
super.onFailure(arg0, errorResponse);
btnVerifyAndNextQuestion.setEnabled(true);
setProgressBarIndeterminateVisibility(false);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.question, menu);
return true;
}
public void onClearQuestionAnswer(View v) {
qf.clearAnswerFields();
}
public void onVerifyAndNextQuestionPressed(View v) {
if (btnVerifyAndNextQuestion.getText().toString().equals(VERIFY_ANSWER_BTN_TITLE)) {
onVerifyQuestionAnswer(v);
} else if (btnVerifyAndNextQuestion.getText().toString().equals(NEXT_QUESTION_BTN_TITLE)){
onNextQuestion(v);
} else {
qf.saveUserAnswer();
finalizeQuiz();
}
}
public void onVerifyQuestionAnswer(View v) {
qf.saveUserAnswer();
if (subject.equalsIgnoreCase("Fractions")) {
((FractionQuestionAnswerFragment) qaf).setQuestion(questionList.get(currentQuestionIndex));
// Create and commit a new fragment transaction that adds the fragment for the back of
// the card, uses custom animations, and is part of the fragment manager's back stack.
getFragmentManager().beginTransaction()
// Replace the default fragment animations with animator resources representing
// rotations when switching to the back of the card, as well as animator
// resources representing rotations when flipping back to the front (e.g. when
// the system Back button is pressed).
.setCustomAnimations(R.animator.card_flip_right_in, R.animator.card_flip_right_out,
R.animator.card_flip_left_in, R.animator.card_flip_left_out)
// Replace any fragments currently in the container view with a fragment
// representing the next page (indicated by the just-incremented currentPage
// variable).
.replace(R.id.fragmentForQuestion, (FractionQuestionAnswerFragment) qaf)
// Add this transaction to the back stack, allowing users to press Back
// to get to the front of the card.
.addToBackStack(null)
// Commit the transaction.
.commit();
} else {
((ArithmeticQuestionAnswerFragment) qaf).setQuestion(questionList.get(currentQuestionIndex));
// Create and commit a new fragment transaction that adds the fragment for the back of
// the card, uses custom animations, and is part of the fragment manager's back stack.
getFragmentManager().beginTransaction()
// Replace the default fragment animations with animator resources representing
// rotations when switching to the back of the card, as well as animator
// resources representing rotations when flipping back to the front (e.g. when
// the system Back button is pressed).
.setCustomAnimations(R.animator.card_flip_right_in, R.animator.card_flip_right_out,
R.animator.card_flip_left_in, R.animator.card_flip_left_out)
// Replace any fragments currently in the container view with a fragment
// representing the next page (indicated by the just-incremented currentPage
// variable).
.replace(R.id.fragmentForQuestion, (ArithmeticQuestionAnswerFragment) qaf)
// Add this transaction to the back stack, allowing users to press Back
// to get to the front of the card.
.addToBackStack(null)
// Commit the transaction.
.commit();
}
//we reached end of questions, remove the Next Question button and
//let user use End Quiz button
if(currentQuestionIndex+1 >= this.questionList.size()) {
btnVerifyAndNextQuestion.setText(END_QUIZ_BTN_TITLE);
} else {
btnVerifyAndNextQuestion.setText(NEXT_QUESTION_BTN_TITLE);
}
}
public void onNextQuestion(View v) {
if (currentQuestionIndex < this.questionList.size()) {
btnVerifyAndNextQuestion.setText(VERIFY_ANSWER_BTN_TITLE);
//if user forgot to press save button and just presses next question
qf.saveUserAnswer();
Question q = qf.getQuestion();
this.questionList.remove(currentQuestionIndex);
this.questionList.add(currentQuestionIndex, q);
currentQuestionIndex++;
if(currentQuestionIndex < this.questionList.size()) {
getFragmentManager().popBackStack();
getFragmentManager().beginTransaction().remove(qf).commit();
if (this.subject.equalsIgnoreCase("Fractions")) {
qf = new FractionQuestionFragment();
} else {
qf = new ArithmeticQuestionFragment();
}
qf.setBackgroundColor(backgroundColor);
qf.setQuestion(this.questionList.get(currentQuestionIndex));
getFragmentManager().beginTransaction().add(R.id.fragmentForQuestion, qf).commit();
tvQuestionProgress.setText(String.valueOf(currentQuestionIndex + 1));
} else {
finalizeQuiz();
}
}
else {
finalizeQuiz();
}
}
public void onEndQuiz(View v) {
qf.saveUserAnswer();
finalizeQuiz();
}
private void finalizeQuiz() {
Intent i = new Intent(this, ResultActivity.class);
i.putExtra(QuestionActivity.QUESTIONS_ANSWERED_INTENT_KEY, this.questionList);
i.putExtra(ResultActivity.SUBJECT_INTENT_KEY, subject);
i.putExtra(QuestionActivity.IS_MOCK_QUIZ_INTENT_KEY, isMockQuiz);
startActivity(i);
}
@Override
public void onBackPressed() {
Intent i = new Intent(this, SubjectActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} |
package org.helioviewer.jhv.plugins.swek.config;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.helioviewer.base.logging.Log;
import org.helioviewer.jhv.Settings;
import org.helioviewer.jhv.plugins.swek.settings.SWEKProperties;
import org.helioviewer.jhv.plugins.swek.settings.SWEKSettings;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @author Bram.Bourgognie@oma.be
*
*/
public class SWEKConfigurationManager {
/** Singleton instance */
private static SWEKConfigurationManager singletonInstance;
/** Config loaded */
private boolean configLoaded;
/** Config file URL */
private URL configFileURL;
/** The loaded configuration */
private SWEKConfiguration configuration;
/** Map containing the sources */
private final Map<String, SWEKSource> sources;
/** Map containing the parameters */
private final Map<String, SWEKParameter> parameters;
/** Map containing the event types */
private final Map<String, SWEKEventType> eventTypes;
private final Properties swekProperties;
/**
* private constructor
*/
private SWEKConfigurationManager() {
this.configLoaded = false;
this.sources = new HashMap<String, SWEKSource>();
this.parameters = new HashMap<String, SWEKParameter>();
this.eventTypes = new HashMap<String, SWEKEventType>();
this.swekProperties = SWEKProperties.getSingletonInstance().getSWEKProperties();
}
/**
* Gives access to the singleton instance
*
* @return the singleton instance
*/
public static SWEKConfigurationManager getSingletonInstance() {
if (singletonInstance == null) {
singletonInstance = new SWEKConfigurationManager();
}
return singletonInstance;
}
/**
* Loads the configuration.
*
* If no configuration file is set by the user, the program downloads the
* configuration file online and saves it the
* JHelioviewer/Plugins/swek-plugin folder.
*
*/
public void loadConfiguration() {
if (!this.configLoaded) {
Log.debug("search and open the configuration file");
boolean isConfigParsed;
if (checkAndOpenUserSetFile()) {
isConfigParsed = parseConfigFile();
} else if (checkAndOpenHomeDirectoryFile()) {
isConfigParsed = parseConfigFile();
} else if (checkAndOpenOnlineFile()) {
isConfigParsed = parseConfigFile();
} else {
isConfigParsed = false;
}
if (!isConfigParsed) {
// TODO set on the panel the config file could not be parsed.
this.configLoaded = false;
} else {
this.configLoaded = true;
}
}
}
/**
* Gives a map with all the event types. The event type name is the key and
* the event type is the value.
*
* @return map containing the event types found in the configuration file
*/
public Map<String, SWEKEventType> getEventTypes() {
loadConfiguration();
return this.eventTypes;
}
/**
* Gives a map with all the event sources. The source name is the key and
* the source is the value.
*
* @return map containing the sources found in the configuration file
*/
public Map<String, SWEKSource> getSources() {
loadConfiguration();
return this.sources;
}
/**
* Downloads the SWEK configuration from the Internet and saves it in the
* plugin home directory.
*
* @return true if the the file was found and copied to the home directory,
* false if the file could not be found, copied or something else
* went wrong.
*/
private boolean checkAndOpenOnlineFile() {
Log.debug("Download the configuration file from the net and copy it to the plugin home directory");
try {
URL url = new URL(this.swekProperties.getProperty("plugin.swek.onlineconfigfile"));
ReadableByteChannel rbc = Channels.newChannel(url.openStream());
String saveFile = SWEKSettings.SWEK_HOME + this.swekProperties.getProperty("plugin.swek.configfilename");
FileOutputStream fos = new FileOutputStream(saveFile);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
this.configFileURL = new URL("file://" + saveFile);
return true;
} catch (MalformedURLException e) {
Log.debug("Could not create a URL from the value found in the properties file: "
+ this.swekProperties.getProperty("plugin.swek.onlineconfigfile") + " : " + e);
} catch (IOException e) {
Log.debug("Something went wrong downloading the configuration file from the server or saving it to the local machine : " + e);
}
return false;
}
/**
* Checks the home directory of the plugin (normally
* ~/JHelioviewer/Plugins/swek-plugin/) for the existence of the
* SWEKSettings.json file.
*
* @return true if the file was found and useful, false if the file was not
* found.
*/
private boolean checkAndOpenHomeDirectoryFile() {
String configFile = SWEKSettings.SWEK_HOME + this.swekProperties.getProperty("plugin.swek.configfilename");
try {
File f = new File(configFile);
if (f.exists()) {
this.configFileURL = new URL("file://" + configFile);
return true;
} else {
Log.debug("File created from the settings : " + configFile + " does not exists on this system.");
}
} catch (MalformedURLException e) {
Log.debug("File at possition " + configFile + " could not be parsed into an URL");
}
return false;
}
/**
* Checks the jhelioviewer settings file for a swek configuration file.
*
* @return true if the file as found and useful, false if the file was not
* found.
*/
private boolean checkAndOpenUserSetFile() {
Log.debug("Search for a user defined configuration file in the JHelioviewer setting file.");
Settings jhvSettings = Settings.getSingletonInstance();
String fileName = jhvSettings.getProperty("plugin.swek.configfile");
if (fileName == null) {
Log.debug("No configured filename found.");
return false;
} else {
try {
URI fileLocation = new URI(fileName);
this.configFileURL = fileLocation.toURL();
Log.debug("Config file : " + this.configFileURL.toString());
return true;
} catch (URISyntaxException e) {
Log.debug("Wrong URI syntax for the found file name : " + fileName);
} catch (MalformedURLException e) {
Log.debug("Could not convert the URI in a correct URL. The found file name : " + fileName);
}
return false;
}
}
/**
* Parses the SWEK settings.
*/
private boolean parseConfigFile() {
try {
InputStream configIs = this.configFileURL.openStream();
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(configIs));
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
JSONObject configJSON = new JSONObject(sb.toString());
return parseJSONConfig(configJSON);
} catch (IOException e) {
Log.debug("The configuration file could not be parsed : " + e);
} catch (JSONException e) {
Log.debug("Could not parse the given JSON : " + e);
}
return false;
}
/**
* Parses the JSON from start
*
* @param configJSON
* The JSON to parse
* @return true if the JSON configuration could be parsed, false if not.
*/
private boolean parseJSONConfig(JSONObject configJSON) {
this.configuration = new SWEKConfiguration();
try {
this.configuration.setManuallyChanged(parseManuallyChanged(configJSON));
this.configuration.setConfigurationVersion(parseVersion(configJSON));
this.configuration.setSources(parseSources(configJSON));
this.configuration.setEventTypes(parseEventTypes(configJSON));
this.configuration.setRelatedEvents(parseRelatedEvents(configJSON));
return true;
} catch (JSONException e) {
Log.error("Could not parse config json");
e.printStackTrace();
return false;
}
}
/**
* Parses a if the configuration was manually changed from a json.
*
* @param jsonObject
* the json from which to parse the manually changed indication
* @return the parsed manually changed indication
* @throws JSONException
* if the manually changed indication could not be parsed
*/
private boolean parseManuallyChanged(JSONObject configJSON) throws JSONException {
return configJSON.getBoolean("manually_changed");
}
/**
* Parses the configuration version from the big json.
*
* @param configJSON
* The JSON from which to parse
* @return The parsed configuration version
* @throws JSONException
* If the configuration version could not be parsed.
*/
private String parseVersion(JSONObject configJSON) throws JSONException {
return configJSON.getString("config_version");
}
/**
* Parses the list of sources from a json and adds the sources to a map
* indexed on the name of the source.
*
* @param configJSON
* the JSON from which to parse the sources
* @return a list of sources parsed from the JSON
* @throws JSONException
* if the sources could not be parsed
*/
private List<SWEKSource> parseSources(JSONObject configJSON) throws JSONException {
ArrayList<SWEKSource> swekSources = new ArrayList<SWEKSource>();
JSONArray sourcesArray = configJSON.getJSONArray("sources");
for (int i = 0; i < sourcesArray.length(); i++) {
SWEKSource source = parseSource(sourcesArray.getJSONObject(i));
this.sources.put(source.getSourceName(), source);
swekSources.add(source);
}
return swekSources;
}
/**
* Parses a source from a json.
*
* @param jsonObject
* the json from which to parse the source
* @return the parsed source
* @throws JSONException
* if the source could not be parsed
*/
private SWEKSource parseSource(JSONObject jsonObject) throws JSONException {
SWEKSource source = new SWEKSource();
source.setSourceName(parseSourceName(jsonObject));
source.setProviderName(parseProviderName(jsonObject));
source.setDownloaderClass(parseDownloader(jsonObject));
source.setEventParserClass(parseEventParser(jsonObject));
source.setJarLocation(parseJarLocation(jsonObject));
source.setBaseURL(parseBaseURL(jsonObject));
source.setGeneralParameters(parseGeneralParameters(jsonObject));
return source;
}
/**
* Parses the source from a json.
*
* @param jsonObject
* the json from which to parse the source
* @return the parsed source
* @throws JSONException
* if the source could not be parsed
*/
private String parseSourceName(JSONObject jsonObject) throws JSONException {
return jsonObject.getString("name");
}
/**
* Parses the provider name from a json.
*
* @param jsonObject
* the json from which to parse the provider name
* @return the parsed provider name
* @throws JSONException
* if the provider name could not be parsed
*/
private String parseProviderName(JSONObject jsonObject) throws JSONException {
return jsonObject.getString("provider_name");
}
/**
* Parses the downloader description from a json.
*
* @param jsonObject
* the json from which to parse the downloader description
* @return the parsed downloader description
* @throws JSONException
* if the downloader description could not be parsed
*/
private String parseDownloader(JSONObject jsonObject) throws JSONException {
return jsonObject.getString("downloader");
}
/**
* Parses the event parser from a json.
*
* @param jsonObject
* the json from which to parse the event parser
* @return the parsed event parser
* @throws JSONException
* if the event parser could not be parsed
*/
private String parseEventParser(JSONObject jsonObject) throws JSONException {
return jsonObject.getString("event_parser");
}
/**
* Parses the jar location from a json.
*
* @param jsonObject
* the json from which to parse the jar location
* @return the parsed jar location
* @throws JSONException
* if the event parser could not be parsed
*/
private String parseJarLocation(JSONObject jsonObject) throws JSONException {
return jsonObject.getString("jar_location");
}
/**
* Parses the base url from a json.
*
* @param jsonObject
* the json from which to parse the base url
* @return the parsed base url
* @throws JSONException
* if the base url could not be parsed
*/
private String parseBaseURL(JSONObject jsonObject) throws JSONException {
return jsonObject.getString("base_url");
}
/**
* Parses the general parameters from a json.
*
* @param jsonObject
* the json from which to parse the general parameters
* @return the parsed general parameters
* @throws JSONException
* if the general parameters could not be parsed
*/
private List<SWEKParameter> parseGeneralParameters(JSONObject jsonObject) throws JSONException {
List<SWEKParameter> parameterList = new ArrayList<SWEKParameter>();
JSONArray parameterArray = jsonObject.getJSONArray("general_parameters");
for (int i = 0; i < parameterArray.length(); i++) {
SWEKParameter parameter = parseParameter(parameterArray.getJSONObject(i));
parameterList.add(parameter);
this.parameters.put(parameter.getParameterName(), parameter);
}
return parameterList;
}
/**
* Parses the list of event types from a json.
*
* @param configJSON
* the JSON from which to parse the event types
* @return a list of event types parsed from the JSON
* @throws JSONException
* if the event types could not be parsed
*/
private List<SWEKEventType> parseEventTypes(JSONObject configJSON) throws JSONException {
List<SWEKEventType> result = new ArrayList<SWEKEventType>();
JSONArray eventJSONArray = configJSON.getJSONArray("events_types");
for (int i = 0; i < eventJSONArray.length(); i++) {
SWEKEventType eventType = parseEventType(eventJSONArray.getJSONObject(i));
result.add(eventType);
this.eventTypes.put(eventType.getEventName(), eventType);
}
return result;
}
/**
* Parses an event type from a json.
*
* @param object
* The event type to parse
* @return The parsed event type
* @throws JSONException
*/
private SWEKEventType parseEventType(JSONObject object) throws JSONException {
SWEKEventType eventType = new SWEKEventType();
eventType.setEventName(parseEventName(object));
eventType.setSuppliers(parseSuppliers(object));
eventType.setParameterList(parseParameterList(object));
eventType.setRequestIntervalExtension(parseRequestIntervalExtension(object));
eventType.setStandardSelected(parseStandardSelected(object));
eventType.setGroupOn(parseGroupOn(object));
eventType.setCoordinateSystem(parseCoordinateSystem(object));
eventType.setSpatialRegion(parseSpatialRegion(object));
return eventType;
}
/**
* Parses the event name from a json.
*
* @param object
* the json from which the event name is parsed
* @return the event name
* @throws JSONException
* if the supplier name could not be parsed
*/
private String parseEventName(JSONObject object) throws JSONException {
return object.getString("event_name");
}
/**
* Parses the suppliers from a json.
*
* @param jsonObject
* the json from which the suppliers are parsed
* @return the suppliers list
* @throws JSONException
* if the suppliers could not be parsed
*/
private List<SWEKSupplier> parseSuppliers(JSONObject object) throws JSONException {
List<SWEKSupplier> suppliers = new ArrayList<SWEKSupplier>();
JSONArray suppliersArray = object.getJSONArray("suppliers");
for (int i = 0; i < suppliersArray.length(); i++) {
suppliers.add(parseSupplier(suppliersArray.getJSONObject(i)));
}
return suppliers;
}
/**
* Parses a supplier from a json.
*
* @param object
* the json from which the supplier is parsed
* @return the supplier
* @throws JSONException
* if the supplier could not be parsed
*/
private SWEKSupplier parseSupplier(JSONObject object) throws JSONException {
SWEKSupplier supplier = new SWEKSupplier();
supplier.setSupplierName(parseSupplierName(object));
supplier.setSource(parseSupplierSource(object));
return supplier;
}
/**
* Parses the supplier name from a json.
*
* @param object
* the json from which the supplier name is parsed
* @return the supplier name
* @throws JSONException
* if the supplier name could not be parsed
*/
private String parseSupplierName(JSONObject object) throws JSONException {
return object.getString("supplier_name");
}
/**
* Parses a supplier source from a json.
*
* @param object
* the json from which the supplier source is parsed
* @return the supplier source
* @throws JSONException
* if the supplier source could not be parsed
*/
private SWEKSource parseSupplierSource(JSONObject object) throws JSONException {
return this.sources.get(object.getString("source"));
}
/**
* Parses the parameter list from the given JSON.
*
* @param object
* the json from which to parse the parameter list
* @return the parameter list
* @throws JSONException
* if the parameter list could not be parsed.
*/
private List<SWEKParameter> parseParameterList(JSONObject object) throws JSONException {
List<SWEKParameter> parameterList = new ArrayList<SWEKParameter>();
JSONArray parameterListArray = object.getJSONArray("parameter_list");
for (int i = 0; i < parameterListArray.length(); i++) {
SWEKParameter parameter = parseParameter((JSONObject) parameterListArray.get(i));
parameterList.add(parameter);
this.parameters.put(parameter.getParameterName(), parameter);
}
return parameterList;
}
/**
* Parses a parameter from json.
*
* @param jsonObject
* the json from which to parse
* @return the parsed parameter
* @throws JSONException
* if the parameter could not be parsed
*/
private SWEKParameter parseParameter(JSONObject jsonObject) throws JSONException {
SWEKParameter parameter = new SWEKParameter();
parameter.setSource(parseSourceInParameter(jsonObject));
parameter.setParameterName(parseParameterName(jsonObject));
parameter.setParameterDisplayName(parseParameterDisplayName(jsonObject));
parameter.setParameterFilter(parseParameterFilter(jsonObject));
parameter.setDefaultVisible(parseDefaultVisible(jsonObject));
return parameter;
}
/**
* Parses the source from a json.
*
* @param jsonObject
* the json from which the source is parsed
* @return the source
* @throws JSONException
* if the source could not be parsed
*/
private String parseSourceInParameter(JSONObject jsonObject) throws JSONException {
return jsonObject.getString("source");
}
/**
* Parses the parameter name from a json.
*
* @param jsonObject
* the json from which the parameter name is parsed
* @return the parameter name
* @throws JSONException
* if the parameter name could not be parsed
*/
private String parseParameterName(JSONObject jsonObject) throws JSONException {
return jsonObject.getString("parameter_name");
}
/**
* Parses the parameter display name from a json.
*
* @param jsonObject
* the json from which the parameter display name is parsed
* @return the parameter display name
* @throws JSONException
* if the parameter display name could not be parsed
*/
private String parseParameterDisplayName(JSONObject jsonObject) throws JSONException {
return jsonObject.getString("parameter_display_name");
}
/**
* Parses the parameter filter from a given json.
*
* @param jsonObject
* the json to parse from
* @return the parsed filter
* @throws JSONException
* if the filter could not be parsed
*/
private SWEKParameterFilter parseParameterFilter(JSONObject jsonObject) throws JSONException {
SWEKParameterFilter filter = new SWEKParameterFilter();
JSONObject filterobject = jsonObject.optJSONObject("filter");
if (filterobject != null) {
filter.setFilterType(parseFilterType(filterobject));
filter.setMin(parseMin(filterobject));
filter.setMax(parseMax(filterobject));
return filter;
} else {
return null;
}
}
/**
* Parses the filter type from a json.
*
* @param object
* the json from which the filter type is parsed
* @return the filter type
* @throws JSONException
* if the filter type could not be parsed
*/
private String parseFilterType(JSONObject object) throws JSONException {
return object.getString("filter_type");
}
/**
* parses the minimum filter value from a json.
*
* @param object
* the json from which to filter the minimum value
* @return the minimum filter value
* @throws JSONException
* if the minimum filter value could not be parsed
*/
private double parseMin(JSONObject object) throws JSONException {
return object.getDouble("min");
}
/**
* Parses the maximum filter value from the json.
*
* @param object
* the json from which to filter the maximum filter value
* @return the maximum filter value
* @throws JSONException
* if the maximum filter value could not be parsed
*/
private double parseMax(JSONObject object) throws JSONException {
return object.getDouble("max");
}
/**
* Parses the default visible from the given json.
*
* @param jsonObject
* the json from which to parse
* @return the parsed default visible
* @throws JSONException
* if the default visible could not be parsed
*/
private boolean parseDefaultVisible(JSONObject jsonObject) throws JSONException {
return jsonObject.getBoolean("default_visible");
}
/**
* Parses the request interval extension from the json.
*
* @param object
* the json from which to parse the request interval extension
* @return the parsed request interval extension
* @throws JSONException
* if the request interval extension could not be parsed
*/
private Long parseRequestIntervalExtension(JSONObject object) throws JSONException {
return object.getLong("request_interval_extension");
}
/**
* Parses the standard selected from the json.
*
* @param object
* the json from which to parse the standard selected
* @return true if standard selected is true in json, false if standard
* selected is false in json
* @throws JSONException
* if the standard selected could not be parsed from json.
*/
private boolean parseStandardSelected(JSONObject object) throws JSONException {
return object.getBoolean("standard_selected");
}
/**
* Parses the "group on" from the json.
*
* @param object
* the json from which to parse the "group on"
* @return the group on parameter
* @throws JSONException
* if the "group on" could not be parsed from the json.
*/
private SWEKParameter parseGroupOn(JSONObject object) throws JSONException {
return this.parameters.get(object.getString("group_on"));
}
/**
* Parses the "coordinate_system" from the json.
*
* @param object
* the json from which to parse the "coordinate_system"
* @return the coordinate system
* @throws JSONException
* if the "coordinate_system" could not be parsed from the json
*/
private String parseCoordinateSystem(JSONObject object) throws JSONException {
return object.getString("coordinate_system");
}
/**
* Parses the "spacial_region" from the json.
*
* @param object
* the object from which to parse the "spatial_region"
* @return the spatial region
* @throws JSONException
* if the "spatial_region" could not be parsed from the json
*/
private SWEKSpatialRegion parseSpatialRegion(JSONObject object) throws JSONException {
SWEKSpatialRegion spacialRegion = new SWEKSpatialRegion();
spacialRegion.setX1(parseX1(object.getJSONObject("spatial_region")));
spacialRegion.setY1(parseY1(object.getJSONObject("spatial_region")));
spacialRegion.setX2(parseX2(object.getJSONObject("spatial_region")));
spacialRegion.setY2(parseY2(object.getJSONObject("spatial_region")));
return spacialRegion;
}
/**
* Parses the x1 coordinate of the spatial region from the json.
*
* @param jsonObject
* the object from which to parse the x1-coordinate
* @return the x1 coordinate
* @throws JSONException
* if the x1 coordinate could not be parsed from the json
*/
private int parseX1(JSONObject jsonObject) throws JSONException {
return jsonObject.getInt("x1");
}
/**
* Parses the y1 coordinate of the spatial region from the json.
*
* @param jsonObject
* the object from which to parse the y1-coordinate
* @return the y1 coordinate
* @throws JSONException
* if the y1 coordinate could not be parsed from the json
*/
private int parseY1(JSONObject jsonObject) throws JSONException {
return jsonObject.getInt("y1");
}
/**
* Parses the x2 coordinate of the spatial region from the json.
*
* @param jsonObject
* the object from which to parse the x2-coordinate
* @return the x2 coordinate
* @throws JSONException
* if the x2 coordinate could not be parsed
*/
private int parseX2(JSONObject jsonObject) throws JSONException {
return jsonObject.getInt("x2");
}
/**
* Parses the y2 coordinate of the spatial region from the json.
*
* @param jsonObject
* the object from which to parse the y2 coordinate
* @return the y2 coordinate
* @throws JSONException
* if the y2 coordinate could not be parsed
*/
private int parseY2(JSONObject jsonObject) throws JSONException {
return jsonObject.getInt("y2");
}
/**
* Parses the list of related events from a json.
*
* @param jsonObject
* the json from which to parse the list of related events
* @return the parsed list of related events
* @throws JSONException
* if the list of related events could not be parsed
*/
private List<SWEKRelatedEvents> parseRelatedEvents(JSONObject configJSON) throws JSONException {
List<SWEKRelatedEvents> relatedEventsList = new ArrayList<SWEKRelatedEvents>();
JSONArray relatedEventsArray = configJSON.getJSONArray("related_events");
for (int i = 0; i < relatedEventsArray.length(); i++) {
relatedEventsList.add(parseRelatedEvent(relatedEventsArray.getJSONObject(i)));
}
return relatedEventsList;
}
/**
* Parses related events from a json.
*
* @param jsonObject
* the json from which to parse related events
* @return the parsed related events
* @throws JSONException
* if the related events could not be parsed
*/
private SWEKRelatedEvents parseRelatedEvent(JSONObject jsonObject) throws JSONException {
SWEKRelatedEvents relatedEvents = new SWEKRelatedEvents();
relatedEvents.setEvent(parseRelatedEventName(jsonObject));
relatedEvents.setRelatedWith(parseRelatedWith(jsonObject));
relatedEvents.setRelatedOnList(parseRelatedOnList(jsonObject));
return relatedEvents;
}
/**
* Parses a related event name from a json.
*
* @param jsonObject
* the json from which to parse the related event name
* @return the parsed related event type
* @throws JSONException
* if the related event name could not be parsed
*/
private SWEKEventType parseRelatedEventName(JSONObject jsonObject) throws JSONException {
return this.eventTypes.get(jsonObject.getString("event_name"));
}
/**
* Parses a "related with" from a json.
*
* @param jsonObject
* the json from which to parse the "related with"
* @return the parsed "related with" event type
* @throws JSONException
* if the "related with" could not be parsed
*/
private SWEKEventType parseRelatedWith(JSONObject jsonObject) throws JSONException {
return this.eventTypes.get(jsonObject.getString("related_with"));
}
/**
* Parses a list of "related on" from a json.
*
* @param jsonObject
* the json from which to parse the "related on" list
* @return the parsed "related on" list
* @throws JSONException
* if the "related on" list could not be parsed
*/
private List<SWEKRelatedOn> parseRelatedOnList(JSONObject jsonObject) throws JSONException {
List<SWEKRelatedOn> relatedOnList = new ArrayList<SWEKRelatedOn>();
JSONArray relatedOnArray = jsonObject.getJSONArray("related_on");
for (int i = 0; i < relatedOnArray.length(); i++) {
relatedOnList.add(parseRelatedOn(relatedOnArray.getJSONObject(i)));
}
return relatedOnList;
}
/**
* Parses a "related on" from a json.
*
* @param jsonObject
* the json from which to parse the "related on"
* @return the parsed "related on"
* @throws JSONException
* if the "related on" could not be parsed
*/
private SWEKRelatedOn parseRelatedOn(JSONObject jsonObject) throws JSONException {
SWEKRelatedOn relatedOn = new SWEKRelatedOn();
relatedOn.setParameterFrom(parseParameterFrom(jsonObject));
relatedOn.setParameterWith(parseParameterWith(jsonObject));
return relatedOn;
}
/**
* Parses a "parameter from" from a json.
*
* @param jsonObject
* the json from which to parse the "parameter from"
* @return the parsed "parameter from"
* @throws JSONException
* if the "parameter from" could not be parsed
*/
private SWEKParameter parseParameterFrom(JSONObject jsonObject) throws JSONException {
return this.parameters.get(jsonObject.getString("parameter_from"));
}
/**
* Parses a "parameter with" from a json.
*
* @param jsonObject
* the json from which to parse the "parameter with"
* @return the parsed "parameter with"
* @throws JSONException
* if the "parameter with" could not be parsed
*/
private SWEKParameter parseParameterWith(JSONObject jsonObject) throws JSONException {
return this.parameters.get(jsonObject.getString("parameter_with"));
}
} |
package ch.ntb.inf.deep.eclipse.ui.view;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.eclipse.core.runtime.preferences.InstanceScope;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.CheckboxCellEditor;
import org.eclipse.jface.viewers.ComboBoxCellEditor;
import org.eclipse.jface.viewers.EditingSupport;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Table;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.part.ViewPart;
import org.osgi.service.prefs.BackingStoreException;
import ch.ntb.inf.deep.classItems.Class;
import ch.ntb.inf.deep.classItems.DataItem;
import ch.ntb.inf.deep.classItems.ICdescAndTypeConsts;
import ch.ntb.inf.deep.classItems.Method;
import ch.ntb.inf.deep.classItems.Type;
import ch.ntb.inf.deep.config.Configuration;
import ch.ntb.inf.deep.config.Parser;
import ch.ntb.inf.deep.config.Register;
import ch.ntb.inf.deep.config.RegisterMap;
import ch.ntb.inf.deep.eclipse.DeepPlugin;
import ch.ntb.inf.deep.eclipse.ui.model.OperationObject;
import ch.ntb.inf.deep.host.StdStreams;
import ch.ntb.inf.deep.loader.Downloader;
import ch.ntb.inf.deep.loader.DownloaderException;
import ch.ntb.inf.deep.loader.UsbMpc555Loader;
import ch.ntb.inf.deep.strings.HString;
import ch.ntb.mcdp.blackbox.uart.Uart0;
public class TargetOperationView extends ViewPart implements ICdescAndTypeConsts {
public static final String ID = "ch.ntb.inf.deep.eclipse.ui.view.TargetOperationView";
private TableViewer viewer;
private OperationObject[] elements;
private Downloader bdi;
private Action toChar;
private Action toHex;
private Action toDez;
private Action toDouble;
private IEclipsePreferences prefs;
private static String KERNEL;
private static String cmdAddrName = "cmdAddr";
private String[] choise =new String[]{"", "Register", "Variable","Address", "TargetCMD", "send over SCI1" };
private static Image UP = DeepPlugin.createImage("full/obj32/up.gif");
private static Image DOWN = DeepPlugin.createImage("full/obj32/down.gif");
public static final int tVoid = 0, tRef = 3, tBoolean = 4, tChar = 5, tFloat = 6,
tDouble = 7, tByte = 8, tShort = 9, tInteger = 10, tLong = 11;
static final byte slotSize = 4; // 4 bytes
static {
assert (slotSize & (slotSize - 1)) == 0; // assert: slotSize == power of
}
class ViewLabelProvider extends LabelProvider implements
ITableLabelProvider {
public String getColumnText(Object obj, int index) {
if ((obj instanceof OperationObject)) {
OperationObject op = (OperationObject)obj;
if(index == 0){
return choise[op.operation];
}else if(index == 1){
return op.description;
}else if(index == 2){
if(op.isReaded && !choise[op.operation].equals("")){
switch(op.operation){
case 1:
switch(op.registerType){
case Parser.sCR:
case Parser.sFPSCR:
case Parser.sMSR:
return String.format("0x%04X",(short)op.value);
case Parser.sGPR:
if(op.representation == 1){//Hex
return String.format("0x%08X",(int)op.value);
}else{
return String.format("%d",(int)op.value);
}
case Parser.sFPR:
if(op.representation == 1){//Hex
return String.format("0x%016X",op.value);
}else{
return String.format("%f",Double.longBitsToDouble(op.value));
}
case Parser.sSPR:
case Parser.sIOR:
switch(op.registerSize){
case 1:
return String.format("0x%02X",(byte)op.value);
case 2:
return String.format("0x%04X",(short)op.value);
case 4:
return String.format("0x%08X",(int)op.value);
case 8:
return String.format("0x%016X",op.value);
default:
return String.format("0x%08X",(int)op.value);
}
}
case 2:
switch (op.valueType){
case tBoolean:
return String.valueOf(op.value > 0);
case tByte:
if(op.representation == 1){//Hex
return String.format("0x%02X",(byte)op.value);
}
return Byte.toString((byte)op.value);
case tChar:
if(op.representation == 1){//Hex
return String.format("0x%04X",(short)op.value);
}
if(op.representation == 2){//Dez{
return String.format("%d",(int)op.value);
}
return String.format("%c",((char)op.value));
case tShort:
if(op.representation == 1){//Hex
return String.format("0x%04X",(short)op.value);
}
return String.format("%d",((short)op.value));
case tInteger:
if(op.representation == 1){//Hex
return String.format("0x%08X",(int)op.value);
}
return String.format("%d",(int)op.value);
case tFloat:
if(op.representation == 1){//Hex
return String.format("0x%08X",(int)op.value);
}
return String.format("%f",Float.intBitsToFloat((int)op.value));
case tLong:
if(op.representation == 1){//Hex
return String.format("0x%016X",op.value);
}
return String.format("%d",op.value);
case tDouble:
if(op.representation == 1){//Hex
return String.format("0x%016X",op.value);
}
return String.format("%f",Double.longBitsToDouble(op.value));
case tRef:
return String.format("0x%08X",(int)op.value);
default:
throw new RuntimeException("Should not happen");
}
case 3:
return String.format("0x%08X",(int)op.value);
case 4:
case 5:
return "";
default:
throw new RuntimeException("Should not happen");
}
}
}else if(index == 3){
switch(op.operation){
case 1:
if(op.isReaded && op.registerType == Parser.sIOR){
return String.format("0x%8X", op.addr);
}else{
return "";
}
case 2:
if(op.isReaded){
return String.format("0x%8X", op.addr);
}else{
return "";
}
case 4:
if(op.cmdSend){
return String.format("0x%8X", op.addr);
}else{
return "";
}
case 5:
return "";
default :
return "";
}
}else if(index == 4){
return null;
}else if(index == 5){
return null;
}else if(index == 6){
return op.errorMsg;
}
}
return "";
}
@Override
public Image getColumnImage(Object element, int columnIndex) {
if ((element instanceof OperationObject)) {
OperationObject op = (OperationObject)element;
if(op.operation != 0 && op.operation < 4 && columnIndex == 4){
return UP;
}
if(op.operation != 0 && columnIndex == 5){
return DOWN;
}
}
return null;
}
}
@Override
public void createPartControl(Composite parent) {
prefs = new InstanceScope().getNode(DeepPlugin.PLUGIN_ID);
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout(1, false));
viewer = new TableViewer(composite, SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER);
String[] titels = { "Operation", "Descriptor", "Value","MemAddr" , "", "", "Error Message" };
int[] bounds = { 100, 100, 100, 100, 18, 18, 250 };
TableViewerColumn column = new TableViewerColumn(viewer, SWT.NONE);
column.getColumn().setText(titels[0]);
column.getColumn().setWidth(bounds[0]);
column.getColumn().setResizable(true);
column.getColumn().setMoveable(false);
column.setEditingSupport(new OperationEditingSupport(viewer));
column = new TableViewerColumn(viewer, SWT.NONE);
column.getColumn().setText(titels[1]);
column.getColumn().setWidth(bounds[1]);
column.getColumn().setResizable(true);
column.getColumn().setMoveable(false);
column.setEditingSupport(new DescriptorEditingSupport(viewer));
column = new TableViewerColumn(viewer, SWT.NONE);
column.getColumn().setText(titels[2]);
column.getColumn().setWidth(bounds[2]);
column.getColumn().setResizable(true);
column.getColumn().setMoveable(false);
column.setEditingSupport(new ValueEditingSupport(viewer));
column = new TableViewerColumn(viewer, SWT.NONE);
column.getColumn().setText(titels[3]);
column.getColumn().setWidth(bounds[3]);
column.getColumn().setResizable(false);
column.getColumn().setMoveable(false);
column = new TableViewerColumn(viewer, SWT.NONE);
column.getColumn().setText(titels[4]);
column.getColumn().setWidth(bounds[4]);
column.getColumn().setResizable(false);
column.getColumn().setMoveable(false);
column.setEditingSupport(new RefreshEditingSupport(viewer));
column = new TableViewerColumn(viewer, SWT.NONE);
column.getColumn().setText(titels[5]);
column.getColumn().setWidth(bounds[5]);
column.getColumn().setResizable(false);
column.getColumn().setMoveable(false);
column.setEditingSupport(new DownloadEditingSupport(viewer));
column = new TableViewerColumn(viewer, SWT.NONE);
column.getColumn().setText(titels[6]);
column.getColumn().setWidth(bounds[6]);
column.getColumn().setResizable(false);
column.getColumn().setMoveable(false);
final Table table = viewer.getTable();
table.setHeaderVisible(true);
table.setLinesVisible(true);
table.setLayoutData(new GridData(GridData.FILL_BOTH));
viewer.setColumnProperties(titels);
viewer.setContentProvider(new ArrayContentProvider());
viewer.setLabelProvider(new ViewLabelProvider());
getSite().setSelectionProvider(viewer);
String storedOperations = prefs.get("storedOperations", "");
String[] vars = storedOperations.split(";");
// Get the content for the viewer, setInput will call getElements in the
// contentProvider
elements = new OperationObject[32];
if(vars.length > 1){
for(int i = 0; i < vars.length; i++){
String[] obj = vars[i].split(",");
if(obj.length > 1){
elements[i] = new OperationObject(Integer.decode(obj[0]),obj[1]);
}else{
elements[i] = new OperationObject();
}
}
}else{
for (int i = 0; i < 32; i++) {
elements[i] = new OperationObject();
}
}
viewer.setInput(elements);
createActions();
hookContextMenu();
}
@Override
public void setFocus() {
viewer.getControl().setFocus();
}
private void hookContextMenu() {
MenuManager menuMgr = new MenuManager("#PopupMenu");
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(new IMenuListener() {
public void menuAboutToShow(IMenuManager manager) {
TargetOperationView.this.fillContextMenu(manager);
}
});
Menu menu = menuMgr.createContextMenu(viewer.getControl());
viewer.getControl().setMenu(menu);
getSite().registerContextMenu(menuMgr, viewer);
}
protected void fillContextMenu(IMenuManager menu) {
menu.add(toHex);
menu.add(toDez);
menu.add(toDouble);
menu.add(toChar);
// Other plug-ins can contribute there actions here
menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
}
protected void createActions() {
toChar = new Action(){
public void run() {
ISelection selection = viewer.getSelection();
Object obj = ((IStructuredSelection) selection).getFirstElement();
if(obj instanceof OperationObject){
((OperationObject)obj).representation = 4;
}
viewer.refresh();
}
};
toChar.setText("ToChar");
toHex = new Action(){
public void run() {
ISelection selection = viewer.getSelection();
Object obj = ((IStructuredSelection) selection).getFirstElement();
if(obj instanceof OperationObject){
((OperationObject)obj).representation = 1;
}
viewer.refresh();
}
};
toHex.setText("ToHex");
toDez = new Action(){
public void run() {
ISelection selection = viewer.getSelection();
Object obj = ((IStructuredSelection) selection).getFirstElement();
if(obj instanceof OperationObject){
((OperationObject)obj).representation = 2;
}
viewer.refresh();
}
};
toDez.setText("ToDez");
toDouble = new Action(){
public void run() {
ISelection selection = viewer.getSelection();
Object obj = ((IStructuredSelection) selection).getFirstElement();
if(obj instanceof OperationObject){
((OperationObject)obj).representation = 3;
}
viewer.refresh();
}
};
toDouble.setText("ToDouble");
}
public class DescriptorEditingSupport extends EditingSupport {
private final TableViewer viewer;
public DescriptorEditingSupport(TableViewer viewer) {
super(viewer);
this.viewer = viewer;
}
@Override
protected CellEditor getCellEditor(Object element) {
return new TextCellEditor(viewer.getTable());
}
@Override
protected boolean canEdit(Object element) {
return true;
}
@Override
protected Object getValue(Object element) {
return ((OperationObject)element).description;
}
@Override
protected void setValue(Object element, Object value) {
OperationObject op = (OperationObject)element;
if(value == null){
return;
}
op.errorMsg = "";
String param = String.valueOf(value);
if(choise[op.operation].equals("Register")){
HString register = HString.getHString(param.toUpperCase());
readFromRegister(op, register);
}else if(choise[op.operation].equals("Variable")){
if(!param.equals("")){
readVariable(op, param);
}
}else if(choise[op.operation].equals("Address")){
try{
if(param.length() > 0){
//work around for problem when in hex-int-number the most significant bit is set;
if(param.charAt(0) == '0' && param.length() > 9 && param.charAt(2) > '7'){
String most = param.substring(2, 3);
param = "0x0" + param.substring(3);
op.addr = (Integer.parseInt(most,16) << 28) |Integer.decode(param);
}else{
op.addr = Integer.decode(param);
}
}
op.description = param;// do it first, so we need only one parameter for the functions
readFromAddress(op);
}catch (Exception e) {
}
}else if(choise[op.operation].equals("TargetCMD")){
sendCMD(op, param);
}else if(choise[op.operation].equals("send over SCI1")){
UsbMpc555Loader.getInstance();//Needs only to connect to the device
Uart0.write(param.getBytes(), param.length());
op.description = param;
}else if(param.equals("stirb!!!")){
MessageDialog dialog = new MessageDialog( viewer.getControl().getShell(), "bye bye", null, "aaaaaaaaaaahhhhhhhh", MessageDialog.ERROR, new String[] { "tot" }, 0);
dialog.open();
System.exit(0);
}
saveView();
viewer.refresh();
}
}
public class ValueEditingSupport extends EditingSupport {
private final TableViewer viewer;
public ValueEditingSupport(TableViewer viewer) {
super(viewer);
this.viewer = viewer;
}
@Override
protected CellEditor getCellEditor(Object element) {
return new TextCellEditor(viewer.getTable());
}
@Override
protected boolean canEdit(Object element) {
return true;
}
@Override
protected Object getValue(Object element) {
OperationObject op = (OperationObject) element;
switch (op.operation) {
case 1:
switch (op.registerType) {
case Parser.sCR:
case Parser.sFPSCR:
case Parser.sMSR:
return String.format("0x%04X", op.value);
case Parser.sGPR:
if (op.representation == 1) {// Hex
return String.format("0x%08X", op.value);
} else {
return String.format("%d", (int) op.value);
}
case Parser.sFPR:
if (op.representation == 1) {// Hex
return String.format("0x%016X", op.value);
} else {
return String.format("%f", Double.longBitsToDouble(op.value));
}
case Parser.sSPR:
case Parser.sIOR:
switch (op.registerSize) {
case 1:
return String.format("0x%02X", op.value);
case 2:
return String.format("0x%04X", op.value);
case 4:
return String.format("0x%08X", op.value);
case 8:
return String.format("0x%016X", op.value);
default:
return String.format("0x%08X", op.value);
}
}
case 2:
switch (op.valueType) {
case tBoolean:
return String.valueOf(op.value > 0);
case tByte:
if (op.representation == 1) {// Hex
return String.format("0x%02X", op.value);
}
return Byte.toString((byte) op.value);
case tChar:
if (op.representation == 1) {// Hex
return String.format("0x%04X", op.value);
}
if (op.representation == 2) {// Dez{
return String.format("%d", (int) op.value);
}
return String.format("%c", ((char) op.value));
case tShort:
if (op.representation == 1) {// Hex
return String.format("0x%04X", op.value);
}
return String.format("%d", ((short) op.value));
case tInteger:
if (op.representation == 1) {// Hex
return String.format("0x%08X", op.value);
}
return String.format("%d", (int) op.value);
case tFloat:
if (op.representation == 1) {// Hex
return String.format("0x%08X", op.value);
}
return String.format("%f", Float.intBitsToFloat((int) op.value));
case tLong:
if (op.representation == 1) {// Hex
return String.format("0x%016X", op.value);
}
return String.format("%d", op.value);
case tDouble:
if (op.representation == 1) {// Hex
return String.format("0x%016X", op.value);
}
return String.format("%f", Double.longBitsToDouble(op.value));
case tRef:
return String.format("0x%08X", op.value);
default:
return String.format("%d", op.value);
}
case 3:
return String.format("0x%08X", op.value);
case 4:
case 5:
return "";
default:
throw new RuntimeException("Should not happen");
}
}
@Override
protected void setValue(Object element, Object value) {
OperationObject op = (OperationObject)element;
try{
if(choise[op.operation].equals("Register")){
if(((OperationObject)element).registerType != -1){
if(((OperationObject)element).registerType == Parser.sFPR){
op.value = Double.doubleToLongBits(Double.parseDouble(String.valueOf(value)));
}else{
op.value = Long.decode(String.valueOf(value));
}
setToRegister(op);
}
}else if(choise[op.operation].equals("Variable")){
setVariable(op,String.valueOf(value));
}else if(choise[op.operation].equals("Address")){
try{
op.value = Long.decode(String.valueOf(value));
setToAddress(op);
}catch (Exception e) {
}
}else if(choise[op.operation].equals("TargetCMD")){
op.value = Long.decode(String.valueOf(value));
}
}catch(Exception e){
}
viewer.refresh();
}
}
public class OperationEditingSupport extends EditingSupport {
private final TableViewer viewer;
public OperationEditingSupport(TableViewer viewer) {
super(viewer);
this.viewer = viewer;
}
@Override
protected CellEditor getCellEditor(Object element) {
return new ComboBoxCellEditor(viewer.getTable(), choise);
}
@Override
protected boolean canEdit(Object element) {
return true;
}
@Override
protected Object getValue(Object element) {
OperationObject op = (OperationObject) element;
return op.operation;
}
@Override
protected void setValue(Object element, Object value) {
OperationObject op = (OperationObject)element;
op.errorMsg = "";
if((Integer)value < 0){
op.operation = 0;
}else{
op.operation = (Integer)value;
if(!choise[op.operation].equals("Register")){
op.registerType = -1;
}
}
if(op.operation == 0){//reset all
op.addr = 0;
op.cmdSend = false;
op.description = "";
op.isReaded = false;
op.registerSize = 0;
op.registerType = 0;
op.representation = 0;
op.value = 0;
op.valueType = 0;
}
saveView();
viewer.refresh();
}
}
public class RefreshEditingSupport extends EditingSupport {
private final TableViewer viewer;
public RefreshEditingSupport(TableViewer viewer) {
super(viewer);
this.viewer = viewer;
}
@Override
protected CellEditor getCellEditor(Object element) {
return new CheckboxCellEditor(null, SWT.CHECK | SWT.READ_ONLY);
}
@Override
protected boolean canEdit(Object element) {
return true;
}
@Override
protected Object getValue(Object element) {
OperationObject op = (OperationObject)element;
op.errorMsg = "";
if(choise[op.operation].equals("Register")){
if(((OperationObject)element).registerType != -1){
readFromRegister(op, HString.getHString(op.description));
}
}else if(choise[op.operation].equals("Variable")){
readVariable(op,op.description);
}else if(choise[op.operation].equals("Address")){
readFromAddress(op);
}
viewer.refresh();
return false;//TODO check this
}
@Override
protected void setValue(Object element, Object value) {
viewer.refresh();
}
}
public class DownloadEditingSupport extends EditingSupport {
private final TableViewer viewer;
public DownloadEditingSupport(TableViewer viewer) {
super(viewer);
this.viewer = viewer;
}
@Override
protected CellEditor getCellEditor(Object element) {
return new CheckboxCellEditor(null, SWT.CHECK | SWT.READ_ONLY);
}
@Override
protected boolean canEdit(Object element) {
return true;
}
@Override
protected Object getValue(Object element) {
OperationObject op = (OperationObject)element;
op.errorMsg = "";
if(choise[op.operation].equals("Register")){
if(((OperationObject)element).registerType != -1){
setToRegister(op);
}
}else if(choise[op.operation].equals("Variable")){
setVariable(op,String.valueOf(op.value));
}else if(choise[op.operation].equals("Address")){
setToAddress(op);
}else if(choise[op.operation].equals("TargetCMD")){
sendCMD(op, op.description);
}else if(choise[op.operation].equals("send over SCI1")){
UsbMpc555Loader.getInstance();//Needs only to connect to the device
Uart0.write(op.description.getBytes(), op.description.length());
}
return false;//TODO check this
}
@Override
protected void setValue(Object element, Object value) {
viewer.refresh();
}
}
private void sendCMD(OperationObject op, String param) {
if(param.equals("")){
return;
}
boolean wasFreezeAsserted;
HString kernelName = Configuration.getKernelClassname();
if(kernelName == null){
op.errorMsg = "configuration isn't loaded";
return;
}
KERNEL = kernelName.toString();
String fullQualName = param;
int lastDot = fullQualName.lastIndexOf(".");
if(lastDot < 0){
op.errorMsg = "invalid description";
return;
}
String clazzName = fullQualName.substring(0, lastDot);
clazzName = clazzName.replace('.', '/');
String methName = fullQualName.substring(lastDot + 1);
Class classList = (Class)Type.classList;
if(classList == null){
op.errorMsg = "system not builded";
return;
}
Class clazz = (Class)classList.getItemByName(clazzName);
Class kernel = (Class) classList.getItemByName(KERNEL);
if (clazz != null && kernel != null) {
int cmdAddr = ((DataItem) kernel.classFields.getItemByName(cmdAddrName)).address;
Method meth = (Method) clazz.methods.getItemByName(methName);
if (meth != null) {
//Save address for display
op.addr = meth.address;
if (bdi == null) {
bdi = UsbMpc555Loader.getInstance();
}
try {
wasFreezeAsserted = bdi.isFreezeAsserted();
if (!wasFreezeAsserted) {
bdi.stopTarget();
}
bdi.setMem(cmdAddr, meth.address, 4);
op.description = param;
op.cmdSend = true;
if (!wasFreezeAsserted) {
bdi.startTarget();
}
} catch (DownloaderException e) {
bdi.closeConnection();
StdStreams.err.println("USB connection error");
bdi = null;
}
}else{
op.errorMsg = "method not found";
}
}else{
op.errorMsg = "class not found";
}
}
private void readFromAddress(OperationObject op){
boolean wasFreezeAsserted;
if (bdi == null) {
bdi = UsbMpc555Loader.getInstance();
}
try {
wasFreezeAsserted = bdi.isFreezeAsserted();
if (!wasFreezeAsserted) {
bdi.stopTarget();
}
op.value = bdi.getMem(op.addr, 4);
op.isReaded = true;
if (!wasFreezeAsserted) {
bdi.startTarget();
}
} catch (DownloaderException e) {
bdi.closeConnection();
StdStreams.err.println("USB connection error");
bdi = null;
}
}
private void readVariable(OperationObject op, String fullQualName){
boolean wasFreezeAsserted;
int lastDot = fullQualName.lastIndexOf(".");
if (lastDot == -1){
op.errorMsg = "invalid description";
return;
}
String clazzName = fullQualName.substring(0, lastDot);
clazzName = clazzName.replace('.', '/');
String varName = fullQualName.substring(lastDot + 1);
if(Type.classList == null){
op.errorMsg = "system not builded";
return;
}
Class clazz = (Class)Type.classList.getItemByName(clazzName);
if(clazz != null){
if((DataItem)clazz.classFields == null){
op.errorMsg = "no fields";
return;
}
DataItem var = (DataItem)clazz.classFields.getItemByName(varName);
if(var != null){
//save address for display
op.addr = var.address;
if(bdi == null){
bdi = UsbMpc555Loader.getInstance();
}
try{
wasFreezeAsserted = bdi.isFreezeAsserted();
if(!wasFreezeAsserted){
bdi.stopTarget();
}
if(((Type)var.type).sizeInBits <= 2 * slotSize ) {
op.value = bdi.getMem(var.address, slotSize/4);
if(((Type)var.type).sizeInBits == 1 ){
op.valueType = tBoolean;
}else{
op.valueType = tByte;
}
}else if(((Type)var.type).sizeInBits == 4 * slotSize){
op.value = bdi.getMem(var.address, slotSize/2);
if(var.type == Type.wellKnownTypes[txChar]){
op.valueType = tChar;
}else{
op.valueType = tShort;
}
}else if(((Type)var.type).sizeInBits == 8 * slotSize){
op.value = bdi.getMem(var.address, slotSize);
if(var.type == Type.wellKnownTypes[txInt]){
op.valueType = tInteger;
}else if(var.type == Type.wellKnownTypes[txFloat]){
op.valueType = tFloat;
}else{
op.valueType = tRef;
}
}else if(((Type)var.type).sizeInBits > 8 * slotSize) {
op.value = bdi.getMem(var.address, slotSize);
op.value = op.value << (8 * slotSize) | bdi.getMem(var.address + slotSize, slotSize);
if(var.type == Type.wellKnownTypes[txLong]){
op.valueType = tLong;
}else{
op.valueType = tDouble;
}
}
if(!wasFreezeAsserted){
bdi.startTarget();
}
op.isReaded = true;
op.description = fullQualName;
}catch(DownloaderException e){
bdi.closeConnection();
StdStreams.err.println("USB connection error");
bdi = null;
}
}else{
op.errorMsg = "field not found";
}
}else{
op.errorMsg = "class not found";
}
}
private void readFromRegister(OperationObject op, HString register){
RegisterMap regMap = Configuration.getRegisterMap();
boolean found = false;
Register current = regMap.getCR();
if(current != null && current.getName().equals(register)){
op.registerSize = current.getSize();
op.registerType = current.getType();
op.addr = current.getAddress();
op.description = register.toString();
found = true;
}
current = regMap.getFpscr();
if(!found && current != null && current.getName().equals(register)){
op.registerSize = current.getSize();
op.registerType = current.getType();
op.addr = current.getAddress();
op.description = register.toString();
found = true;
}
current = regMap.getMSR();
if(!found && current != null && current.getName().equals(register)){
op.registerSize = current.getSize();
op.registerType = current.getType();
op.addr = current.getAddress();
op.description = register.toString();
found = true;
}
current = regMap.getGprRegister();
while(!found && current != null){
if(current.getName().equals(register)){
op.registerSize = current.getSize();
op.registerType = current.getType();
op.addr = current.getAddress();
op.description = register.toString();
found = true;
}
current = current.next;
}
current = regMap.getFprRegister();
while(!found && current != null){
if(current.getName().equals(register)){
op.registerSize = current.getSize();
op.registerType = current.getType();
op.addr = current.getAddress();
op.description = register.toString();
found = true;
}
current = current.next;
}
current = regMap.getSprRegister();
while(!found && current != null){
if(current.getName().equals(register)){
op.registerSize = current.getSize();
op.registerType = current.getType();
op.addr = current.getAddress();
op.description = register.toString();
found = true;
}
current = current.next;
}
current = regMap.getIorRegister();
while(!found && current != null){
if(current.getName().equals(register)){
op.registerSize = current.getSize();
op.registerType = current.getType();
op.addr = current.getAddress();
op.description = register.toString();
found = true;
}
current = current.next;
}
if(found){
boolean wasFreezeAsserted;
if (bdi == null) {
bdi = UsbMpc555Loader.getInstance();
}
try {
wasFreezeAsserted = bdi.isFreezeAsserted();
if (!wasFreezeAsserted) {
bdi.stopTarget();
}
switch(op.registerType){
case Parser.sCR:
op.value = bdi.getCR();
break;
case Parser.sMSR:
op.value = bdi.getMSR();
break;
case Parser.sFPSCR:
op.value = bdi.getFPSCR();
break;
case Parser.sGPR:
op.value = bdi.getGPR(op.addr);
break;
case Parser.sFPR:
op.value = bdi.getFPR(op.addr);
break;
case Parser.sSPR:
op.value = bdi.getSPR(op.addr);
break;
case Parser.sIOR:
op.value = bdi.getMem(op.addr, op.registerSize);
break;
default:
}
op.isReaded = true;
if (!wasFreezeAsserted) {
bdi.startTarget();
}
} catch (DownloaderException e) {
bdi.closeConnection();
StdStreams.err.println("USB connection error");
bdi = null;
}
}else{
op.errorMsg = "register not found";
}
}
private void setToAddress(OperationObject op){
boolean wasFreezeAsserted;
if (bdi == null) {
bdi = UsbMpc555Loader.getInstance();
}
try {
wasFreezeAsserted = bdi.isFreezeAsserted();
if (!wasFreezeAsserted) {
bdi.stopTarget();
}
bdi.setMem(op.addr, (int)op.value, 4);
if (!wasFreezeAsserted) {
bdi.startTarget();
}
} catch (DownloaderException e) {
bdi.closeConnection();
StdStreams.err.println("USB connection error");
bdi = null;
}
}
private void setVariable(OperationObject op, String value){
boolean wasFreezeAsserted;
int lastDot = op.description.lastIndexOf(".");
if(lastDot < 0){
op.errorMsg = "invalide descriptor";
return;
}
String clazzName = op.description.substring(0, lastDot);
clazzName = clazzName.replace('.', '/');
String varName = op.description.substring(lastDot + 1);
if(Type.classList == null){
op.errorMsg = "system not builded";
}
Class clazz = (Class)Type.classList.getItemByName(clazzName);
if(clazz != null){
if(clazz.classFields == null){
op.errorMsg = "no fields";
return;
}
DataItem var = (DataItem)clazz.classFields.getItemByName(varName);
if(var != null){
if(bdi == null){
bdi = UsbMpc555Loader.getInstance();
}
try{
long val = Long.decode(value);
wasFreezeAsserted = bdi.isFreezeAsserted();
if(!wasFreezeAsserted){
bdi.stopTarget();
}
if(((Type)var.type).sizeInBits <= 2 * slotSize ) {
bdi.setMem(var.address,(int)(val & 0xFF), slotSize/4);
}else if(((Type)var.type).sizeInBits == 4 * slotSize){
bdi.setMem(var.address,(int)(val & 0xFFFF), slotSize/2);
}else if(((Type)var.type).sizeInBits == 8 * slotSize){
bdi.setMem(var.address,(int)(val & 0xFFFFFFFF), slotSize);
}else if(((Type)var.type).sizeInBits > 8 * slotSize) {
bdi.setMem(var.address,(int)((val >> 32) & 0xFFFFFFFF), slotSize);
bdi.setMem(var.address,(int)(val + slotSize & 0xFFFFFFFF), slotSize);
}
op.value = val;
if(!wasFreezeAsserted){
bdi.startTarget();
}
}catch(DownloaderException e){
bdi.closeConnection();
StdStreams.err.println("USB connection error");
bdi = null;
}
}else{
op.errorMsg = "field not found";
}
}else{
op.errorMsg = "class not found";
}
}
private void setToRegister(OperationObject op){
boolean wasFreezeAsserted;
if (bdi == null) {
bdi = UsbMpc555Loader.getInstance();
}
try {
wasFreezeAsserted = bdi.isFreezeAsserted();
if (!wasFreezeAsserted) {
bdi.stopTarget();
}
switch (op.registerType) {
case Parser.sCR:
bdi.setCR((int)op.value);
break;
case Parser.sGPR:
bdi.setGPR(op.addr, (int)op.value);
break;
case Parser.sFPR:
bdi.setFPR(op.addr,op.value);
break;
case Parser.sSPR:
bdi.setSPR(op.addr, (int)op.value);
break;
case Parser.sIOR:
bdi.setMem(op.addr, (int)op.value, op.registerSize);
break;
default:
}
if (!wasFreezeAsserted) {
bdi.startTarget();
}
} catch (DownloaderException e) {
bdi.closeConnection();
StdStreams.err.println("USB connection error");
bdi = null;
}
}
private void saveView(){
StringBuffer sb = new StringBuffer();
for(int i = 0; i < elements.length; i++){
sb.append(elements[i].operation + "," + elements[i].description + ";");
}
prefs.put("storedOperations", sb.toString());
try {
prefs.flush();
} catch (BackingStoreException e) {
e.printStackTrace();
}
}
} |
package com.haxademic.core.draw.image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.nio.ByteBuffer;
import com.haxademic.core.app.P;
import com.haxademic.core.draw.color.ColorHax;
import com.haxademic.core.draw.context.DrawUtil;
import processing.core.PApplet;
import processing.core.PConstants;
import processing.core.PGraphics;
import processing.core.PImage;
import processing.core.PShape;
import processing.opengl.PGL;
import processing.opengl.Texture;
public class ImageUtil {
public static final int BLACK_INT = -16777216;
public static final int WHITE_INT = 16777215;
public static final int CLEAR_INT = 48356;
public static final int EMPTY_INT = 0;
public static final int EMPTY_WHITE_INT = -1;
public static int getPixelIndex( PImage image, int x, int y ) {
return (int) x + y * image.width;
}
public static int getPixelIndex( PApplet image, int x, int y ) {
return (int) x + y * image.width;
}
/**
* Return the color int for a specific pixel of a PImage
* @param image Image to grab pixel color from
* @param x x pixel of the image
* @param y y pixel of the image
* @return The color as an int
*/
public static int getPixelColor( PImage image, int x, int y ) {
if( x < 0 || y < 0 || x > image.width - 1 || y > image.height - 1 || image.pixels == null || image.pixels.length < getPixelIndex( image, x, y ) ) return 0;
return image.pixels[ getPixelIndex( image, x, y ) ];
}
public static int getPixelColor( PGraphics image, int x, int y ) {
if( x < 0 || y < 0 || x > image.width - 1 || y > image.height - 1 || image.pixels == null || image.pixels.length < getPixelIndex( image, x, y ) ) return 0;
return image.pixels[ getPixelIndex( image, x, y ) ];
}
public static int getPixelColor( PApplet image, int x, int y ) {
if( x < 0 || y < 0 || x > image.width - 1 || y > image.height - 1 || image.pixels == null || image.pixels.length < getPixelIndex( image, x, y ) ) return 0;
return image.pixels[ getPixelIndex( image, x, y ) ];
}
public static void setPixelColor( PImage image, int x, int y, int color ) {
if( x < 0 || y < 0 || x > image.width - 1 || y > image.height - 1 || image.pixels == null || image.pixels.length < getPixelIndex( image, x, y ) ) return;
image.pixels[ getPixelIndex( image, x, y ) ] = color;
}
// needs testing....
public static int getPixelColorFast( PApplet p, PGraphics image, int x, int y ) {
PGL pgl = image.beginPGL();
ByteBuffer buffer = ByteBuffer.allocateDirect(1 * 1 * Integer.SIZE / 8);
pgl.readPixels(x, y, 1, 1, PGL.RGBA, PGL.UNSIGNED_BYTE, buffer);
// get the first three bytes
int r = buffer.get() & 0xFF;
int g = buffer.get() & 0xFF;
int b = buffer.get() & 0xFF;
buffer.clear();
image.endPGL();
return p.color(r, g, b);
}
public static float getBrightnessForPixel( PApplet p, PImage image, int x, int y ) {
return p.brightness( image.pixels[ getPixelIndex( image, x, y ) ] ) * 0.1f;
}
public static float colorDifference( PApplet p, int color1, int color2 ) {
return (Math.abs(p.red(color1) - p.red(color2)) + Math.abs(p.green(color1) - p.green(color2)) + Math.abs(p.blue(color1) - p.blue(color2)) ) / 765f;
}
public static float brightnessDifference( PApplet p, int color1, int color2 ) {
return Math.abs((p.red(color1) + p.green(color1) + p.blue(color1)) - (p.red(color2) + p.green(color2) + p.blue(color2))) / 765f;
}
public static PImage getReversePImage( PImage image ) {
PImage reverse = new PImage( image.width, image.height );
for( int i=0; i < image.width; i++ ){
for(int j=0; j < image.height; j++){
reverse.set( image.width - 1 - i, j, image.get(i, j) );
}
}
return reverse;
}
public static PImage getReversePImageFast( PImage image ) {
PImage reverse = new PImage( image.width, image.height );
reverse.loadPixels();
for (int i = 0; i < image.width; i++) {
for (int j = 0; j < image.height; j++) {
reverse.pixels[j*image.width+i] = image.pixels[(image.width - i - 1) + j*image.width]; // Reversing x to mirror the image
}
}
reverse.updatePixels();
return reverse;
}
public static PImage getScaledImage( PImage image, int newWidth, int newHeight ) {
PImage scaled = new PImage( newWidth, newHeight );
scaled.copy( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
return scaled;
}
public static void clearPGraphics( PGraphics pg ) {
// pg.beginDraw();
pg.background(0,0);
// pg.endDraw();
}
public static PImage bufferedToPImage( BufferedImage bimg ) {
try {
PImage img = new PImage(bimg.getWidth(),bimg.getHeight(),PConstants.ARGB);
bimg.getRGB(0, 0, img.width, img.height, img.pixels, 0, img.width);
img.updatePixels();
return img;
}
catch(Exception e) {
System.err.println("Can't create image from buffer");
e.printStackTrace();
}
return null;
}
public static BufferedImage pImageToBuffered( PImage pimg ) {
return (BufferedImage) pimg.getNative();
// BufferedImage dest = new BufferedImage( pimg.width, pimg.height, BufferedImage.TYPE_INT_ARGB );
// Graphics2D g2 = dest.createGraphics();
// g2.drawImage( pimg.getImage(), 0, 0, null );
// g2.finalize();
// g2.dispose();
// return dest;
}
public static PGraphics imageToGraphics(PImage img) {
PGraphics pg = P.p.createGraphics(img.width, img.height, P.P3D);
pg.beginDraw();
pg.image(img,0,0);
pg.endDraw();
return pg;
}
public static PGraphics shapeToGraphics(PShape shape) {
return shapeToGraphics(shape, 1f);
}
public static PGraphics shapeToGraphics(PShape shape, float scale) {
return shapeToGraphics(shape, scale, -999);
}
public static PGraphics shapeToGraphics(PShape shape, float scale, int bgColor) {
PGraphics pg = P.p.createGraphics(P.ceil((float) shape.width * scale), P.ceil((float) shape.height * scale), P.P3D);
pg.beginDraw();
if(bgColor != -999) pg.background(bgColor);
pg.shape(shape, 0, 0, pg.width, pg.height);
pg.endDraw();
return pg;
}
public static PGraphics imageToGraphicsWithPadding(PImage img, float fillAmount) {
PGraphics image = ImageUtil.imageToGraphics(img);
image.beginDraw();
DrawUtil.setDrawCenter(image);
image.clear();
image.translate(image.width/2, image.height/2);
image.image(img, 0, 0, img.width * fillAmount, img.height * fillAmount);
image.endDraw();
return image;
}
public static PGraphics imageToGraphicsCropFill(PImage img, PGraphics pg) {
pg.beginDraw();
ImageUtil.cropFillCopyImage(img, pg, true);
pg.endDraw();
return pg;
}
public static void cropFillCopyImage( PImage src, PImage dest, boolean cropFill ) {
float containerW = dest.width;
float containerH = dest.height;
float imageW = src.width;
float imageH = src.height;
float ratioW = containerW / imageW;
float ratioH = containerH / imageH;
float shorterRatio = ratioW > ratioH ? ratioH : ratioW;
float longerRatio = ratioW > ratioH ? ratioW : ratioH;
float resizedW = cropFill ? (float)Math.ceil(imageW * longerRatio) : (float)Math.ceil(imageW * shorterRatio);
float resizedH = cropFill ? (float)Math.ceil(imageH * longerRatio) : (float)Math.ceil(imageH * shorterRatio);
float offsetX = (float)Math.ceil((containerW - resizedW) * 0.5f);
float offsetY = (float)Math.ceil((containerH - resizedH) * 0.5f);
dest.copy( src, 0, 0, (int) imageW, (int) imageH, (int) offsetX, (int) offsetY, (int) resizedW, (int) resizedH );
}
public static void flipH(PImage img) {
img.copy(0, 0, img.width, img.height, img.width, 0, -img.width, img.height);
}
public static float[] offsetAndSize = new float[]{0,0,0,0};
public static float[] getOffsetAndSizeToCrop( float containerW, float containerH, float imageW, float imageH, boolean cropFill ) {
float ratioW = containerW / imageW;
float ratioH = containerH / imageH;
float shorterRatio = ratioW > ratioH ? ratioH : ratioW;
float longerRatio = ratioW > ratioH ? ratioW : ratioH;
float resizedW = (cropFill) ? (float) Math.ceil(imageW * longerRatio) : (float) Math.ceil(imageW * shorterRatio);
float resizedH = (cropFill) ? (float) Math.ceil(imageH * longerRatio) : (float) Math.ceil(imageH * shorterRatio);
float offsetX = (float) Math.ceil((containerW - resizedW) * 0.5f);
float offsetY = (float) Math.ceil((containerH - resizedH) * 0.5f);
offsetAndSize[0] = offsetX;
offsetAndSize[1] = offsetY;
offsetAndSize[2] = resizedW;
offsetAndSize[3] = resizedH;
return offsetAndSize;
}
public static void removeImageFromGraphicsCache(PImage img, PGraphics pg) {
// for (int i = 0; i < imageSequence.size(); i++) {
Object cache = pg.getCache(img);
pg.removeCache(img);
if (cache instanceof Texture) {
((Texture) cache).disposeSourceBuffer();
}
// imageSequence.clear();
}
public static int[] zero4 = new int[] {0, 0, 0, 0};
public static void imageCroppedEmptySpace(PGraphics sourceImg, PImage destImg, int emptyColor, boolean debug) {
imageCroppedEmptySpace(sourceImg, destImg, emptyColor, debug, zero4, zero4, P.p.color(0,0));
}
public static void imageCroppedEmptySpace(PGraphics sourceImg, PImage destImg, int emptyColor, boolean debug, int[] padding, int[] cropIn, int bgColor) {
if(debug) P.println("SEARCHING =======================");
Rectangle bounds = null;
sourceImg.loadPixels();
// debug
if(debug) sourceImg.beginDraw();
if(debug) sourceImg.fill(255,0,0, 255);
// find initial low-resolution bounds
int searchSpacing = 10;
for(int x=0; x < sourceImg.width; x += searchSpacing) {
for(int y=0; y < sourceImg.height; y += searchSpacing) {
int pixelColor = ImageUtil.getPixelColor(sourceImg, x, y);
if(pixelColor != emptyColor) {
if(bounds == null) bounds = new Rectangle(x, y, 1, 1);
if(debug) sourceImg.rect(x, y, 1, 1);
bounds.add(x, y);
}
}
}
if(debug) P.println("low res bounds:", bounds);
// create boundary padded by spacing to search within
int refineX = P.max(0, bounds.x - searchSpacing);
int refineY = P.max(0, bounds.y - searchSpacing);
int refineW = P.min(sourceImg.width, bounds.width + searchSpacing * 2);
int refineH = P.min(sourceImg.height, bounds.height + searchSpacing * 2);
Rectangle refineBounds = new Rectangle(
refineX,
refineY,
refineW,
refineH
);
if(debug) P.println("refineBounds:", refineBounds);
if(debug) sourceImg.fill(255,255,0, 127); // set refine color
// move out one spacing and run through the process again per-pixel
// vertical
for(int x = refineBounds.x; x < refineBounds.x + refineBounds.width; x++) {
for(int y = refineBounds.y; y < refineBounds.y + searchSpacing; y++) {
int pixelColor = ImageUtil.getPixelColor(sourceImg, x, y);
if(pixelColor != emptyColor) {
if(debug) sourceImg.rect(x, y, 1, 1);
bounds.add(x, y);
}
}
for(int y = refineBounds.y + refineBounds.height - searchSpacing; y < refineBounds.y + refineBounds.height; y++) {
int pixelColor = ImageUtil.getPixelColor(sourceImg, x, y);
if(pixelColor != emptyColor) {
if(debug) sourceImg.rect(x, y, 1, 1);
bounds.add(x, y);
}
}
}
// horizontal
for(int y = refineBounds.y; y < refineBounds.y + refineBounds.height; y++) {
for(int x = refineBounds.x; x < refineBounds.x + searchSpacing; x++) {
int pixelColor = ImageUtil.getPixelColor(sourceImg, x, y);
if(pixelColor != emptyColor) {
if(debug) sourceImg.rect(x, y, 1, 1);
bounds.add(x, y);
}
}
for(int x = refineBounds.x + refineBounds.width - searchSpacing; x < refineBounds.x + refineBounds.width; x++) {
int pixelColor = ImageUtil.getPixelColor(sourceImg, x, y);
if(pixelColor != emptyColor) {
if(debug) sourceImg.rect(x, y, 1, 1);
bounds.add(x, y);
}
}
}
// show result outline
if(debug) {
sourceImg.noFill();
sourceImg.stroke(0,255,0, 127);
sourceImg.rect(bounds.x, bounds.y, bounds.width, bounds.height-1);
sourceImg.stroke(255,255,0, 255);
sourceImg.rect(refineBounds.x, refineBounds.y, refineBounds.width, refineBounds.height-1);
}
// copy to cropped image buffer
// padding & crop arrays go top, right, bottom, left
// resize destination image
int destW = bounds.width + 1;
int destH = bounds.height + 1;
int cropW = destW - cropIn[1] - cropIn[3];
int cropH = destH - cropIn[0] - cropIn[2];
destW += padding[1] + padding[3] - cropIn[1] - cropIn[3];
destH += padding[0] + padding[2] - cropIn[0] - cropIn[2];
destImg.resize(destW, destH);
if(debug) P.println("destW, destH", destW, destH);
// get size of image to crop
// clear destination image
destImg.loadPixels();
int numPixels = destImg.width * destImg.height;
for (int i = 0; i < numPixels; i++) destImg.pixels[i] = bgColor;
destImg.updatePixels();
// copy with padding
destImg.copy(sourceImg, bounds.x + cropIn[3], bounds.y + cropIn[0], cropW, cropH, padding[3], padding[0], cropW, cropH);
if(debug) P.println(bounds);
if(debug) P.println(refineBounds);
if(debug) sourceImg.endDraw();
}
public static void chromaKeyImage( PApplet p, PImage sourceImg, PImage dest ) {
float threshRange = 20f;
float r = 0;
float g = 0;
float b = 0;
for( int x=0; x < sourceImg.width; x++ ){
for( int y=0; y < sourceImg.height; y++ ){
int pixelColor = ImageUtil.getPixelColor( sourceImg, x, y );
r = ColorHax.redFromColorInt( pixelColor );
g = ColorHax.greenFromColorInt( pixelColor );
b = ColorHax.blueFromColorInt( pixelColor );
// if green is greater than both other color components, black it out
if( g > r && g > b ) {
dest.set( x, y, p.color( 255, 0 ) );
} else if( g > r - threshRange && g > b - threshRange ) {
dest.set( x, y, p.color( r, g, b ) );
} else {
dest.set( x, y, p.color( r, g, b ) );
}
}
}
}
} |
package com.hp.hpl.jena.xmloutput.impl;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import com.hp.hpl.jena.util.iterator.IteratorIterator;
import com.hp.hpl.jena.util.iterator.Map1;
import com.hp.hpl.jena.util.iterator.Map1Iterator;
class Relation<T> {
final private Map<T, Set<T>> rows;
final private Map<T, Set<T>> cols;
final private Set<T> index;
/** The empty Relation.
*/
public Relation() {
rows = new HashMap<T, Set<T>>();
cols = new HashMap<T, Set<T>>();
index = new HashSet<T>();
}
/** <code>a</code> is now related to <code>b</code>
*
*/
synchronized public void set(T a, T b) {
index.add(a);
index.add(b);
innerAdd(rows, a, b);
innerAdd(cols, b, a);
}
/** Uniquely <code>a</code> is now related to uniquely <code>b</code>.
*
* When this is called any other <code>a</code> related to this <code>b</code> is removed.
* When this is called any other <code>b</code> related to this <code>a</code> is removed.
*
*/
synchronized public void set11(T a, T b) {
clearX(a, forward(a));
clearX(backward(b), b);
set(a, b);
}
/** Uniquely <code>a</code> is now related to <code>b</code>.
* Many <code>b</code>'s can be related to each <code>a</code>.
* When this is called any other <code>a</code> related to this <code>b</code> is removed.
*/
synchronized public void set1N(T a, T b) {
clearX(backward(b), b);
set(a, b);
}
/** <code>a</code> is now related to uniquely <code>b</code>.
* Many <code>a</code>'s can be related to each <code>b</code>.
* When this is called any other <code>b</code> related to this <code>a</code> is removed.
*/
synchronized public void setN1(T a, T b) {
clearX(a, forward(a));
set(a, b);
}
/** <code>a</code> is now related to <code>b</code>
*
*/
synchronized public void setNN(T a, T b) {
set(a, b);
}
/** <code>a</code> is now <em>not</em> related to <code>b</code>
*
*/
synchronized public void clear(T a, T b) {
innerClear(rows, a, b);
innerClear(cols, b, a);
}
private void clearX(Set<T> s, T b) {
if (s == null)
return;
Iterator<T> it = s.iterator();
while (it.hasNext())
clear(it.next(), b);
}
private void clearX(T a, Set<T> s) {
if (s == null)
return;
Iterator<T> it = s.iterator();
while (it.hasNext())
clear(a, it.next());
}
static private <T> void innerAdd(Map<T, Set<T>> s, T a, T b) {
Set<T> vals = s.get(a);
if (vals == null) {
vals = new HashSet<T>();
s.put(a, vals);
}
vals.add(b);
}
static private <T> void innerClear(Map<T, Set<T>> s, T a, T b) {
Set<T> vals = s.get(a);
if (vals != null) {
vals.remove(b);
}
}
/** Is <code>a</code> related to <code>b</code>?
*
*/
public boolean get(T a, T b) {
Set <T> vals = rows.get(a);
return vals != null && vals.contains(b);
}
/**
* Takes this to its transitive closure.
See B. Roy. <b>Transitivit et connexit.</b> <i>C.R. Acad. Sci.</i> Paris <b>249</b>, 1959 pp 216-218.
or
S. Warshall, <b>A theorem on Boolean matrices</b>, <i>Journal of the ACM</i>, <b>9</b>(1), 1962, pp11-12
*/
synchronized public void transitiveClosure() {
Iterator<T> j = index.iterator();
while (j.hasNext()) {
Object oj = j.next();
Set<T> si = cols.get(oj);
Set<T> sk = rows.get(oj);
if (si != null && sk != null) {
Iterator<T> i = si.iterator();
while (i.hasNext()) {
T oi = i.next();
if (oi != oj) {
Iterator<T> k = sk.iterator();
while (k.hasNext()) {
T ok = k.next();
if (ok != oj)
set(oi, ok);
}
}
}
}
}
}
/**
* The set of <code>a</code> such that <code>a</code> is related to <code>a</code>.
*
*/
synchronized public Set<T> getDiagonal() {
Set<T> rslt = new HashSet<T>();
Iterator<T> it = index.iterator();
while (it.hasNext()) {
T o = it.next();
if (get(o, o))
rslt.add(o);
}
return rslt;
}
/**
* The set of <code>b</code> such that <code>a</code> is related to <code>b</code>.
*
*/
public Set<T> forward(T a) {
return rows.get(a);
}
/**
* The set of <code>a</code> such that <code>a</code> is related to <code>b</code>.
*
*/
public Set<T> backward(T b) {
return cols.get(b);
}
/**
* An Iterator over the pairs of the Relation.
* Each pair is returned as a java.util.Map.Entry.
* The first element is accessed through <code>getKey()</code>,
* the second through <code>getValue()</code>.
*@see java.util.Map.Entry
*/
public Iterator<PairEntry<T, T>> iterator()
{
return new IteratorIterator<PairEntry<T, T>>(new Map1Iterator<Map.Entry<T, Set<T>>, Iterator<PairEntry<T, T>>>(new Map1<Map.Entry<T, Set<T>>, Iterator<PairEntry<T, T>>>() {
// Convert a Map.Entry into an iterator over Map.Entry
public Iterator<PairEntry<T, T>> map1(Map.Entry<T, Set<T>> pair)
{
final T a = pair.getKey() ;
Set<T> bs = pair.getValue() ;
return new Map1Iterator<T, PairEntry<T, T>>(
// Converts a b into a Map.Entry pair.
new Map1<T, PairEntry<T, T>>() {
public PairEntry<T, T> map1(T b)
{
return new PairEntry<T, T>(a, b) ;
}
}, bs.iterator()) ;
}
//Map<T, Set<T>>
}, rows.entrySet().iterator())) ;
}
synchronized public Relation<T> copy() {
Relation<T> rslt = new Relation<T>();
Iterator<PairEntry<T, T>> it = iterator();
while ( it.hasNext() ) {
Map.Entry<T, T> e = it.next();
rslt.set(e.getKey(),e.getValue());
}
return rslt;
}
} |
package com.scwang.smartrefresh.layout.impl;
import android.animation.TimeInterpolator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.database.DataSetObserver;
import android.graphics.PointF;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.view.NestedScrollingChild;
import android.support.v4.view.NestedScrollingParent;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.PagerAdapterWrapper;
import android.support.v4.view.ScrollingView;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import android.webkit.WebView;
import android.widget.AbsListView;
import android.widget.ScrollView;
import com.scwang.smartrefresh.layout.api.RefreshContent;
import com.scwang.smartrefresh.layout.api.RefreshKernel;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
public class RefreshContentWrapper implements RefreshContent {
private View mContentView;
private View mScrollableView;
private MotionEvent mMotionEvent;
private boolean mEnableAutoLoadmore = false;
public RefreshContentWrapper(View view) {
this.mContentView = view;
this.findScrollableView(view);
}
public RefreshContentWrapper(Context context) {
this.mContentView = new View(context);
this.findScrollableView(mContentView);
}
//<editor-fold desc="findScrollableView">
private void findScrollableView(View content) {
mScrollableView = findScrollableViewInternal(content, true);
if (mScrollableView instanceof NestedScrollingParent
&& !(mScrollableView instanceof NestedScrollingChild)) {
mScrollableView = findScrollableViewInternal(mScrollableView, false);
}
if (mScrollableView instanceof ViewPager) {
wrapperViewPager((ViewPager) this.mScrollableView);
}
}
private void wrapperViewPager(final ViewPager viewPager) {
wrapperViewPager(viewPager, null);
}
private void wrapperViewPager(final ViewPager viewPager, PagerPrimaryAdapter primaryAdapter) {
viewPager.post(new Runnable() {
int count = 0;
PagerPrimaryAdapter mAdapter = primaryAdapter;
@Override
public void run() {
count++;
PagerAdapter adapter = viewPager.getAdapter();
if (adapter != null) {
if (adapter instanceof PagerPrimaryAdapter) {
if (adapter == primaryAdapter) {
viewPager.postDelayed(this, 500);
}
} else {
if (mAdapter == null) {
mAdapter = new PagerPrimaryAdapter(adapter);
} else {
mAdapter.wrapper(adapter);
}
mAdapter.attachViewPager(viewPager);
}
} else if (count < 10) {
viewPager.postDelayed(this, 500);
}
}
});
}
private View findScrollableViewInternal(View content, boolean selfable) {
View scrollableView = null;
Queue<View> views = new LinkedBlockingQueue<>(Collections.singletonList(content));
while (!views.isEmpty() && scrollableView == null) {
View view = views.poll();
if (view != null) {
if ((selfable || view != content) && (view instanceof AbsListView
|| view instanceof ScrollView
|| view instanceof ScrollingView
|| view instanceof NestedScrollingChild
|| view instanceof NestedScrollingParent
|| view instanceof WebView
|| view instanceof ViewPager)) {
scrollableView = view;
} else if (view instanceof ViewGroup) {
ViewGroup group = (ViewGroup) view;
for (int j = 0; j < group.getChildCount(); j++) {
views.add(group.getChildAt(j));
}
}
}
}
return scrollableView;
}
//</editor-fold>
@NonNull
public View getView() {
return mContentView;
}
@Override
public void moveSpinner(int spinner) {
mContentView.setTranslationY(spinner);
}
@Override
public boolean canScrollUp() {
return canScrollUp(mContentView, mMotionEvent);
}
@Override
public boolean canScrollDown() {
return canScrollDown(mContentView, mMotionEvent);
}
@Override
public void measure(int widthSpec, int heightSpec) {
mContentView.measure(widthSpec, heightSpec);
}
@Override
public ViewGroup.LayoutParams getLayoutParams() {
return mContentView.getLayoutParams();
}
@Override
public int getMeasuredWidth() {
return mContentView.getMeasuredWidth();
}
@Override
public int getMeasuredHeight() {
return mContentView.getMeasuredHeight();
}
@Override
public void layout(int left, int top, int right, int bottom) {
mContentView.layout(left, top, right, bottom);
}
@Override
public View getScrollableView() {
return mScrollableView;
}
@Override
public void onActionDown(MotionEvent e) {
mMotionEvent = MotionEvent.obtain(e);
mMotionEvent.offsetLocation(-mContentView.getLeft(), -mContentView.getTop());
}
@Override
public void onActionUpOrCancel(MotionEvent e) {
mMotionEvent = null;
}
@Override
public void setupComponent(boolean autoLoadmore, RefreshKernel kernel) {
mEnableAutoLoadmore = autoLoadmore;
if (mScrollableView != null && autoLoadmore) {
setUpAutoLoadmore(mScrollableView, kernel);
}
if (mScrollableView instanceof RecyclerView) {
RecyclerViewScrollComponent component = new RecyclerViewScrollComponent(autoLoadmore, kernel);
component.attach((RecyclerView) mScrollableView);
} else if (mScrollableView instanceof AbsListView) {
AbsListViewScrollComponent component = new AbsListViewScrollComponent(autoLoadmore, kernel);
component.attach(((AbsListView) mScrollableView));
}
}
@Override
public boolean onLoadingFinish(int footerHeight) {
return mScrollableView != null && scrollAViewBy(mScrollableView, footerHeight);
}
//<editor-fold desc="private">
private static boolean scrollAViewBy(View view, int height) {
if (view instanceof RecyclerView) ((RecyclerView) view).smoothScrollBy(0, height);
else if (view instanceof ScrollView) ((ScrollView) view).smoothScrollBy(0, height);
else if (view instanceof AbsListView) ((AbsListView) view).smoothScrollBy(height, 150);
else {
try {
Method method = view.getClass().getDeclaredMethod("smoothScrollBy", Integer.class, Integer.class);
method.invoke(view, 0, height);
} catch (Exception e) {
view.scrollBy(0, height);
return false;
}
}
return true;
}
private void setUpAutoLoadmore(View scrollableView, RefreshKernel kernel) {
if (scrollableView instanceof AbsListView) {
AbsListView absListView = ((AbsListView) scrollableView);
absListView.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (absListView.getAdapter() != null && absListView.getLastVisiblePosition() == absListView.getAdapter().getCount() - 1) {
kernel.getRefreshLayout().autoLoadmore(0,1);
}
}
});
} else if (scrollableView instanceof RecyclerView) {
RecyclerView recyclerView = ((RecyclerView) scrollableView);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
if (manager instanceof LinearLayoutManager) {
LinearLayoutManager linearManager = ((LinearLayoutManager) manager);
if(newState == RecyclerView.SCROLL_STATE_IDLE){
int lastVisiblePosition = linearManager.findLastVisibleItemPosition();
if(lastVisiblePosition >= linearManager.getItemCount() - 1){
kernel.getRefreshLayout().autoLoadmore(0,1);
}
}
}
}
});
}
}
//</editor-fold>
//<editor-fold desc="">
private static boolean canScrollUp(View targetView, MotionEvent event) {
if (canScrollUp(targetView)) {
return true;
}
if (targetView instanceof ViewGroup && event != null) {
ViewGroup viewGroup = (ViewGroup) targetView;
final int childCount = viewGroup.getChildCount();
PointF point = new PointF();
for (int i = 0; i < childCount; i++) {
View child = viewGroup.getChildAt(i);
if (isTransformedTouchPointInView(viewGroup,child, event.getX(), event.getY() , point)) {
event = MotionEvent.obtain(event);
event.offsetLocation(point.x, point.y);
return canScrollUp(child, event);
}
}
}
return false;
}
private static boolean pointInView(View view, float localX, float localY, float slop) {
return localX >= -slop && localY >= -slop && localX < ((view.getWidth()) + slop) &&
localY < ((view.getHeight()) + slop);
}
private static boolean canScrollUp(View targetView) {
if (android.os.Build.VERSION.SDK_INT < 14) {
if (targetView instanceof AbsListView) {
final AbsListView absListView = (AbsListView) targetView;
return absListView.getChildCount() > 0
&& (absListView.getFirstVisiblePosition() > 0 || absListView.getChildAt(0)
.getTop() < absListView.getPaddingTop());
} else {
return targetView.getScrollY() > 0;
}
} else {
return targetView.canScrollVertically(-1);
}
}
private static boolean canScrollDown(View targetView, MotionEvent event) {
if (canScrollDown(targetView)) {
return true;
}
if (targetView instanceof ViewGroup && event != null) {
ViewGroup viewGroup = (ViewGroup) targetView;
final int childCount = viewGroup.getChildCount();
PointF point = new PointF();
for (int i = 0; i < childCount; i++) {
View child = viewGroup.getChildAt(i);
if (isTransformedTouchPointInView(viewGroup,child, event.getX(), event.getY() , point)) {
event = MotionEvent.obtain(event);
event.offsetLocation(point.x, point.y);
return canScrollDown(child, event);
}
}
}
return false;
}
private static boolean canScrollDown(View mScrollableView) {
if (android.os.Build.VERSION.SDK_INT < 14) {
if (mScrollableView instanceof AbsListView) {
final AbsListView absListView = (AbsListView) mScrollableView;
return absListView.getChildCount() > 0
&& (absListView.getLastVisiblePosition() < absListView.getChildCount() - 1
|| absListView.getChildAt(absListView.getChildCount() - 1).getBottom() > absListView.getPaddingBottom());
} else {
return mScrollableView.getScrollY() < 0;
}
} else {
return mScrollableView.canScrollVertically(1);
}
}
private static boolean isTransformedTouchPointInView(ViewGroup group, View child, float x, float y,PointF outLocalPoint) {
final float[] point = new float[2];
point[0] = x;
point[1] = y;
transformPointToViewLocal(group, child, point);
final boolean isInView = pointInView(child, point[0], point[1], 0);
if (isInView && outLocalPoint != null) {
outLocalPoint.set(point[0]-x, point[1]-y);
}
return isInView;
}
private static void transformPointToViewLocal(ViewGroup group, View child, float[] point) {
point[0] += group.getScrollX() - child.getLeft();
point[1] += group.getScrollY() - child.getTop();
}
//</editor-fold>
private class AbsListViewScrollComponent implements AbsListView.OnScrollListener {
int lasty;
int lastDy;
int lastState;
boolean autoLoadmore;
int mCurrentfirstVisibleItem = 0;
RefreshKernel kernel;
SparseArray<ItemRecod> recordSp = new SparseArray<>(0);
TimeInterpolator interpolator = new DecelerateInterpolator();
ValueAnimator.AnimatorUpdateListener updateListener = animation -> kernel.moveSpinner((int) animation.getAnimatedValue(), true);
AbsListViewScrollComponent(boolean autoLoadmore, RefreshKernel kernel) {
this.kernel = kernel;
this.autoLoadmore = autoLoadmore;
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (scrollState == 0 && lastState == SCROLL_STATE_FLING && Math.abs(lastDy) > 1) {
RefreshLayout layout = kernel.getRefreshLayout();
if ((autoLoadmore && !layout.isLoadmoreFinished() && lastDy > 0)
|| layout.isRefreshing() || layout.isLoading()) {
return;
}
ValueAnimator animator = ValueAnimator.ofInt(0, -lastDy * 2, 0);
animator.setDuration(300);
animator.addUpdateListener(updateListener);
animator.setInterpolator(interpolator);
animator.start();
lastDy = 0;
}
lastState = scrollState;
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
int scrollY = getScrollY(view, firstVisibleItem);
lastDy = scrollY - lasty;
lasty = scrollY;
}
void attach(AbsListView listView) {
listView.setOnScrollListener(this);
}
private int getScrollY(AbsListView view, int firstVisibleItem) {
mCurrentfirstVisibleItem = firstVisibleItem;
View firstView = view.getChildAt(0);
if (null != firstView) {
ItemRecod itemRecord = recordSp.get(firstVisibleItem);
if (null == itemRecord) {
itemRecord = new ItemRecod();
}
itemRecord.height = firstView.getHeight();
itemRecord.top = firstView.getTop();
recordSp.append(firstVisibleItem, itemRecord);
int height = 0;
for (int i = 0; i < mCurrentfirstVisibleItem; i++) {
ItemRecod itemRecod = recordSp.get(i);
height += itemRecod.height;
}
ItemRecod itemRecod = recordSp.get(mCurrentfirstVisibleItem);
if (null == itemRecod) {
itemRecod = new ItemRecod();
}
return height - itemRecod.top;
}
return 0;
}
class ItemRecod {
int height = 0;
int top = 0;
}
}
private class RecyclerViewScrollComponent extends RecyclerView.OnScrollListener {
int lastDy;
long lastFlingTime;
boolean autoLoadmore;
RefreshKernel kernel;
TimeInterpolator interpolator = new DecelerateInterpolator();
ValueAnimator.AnimatorUpdateListener updateListener = animation -> kernel.moveSpinner((int) animation.getAnimatedValue(), true);
RecyclerViewScrollComponent(boolean autoLoadmore, RefreshKernel kernel) {
this.autoLoadmore = autoLoadmore;
this.kernel = kernel;
}
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
if (newState == 0 && Math.abs(lastDy) > 1 && System.currentTimeMillis() - lastFlingTime < 1000) {
RefreshLayout layout = kernel.getRefreshLayout();
if ((autoLoadmore && !layout.isLoadmoreFinished() && lastDy > 0)
|| layout.isRefreshing() || layout.isLoading()) {
return;
}
ValueAnimator animator = ValueAnimator.ofInt(0, -lastDy * 2, 0);
animator.setDuration(400);
animator.addUpdateListener(updateListener);
animator.setInterpolator(interpolator);
animator.start();
lastDy = 0;
}
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
lastDy = dy;
}
void attach(RecyclerView recyclerView) {
recyclerView.addOnScrollListener(this);
recyclerView.setOnFlingListener(new RecyclerView.OnFlingListener() {
@Override
public boolean onFling(int velocityX, int velocityY) {
lastFlingTime = System.currentTimeMillis();
return false;
}
});
}
}
private class PagerPrimaryAdapter extends PagerAdapterWrapper {
private ViewPager mViewPager;
PagerPrimaryAdapter(PagerAdapter wrapped) {
super(wrapped);
}
void wrapper(PagerAdapter adapter) {
wrapped = adapter;
}
@Override
public void attachViewPager(ViewPager viewPager) {
mViewPager = viewPager;
super.attachViewPager(viewPager);
}
@Override
public void setViewPagerObserver(DataSetObserver observer) {
super.setViewPagerObserver(observer);
if (observer == null) {
wrapperViewPager(mViewPager, this);
}
}
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
super.setPrimaryItem(container, position, object);
if (object instanceof View) {
mScrollableView = ((View) object);
} else if (object instanceof Fragment) {
mScrollableView = ((Fragment) object).getView();
}
if (mScrollableView != null) {
mScrollableView = findScrollableViewInternal(mScrollableView, true);
if (mScrollableView instanceof NestedScrollingParent
&& !(mScrollableView instanceof NestedScrollingChild)) {
mScrollableView = findScrollableViewInternal(mScrollableView, false);
}
}
}
}
} |
public class item55_optimize_judiciously {
public static void main(String[] args) {
System.out.println("do not strive to write fast programs—strive to write good ones; speed will follow.");
}
} |
package com.rapid.security;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletContext;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlRootElement;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.rapid.core.Application;
import com.rapid.server.Rapid;
import com.rapid.server.RapidHttpServlet;
import com.rapid.server.RapidRequest;
import com.rapid.utils.Files;
public class RapidSecurityAdapter extends SecurityAdapter {
// security object which is marshalled and unmarshalled
@XmlRootElement
public static class Security {
private Roles _roles;
private Users _users;
// properties (these are marshalled in and out of the security.xml file)
public Roles getRoles() { return _roles; }
public void setRoles(Roles roles) { _roles = roles; }
public Users getUsers() { return _users; }
public void setUsers(Users users) { _users = users; }
// constructors
public Security() {
_roles = new Roles();
_users = new Users();
}
}
// instance variables
private static Logger _logger = LogManager.getLogger(RapidSecurityAdapter.class);
private Marshaller _marshaller;
private Unmarshaller _unmarshaller;
private Security _security;
// constructor
public RapidSecurityAdapter(ServletContext servletContext, Application application) {
// call the super method which retains the context and application
super(servletContext, application);
// init the marshaller and ununmarshaller
try {
JAXBContext jaxb = JAXBContext.newInstance(Security.class);
_marshaller = jaxb.createMarshaller();
_marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
_marshaller.setAdapter(RapidHttpServlet.getEncryptedXmlAdapter());
_unmarshaller = jaxb.createUnmarshaller();
_unmarshaller.setAdapter(RapidHttpServlet.getEncryptedXmlAdapter());
} catch (JAXBException ex) {
_logger.error(ex);
}
// load the users and roles
load();
}
// instance methods
private void load() {
try {
// create a file object for the security.xml file
File securityFile = new File(_application.getConfigFolder(_servletContext) + "/security.xml");
// check the file exists
if (securityFile.exists()) {
// unmarshal the xml into an object
_security = (Security) _unmarshaller.unmarshal(securityFile);
} else {
// initialise the security object
_security = new Security();
}
// initialise roles if necessary
if (_security.getRoles() == null) _security.setRoles(new Roles());
// initialise users if necessary
if (_security.getUsers() == null) _security.setUsers(new Users());
// retain whether we added users or roles to the security object
boolean modified = false;
// some old versions of rapid did not have roles with separate names and descriptions check them here
for (int i = 0; i < _security.getRoles().size(); i ++) {
// we're using a for loop as we will later the collection
Role role = _security.getRoles().get(i);
// if the role has no name
if (role.getName() == null) {
// remove it
_security.getRoles().remove(i);
// record that we modified
modified = true;
// set i back one as we've shrunk the collection
i
}
}
// some old versions of rapid held the users in a hashtable since we are now using a list we need to remove invalid entries
for (int i = 0; i < _security.getUsers().size(); i ++) {
// we're using a for loop as we will later the collection
User user = _security.getUsers().get(i);
// if the user has no name
if (user.getName() == null) {
// remove it
_security.getUsers().remove(i);
// record that we modified
modified = true;
// set i back one as we've shrunk the collection
i
}
}
// assume we don't have the admin role
boolean gotAdminRole = false;
// assume we don't have the design role
boolean gotDesignRole = false;
// loop all the roles
for (Role role : _security.getRoles()) {
if (Rapid.ADMIN_ROLE.equals(role.getName())) gotAdminRole = true;
if (Rapid.DESIGN_ROLE.equals(role.getName())) gotDesignRole = true;
}
// if no admin role
if (!gotAdminRole) {
// add it
_security.getRoles().add(new Role(Rapid.ADMIN_ROLE, "Manage application in Rapid Admin"));
// record that we modified
modified = true;
}
// if no design role
if (!gotDesignRole) {
// add it
_security.getRoles().add(new Role(Rapid.DESIGN_ROLE, "Design application in Rapid Designer"));
// record that we modified
modified = true;
}
// save the files if we modified it
if (modified) save();
} catch (Exception ex) {
_logger.error(ex);
}
}
private void save() {
try {
// create a file object for the security.xml file
File securityFile = new File(_application.getConfigFolder(_servletContext) + "/security.xml");
// create a temp file for saving the application to
File tempFile = new File(_application.getConfigFolder(_servletContext) + "/security-saving.xml");
// get a file output stream to write the data to
FileOutputStream fos = new FileOutputStream(tempFile.getAbsolutePath());
// marshal the security object to the temp file
_marshaller.marshal(_security, fos);
// close the stream
fos.close();
// copy / overwrite the app file with the temp file
Files.copyFile(tempFile, securityFile);
// delete the temp file
tempFile.delete();
} catch (Exception ex) {
_logger.error(ex);
}
}
// overrides
@Override
public Roles getRoles(RapidRequest rapidRequest) throws SecurityAdapaterException {
return _security.getRoles();
}
@Override
public Users getUsers(RapidRequest rapidRequest) throws SecurityAdapaterException {
return _security.getUsers();
}
@Override
public Role getRole(RapidRequest rapidRequest, String roleName) throws SecurityAdapaterException {
for (Role role : _security.getRoles()) if (role.getName().toLowerCase().equals(roleName.toLowerCase())) return role;
return null;
}
@Override
public User getUser(RapidRequest rapidRequest) throws SecurityAdapaterException {
for (User user : _security.getUsers()) {
if (user.getName() != null && rapidRequest.getUserName() != null) {
if (user.getName().toLowerCase().equals(rapidRequest.getUserName().toLowerCase())) return user;
}
}
return null;
}
@Override
public void addRole(RapidRequest rapidRequest, Role role) throws SecurityAdapaterException {
Roles roles = _security.getRoles();
if (!roles.contains(role)) roles.add(role);
roles.sort();
save();
}
@Override
public boolean deleteRole(RapidRequest rapidRequest, String roleName) throws SecurityAdapaterException {
Roles roles = _security.getRoles();
boolean removed = roles.remove(roleName);
if (removed) save();
return removed;
}
@Override
public void addUser(RapidRequest rapidRequest, User user) throws SecurityAdapaterException {
// get the list of users
Users users = _security.getUsers();
// get this user name
String userName = user.getName();
// users to remove - their may be more than one for legacy reasons
List<User> removeUsers = new ArrayList<User>();
// loop the users looking for anyone with the same name as the current user
for (User u : users) if (u.getName().equalsIgnoreCase(userName)) {
// remember to remove this user
removeUsers.add(u);
}
// if we are removing any users
if (removeUsers.size() > 0) {
// loop remove users
for (User u : removeUsers) users.remove(u);
}
users.add(user);
users.sort();
save();
}
@Override
public boolean deleteUser(RapidRequest rapidRequest) throws SecurityAdapaterException {
for (User user : _security.getUsers()) if (user.getName().equals(rapidRequest.getUserName())){
boolean removed = _security.getUsers().remove(user);
if (removed) {
_security.getUsers().sort();
save();
}
return removed;
}
return false;
}
@Override
public void addUserRole(RapidRequest rapidRequest, String roleName) throws SecurityAdapaterException {
User user = getUser(rapidRequest);
if (user == null) throw new SecurityAdapaterException("User " + rapidRequest.getUserName() + " cannot be found");
user.getRoles().add(roleName);
user.getRoles().sort();
save();
}
@Override
public boolean deleteUserRole(RapidRequest rapidRequest, String roleName) throws SecurityAdapaterException {
User user = getUser(rapidRequest);
if (user == null) throw new SecurityAdapaterException("User " + rapidRequest.getUserName() + " cannot be found");
boolean removed = user.getRoles().remove(roleName);
if (removed) {
user.getRoles().sort();
save();
}
return removed;
}
@Override
public boolean checkUserRole(RapidRequest rapidRequest, String roleName) throws SecurityAdapaterException {
User user = getUser(rapidRequest);
if (user != null) {
return user.getRoles().contains(roleName);
}
return false;
}
@Override
public boolean checkUserRole(RapidRequest rapidRequest, List<String> roleNames) throws SecurityAdapaterException {
User user = getUser(rapidRequest);
if (user != null) {
for (String roleName : roleNames) {
if (user.getRoles().contains(roleName)) return true;
}
}
return false;
}
@Override
public void updateRole(RapidRequest rapidRequest, Role role) throws SecurityAdapaterException {
Role currentRole = getRole(rapidRequest, role.getName());
if (currentRole == null) throw new SecurityAdapaterException("Role " + role.getName() + " cannot be found");
currentRole.setDescription(role.getDescription());
save();
}
@Override
public void updateUser(RapidRequest rapidRequest, User user) throws SecurityAdapaterException {
// the form adapter will return true to any password check so it looks like any user is in the app, only save if delete returns true meaning user was really in the app
if (deleteUser(rapidRequest)) {
_security.getUsers().add(user);
_security.getUsers().sort();
save();
}
}
@Override
public boolean checkUserPassword(RapidRequest rapidRequest, String userName, String password) throws SecurityAdapaterException {
User user = null;
for (User u : _security.getUsers()) {
if (u.getName().toLowerCase().equals(userName.toLowerCase())) {
user = u;
break;
}
}
if (user != null && password != null) {
if (password.equals(user.getPassword())) {
// get the application
Application application = rapidRequest.getApplication();
// if there was one (soa authentication doesn't)
if (application == null) {
return true;
} else {
// if it has device security
if (application.getDeviceSecurity()) {
// check device security as well
if (user.checkDevice(rapidRequest)) return true;
} else return true;
}
}
}
return false;
}
} |
// This file is part of Serleena.
// Nicola Mometto, Filippo Sestini, Tobia Tesan, Sebastiano Valle.
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// all copies or substantial portions of the Software.
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
package com.kyloth.serleena.persistence.sqlite;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import com.kyloth.serleena.BuildConfig;
import com.kyloth.serleena.common.GeoPoint;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import java.net.URISyntaxException;
import java.util.ArrayList;
import static com.kyloth.serleena.persistence.sqlite.SerleenaDatabaseTestUtils.makeExperience;
import static com.kyloth.serleena.persistence.sqlite.SerleenaDatabaseTestUtils.makeTelemetry;
import static com.kyloth.serleena.persistence.sqlite.SerleenaDatabaseTestUtils.makeTrack;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;
@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class, emulateSdk = 19)
public class SerleenaDatabaseTest {
SerleenaDatabase sh;
SQLiteDatabase db;
ArrayList<String> basicStrings;
ArrayList<String> nastyStrings;
ArrayList<String> invalidStrings;
@Test
public void testGetReadableDatabase() throws Exception {
db = sh.getReadableDatabase();
}
/*
* TABLE_EXPERIENCES
*/
/**
* Verifica che sia possibile aggiungere correttamente un'Esperienza.
*/
@Test
public void testAddExperience() {
ContentValues values;
ArrayList<String> names = new ArrayList<String>();
names.addAll(basicStrings);
names.addAll(nastyStrings);
names.addAll(invalidStrings);
for (String name : names) {
values = new ContentValues();
values.put("experience_name", name);
db.insertOrThrow(SerleenaDatabase.TABLE_EXPERIENCES, null, values);
}
}
/**
* Verifica che sia non sia possibile aggiungere un'Esperienza senza nome.
*/
@Test(expected = SQLException.class)
public void testExperienceNoNameFails() {
ContentValues values = (new ContentValues());
values.put("experience_name", (String)null);
db.insertOrThrow(SerleenaDatabase.TABLE_EXPERIENCES, null, values);
}
/*
* TABLE_TRACKS
*/
/**
* Verifica che sia possibile aggiungere correttamente un Percorso
*/
@Test
public void testAddTrack() {
ContentValues values;
long id = makeExperience(db);
ArrayList<String> names = new ArrayList<String>();
names.addAll(basicStrings);
names.addAll(nastyStrings);
names.addAll(invalidStrings);
for (String name : names) {
values = new ContentValues();
values.put("track_experience", id);
values.put("track_name", name);
db.insertOrThrow(SerleenaDatabase.TABLE_TRACKS, null, values);
}
}
/**
* Verifica che non sia possibile aggiungere un Percorso senza nome
*/
@Test(expected = SQLException.class)
public void testTrackNoNameFails() {
ContentValues values = (new ContentValues());
values.put("track_name", (String) null);
db.insertOrThrow(SerleenaDatabase.TABLE_TRACKS, null, values);
}
/**
* Verifica che non sia possibile aggiungere un percorso che fa riferimento a un'Esperiezna
* inesistente.
*/
@Test(expected = SQLException.class)
public void testTrackWrongID() {
long id = makeExperience(db);
// Questo dovrebbe rompere l'integrita' referenziale?
id += 123;
ContentValues values;
values = new ContentValues();
values.put("track_experience", id);
values.put("track_name", "bar");
db.insertOrThrow(SerleenaDatabase.TABLE_TRACKS, null, values);
}
/**
* Verifica che non sia possibile aggiungere un percorso che non fa riferimento ad alcuna
* Esperienza
*/
@Test(expected = SQLException.class)
public void testTrackNoExpFails() {
ContentValues values = (new ContentValues());
values.put("track_name", "foo");
db.insertOrThrow(SerleenaDatabase.TABLE_TRACKS, null, values);
}
/**
* Verifica che l'eliminazione di un'Esperienza elimini i suoi Percorsi.
*/
@Test
public void testTrackCascade() {
ContentValues values;
long id = makeExperience(db);
values = new ContentValues();
values.put("track_experience", id);
values.put("track_name", "bar");
db.insertOrThrow(SerleenaDatabase.TABLE_TRACKS, null, values);
db.delete(SerleenaDatabase.TABLE_EXPERIENCES, "experience_id = " + id, null);
Cursor query = db.query(SerleenaDatabase.TABLE_TRACKS,
null,
"track_experience = " + id,
null,
null,
null,
null);
assertTrue(query.getCount() == 0);
}
/*
* TABLE_TELEMETRY
*/
/**
* Verifica che sia possibile aggiungere correttamente un Tracciamento.
*/
@Test
public void testAddTelem() {
ContentValues values;
long id = makeTelemetry(db);
values = new ContentValues();
values.put("eventc_telem", id);
values.put("eventc_timestamp", 300);
values.put("eventc_value", "1");
db.insertOrThrow(SerleenaDatabase.TABLE_TELEM_EVENTS_CHECKP, null, values);
}
/**
* Verifica che non sia possibile aggiungere un Tracciamento senza Percorso.
*/
@Test(expected = SQLException.class)
public void testTelemNoTrackFails() {
ContentValues values = new ContentValues();
db.insertOrThrow(SerleenaDatabase.TABLE_TELEMETRIES, null, values);
}
/*
* TABLE_TELEM_EVENTS_LOCATION
*/
/**
* Verifica che non sia possibile aggiungere un Tracciamento che fa riferimento a un
* Percorso inesistente.
*/
@Test(expected = SQLException.class)
public void testCheckpointWrongTelemFails() {
ContentValues values = new ContentValues();
values.put("eventc_telem", 2342342);
values.put("eventc_timestamp", 300);
values.put("eventc_value", "1");
db.insertOrThrow(SerleenaDatabase.TABLE_TELEM_EVENTS_CHECKP, null, values);
}
/**
* Verifica che non sia possibile aggiungere un evento checkpoint che non
* fa riferimanto ad alcun Tracciamento.
*/
@Test(expected = SQLException.class)
public void testHeartWrongTelemFails() {
ContentValues values = new ContentValues();
values.put("eventc_telem", 1234567890);
values.put("eventc_timestamp", 1);
values.put("eventc_value", 1);
db.insertOrThrow(SerleenaDatabase.TABLE_TELEM_EVENTS_CHECKP, null, values);
}
/**
* Verifica che l'eliminazione di un Tracciamento causi l'eliminazione dei
* suoi eventi checkpoint.
*/
@Test(expected = SQLException.class)
public void testHeartCascade() {
ContentValues values = new ContentValues();
long id = makeTrack(db);
values.put("eventc_telem", id);
values.put("eventc_timestamp", 1);
values.put("eventc_value", 1);
db.insertOrThrow(SerleenaDatabase.TABLE_TELEM_EVENTS_CHECKP, null, values);
db.delete(SerleenaDatabase.TABLE_TRACKS, "track_id = " + id, null);
Cursor query = db.query(SerleenaDatabase.TABLE_TELEM_EVENTS_CHECKP, null,
"eventc_telem = " + id, null, null, null, null);
assertTrue(query.getCount() == 0);
}
/**
* Verifica che non sia possibile aggiungere eventi checkpoint senza
* timestamp.
*/
@Test(expected = SQLException.class)
public void testHeartNullTimestampFails() {
long id = makeTelemetry(db);
ContentValues values;
values = new ContentValues();
values.put("eventc_telem", id);
values.put("eventc_value", 1);
db.insertOrThrow(SerleenaDatabase.TABLE_TELEM_EVENTS_CHECKP, null, values);
}
/**
* Verifica che non sia possibile aggiungere eventi checkpoint senza value.
*/
@Test(expected = SQLException.class)
public void testHeartNullValueFails() {
long id = makeTelemetry(db);
ContentValues values;
values = new ContentValues();
values.put("eventl_telem", id);
values.put("eventl_timestamp", 1);
db.insertOrThrow(SerleenaDatabase.TABLE_TELEM_EVENTS_CHECKP, null, values);
}
/*
* TABLE_CONTACTS
*/
/**
* Verifica che sia possibile aggiungere correttamente un Contatto.
*/
@Test
public void testAddContact() {
ContentValues values;
values = new ContentValues();
ArrayList<String> names = new ArrayList<String>();
names.addAll(basicStrings);
names.addAll(nastyStrings);
names.addAll(invalidStrings);
for (String name : names) {
for (String contact : names) {
values.put("contact_name", name);
values.put("contact_value", contact);
values.put("contact_nw_corner_latitude", 1);
values.put("contact_nw_corner_longitude", 1);
values.put("contact_se_corner_latitude", 1);
values.put("contact_se_corner_longitude", 1);
db.insertOrThrow(SerleenaDatabase.TABLE_CONTACTS, null, values);
}
}
}
/**
* Verifica che non sia possibile aggiungere un Contatto senza nome.
*/
@Test(expected = SQLException.class)
public void testContactNullNameFails() {
ContentValues values;
values = new ContentValues();
values.put("contact_value", "foo");
values.put("contact_nw_corner_latitude", 1);
values.put("contact_nw_corner_longitude", 1);
values.put("contact_se_corner_latitude", 1);
values.put("contact_se_corner_longitude", 1);
db.insertOrThrow(SerleenaDatabase.TABLE_CONTACTS, null, values);
}
/**
* Verifica che non sia possibile aggiungere un Contatto senza value.
*/
@Test(expected = SQLException.class)
public void testContactNullValueFails() {
ContentValues values;
values = new ContentValues();
values.put("contact_name", "foo");
values.put("contact_nw_corner_latitude", 1);
values.put("contact_nw_corner_longitude", 1);
values.put("contact_se_corner_latitude", 1);
values.put("contact_se_corner_longitude", 1);
db.insertOrThrow(SerleenaDatabase.TABLE_CONTACTS, null, values);
}
/*
* WEATHER_FORECASTS
*/
/**
* Verifica che sia possibile aggiungere correttamente un Forecast.
*/
@Test
public void testAddForecast() {
ContentValues values;
values = new ContentValues();
ArrayList<String> strings = new ArrayList<String>();
strings.addAll(basicStrings);
strings.addAll(nastyStrings);
strings.addAll(invalidStrings);
for (String value : strings) {
values.put("weather_condition_morning", value);
values.put("weather_temperature_morning", 1);
values.put("weather_condition_afternoon", value);
values.put("weather_temperature_afternoon", 1);
values.put("weather_condition_night", value);
values.put("weather_temperature_night", 1);
values.put("weather_date", 1);
values.put("weather_nw_corner_latitude", 1);
values.put("weather_nw_corner_longitude", 1);
values.put("weather_se_corner_latitude", 1);
values.put("weather_se_corner_longitude", 1);
}
db.insertOrThrow(SerleenaDatabase.TABLE_WEATHER_FORECASTS, null, values);
}
/**
* Verifica che non sia possibile aggiungere un Forecast con attributo start nullo.
*/
@Test(expected = SQLException.class)
public void testForecastNullStartFails() {
ContentValues values;
values = new ContentValues();
values.put("weather_condition", "foo");
values.put("weather_temperature", 1);
values.put("weather_end", 1);
values.put("weather_nw_corner_latitude", 1);
values.put("weather_nw_corner_longitude", 1);
values.put("weather_se_corner_latitude", 1);
values.put("weather_se_corner_longitude", 1);
db.insertOrThrow(SerleenaDatabase.TABLE_WEATHER_FORECASTS, null, values);
}
/**
* Verifica che non sia possibile aggiungere un Forecast con attributo end nullo.
*/
@Test(expected = SQLException.class)
public void testForecastNullEndFails() {
ContentValues values;
values = new ContentValues();
values.put("weather_condition", "foo");
values.put("weather_temperature", 1);
values.put("weather_start", 1);
values.put("weather_nw_corner_latitude", 1);
values.put("weather_nw_corner_longitude", 1);
values.put("weather_se_corner_latitude", 1);
values.put("weather_se_corner_longitude", 1);
db.insertOrThrow(SerleenaDatabase.TABLE_WEATHER_FORECASTS, null, values);
}
/*
* TABLE_USER_POINTS
*/
/**
* Verifica che sia possibile aggiungere correttamente un Punto Utente
*/
@Test
public void testAddUserPoint() {
ContentValues values;
values = new ContentValues();
values.put("userpoint_experience", makeExperience(db));
values.put("userpoint_x", 1);
values.put("userpoint_y", 1);
db.insertOrThrow(SerleenaDatabase.TABLE_USER_POINTS, null, values);
}
/**
* Verifica che non sia possibile aggiungere un Punto Utente senza Esperienza.
*/
@Test(expected = SQLException.class)
public void testUserPointNoExperienceFails() {
ContentValues values;
values = new ContentValues();
values.put("userpoint_x", 1);
values.put("userpoint_y", 1);
db.insertOrThrow(SerleenaDatabase.TABLE_USER_POINTS, null, values);
}
/**
* Verifica che non sia possibile aggiungere un Punto Utente che fa riferimetno ad una
* Esperienza inesistente.
*/
@Test(expected = SQLException.class)
public void testUserPointWrongExperienceFails() {
ContentValues values;
values = new ContentValues();
values.put("userpoint_experience", 12345);
values.put("userpoint_x", 1);
values.put("userpoint_y", 1);
db.insertOrThrow(SerleenaDatabase.TABLE_USER_POINTS, null, values);
}
/**
* Verifica che non sia possibile aggiungere un Punto Utente che fa riferimento ad una
* Esperienza inesistente.
*/
@Test
public void testUserPointCascade() {
ContentValues values;
long id = makeExperience(db);
values = new ContentValues();
values.put("userpoint_experience", id);
values.put("userpoint_x", 1);
values.put("userpoint_y", 1);
db.insertOrThrow(SerleenaDatabase.TABLE_USER_POINTS, null, values);
db.delete(SerleenaDatabase.TABLE_EXPERIENCES, "experience_id = " + id, null);
Cursor query = db.query(SerleenaDatabase.TABLE_USER_POINTS, null, "userpoint_experience = " + id, null, null, null, null);
assertTrue(query.getCount() == 0);
}
/*
* TABLE_CHECKPOINTS
*/
/**
* Verifica che sia possibile aggiungere correttamente un Checkpoint.
*/
@Test
public void testAddCheckpoint() {
ContentValues values;
values = new ContentValues();
values.put("checkpoint_latitude", 1);
values.put("checkpoint_longitude", 1);
values.put("checkpoint_num", 1);
values.put("checkpoint_track", makeTrack(db));
db.insertOrThrow(SerleenaDatabase.TABLE_CHECKPOINTS, null, values);
}
/**
* Verifica che non sia possibile aggiungere un Checkpoint senza Percorso.
*/
@Test(expected = SQLException.class)
public void testCheckpointNoTrackFails() {
ContentValues values;
values = new ContentValues();
values.put("checkpoint_latitude", 1);
values.put("checkpoint_longitude", 1);
values.put("checkpoint_num", 1);
db.insertOrThrow(SerleenaDatabase.TABLE_CHECKPOINTS, null, values);
}
/**
* Verifica che non sia possibile aggiungere un Checkpoint che fa riferimento
* a un Percorso inesistente.
*/
@Test(expected = SQLException.class)
public void testCheckpointWrongTrackFails() {
ContentValues values;
values = new ContentValues();
values.put("checkpoint_latitude", 1);
values.put("checkpoint_longitude", 1);
values.put("checkpoint_num", 1);
values.put("checkpoint_track", 12345);
db.insertOrThrow(SerleenaDatabase.TABLE_CHECKPOINTS, null, values);
}
/**
* Verifica che l'eliminazione di un Percorso ne elimini i Checkpoint.
*/
@Test
public void testCheckpointCascade() {
ContentValues values;
values = new ContentValues();
long id = makeTrack(db);
values.put("checkpoint_latitude", 1);
values.put("checkpoint_longitude", 1);
values.put("checkpoint_num", 1);
values.put("checkpoint_track", id);
db.insertOrThrow(SerleenaDatabase.TABLE_CHECKPOINTS, null, values);
db.delete(SerleenaDatabase.TABLE_TRACKS, "track_id = " + id, null);
Cursor query = db.query(SerleenaDatabase.TABLE_CHECKPOINTS, null, "checkpoint_track = " + id, null, null, null, null);
assertTrue(query.getCount() == 0);
}
@Test
public void shouldBePossibleToAddARaster() {
ContentValues values = new ContentValues();
values.put("raster_nw_corner_latitude", 2);
values.put("raster_nw_corner_longitude", 0);
values.put("raster_se_corner_latitude", 0);
values.put("raster_se_corner_longitude", 2);
values.put("raster_path", "asdlolasdlol");
db.insertOrThrow(SerleenaDatabase.TABLE_RASTERS, null, values);
double latitude = 1;
double longitude = 1;
Cursor query = db.query(SerleenaDatabase.TABLE_RASTERS, null,
"raster_nw_corner_latitude >= " + latitude + " AND " +
"raster_nw_corner_longitude <= " + longitude + " AND " +
"raster_se_corner_latitude <= " + latitude + " AND " +
"raster_se_corner_longitude >= " + longitude,
null, null, null, null);
assertEquals(1, query.getCount());
}
/*
* Util
*/
@Before
public void setup() throws URISyntaxException {
sh = new SerleenaDatabase(RuntimeEnvironment.application, "sample.db", null, 1);
db = sh.getWritableDatabase();
basicStrings = new ArrayList<String>();
nastyStrings = new ArrayList<String>();
invalidStrings = new ArrayList<String>();
basicStrings.add("asdfghjkl");
basicStrings.add("ASDFGHJKL");
basicStrings.add("123456789");
String long256 = "256CHARLONG 3456789012345678901212345678901234567890123456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012123456789012345678901234567890121234567890123456789012345678901212345678901234567890123456789012";
assert(long256.length() == 256);
nastyStrings.add(long256);
String long512 = long256 + long256;
assert(long512.length() == 512);
nastyStrings.add(long512);
invalidStrings.add("");
invalidStrings.add("foo\"bar");
invalidStrings.add("foo`bar");
invalidStrings.add("\\\\\\");
}
@After
public void tearDown() throws Exception {
sh.close();
}
} |
package com.robrua.orianna.api.dto;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.robrua.orianna.type.api.ParamsBuilder;
import com.robrua.orianna.type.core.common.QueueType;
import com.robrua.orianna.type.core.common.Season;
import com.robrua.orianna.type.dto.matchlist.MatchList;
public abstract class MatchListAPI {
private static final Set<QueueType> RANKED_QUEUES = new HashSet<>(
Arrays.asList(new QueueType[] {QueueType.TEAM_BUILDER_DRAFT_RANKED_5x5, QueueType.RANKED_SOLO_5x5, QueueType.RANKED_TEAM_3x3, QueueType.RANKED_TEAM_5x5}));
public static MatchList getMatchList(final long summonerID) {
final String request = BaseRiotAPI.API_VERSIONS.get("matchlist") + "/matchlist/by-summoner/" + summonerID;
return BaseRiotAPI.GSON.fromJson(BaseRiotAPI.get(request, null, false), MatchList.class);
}
public static MatchList getMatchList(final long summonerID, final int numMatches) {
final String request = BaseRiotAPI.API_VERSIONS.get("matchlist") + "/matchlist/by-summoner/" + summonerID;
final Map<String, String> params = new ParamsBuilder().add("beginIndex", 0).add("endIndex", numMatches).build();
return BaseRiotAPI.GSON.fromJson(BaseRiotAPI.get(request, params, false), MatchList.class);
}
public static MatchList getMatchList(final long summonerID, final int numMatches, final int beginIndex) {
final String request = BaseRiotAPI.API_VERSIONS.get("matchlist") + "/matchlist/by-summoner/" + summonerID;
final Map<String, String> params = new ParamsBuilder().add("beginIndex", beginIndex).add("endIndex", beginIndex + numMatches).build();
return BaseRiotAPI.GSON.fromJson(BaseRiotAPI.get(request, params, false), MatchList.class);
}
public static MatchList getMatchList(final long summonerID, final int numMatches, final int beginIndex, final long beginTime) {
final String request = BaseRiotAPI.API_VERSIONS.get("matchlist") + "/matchlist/by-summoner/" + summonerID;
final Map<String, String> params = new ParamsBuilder().add("beginIndex", beginIndex).add("endIndex", beginIndex + numMatches)
.add("beginTime", beginTime).build();
return BaseRiotAPI.GSON.fromJson(BaseRiotAPI.get(request, params, false), MatchList.class);
}
public static MatchList getMatchList(final long summonerID, final int numMatches, final int beginIndex, final long beginTime, final long endTime) {
final String request = BaseRiotAPI.API_VERSIONS.get("matchlist") + "/matchlist/by-summoner/" + summonerID;
final Map<String, String> params = new ParamsBuilder().add("beginIndex", beginIndex).add("endIndex", beginIndex + numMatches)
.add("beginTime", beginTime).add("endTime", endTime).build();
return BaseRiotAPI.GSON.fromJson(BaseRiotAPI.get(request, params, false), MatchList.class);
}
public static MatchList getMatchList(final long summonerID, final int numMatches, final int beginIndex, final long beginTime, final long endTime,
final List<QueueType> queueTypes) {
for(final QueueType queue : queueTypes) {
if(!RANKED_QUEUES.contains(queue)) {
throw new IllegalArgumentException("Can't get match history for a non-ranked queue type!");
}
}
final String request = BaseRiotAPI.API_VERSIONS.get("matchlist") + "/matchlist/by-summoner/" + summonerID;
final Map<String, String> params = new ParamsBuilder().add("beginIndex", beginIndex).add("endIndex", beginIndex + numMatches)
.add("beginTime", beginTime).add("endTime", endTime).addIfNotNull("rankedQueues", queueTypes).build();
return BaseRiotAPI.GSON.fromJson(BaseRiotAPI.get(request, params, false), MatchList.class);
}
public static MatchList getMatchList(final long summonerID, final int numMatches, final int beginIndex, final long beginTime, final long endTime,
final List<QueueType> queueTypes, final List<Long> championIDs) {
final String request = BaseRiotAPI.API_VERSIONS.get("matchlist") + "/matchlist/by-summoner/" + summonerID;
final Map<String, String> params = new ParamsBuilder().add("beginIndex", beginIndex).add("endIndex", beginIndex + numMatches)
.add("beginTime", beginTime).add("endTime", endTime).addIfNotNull("rankedQueues", queueTypes).addIfNotNull("championIds", championIDs).build();
return BaseRiotAPI.GSON.fromJson(BaseRiotAPI.get(request, params, false), MatchList.class);
}
public static MatchList getMatchList(final long summonerID, final int numMatches, final int beginIndex, final long beginTime, final long endTime,
final List<QueueType> queueTypes, final List<Long> championIDs, final List<Season> seasons) {
for(final QueueType queue : queueTypes) {
if(!RANKED_QUEUES.contains(queue)) {
throw new IllegalArgumentException("Can't get match history for a non-ranked queue type!");
}
}
final String request = BaseRiotAPI.API_VERSIONS.get("matchlist") + "/matchlist/by-summoner/" + summonerID;
final Map<String, String> params = new ParamsBuilder().add("beginIndex", beginIndex).add("endIndex", beginIndex + numMatches)
.add("beginTime", beginTime).add("endTime", endTime).addIfNotNull("rankedQueues", queueTypes).addIfNotNull("championIds", championIDs)
.addIfNotNull("seasons", seasons).build();
return BaseRiotAPI.GSON.fromJson(BaseRiotAPI.get(request, params, false), MatchList.class);
}
public static MatchList getMatchList(final long summonerID, final long beginTime) {
final String request = BaseRiotAPI.API_VERSIONS.get("matchlist") + "/matchlist/by-summoner/" + summonerID;
final Map<String, String> params = new ParamsBuilder().add("beginTime", beginTime).build();
return BaseRiotAPI.GSON.fromJson(BaseRiotAPI.get(request, params, false), MatchList.class);
}
public static MatchList getMatchList(final long summonerID, final long beginTime, final long endTime) {
final String request = BaseRiotAPI.API_VERSIONS.get("matchlist") + "/matchlist/by-summoner/" + summonerID;
final Map<String, String> params = new ParamsBuilder().add("beginTime", beginTime).add("endTime", endTime).build();
return BaseRiotAPI.GSON.fromJson(BaseRiotAPI.get(request, params, false), MatchList.class);
}
public static MatchList getMatchList(final long summonerID, final long beginTime, final long endTime, final List<QueueType> queueTypes) {
for(final QueueType queue : queueTypes) {
if(!RANKED_QUEUES.contains(queue)) {
throw new IllegalArgumentException("Can't get match history for a non-ranked queue type!");
}
}
final String request = BaseRiotAPI.API_VERSIONS.get("matchlist") + "/matchlist/by-summoner/" + summonerID;
final Map<String, String> params = new ParamsBuilder().add("beginTime", beginTime).add("endTime", endTime).addIfNotNull("rankedQueues", queueTypes)
.build();
return BaseRiotAPI.GSON.fromJson(BaseRiotAPI.get(request, params, false), MatchList.class);
}
public static MatchList getMatchList(final long summonerID, final long beginTime, final long endTime, final List<QueueType> queueTypes,
final List<Long> championIDs) {
for(final QueueType queue : queueTypes) {
if(!RANKED_QUEUES.contains(queue)) {
throw new IllegalArgumentException("Can't get match history for a non-ranked queue type!");
}
}
final String request = BaseRiotAPI.API_VERSIONS.get("matchlist") + "/matchlist/by-summoner/" + summonerID;
final Map<String, String> params = new ParamsBuilder().add("beginTime", beginTime).add("endTime", endTime).addIfNotNull("rankedQueues", queueTypes)
.addIfNotNull("championIds", championIDs).build();
return BaseRiotAPI.GSON.fromJson(BaseRiotAPI.get(request, params, false), MatchList.class);
}
public static MatchList getMatchList(final long summonerID, final long beginTime, final long endTime, final List<QueueType> queueTypes,
final List<Long> championIDs, final List<Season> seasons) {
for(final QueueType queue : queueTypes) {
if(!RANKED_QUEUES.contains(queue)) {
throw new IllegalArgumentException("Can't get match history for a non-ranked queue type!");
}
}
final String request = BaseRiotAPI.API_VERSIONS.get("matchlist") + "/matchlist/by-summoner/" + summonerID;
final Map<String, String> params = new ParamsBuilder().add("beginTime", beginTime).add("endTime", endTime).addIfNotNull("rankedQueues", queueTypes)
.addIfNotNull("championIds", championIDs).addIfNotNull("seasons", seasons).build();
return BaseRiotAPI.GSON.fromJson(BaseRiotAPI.get(request, params, false), MatchList.class);
}
} |
package com.company.dictionary.impl;
import com.company.dictionary.Dictionary;
import com.company.dictionary.DictionaryTree;
import com.company.dictionary.Word;
import java.util.*;
public class LevenshteinDistanceTree
implements DictionaryTree
{
private TreeNode root;
private LinkedList<Word> lastSearchSimilarWords;
private static final int ERROR_MAX_COUNT = 2;
public LevenshteinDistanceTree() {
lastSearchSimilarWords = new LinkedList<>();
}
@Override
public void build(Dictionary dictionary) {
clear();
for (Iterator<Word> iter = dictionary.iterator(); iter.hasNext();) {
addWord(iter.next());
}
}
@Override
public void addWord(Word word) {
if (root == null) {
root = new TreeNode(word.toString());
} else {
addWordInternal(word.toString(), root);
}
}
@Override
public boolean search(Word word) {
lastSearchSimilarWords.clear();
return searchInternal(word.toString(), root);
}
private void addWordInternal(String wordString, TreeNode node) {
int levenshteinDistance = calcLevenshteinDistance(wordString, node.getValue());
if (levenshteinDistance == 0) return;
TreeNode childNode = node.getChild(levenshteinDistance);
if (childNode != null) {
addWordInternal(wordString, childNode);
} else {
node.addChild(levenshteinDistance, new TreeNode(wordString));
}
}
private boolean searchInternal(String wordString, TreeNode node) {
int levenshteinDistance = calcLevenshteinDistance(wordString, node.getValue());
if (levenshteinDistance <= ERROR_MAX_COUNT) {
lastSearchSimilarWords.addFirst(new WordImpl(node.getValue()));
}
if (levenshteinDistance == 0) return true;
int downIndex = Integer.max(1, levenshteinDistance - ERROR_MAX_COUNT);
int upIndex = levenshteinDistance + ERROR_MAX_COUNT;
List<Boolean> recursiveCallResults = new LinkedList<>();
for (int index = downIndex; index <= upIndex; ++index) {
TreeNode childNode = node.getChild(index);
if (childNode != null) {
recursiveCallResults.add(searchInternal(wordString, node.getChild(index)));
}
}
for (Boolean result : recursiveCallResults) {
if (result.equals(Boolean.TRUE)) return true;
}
return false;
}
// returns number of add/edit/delete operations required for equality.
private int calcLevenshteinDistance(String first, String second) {
int firstLength = first.length(), secondLength = second.length();
if (firstLength == 0) return secondLength;
if (secondLength == 0) return firstLength;
int[] distFirst, distSecond = new int[secondLength + 1];
for (int i = 0; i <= secondLength; ++i) {
distSecond[i] = i;
}
for (int i = 1; i <= firstLength; ++i) {
distFirst = distSecond;
distSecond = new int[secondLength + 1];
for (int j = 0; j <= secondLength; ++j) {
if (j == 0) distSecond[j] = i;
else {
int cost = (first.charAt(i - 1) != second.charAt(j - 1)) ? 1 : 0;
if (distSecond[j - 1] < distFirst[j] && distSecond[j - 1] < distFirst[j - 1] + cost)
distSecond[j] = distSecond[j - 1] + 1;
else if (distFirst[j] < distFirst[j - 1] + cost)
distSecond[j] = distFirst[j] + 1;
else
distSecond[j] = distFirst[j - 1] + cost;
}
}
}
return distSecond[secondLength];
}
@Override
public List<Word> getSimilarWords(int limit) {
LinkedList<Word> similarWords = new LinkedList<>();
int count = 0;
for (Iterator<Word> iter = lastSearchSimilarWords.iterator(); iter.hasNext() && count++ < limit;) {
similarWords.add(iter.next());
}
return similarWords;
}
@Override
public void clear() {
root = null;
}
static final class TreeNode
{
private String word;
private HashMap<Integer, TreeNode> childs; // Levenshtein distance as index
TreeNode(String word) {
this(word, new HashMap<>());
}
TreeNode(String word, HashMap<Integer, TreeNode> childs) {
this.word = word;
this.childs = childs;
}
public String getValue() {
return word;
}
public boolean hasChilds() {
return childs.size() > 0;
}
public TreeNode getChild(int levenshteinDistance) {
return childs.get(levenshteinDistance);
}
public HashMap<Integer, TreeNode> getChilds() {
return childs;
}
public void addChild(int levenshteinDistance, TreeNode node) {
childs.put(levenshteinDistance, node);
}
}
} |
package com.sensei.search.facet;
import it.unimi.dsi.fastutil.longs.LongOpenHashSet;
import it.unimi.dsi.fastutil.longs.LongSet;
import java.io.IOException;
import java.util.Arrays;
import java.util.Properties;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.search.ScoreDoc;
import proj.zoie.api.ZoieIndexReader;
import proj.zoie.api.ZoieSegmentReader;
import com.browseengine.bobo.api.BoboIndexReader;
import com.browseengine.bobo.api.BrowseSelection;
import com.browseengine.bobo.api.FacetSpec;
import com.browseengine.bobo.docidset.RandomAccessDocIdSet;
import com.browseengine.bobo.facets.FacetCountCollectorSource;
import com.browseengine.bobo.facets.FacetHandler;
import com.browseengine.bobo.facets.filter.EmptyFilter;
import com.browseengine.bobo.facets.filter.RandomAccessFilter;
import com.browseengine.bobo.facets.filter.RandomAccessNotFilter;
import com.browseengine.bobo.sort.DocComparator;
import com.browseengine.bobo.sort.DocComparatorSource;
public class UIDFacetHandler extends FacetHandler<long[]> {
public UIDFacetHandler(String name) {
super(name);
}
private RandomAccessFilter buildRandomAccessFilter(final long val) throws IOException {
return new RandomAccessFilter() {
private static final long serialVersionUID = 1L;
@Override
public RandomAccessDocIdSet getRandomAccessDocIdSet(BoboIndexReader reader)
throws IOException {
final long[] uidArray = UIDFacetHandler.this.getFacetData(reader);
final int[] delDocs = ((ZoieIndexReader<?>)(reader.getInnerReader())).getDelDocIds();
Arrays.sort(delDocs);
return new RandomAccessDocIdSet() {
@Override
public DocIdSetIterator iterator() throws IOException {
return new DocIdSetIterator() {
protected int _doc = -1;
private int _len = uidArray.length;
private int _idxInDelDocs = 0;
private int _lenDelDocs = delDocs.length;
@Override
public int advance(int id) throws IOException {
if (_doc < id){
_doc = id - 1;
}
while(++_doc < _len) // not yet reached end
{
// check if the docId was deleted
while(_idxInDelDocs<_lenDelDocs && delDocs[_idxInDelDocs] < _doc)
{
++_idxInDelDocs;
}
if(_idxInDelDocs < _lenDelDocs && delDocs[_idxInDelDocs] == _doc)
{
++_idxInDelDocs;
continue;
}
if (uidArray[_doc] == val){
return _doc;
}
}
return _doc=DocIdSetIterator.NO_MORE_DOCS;
}
@Override
public int docID() {
return _doc;
}
@Override
public int nextDoc() throws IOException {
while(++_doc < _len) // not yet reached end
{
// check if the docId was deleted
while(_idxInDelDocs<_lenDelDocs && delDocs[_idxInDelDocs] < _doc)
{
++_idxInDelDocs;
}
if(_idxInDelDocs < _lenDelDocs && delDocs[_idxInDelDocs] == _doc)
{
++_idxInDelDocs;
continue;
}
if (uidArray[_doc] == val){
return _doc;
}
}
return _doc = DocIdSetIterator.NO_MORE_DOCS;
}
};
}
@Override
public boolean get(int docId) {
return (Arrays.binarySearch(delDocs, docId)<0) && val == uidArray[docId];
}
};
}
};
}
private RandomAccessFilter buildRandomAccessFilter(final LongSet valSet) throws IOException {
return new RandomAccessFilter() {
private static final long serialVersionUID = 1L;
@Override
public RandomAccessDocIdSet getRandomAccessDocIdSet(BoboIndexReader reader)
throws IOException {
final long[] uidArray = UIDFacetHandler.this.getFacetData(reader);
final int[] delDocs = ((ZoieIndexReader<?>)(reader.getInnerReader())).getDelDocIds();
Arrays.sort(delDocs);
return new RandomAccessDocIdSet() {
@Override
public DocIdSetIterator iterator() throws IOException {
return new DocIdSetIterator() {
protected int _doc = -1;
private int _len = uidArray.length;
private int _idxInDelDocs = 0;
private int _lenDelDocs = delDocs.length;
@Override
public int advance(int id) throws IOException {
if (_doc < id){
_doc = id - 1;
}
while(++_doc < _len) // not yet reached end
{
// check if the docId was deleted
while(_idxInDelDocs<_lenDelDocs && delDocs[_idxInDelDocs] < _doc)
{
++_idxInDelDocs;
}
if(_idxInDelDocs < _lenDelDocs && delDocs[_idxInDelDocs] == _doc)
{
++_idxInDelDocs;
continue;
}
if (valSet.contains(uidArray[_doc])){
return _doc;
}
}
return _doc=DocIdSetIterator.NO_MORE_DOCS;
}
@Override
public int docID() {
return _doc;
}
@Override
public int nextDoc() throws IOException {
while(++_doc < _len) // not yet reached end
{
// check if the docId was deleted
while(_idxInDelDocs<_lenDelDocs && delDocs[_idxInDelDocs] < _doc)
{
++_idxInDelDocs;
}
if(_idxInDelDocs < _lenDelDocs && delDocs[_idxInDelDocs] == _doc)
{
++_idxInDelDocs;
continue;
}
if (valSet.contains(uidArray[_doc])){
return _doc;
}
}
return _doc = DocIdSetIterator.NO_MORE_DOCS;
}
};
}
@Override
public boolean get(int docId) {
return (Arrays.binarySearch(delDocs, docId)<0) && valSet.contains(uidArray[docId]);
}
};
}
};
}
@Override
public RandomAccessFilter buildRandomAccessFilter(String value,
Properties selectionProperty) throws IOException {
try{
long val = Long.parseLong(value);
return buildRandomAccessFilter(val);
}
catch(Exception e){
throw new IOException(e.getMessage());
}
}
@Override
public RandomAccessFilter buildRandomAccessAndFilter(String[] vals,
Properties prop) throws IOException {
LongSet longSet = new LongOpenHashSet();
for (String val : vals){
try{
longSet.add(Long.parseLong(val));
}
catch(Exception e){
throw new IOException(e.getMessage());
}
}
if (longSet.size()!=1){
return EmptyFilter.getInstance();
}
else{
return buildRandomAccessFilter(longSet.iterator().nextLong());
}
}
@Override
public RandomAccessFilter buildRandomAccessOrFilter(String[] vals,
Properties prop, boolean isNot) throws IOException {
LongSet longSet = new LongOpenHashSet();
for (String val : vals){
try{
longSet.add(Long.parseLong(val));
}
catch(Exception e){
throw new IOException(e.getMessage());
}
}
RandomAccessFilter filter = buildRandomAccessFilter(longSet);
if (filter == null) return filter;
if (isNot)
{
filter = new RandomAccessNotFilter(filter);
}
return filter;
}
@Override
public DocComparatorSource getDocComparatorSource() {
return new DocComparatorSource() {
@Override
public DocComparator getComparator(IndexReader reader, int docbase)
throws IOException {
final UIDFacetHandler uidFacetHandler = UIDFacetHandler.this;
if (reader instanceof BoboIndexReader){
BoboIndexReader boboReader = (BoboIndexReader)reader;
final long[] uidArray = uidFacetHandler.getFacetData(boboReader);
return new DocComparator() {
@Override
public Comparable value(ScoreDoc doc) {
int docid = doc.doc;
return Long.valueOf(uidArray[docid]);
}
@Override
public int compare(ScoreDoc doc1, ScoreDoc doc2) {
long uid1 = uidArray[doc1.doc];
long uid2 = uidArray[doc2.doc];
if (uid1==uid2){
return 0;
}
else{
if (uid1<uid2) return -1;
return 1;
}
}
};
}
else{
throw new IOException("reader must be instance of: "+BoboIndexReader.class);
}
}
};
}
@Override
public FacetCountCollectorSource getFacetCountCollectorSource(
BrowseSelection sel, FacetSpec fspec) {
throw new UnsupportedOperationException("not supported");
}
@Override
public String[] getFieldValues(BoboIndexReader reader, int id) {
long[] uidArray = getFacetData(reader);
return new String[]{String.valueOf(uidArray[id])};
}
@Override
public Object[] getRawFieldValues(BoboIndexReader reader, int id) {
long[] uidArray = getFacetData(reader);
return new Long[]{uidArray[id]};
}
@Override
public long[] load(BoboIndexReader reader) throws IOException {
IndexReader innerReader = reader.getInnerReader();
if (innerReader instanceof ZoieSegmentReader){
ZoieSegmentReader zoieReader = (ZoieSegmentReader)innerReader;
return zoieReader.getUIDArray();
}
else{
throw new IOException("inner reader not instance of "+ZoieSegmentReader.class);
}
}
} |
package sg.ncl.service.experiment.logic;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import sg.ncl.adapter.deterlab.AdapterDeterLab;
import sg.ncl.adapter.deterlab.ConnectionProperties;
import sg.ncl.common.exception.base.ForbiddenException;
import sg.ncl.service.experiment.data.jpa.ExperimentEntity;
import sg.ncl.service.experiment.data.jpa.ExperimentRepository;
import sg.ncl.service.experiment.domain.Experiment;
import sg.ncl.service.experiment.domain.ExperimentService;
import sg.ncl.service.experiment.exceptions.ExperimentNameAlreadyExistsException;
import sg.ncl.service.experiment.exceptions.TeamIdNullOrEmptyException;
import sg.ncl.service.experiment.exceptions.UserIdNullOrEmptyException;
import sg.ncl.service.mail.domain.MailService;
import sg.ncl.service.realization.data.jpa.RealizationEntity;
import sg.ncl.service.realization.domain.RealizationService;
import sg.ncl.service.team.domain.TeamService;
import javax.inject.Inject;
import javax.inject.Named;
import javax.validation.constraints.NotNull;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import static sg.ncl.service.experiment.validation.Validator.checkPermissions;
/**
* @Authors: Desmond, Tran Ly Vu
*/
@Service
@Slf4j
public class ExperimentServiceImpl implements ExperimentService {
private final ExperimentRepository experimentRepository;
private final AdapterDeterLab adapterDeterLab;
private final RealizationService realizationService;
private final ConnectionProperties adapterConnectionProperties;
private final TeamService teamService;
private final MailService mailService;
private final Template internetRequestTemplate;
@Inject
ExperimentServiceImpl(@NotNull final ExperimentRepository experimentRepository,
@NotNull final AdapterDeterLab adapterDeterLab,
@NotNull final RealizationService realizationService,
@NotNull final ConnectionProperties connectionProperties,
@NotNull final TeamService teamService,
@NotNull final MailService mailService,
@NotNull @Named("internetRequestTemplate") final Template internetRequestTemplate) {
this.experimentRepository = experimentRepository;
this.adapterDeterLab = adapterDeterLab;
this.realizationService = realizationService;
this.adapterConnectionProperties = connectionProperties;
// FIXME Do not expose the internal workings of the DeterLab adapter to the experiment service; i.e., should not need to inject ConnectionProperties
this.teamService = teamService;
this.mailService = mailService;
this.internetRequestTemplate = internetRequestTemplate;
}
@Override
public Experiment get(Long id) {
if (id == null) {
return null;
}
return experimentRepository.findOne(id);
}
/**
* Creates an experiment and realization object on DB.
* Also creates the experiment on Deterlab DB.
*
* @param experiment the experiment object passed from web service
* @return the experiment entity stored on our DB
*/
@Transactional
public Experiment save(Experiment experiment) {
log.info("Save experiment");
String fileName = craftFileName(experiment);
// check if team already has am experiment with the same name
List<ExperimentEntity> experimentEntityList = experimentRepository.findByTeamName(experiment.getTeamName());
if (experimentEntityList != null) {
for (ExperimentEntity one : experimentEntityList) {
if (one.getName().equals(experiment.getName())) {
log.warn("Experiment name is in use: {}", experiment.getName());
throw new ExperimentNameAlreadyExistsException(experiment.getName());
}
}
}
ExperimentEntity savedExperimentEntity = experimentRepository.save(setupEntity(experiment, fileName));
log.info("Experiment saved: {}", savedExperimentEntity);
RealizationEntity realizationEntity = new RealizationEntity();
realizationEntity.setExperimentId(savedExperimentEntity.getId());
realizationEntity.setExperimentName(savedExperimentEntity.getName());
realizationEntity.setUserId(savedExperimentEntity.getUserId());
realizationEntity.setTeamId(savedExperimentEntity.getTeamId());
realizationEntity.setNumberOfNodes(0);
realizationEntity.setIdleMinutes(0L);
realizationEntity.setRunningMinutes(0L);
realizationService.save(realizationEntity);
log.info("Realization saved: {}", realizationEntity);
// createNsFile(fileName, experiment.getNsFileContent());
createExperimentInDeter(savedExperimentEntity);
return savedExperimentEntity;
}
private String craftDate() {
Date date = new Date();
return new SimpleDateFormat("yyyyMMdd").format(date);
}
private String craftFileName(Experiment experiment) {
String fileName = experiment.getNsFile() + ".ns";
return experiment.getUserId() + "_" + experiment.getTeamId() + "_" + craftDate() + "_" + fileName;
}
private ExperimentEntity setupEntity(Experiment experiment, String fileName) {
ExperimentEntity experimentEntity = new ExperimentEntity();
experimentEntity.setUserId(experiment.getUserId());
experimentEntity.setTeamId(experiment.getTeamId());
experimentEntity.setTeamName(experiment.getTeamName());
experimentEntity.setName(experiment.getName());
experimentEntity.setDescription(experiment.getDescription());
experimentEntity.setNsFile(fileName);
experimentEntity.setNsFileContent(experiment.getNsFileContent());
experimentEntity.setIdleSwap(experiment.getIdleSwap());
experimentEntity.setMaxDuration(experiment.getMaxDuration());
return experimentEntity;
}
@Transactional
public List<Experiment> getAll() {
log.info("Get all experiments");
return experimentRepository.findAll().stream().collect(Collectors.toList());
}
@Transactional
public List<Experiment> findByUser(String userId) {
log.info("Find user by user id: {}", userId);
if (userId == null || userId.isEmpty()) {
// FIXME: this is the wrong exception to throw; it should be a BadRequestException type
throw new UserIdNullOrEmptyException();
}
return experimentRepository.findByUserId(userId).stream().collect(Collectors.toList());
}
@Transactional
public List<Experiment> findByTeam(String teamId) {
log.info("Find teams by team id: {}", teamId);
if (teamId == null || teamId.isEmpty()) {
// FIXME: this is the wrong exception to throw; it should be a BadRequestException type
throw new TeamIdNullOrEmptyException();
}
return experimentRepository.findByTeamId(teamId).stream().collect(Collectors.toList());
}
public String createNsFile(String filename, String contents) {
log.info("Create NS file");
File file;
FileOutputStream fileOutputStream = null;
try {
file = new File(filename);
fileOutputStream = new FileOutputStream(file);
// if file doesn't exist, create it
if (!file.exists()) {
file.createNewFile();
}
// getAll contents in bytes
byte[] contentInBytes = contents.getBytes();
fileOutputStream.write(contentInBytes);
fileOutputStream.flush();
fileOutputStream.close();
} catch (IOException e) {
log.error("File cannot be created.\n" + e.getMessage());
filename = "error";
} finally {
try {
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (IOException e) {
log.error("File cannot be created.\n" + e.getMessage());
filename = "error";
}
}
return filename;
}
/**
* Invokes the adapter to create an experiment on Deterlab DB
*
* @param experiment the experiment object
*/
private void createExperimentInDeter(Experiment experiment) {
log.info("Begin creating experiment: {} for team: {}", experiment.getName(), experiment.getTeamName());
JSONObject userObject = new JSONObject();
userObject.put("id", experiment.getId().toString());
userObject.put("userId", experiment.getUserId());
userObject.put("teamId", experiment.getTeamId());
userObject.put("teamName", experiment.getTeamName());
userObject.put("name", experiment.getName());
userObject.put("description", experiment.getDescription());
userObject.put("nsFile", experiment.getNsFile());
userObject.put("nsFileContent", experiment.getNsFileContent());
userObject.put("idleSwap", experiment.getIdleSwap().toString());
userObject.put("maxDuration", experiment.getMaxDuration().toString());
userObject.put("deterLogin", adapterDeterLab.getDeterUserIdByNclUserId(experiment.getUserId()));
userObject.put("userServerUri", adapterConnectionProperties.getUserUrl());
adapterDeterLab.createExperiment(userObject.toString());
log.info("Create experiment : {}, success", experiment);
}
/**
* Deletes the experiment and realization object from our DB.
* Also deletes the experiment on Deterlab DB.
*
* @param id the experiment id (DB UUID), i.e. not the experiment name
* @param teamId the team where the experiment is in (required by Deterlab so that we delete the correct experiment)
* @param claims the decrypted claims from the jwt web token
* @return the deleted experiment object
* @implNote delete the realization object first, follow by the experiment object (the reverse process of create)
* @throws ForbiddenException if user is not the experiment creator and user is not an admin
*/
@Transactional
public Experiment deleteExperiment(final Long id, final String teamId, final Claims claims) {
log.info("Deleting Experiment: {} from Team: {}", id, teamId);
Experiment experimentEntity = null;
RealizationEntity realizationEntity = realizationService.getByExperimentId(id);
Long realizationId = realizationEntity.getId();
// put the check inside here because we do not want to add the realization service and team service on the controller
checkPermissions(realizationEntity, teamService.isOwner(teamId, claims.getSubject()), claims);
if (realizationId != null && realizationId > 0) {
realizationService.deleteRealization(realizationId);
log.info("Realization deleted: {}", realizationId);
experimentEntity = experimentRepository.getOne(id);
// TODO: use other deleteExperimentInDeter(teamName, experimentName) if using script_wrapper.py
// deleteExperimentInDeter(experimentEntity.getName(), realizationEntity.getUserId());
experimentRepository.delete(id);
log.info("Experiment deleted from experiment repository: {} from Team: {}", experimentEntity.getName(), experimentEntity.getTeamName());
adapterDeterLab.deleteExperiment(experimentEntity.getTeamName(), experimentEntity.getName(), claims.getSubject());
log.info("Experiment deleted in deter: {} from Team: {}", experimentEntity.getName(), experimentEntity.getTeamName());
} else {
log.warn("Experiment not deleted");
}
log.info("End deleteExperiment");
return experimentEntity;
}
/**
* Get experiment details from deterlab for experiment profile
*
* @param teamId the team to get the exp for
* @param expId the experiment to get the experiment details
* @return a json dump of the experiment details from deterlab in the format
* {
* 'ns_file' :
* {
* 'msg' : 'success/fail',
* 'ns_file' : 'ns_file_contents'
* },
* 'realization_details' :
* {
* 'msg' : 'success/fail',
* 'realization_details' : 'realization_details_contents'
* },
* 'activity_log' :
* {
* 'msg' : 'success/fail',
* 'activity_log' : 'activity_log_contents'
* }
* }
* Otherwise, returns "{}"
*/
@Override
public String getExperimentDetails(String teamId, Long expId) {
Experiment experimentEntity = experimentRepository.getOne(expId);
String teamName = experimentEntity.getTeamName();
String experimentName = experimentEntity.getName();
JSONObject jsonObject = new JSONObject();
jsonObject.put("pid", teamName);
jsonObject.put("eid", experimentName);
return adapterDeterLab.getExperimentDetails(jsonObject.toString());
}
/**
* Get the network topology map thumbnail from deterlab.
*
* @param teamId the team to get the exp for
* @param expId the experiment to get the thumbnail
* @return Base64 image string
*/
@Override
public String getTopology(String teamId, Long expId) {
Experiment experimentEntity = experimentRepository.getOne(expId);
String teamName = experimentEntity.getTeamName();
String experimentName = experimentEntity.getName();
JSONObject jsonObject = new JSONObject();
jsonObject.put("pid", teamName);
jsonObject.put("eid", experimentName);
return adapterDeterLab.getTopologyThumbnail(jsonObject.toString());
}
/**
* Send email to ncl support to notify internet access request
*
* @param expId the experiment id (DB UUID), i.e. not the experiment name
* @param teamId the team id
* @param reason the reason for internet access request
*
* @return experiment with requested internet access
*/
@Override
public Experiment requestInternet(String teamId, Long expId, String reason, final Claims claims) {
log.info("Requesting internet access for Experiment {} from Team {}", expId, teamId);
RealizationEntity realizationEntity = realizationService.getByExperimentId(expId);
// put the check inside here because we do not want to add the realization service and team service on the controller
checkPermissions(realizationEntity, teamService.isOwner(teamId, claims.getSubject()), claims);
Experiment experimentEntity = experimentRepository.getOne(expId);
String teamName = experimentEntity.getTeamName();
String experimentName = experimentEntity.getName();
final Map<String, String> map = new HashMap<>();
map.put("projectName", teamName);
map.put("expName", experimentName);
map.put("reason", reason);
try {
String from = "NCL Testbed Ops <testbed-ops@ncl.sg>";
String[] to = new String[1];
to[0] = "support@ncl.sg";
String subject = "Internet access request";
String msgText = FreeMarkerTemplateUtils.processTemplateIntoString(internetRequestTemplate, map);
mailService.send(from , to , subject, msgText, false, null, null);
log.info("Email sent for internet request for Experiment {} from Team {}", expId, teamId);
} catch (IOException | TemplateException e) {
log.warn("Error sending email for internet access request: {}", e);
}
return experimentEntity;
}
@Override
public Experiment updateExperiment(Long expId, String teamId) {
log.info("Updating experiment {}, team {}", expId, teamId);
ExperimentEntity experimentEntity = experimentRepository.getOne(expId);
adapterDeterLab.modifyExperiment();
return null;
}
} |
package com.twu.biblioteca.helper;
import com.twu.biblioteca.entity.Book;
import com.twu.biblioteca.entity.Library;
import com.twu.biblioteca.entity.User;
import java.util.ArrayList;
import java.util.List;
public class Libraryhelper {
public Library initLibrary() {
List<Book> books = new ArrayList<Book>();
books.add(new Book("Refactoring: Improving the Design of Existing Code", "Martin Fowler", "July 8, 1999"));
books.add(new Book("Head First Design Patterns", "Eric Freeman", "November 4, 2004"));
books.add(new Book("Clean Code", "Robert C. Martin ", "August 11, 2008"));
books.add(new Book("Programming in Scala", "Martin Odersky", "January 4, 2011"));
books.add(new Book("Head First Java", "Kathy Sierra", "February 9, 2005"));
books.add(new Book("JavaScript: The Good Parts", "Douglas Crockford", "May, 2008"));
List<User> users = new ArrayList<User>();
users.add(new User("zhzhang", "1111", "customer"));
users.add(new User("yanzi", "1111", "librarian"));
users.add(new User("xueqian", "1111", "librarian"));
return new Library(books, users);
}
} |
package org.sagebionetworks.repo.web.service;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.sagebionetworks.repo.manager.UserManager;
import org.sagebionetworks.repo.manager.file.FileHandleManager;
import org.sagebionetworks.repo.manager.wiki.V2WikiManager;
import org.sagebionetworks.repo.manager.wiki.V2WikiMirrorManager;
import org.sagebionetworks.repo.manager.wiki.WikiManager;
import org.sagebionetworks.repo.model.DatastoreException;
import org.sagebionetworks.repo.model.PaginatedResults;
import org.sagebionetworks.repo.model.UnauthorizedException;
import org.sagebionetworks.repo.model.UserInfo;
import org.sagebionetworks.repo.model.dao.WikiPageKey;
import org.sagebionetworks.repo.model.file.FileHandleResults;
import org.sagebionetworks.repo.model.ObjectType;
import org.sagebionetworks.repo.model.v2.wiki.V2WikiHeader;
import org.sagebionetworks.repo.model.v2.wiki.V2WikiPage;
import org.sagebionetworks.repo.model.wiki.WikiHeader;
import org.sagebionetworks.repo.model.wiki.WikiPage;
import org.sagebionetworks.repo.web.NotFoundException;
import org.sagebionetworks.repo.web.WikiModelTranslator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
public class WikiServiceImpl implements WikiService {
@Autowired
UserManager userManager;
@Autowired
WikiManager wikiManager;
@Autowired
V2WikiManager v2WikiManager;
@Autowired
V2WikiMirrorManager v2WikiMirrorManager;
@Autowired
WikiModelTranslator wikiModelTranslationHelper;
@Autowired
FileHandleManager fileHandleManager;
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
@Override
public WikiPage createWikiPage(String userId, String objectId, ObjectType objectType, WikiPage toCreate) throws DatastoreException, NotFoundException, IOException {
// Resolve the userID
UserInfo user = userManager.getUserInfo(userId);
// Create the V1 wiki
WikiPage createdResult = wikiManager.createWikiPage(user, objectId, objectType, toCreate);
// Translate the created V1 wiki into a V2 and create it
V2WikiPage translated = wikiModelTranslationHelper.convertToV2WikiPage(createdResult, user);
V2WikiPage result = v2WikiMirrorManager.createWikiPage(user, objectId, objectType, translated);
return createdResult;
}
@Override
public WikiPage getWikiPage(String userId, WikiPageKey key) throws DatastoreException, NotFoundException, IOException {
UserInfo user = userManager.getUserInfo(userId);
return wikiManager.getWikiPage(user, key);
}
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
@Override
public WikiPage updateWikiPage(String userId, String objectId, ObjectType objectType, WikiPage toUpdate) throws DatastoreException, NotFoundException, IOException {
UserInfo user = userManager.getUserInfo(userId);
// Update the V1 wiki
WikiPage updateResult = wikiManager.updateWikiPage(user, objectId, objectType, toUpdate);
// Translate the updated V1 wiki
V2WikiPage translated = wikiModelTranslationHelper.convertToV2WikiPage(updateResult, user);
// Reset the updated etag to the previous etag so we can lock / updated etag will be set after the lock
translated.setEtag(toUpdate.getEtag());
// Update the V2 wiki and pass in the updated etag we will set
V2WikiPage result = v2WikiMirrorManager.updateWikiPage(user, objectId, objectType, translated, updateResult.getEtag());
return updateResult;
}
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
@Override
public void deleteWikiPage(String userId, WikiPageKey wikiPageKey) throws DatastoreException, NotFoundException {
UserInfo user = userManager.getUserInfo(userId);
// Delete the V1 wiki and its mirror V2 wiki
wikiManager.deleteWiki(user, wikiPageKey);
v2WikiMirrorManager.deleteWiki(user, wikiPageKey);
}
@Override
public PaginatedResults<WikiHeader> getWikiHeaderTree(String userId, String ownerId, ObjectType type, Long limit, Long offest) throws DatastoreException, NotFoundException {
UserInfo user = userManager.getUserInfo(userId);
return wikiManager.getWikiHeaderTree(user, ownerId, type, limit, offest);
}
@Override
public FileHandleResults getAttachmentFileHandles(String userId, WikiPageKey wikiPageKey) throws DatastoreException, NotFoundException {
UserInfo user = userManager.getUserInfo(userId);
return wikiManager.getAttachmentFileHandles(user, wikiPageKey);
}
@Override
public URL getAttachmentRedirectURL(String userId, WikiPageKey wikiPageKey, String fileName) throws DatastoreException, NotFoundException {
UserInfo user = userManager.getUserInfo(userId);
// First lookup the FileHandle
String fileHandleId = wikiManager.getFileHandleIdForFileName(user, wikiPageKey, fileName);
// Use the FileHandle ID to get the URL
return fileHandleManager.getRedirectURLForFileHandle(fileHandleId);
}
@Override
public URL getAttachmentPreviewRedirectURL(String userId, WikiPageKey wikiPageKey, String fileName) throws DatastoreException, NotFoundException {
UserInfo user = userManager.getUserInfo(userId);
// First lookup the FileHandle
String fileHandleId = wikiManager.getFileHandleIdForFileName(user, wikiPageKey, fileName);
// Get FileHandle
String previewId = fileHandleManager.getPreviewFileHandleId(fileHandleId);
// Get the URL of the preview.
return fileHandleManager.getRedirectURLForFileHandle(previewId);
}
@Override
public WikiPage getRootWikiPage(String userId, String ownerId, ObjectType type) throws UnauthorizedException, NotFoundException, IOException {
UserInfo user = userManager.getUserInfo(userId);
return wikiManager.getRootWikiPage(user, ownerId, type);
}
} |
package com.valkryst.VTerminal.component;
import com.valkryst.VRadio.Radio;
import com.valkryst.VRadio.Receiver;
import com.valkryst.VTerminal.AsciiCharacter;
import com.valkryst.VTerminal.AsciiString;
import com.valkryst.VTerminal.Panel;
import com.valkryst.VTerminal.builder.component.*;
import com.valkryst.VTerminal.font.Font;
import com.valkryst.VTerminal.misc.ImageCache;
import com.valkryst.VTerminal.misc.IntRange;
import com.valkryst.VTerminal.printer.RectanglePrinter;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
import lombok.ToString;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.util.*;
import java.util.concurrent.locks.ReentrantReadWriteLock;
@ToString
public class Screen extends Component implements Receiver<String> {
/** The panel on which the screen is displayed. */
@Getter @Setter private Panel parentPanel;
/** The non-layer components displayed on the screen. */
private ArrayList<Component> components = new ArrayList<>();
/** The layer components displayed on the screen. */
private ArrayList<Layer> layerComponents = new ArrayList<>();
/** The screen components displayed on the screen. */
private ArrayList<Screen> screenComponents = new ArrayList<>();
private ReentrantReadWriteLock componentsLock = new ReentrantReadWriteLock();
/**
* Constructs a new Screen.
*
* @param builder
* The builder to use.
*
* @throws NullPointerException
* If the builder is null.
*/
public Screen(final @NonNull ScreenBuilder builder) {
super(builder);
setBackgroundColor(new Color(45, 45, 45, 255));
if (builder.getJsonObject() != null) {
parseJSON(builder.getJsonObject());
}
}
@Override
public void receive(final String event, final String data) {
if (radio != null) {
if (event.equals("DRAW")) {
transmitDraw();
}
}
}
private void parseJSON(final @NonNull JSONObject jsonObject) {
final JSONArray components = (JSONArray) jsonObject.get("components");
if (components != null) {
for (final Object obj : components) {
final JSONObject arrayElement = (JSONObject) obj;
if (arrayElement != null) {
final ComponentBuilder componentBuilder = loadElementFromJSON(arrayElement);
if (componentBuilder != null) {
final Component component = componentBuilder.build();
addComponent(component);
}
}
}
}
}
private ComponentBuilder loadElementFromJSON(final @NonNull JSONObject jsonObject) {
String componentType = (String) jsonObject.get("type");
if (componentType == null) {
return null;
}
componentType = componentType.toLowerCase();
switch (componentType) {
case "button": {
final ButtonBuilder buttonBuilder = new ButtonBuilder();
buttonBuilder.parse(jsonObject);
return buttonBuilder;
}
case "check box": {
final CheckBoxBuilder checkBoxBuilder = new CheckBoxBuilder();
checkBoxBuilder.parse(jsonObject);
return checkBoxBuilder;
}
case "label": {
final LabelBuilder labelBuilder = new LabelBuilder();
labelBuilder.parse(jsonObject);
return labelBuilder;
}
case "layer": {
final LayerBuilder layerBuilder = new LayerBuilder();
layerBuilder.parse(jsonObject);
return layerBuilder;
}
case "progress bar": {
final ProgressBarBuilder progressBarBuilder = new ProgressBarBuilder();
progressBarBuilder.parse(jsonObject);
return progressBarBuilder;
}
case "radio button": {
final RadioButtonBuilder radioButtonBuilder = new RadioButtonBuilder();
radioButtonBuilder.parse(jsonObject);
return radioButtonBuilder;
}
case "radio button group": {
final RadioButtonGroup radioButtonGroup = new RadioButtonGroup();
final JSONArray radioButtons = (JSONArray) jsonObject.get("components");
if (radioButtons != null) {
for (final Object object : radioButtons) {
final JSONObject buttonJSON = (JSONObject) object;
final RadioButtonBuilder builder = (RadioButtonBuilder) loadElementFromJSON(buttonJSON);
builder.setGroup(radioButtonGroup);
addComponent(builder.build());
}
}
return null;
}
case "screen": {
final ScreenBuilder screenBuilder = new ScreenBuilder();
screenBuilder.parse(jsonObject);
return screenBuilder;
}
case "text field": {
final TextFieldBuilder textFieldBuilder = new TextFieldBuilder();
textFieldBuilder.parse(jsonObject);
return textFieldBuilder;
}
case "text area": {
final TextAreaBuilder textAreaBuilder = new TextAreaBuilder();
textAreaBuilder.parse(jsonObject);
return textAreaBuilder;
}
case "rectangle printer": {
final RectanglePrinter rectanglePrinter = new RectanglePrinter();
rectanglePrinter.printFromJSON(this, jsonObject);
return null;
}
default: {
throw new IllegalArgumentException("The element type '" + componentType + "' is not supported.");
}
}
}
@Override
public void draw(final @NonNull Screen screen) {
throw new UnsupportedOperationException("A Screen must be drawn using the draw(canvas, font) method.");
}
/**
* Draws the screen onto the specified graphics context..
*
* @param gc
* The graphics context to draw with.
*
* @param imageCache
* The image cache to retrieve character images from.
*
* @throws NullPointerException
* If the gc or image cache is null.
*/
public void draw(final @NonNull Graphics2D gc, final @NonNull ImageCache imageCache) {
draw(gc, imageCache, getPosition());
}
/**
* Draws the screen onto the specified graphics context..
*
* @param gc
* The graphics context to draw with.
*
* @param imageCache
* The image cache to retrieve character images from.
*
* @param offset
* The x/y-axis (column/row) offsets to alter the position at which the
* screen is drawn.
*
* @throws NullPointerException
* If the gc or image cache is null.
*/
public void draw(final @NonNull Graphics2D gc, final @NonNull ImageCache imageCache, final Point offset) {
componentsLock.readLock().lock();
// Draw non-layer components onto the screen:
components.forEach(component -> component.draw(this));
// Draw the screen onto the canvas:
final AsciiString[] strings = super.getStrings();
final Thread thread = new Thread(() -> {
for (int row = 0 ; row < getHeight()/2 ; row++) {
strings[row].draw(gc, imageCache, row, offset);
}
});
thread.start();
for (int row = getHeight()/2 ; row < getHeight() ; row++) {
strings[row].draw(gc, imageCache, row, offset);
}
try {
thread.join();
} catch(final InterruptedException e) {
e.printStackTrace();
}
// Draw layer components onto the screen:
layerComponents.forEach(layer -> layer.draw(gc, imageCache, offset));
// Draw screen components onto the screen:
screenComponents.forEach(screen -> {
final Point position = screen.getPosition();
screen.draw(gc, imageCache, position);
});
componentsLock.readLock().unlock();
}
/**
* Clears the specified section of the screen.
*
* Does nothing if the (columnIndex, rowIndex) or (width, height) pairs point
* to invalid positions.
*
* @param character
* The character to replace all characters being cleared with.
*
* @param position
* The x/y-axis (column/row) coordinates of the cell to clear.
*
* @param width
* The width of the area to clear.
*
* @param height
* The height of the area to clear.
*/
public void clear(final char character, final Point position, int width, int height) {
boolean canProceed = isPositionValid(position);
canProceed &= width >= 0;
canProceed &= height >= 0;
if (canProceed) {
width += position.x;
height += position.y;
final Point writePosition = new Point(0, 0);
for (int column = position.x ; column < width ; column++) {
for (int row = position.y ; row < height ; row++) {
writePosition.setLocation(column, row);
write(character, writePosition);
}
}
}
}
/**
* Clears the entire screen.
*
* @param character
* The character to replace every character on the screen with.
*/
public void clear(final char character) {
clear(character, new Point(0, 0), super.getWidth(), super.getHeight());
}
/**
* Write the specified character to the specified position.
*
* @param character
* The character.
*
* @param position
* The x/y-axis (column/row) coordinate to write to.
*
* @throws NullPointerException
* If the character is null.
*/
public void write(final @NonNull AsciiCharacter character, final Point position) {
if (isPositionValid(position)) {
super.getString(position.y).setCharacter(position.x, character);
}
}
/**
* Write the specified character to the specified position.
*
* @param character
* The character.
*
* @param position
* The x/y-axis (column/row) coordinates to write to.
*/
public void write(final char character, final Point position) {
if (isPositionValid(position)) {
super.getString(position.y).setCharacter(position.x, character);
}
}
/**
* Write a string to the specified position.
*
* Does nothing if the (columnIndex, rowIndex) points to invalid position.
*
* @param string
* The string.
*
* @param position
* The x/y-axis (column/row) coordinates to begin writing from.
*
* @throws NullPointerException
* If the string is null.
*/
public void write(final @NonNull AsciiString string, final Point position) {
if (isPositionValid(position)) {
final AsciiCharacter[] characters = string.getCharacters();
for (int i = 0; i < characters.length && i < super.getWidth(); i++) {
write(characters[i], new Point(position.x + i, position.y));
}
}
}
/**
* Write a string to the specified position.
*
* Does nothing if the (columnIndex, rowIndex) points to invalid position.
*
* @param string
* The string.
*
* @param position
* The x/y-axis (column/row) coordinates to begin writing from.
*
* @throws NullPointerException
* If the string is null.
*/
public void write(final @NonNull String string, final Point position) {
write(new AsciiString(string), position);
}
@Override
public void setPosition(final Point position) {
// Recalculate bounding box positions.
for (final Component component : getComponents()) {
final Rectangle boundingBox = component.getBoundingBox();
final int x = boundingBox.x - super.getPosition().x + position.x;
final int y = boundingBox.y - super.getPosition().y + position.y;
component.getBoundingBox().setLocation(x, y);
}
super.setPosition(position);
}
/**
* Draws the screen onto an image.
*
* This calls the draw function, so the screen may look a little different
* if there are blink effects or new updates to characters that haven't yet
* been drawn.
*
* This is an expensive operation as it essentially creates an in-memory
* screen and draws each AsciiCharacter onto that screen.
*
* @param imageCache
* The image cache to retrieve character images from.
*
* @return
* An image of the screen.
*
* @throws NullPointerException
* If the image cache is null.
*/
public BufferedImage screenshot(final @NonNull ImageCache imageCache) {
final Font font = imageCache.getFont();
final int width = this.getWidth() * font.getWidth();
final int height = this.getHeight() * font.getHeight();
final BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
final Graphics2D gc = img.createGraphics();
draw(gc, imageCache);
gc.dispose();
return img;
}
/**
* Sets the background color of all characters.
*
* @param color
* The new background color.
*
* @throws NullPointerException
* If the color is null.
*/
public void setBackgroundColor(final @NonNull Color color) {
for (final AsciiString string : getStrings()) {
string.setBackgroundColor(color);
}
}
/**
* Sets the foreground color of all characters.
*
* @param color
* The new foreground color.
*
* @throws NullPointerException
* If the color is null.
*/
public void setForegroundColor(final @NonNull Color color) {
for (final AsciiString string : getStrings()) {
string.setForegroundColor(color);
}
}
/**
* Sets the background and foreground color of all characters.
*
* @param background
* The new background color.
*
* @param foreground
* The new foreground color.
*
* @throws NullPointerException
* If the background or foreground color is null.
*/
public void setBackgroundAndForegroundColor(final @NonNull Color background, final @NonNull Color foreground) {
for (final AsciiString string : getStrings()) {
string.setBackgroundColor(background);
string.setForegroundColor(foreground);
}
}
/**
* Adds a component to the screen and registers event listeners of the
* component, to the parent panel, if required.
*
* If the component is already present on the screen, then the component is
* not added.
*
* If the component is a screen and it has already been added to this screen,
* or any sub-screen of this screen, then the component is not added.
*
* @param component
* The component.
*/
public void addComponent(final Component component) {
componentsLock.writeLock().lock();
boolean containsComponent = containsComponent(component);
if (containsComponent) {
componentsLock.writeLock().unlock();
return;
}
// Add the component to one of the component lists:
component.getRadio().addReceiver("DRAW", this);
if (component instanceof Screen) {
((Screen) component).setParentPanel(parentPanel);
screenComponents.add((Screen) component);
} else if (component instanceof Layer) {
layerComponents.add((Layer) component);
} else {
components.add(component);
}
// Add screen position as offset to bounding box position of component.
final Rectangle boundingBox = component.getBoundingBox();
final int x = boundingBox.x + super.getPosition().x;
final int y = boundingBox.y + super.getPosition().y;
component.getBoundingBox().setLocation(x, y);
componentsLock.writeLock().unlock();
// Set up event listeners:
component.createEventListeners(parentPanel);
for (final EventListener eventListener : component.getEventListeners()) {
parentPanel.addListener(eventListener);
}
}
/**
* Adds one or more components to the screen.
*
* @param components
* The components.
*/
public void addComponents(final Component ... components) {
if (components == null) {
return;
}
for (final Component component : components) {
addComponent(component);
}
}
public void removeComponent(final Component component) {
componentsLock.writeLock().lock();
if (component == null) {
componentsLock.writeLock().unlock();
return;
}
if (component == this) {
componentsLock.writeLock().unlock();
throw new IllegalArgumentException("A screen cannot be removed from itself.");
}
component.getRadio().removeReceiver("DRAW", this);
if (component instanceof Screen) {
component.getEventListeners().forEach(listener -> parentPanel.removeListener(listener));
screenComponents.remove(component);
} else if (component instanceof Layer) {
layerComponents.remove(component);
} else {
components.remove(component);
}
// Remove screen position as offset to bounding box position of component.
final Rectangle boundingBox = component.getBoundingBox();
final int boundingBoxX = boundingBox.x - super.getPosition().x;
final int boundingBoxY = boundingBox.y - super.getPosition().y;
component.getBoundingBox().setLocation(boundingBoxX, boundingBoxY);
componentsLock.writeLock().unlock();
for (final EventListener eventListener : component.getEventListeners()) {
parentPanel.removeListener(eventListener);
}
// Reset component's characters to empty cells.
final Point position = component.getPosition();
final IntRange redrawRange = new IntRange(position.x, position.x + component.getWidth());
for (int y = position.y ; y < position.y + component.getHeight() ; y++) {
final AsciiString string = super.getString(y);
string.setCharacters(' ', redrawRange);
string.setBackgroundColor(new Color(45, 45, 45, 255), redrawRange);
string.setForegroundColor(Color.WHITE, redrawRange);
string.setUnderlined(redrawRange, false);
string.setFlippedHorizontally(redrawRange, false);
string.setFlippedVertically(redrawRange, false);
}
}
/**
* Removes one or more components from the screen.
*
* @param components
* The components.
*/
public void removeComponents(final Component ... components) {
if (components == null) {
return;
}
for (final Component component : components) {
removeComponent(component);
}
}
/**
* Moves one component above another component, in the
* draw order.
*
* Does nothing if either component is null.
*
* Does nothing if components are not of the same type.
*
* @param stationary
* The component that is not being moved.
*
* @param moving
* The component that is being moved.
*/
public void changeDrawOrder(final Component stationary, final Component moving) {
if (stationary == null || moving == null) {
return;
}
if (stationary.getClass().equals(moving.getClass()) == false) {
return;
}
final List list;
if (stationary instanceof Screen) {
list = screenComponents;
} else if (stationary instanceof Layer) {
list = layerComponents;
} else {
list = components;
}
final int index = list.indexOf(stationary);
if (index != -1) {
list.remove(moving);
list.add(index, moving);
}
}
/**
* Determines whether or not the screen contains a specific component.
*
* @param component
* The component.
*
* @return
* Whether or not the screen contains the component.
*/
public boolean containsComponent(final Component component) {
componentsLock.readLock().lock();
if (component == null) {
componentsLock.readLock().unlock();
return false;
}
if (component == this) {
componentsLock.readLock().unlock();
return false;
}
if (component instanceof Screen) {
if (screenComponents.contains(component)) {
componentsLock.readLock().unlock();
return true;
}
} else if (component instanceof Layer) {
if (layerComponents.contains(component)) {
componentsLock.readLock().unlock();
return true;
}
}
final boolean result = components.contains(component);
componentsLock.readLock().unlock();
return result;
}
/**
* Determines the total number of components.
*
* @return
* The total number of components.
*/
public int totalComponents() {
componentsLock.readLock().lock();
int sum = components.size();
sum += layerComponents.size();
sum += screenComponents.size();
componentsLock.readLock().unlock();
return sum;
}
/**
* Retrieves the first encountered component that uses the specified ID.
*
* @param id
* The id.
*
* @return
* If no component matches the ID, the null is returned.
* Else the component is returned.
*/
public Component getComponentByID(final String id) {
componentsLock.readLock().lock();
for (final Component component : components) {
if (component.getId().equals(id)) {
componentsLock.readLock().unlock();
return component;
}
}
for (final Layer layer : layerComponents) {
if (layer.getId().equals(id)) {
componentsLock.readLock().unlock();
return layer;
}
}
for (final Screen screen : screenComponents) {
if (screen.getId().equals(id)) {
componentsLock.readLock().unlock();
return screen;
}
}
componentsLock.readLock().unlock();
return null;
}
/**
* Works the same as getComponentByID, but only returns if the result is a
* Button component.
*
* @param id
* The id.
*
* @return
* If no component matches the ID, then null is returned.
* If no button component matches the ID, then null is returned.
* Else the component is returned.
*/
public Button getButtonByID(final String id) {
final Component component = getComponentByID(id);
if (component instanceof Button) {
return (Button) component;
}
return null;
}
/**
* Works the same as getComponentByID, but only returns if the result is a
* Check Box component.
*
* @param id
* The id.
*
* @return
* If no component matches the ID, then null is returned.
* If no check box component matches the ID, then null is returned.
* Else the component is returned.
*/
public CheckBox getCheckBoxByID(final String id) {
final Component component = getComponentByID(id);
if (component instanceof CheckBox) {
return (CheckBox) component;
}
return null;
}
/**
* Works the same as getComponentByID, but only returns if the result is a
* Layer component.
*
* @param id
* The id.
*
* @return
* If no component matches the ID, then null is returned.
* If no layer component matches the ID, then null is returned.
* Else the component is returned.
*/
public Layer getLayerByID(final String id) {
final Component component = getComponentByID(id);
if (component instanceof Layer) {
return (Layer) component;
}
return null;
}
/**
* Works the same as getComponentByID, but only returns if the result is a
* ProgressBar component.
*
* @param id
* The id.
*
* @return
* If no component matches the ID, then null is returned.
* If no progress bar component matches the ID, then null is returned.
* Else the component is returned.
*/
public ProgressBar getProgressBarByID(final String id) {
final Component component = getComponentByID(id);
if (component instanceof ProgressBar) {
return (ProgressBar) component;
}
return null;
}
/**
* Works the same as getComponentByID, but only returns if the result is a
* RadioButton component.
*
* @param id
* The id.
*
* @return
* If no component matches the ID, then null is returned.
* If no radio button component matches the ID, then null is returned.
* Else the component is returned.
*/
public RadioButton getRadioButtonByID(final String id) {
final Component component = getComponentByID(id);
if (component instanceof RadioButton) {
return (RadioButton) component;
}
return null;
}
/**
* Works the same as getComponentByID, but only returns if the result is a
* TextArea component.
*
* @param id
* The id.
*
* @return
* If no component matches the ID, then null is returned.
* If no text area component matches the ID, then null is returned.
* Else the component is returned.
*/
public TextArea getTextAreaByID(final String id) {
final Component component = getComponentByID(id);
if (component instanceof TextArea) {
return (TextArea) component;
}
return null;
}
/**
* Works the same as getComponentByID, but only returns if the result is a
* TextField component.
*
* @param id
* The id.
*
* @return
* If no component matches the ID, then null is returned.
* If no text field component matches the ID, then null is returned.
* Else the component is returned.
*/
public TextField getTextFieldByID(final String id) {
final Component component = getComponentByID(id);
if (component instanceof TextField) {
return (TextField) component;
}
return null;
}
/**
* Retrieves a combined set of all components.
*
* @return
* A combined set of all components.
*/
public Set<Component> getComponents() {
componentsLock.readLock().lock();
final Set<Component> set = new LinkedHashSet<>(components);
set.addAll(layerComponents);
set.addAll(screenComponents);
componentsLock.readLock().unlock();
return set;
}
public void setRadio(final Radio<String> radio) {
super.radio = radio;
}
} |
package com.hp.hpl.jena.reasoner.rulesys;
import com.hp.hpl.jena.graph.*;
import com.hp.hpl.jena.reasoner.TriplePattern;
public interface BindingEnvironment {
/**
* Return the most ground version of the node. If the node is not a variable
* just return it, if it is a varible bound in this environment return the binding,
* if it is an unbound variable return the variable.
*/
public Node getGroundVersion(Node node);
/**
* Bind a variable in the current envionment to the given value.
* Checks that the new binding is compatible with any current binding.
* @param var a Node_RuleVariable defining the variable to bind
* @param value the value to bind
* @return false if the binding fails
*/
public boolean bind(Node var, Node value);
/**
* Instantiate a triple pattern against the current environment.
* This version handles unbound varibles by turning them into bNodes.
* @param pattern the triple pattern to match
* @return a new, instantiated triple
*/
public Triple instantiate(TriplePattern pattern);
} |
package com.valkryst.VTerminal.component;
import com.valkryst.VTerminal.AsciiCharacter;
import com.valkryst.VTerminal.AsciiString;
import com.valkryst.VTerminal.font.Font;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
public class Screen extends Component {
/** The components displayed on the screen. */
private final ArrayList<Component> components = new ArrayList<>();
/**
* Constructs a new AsciiScreen.
*
* @param columnIndex
* The x-axis (column) coordinate of the top-left character.
*
* @param rowIndex
* The y-axis (row) coordinate of the top-left character.
*
* @param width
* Thw width, in characters.
*
* @param height
* The height, in characters.
*/
public Screen(final int columnIndex, final int rowIndex, final int width, final int height) {
super(columnIndex, rowIndex, width, height);
}
@Override
public void draw(final Screen screen) {
throw new UnsupportedOperationException("A Screen must be drawn using the draw(canvas, font) method.");
}
/**
* Draws the screen onto the specified canvas using the specified font.
*
* @param gc
* The graphics context to draw with.
*
* @param font
* The font to draw with.
*/
public void draw(final Graphics2D gc, final Font font) {
// Draw components onto the screen:
components.forEach(component -> component.draw(this));
// Draw the screen onto the canvas:
for (int row = 0 ; row < height ; row++) {
strings[row].draw(gc, font, row);
}
}
/**
* Clears the entire screen.
*
* @param character
* The character to replace every character on the screen with.
*
* @return
* If all characters within the screen were cleared.
*/
public boolean clear(final char character) {
return clear(character, 0, 0, super.getWidth() - 1, super.getHeight() - 1);
}
/**
* Clears the specified section of the screen.
*
* Does nothing if the (columnIndex, rowIndex) or (width, height) pairs point to invalid positions.
*
* @param character
* The character to replace all characters being cleared with.
*
* @param columnIndex
* The x-axis (column) coordinate of the cell to clear.
*
* @param rowIndex
* The y-axis (row) coordinate of the cell to clear.
*
* @param width
* The width of the area to clear.
*
* @param height
* The height of the area to clear.
*
* @return
* If all characters within the specified area were cleared.
*/
public boolean clear(final char character, final int columnIndex, final int rowIndex, final int width, final int height) {
boolean canProceed = isPositionValid(columnIndex, rowIndex);
canProceed &= isPositionValid(width, height);
if (canProceed) {
for (int column = columnIndex ; column < width ; column++) {
for (int row = rowIndex ; row < height ; row++) {
canProceed &= write(character, column, row);
}
}
}
return canProceed;
}
/**
* Write the specified character to the specified position.
*
* @param character
* The character.
*
* @param columnIndex
* The x-axis (column) coordinate to write to.
*
* @param rowIndex
* The y-axis (row) coordinate to write to.
*
* @return
* If the write was successful.
*/
public boolean write(final AsciiCharacter character, final int columnIndex, final int rowIndex) {
boolean canProceed = isPositionValid(columnIndex, rowIndex);
if (canProceed) {
strings[rowIndex].setCharacter(columnIndex, character);
}
return canProceed;
}
/**
* Write the specified character to the specified position.
*
* @param character
* The character.
*
* @param columnIndex
* The x-axis (column) coordinate to write to.
*
* @param rowIndex
* The y-axis (row) coordinate to write to.
*
* @return
* If the write was successful.
*/
public boolean write(final char character, final int columnIndex, final int rowIndex) {
boolean canProceed = isPositionValid(columnIndex, rowIndex);
if (canProceed) {
strings[rowIndex].setCharacter(columnIndex, character);
}
return canProceed;
}
/**
* Write a string to the specified position.
*
* Does nothing if the (columnIndex, rowIndex) points to invalid position.
*
* @param string
* The string.
*
* @param columnIndex
* The x-axis (column) coordinate to begin writing from.
*
* @param rowIndex
* The y-axis (row) coordinate to begin writing from.
*
* @return
* If all writes were successful.
*/
public boolean write(final AsciiString string, final int columnIndex, final int rowIndex) {
if (isPositionValid(columnIndex, rowIndex) == false) {
return false;
}
boolean writesSuccessful = true;
final AsciiCharacter[] characters = string.getCharacters();
for (int i = 0 ; i < characters.length && i < super.getWidth() ; i++) {
writesSuccessful &= write(characters[i], columnIndex + i, rowIndex);
}
return writesSuccessful;
}
/**
* Draws the screen onto an image.
*
* This calls the draw function, so the screen may look a
* little different if there are blink effects or new updates
* to characters that haven't yet been drawn.
*
* This is an expensive operation as it essentially creates
* an in-memory screen and draws each AsciiCharacter onto
* that screen.
*
* @param asciiFont
* The font to render the screen with.
*
* @return
* An image of the screen.
*/
public BufferedImage screenshot(final Font asciiFont) {
final BufferedImage img = new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_RGB);
final Graphics2D gc = img.createGraphics();
for (final AsciiString string : strings) {
string.setAllCharactersToBeRedrawn();
}
draw(gc, asciiFont);
gc.dispose();
return img;
}
/**
* Sets the background color of all characters.
*
* @param color
* The new background color.
*/
public void setBackgroundColor(final Color color) {
for (final AsciiString string : strings) {
string.setBackgroundColor(color);
}
}
/**
* Sets the foreground color of all characters.
*
* @param color
* The new foreground color.
*/
public void setForegroundColor(final Color color) {
for (final AsciiString string : strings) {
string.setForegroundColor(color);
}
}
/**
* Sets the background and foreground color of all characters.
*
* @param background
* The new background color.
*
* @param foreground
* The new foreground color.
*/
public void setBackgroundAndForegroundColor(final Color background, final Color foreground) {
for (final AsciiString string : strings) {
string.setBackgroundAndForegroundColor(background, foreground);
}
}
/**
* Adds a component to the AsciiScreen.
*
* @param component
* The component.
*/
public void addComponent(final Component component) {
if (component == null) {
return;
}
if (component == this) {
throw new IllegalArgumentException("A component cannot be added to itself.");
}
if (components.contains(component)) {
return;
}
components.add(component);
}
/**
* Removes a component from the AsciiScreen.
*
* @param component
* The component.
*/
public void removeComponent(final Component component) {
if (component == null) {
return;
}
if (component == this) {
return;
}
components.remove(component);
}
} |
package com.qmetry.qaf.automation.core;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import org.apache.commons.configuration.AbstractConfiguration;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.event.ConfigurationEvent;
import org.apache.commons.configuration.event.ConfigurationListener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.impl.LogFactoryImpl;
import org.hamcrest.Matchers;
import com.qmetry.qaf.automation.keys.ApplicationProperties;
import com.qmetry.qaf.automation.step.JavaStepFinder;
import com.qmetry.qaf.automation.step.TestStep;
import com.qmetry.qaf.automation.step.client.ScenarioFactory;
import com.qmetry.qaf.automation.step.client.csv.KwdTestFactory;
import com.qmetry.qaf.automation.step.client.excel.ExcelTestFactory;
import com.qmetry.qaf.automation.step.client.text.BDDTestFactory;
import com.qmetry.qaf.automation.util.FileUtil;
import com.qmetry.qaf.automation.util.PropertyUtil;
import com.qmetry.qaf.automation.util.StringComparator;
import com.qmetry.qaf.automation.util.StringMatcher;
import com.qmetry.qaf.automation.util.StringUtil;
/**
* Configuration manager class. Singleton with early initialization.
* <p>
* This class loads file provided by system property
* <code>application.properties.file</code> (Default value is
* "resources/application.properties"). Also loads all property files form
* <code>test.props.dir</code>(default value is "resources") if
* <code>resources.load.subdirs</code> flag is 1.
* <p>
* To access any property value within automation, use following way
* {@link PropertyUtil} props={@link #ConfigurationManager}.
* {@link #getInstance()}.{@link#getApplicationProperties()};<br>
* String sval = props.{@link PropertyUtil#getPropertyValue(String)}
*
* @author chirag
*/
public class ConfigurationManager {
// early initialization
static final Log log = LogFactoryImpl.getLog(ConfigurationManager.class);
private static final ConfigurationManager INSTANCE = new ConfigurationManager();
/**
* Private constructor, prevents instantiation from other classes
*/
private ConfigurationManager() {
AbstractConfiguration.setDefaultListDelimiter(';');
}
public static ConfigurationManager getInstance() {
return INSTANCE;
}
private static InheritableThreadLocal<PropertyUtil> LocalProps =
new InheritableThreadLocal<PropertyUtil>() {
@Override
protected PropertyUtil initialValue() {
PropertyUtil p = new PropertyUtil(
System.getProperty("application.properties.file",
"resources/application.properties"));
p.setProperty("isfw.build.info", getBuildInfo());
File prjDir = new File(".").getAbsoluteFile().getParentFile();
p.setProperty("project.path", prjDir.getAbsolutePath());
if(!p.containsKey("project.name"))
p.setProperty("project.name", prjDir.getName());
log.info("ISFW build info: " + p.getProperty("isfw.build.info"));
String[] resources = p.getStringArray("env.resources", "resources");
for (String resource : resources) {
addBundle(p, resource);
}
ConfigurationListener cl = new PropertyConfigurationListener();
p.addConfigurationListener(cl);
return p;
}
@Override
protected PropertyUtil childValue(PropertyUtil parentValue) {
PropertyUtil cp = new PropertyUtil(parentValue);
ConfigurationListener cl = new PropertyConfigurationListener();
cp.addConfigurationListener(cl);
return cp;
}
};
/**
* To add local resources.
*
* @param fileOrDir
*/
public static void addBundle(String fileOrDir) {
ConfigurationManager.addBundle(getBundle(), fileOrDir);
}
/**
* @param p
* @param fileOrDir
*/
private static void addBundle(PropertyUtil p, String fileOrDir) {
String localResources = p.getString("local.reasources",
p.getString("env.local.resources", "resources"));
fileOrDir = p.getSubstitutor().replace(fileOrDir);
File resourceFile = new File(fileOrDir);
String[] locals = p.getStringArray(ApplicationProperties.LOAD_LOCALES.key);
/**
* will reload existing properties value(if any) if the last loaded
* dir/file is not the current one. case: suit-1 default, suit-2 :
* s2-local, suit-3: default Here after suit-2 you need to reload
* default.
*/
if (!localResources.equalsIgnoreCase(resourceFile.getAbsolutePath())) {
p.addProperty("local.reasources", resourceFile.getAbsolutePath());
if (resourceFile.exists()) {
if (resourceFile.isDirectory()) {
boolean loadSubDirs = p.getBoolean("resources.load.subdirs", true);
File[] propFiles = FileUtil.listFilesAsArray(resourceFile,
".properties", StringComparator.Suffix, loadSubDirs);
log.info("Resource dir: " + resourceFile.getAbsolutePath()
+ ". Found property files to load: " + propFiles.length);
File[] locFiles = FileUtil.listFilesAsArray(resourceFile, ".loc",
StringComparator.Suffix, loadSubDirs);
File[] wscFiles = FileUtil.listFilesAsArray(resourceFile, ".wsc",
StringComparator.Suffix, loadSubDirs);
PropertyUtil p1 = new PropertyUtil();
p1.load(propFiles);
p1.load(locFiles);
p1.load(wscFiles);
p.copy(p1);
propFiles = FileUtil.listFilesAsArray(resourceFile, ".xml",
StringComparator.Suffix, loadSubDirs);
log.info("Resource dir: " + resourceFile.getAbsolutePath()
+ ". Found property files to load: " + propFiles.length);
p1 = new PropertyUtil();
p1.load(propFiles);
p.copy(p1);
} else {
try {
if (fileOrDir.endsWith(".properties")
|| fileOrDir.endsWith(".xml")
|| fileOrDir.endsWith(".loc")
|| fileOrDir.endsWith(".wsc")) {
p.load(new File[]{resourceFile});
}
} catch (Exception e) {
log.error(
"Unable to load " + resourceFile.getAbsolutePath() + "!",
e);
}
}
// add locals if any
if (null != locals && locals.length > 0
&& (locals.length == 1 || StringUtil.isBlank(p.getString(
ApplicationProperties.DEFAULT_LOCALE.key, "")))) {
p.setProperty(ApplicationProperties.DEFAULT_LOCALE.key, locals[0]);
}
for (String local : locals) {
log.info("loading local: " + local);
addLocal(p, local, fileOrDir);
}
} else {
log.error(resourceFile.getAbsolutePath() + " not exist!");
}
}
}
private static void addLocal(PropertyUtil p, String local, String fileOrDir) {
String defaultLocal = p.getString(ApplicationProperties.DEFAULT_LOCALE.key, "");
File resourceFile = new File(fileOrDir);
/**
* will reload existing properties value(if any) if the last loaded
* dir/file is not the current one. case: suit-1 default, suit-2 :
* s2-local, suit-3: default Here after suit-2 you need to reload
* default.
*/
boolean loadSubDirs = p.getBoolean("resources.load.subdirs", true);
if (resourceFile.exists()) {
PropertyUtil p1 = new PropertyUtil();
p1.setEncoding(
p.getString(ApplicationProperties.LOCALE_CHAR_ENCODING.key, "UTF-8"));
if (resourceFile.isDirectory()) {
File[] propFiles = FileUtil.listFilesAsArray(resourceFile, "." + local,
StringComparator.Suffix, loadSubDirs);
p1.load(propFiles);
} else {
try {
if (fileOrDir.endsWith(local)) {
p1.load(fileOrDir);
}
} catch (Exception e) {
log.error("Unable to load " + resourceFile.getAbsolutePath() + "!",
e);
}
}
if (local.equalsIgnoreCase(defaultLocal)) {
p.copy(p1);
} else {
Iterator<?> keyIter = p1.getKeys();
Configuration localSet = p.subset(local);
while (keyIter.hasNext()) {
String key = (String) keyIter.next();
localSet.addProperty(key, p1.getObject(key));
}
}
} else {
log.error(resourceFile.getAbsolutePath() + " not exist!");
}
}
public static void addAll(Map<String, String> props) {
ConfigurationManager.getBundle().addAll(props);
}
public static PropertyUtil getBundle() {
return ConfigurationManager.LocalProps.get();
}
private static Map<String, String> getBuildInfo() {
Manifest manifest = null;
Map<String, String> buildInfo = new HashMap<String, String>();
JarFile jar = null;
try {
URL url = ConfigurationManager.class.getProtectionDomain().getCodeSource()
.getLocation();
File file = new File(url.toURI());
jar = new JarFile(file);
manifest = jar.getManifest();
} catch (NullPointerException ignored) {
} catch (URISyntaxException ignored) {
} catch (IOException ignored) {
} catch (IllegalArgumentException ignored) {
} finally {
if (null != jar)
try {
jar.close();
} catch (IOException e) {
log.warn(e.getMessage());
}
}
if (manifest == null) {
return buildInfo;
}
try {
Attributes attributes = manifest.getAttributes("Build-Info");
Set<Entry<Object, Object>> entries = attributes.entrySet();
for (Entry<Object, Object> e : entries) {
buildInfo.put(String.valueOf(e.getKey()), String.valueOf(e.getValue()));
}
} catch (NullPointerException e) {
// Fall through
}
return buildInfo;
}
/**
* Get test-step mapping for current configuration
*
* @return
*/
@SuppressWarnings("unchecked")
public static Map<String, TestStep> getStepMapping() {
if (!ConfigurationManager.getBundle().containsKey("teststep.mapping")) {
ConfigurationManager.getBundle().addProperty("teststep.mapping",
JavaStepFinder.getAllJavaSteps());
if (ConfigurationManager.getBundle()
.containsKey(ApplicationProperties.STEP_PROVIDER_PKG.key)) {
for (String pkg : ConfigurationManager.getBundle()
.getStringArray(ApplicationProperties.STEP_PROVIDER_PKG.key)) {
for (ScenarioFactory factory : getStepFactories()) {
factory.process(pkg.replaceAll("\\.", "/"));
}
}
}
}
return (Map<String, TestStep>) ConfigurationManager.getBundle()
.getObject("teststep.mapping");
}
private static ScenarioFactory[] getStepFactories() {
return new ScenarioFactory[]{new BDDTestFactory(Arrays.asList("bdl")),
new KwdTestFactory(Arrays.asList("kwl")), new ExcelTestFactory()};
}
private static class PropertyConfigurationListener implements ConfigurationListener {
String oldValue;
@SuppressWarnings("unchecked")
@Override
public void configurationChanged(ConfigurationEvent event) {
if ((event.getType() == AbstractConfiguration.EVENT_CLEAR_PROPERTY
|| event.getType() == AbstractConfiguration.EVENT_SET_PROPERTY)
&& event.isBeforeUpdate()) {
oldValue = String.format("%s",
getBundle().getObject(event.getPropertyName()));
}
if ((event.getType() == AbstractConfiguration.EVENT_ADD_PROPERTY
|| event.getType() == AbstractConfiguration.EVENT_SET_PROPERTY)
&& !event.isBeforeUpdate()) {
String key = event.getPropertyName();
Object value = event.getPropertyValue();
if (null != oldValue && Matchers.equalTo(oldValue).matches(value)) {
// do nothing
return;
}
// driver reset
if (key.equalsIgnoreCase(ApplicationProperties.DRIVER_NAME.key)
// single capability or set of capabilities change
|| StringMatcher.containsIgnoringCase(".capabilit").match(key)
|| key.equalsIgnoreCase(ApplicationProperties.REMOTE_SERVER.key)
|| key.equalsIgnoreCase(ApplicationProperties.REMOTE_PORT.key)) {
TestBaseProvider.instance().get().tearDown();
if(key.equalsIgnoreCase(ApplicationProperties.DRIVER_NAME.key)){
TestBaseProvider.instance().get().setDriver((String)value);
}
}
String[] bundles = null;
// Resource loading
if (key.equalsIgnoreCase("env.resources")) {
if (event.getPropertyValue() instanceof ArrayList<?>) {
ArrayList<String> bundlesArray =
((ArrayList<String>) event.getPropertyValue());
bundles = bundlesArray.toArray(new String[bundlesArray.size()]);
} else {
String resourcesBundle = (String) value;
if (StringUtil.isNotBlank(resourcesBundle))
bundles = resourcesBundle.split(String
.valueOf(PropertyUtil.getDefaultListDelimiter()));
}
if (null != bundles && bundles.length > 0) {
for (String res : bundles) {
log.info("Adding resources from: " + res);
ConfigurationManager.addBundle(res);
}
}
}
// Locale loading
if (key.equalsIgnoreCase(ApplicationProperties.DEFAULT_LOCALE.key)) {
String[] resources =
getBundle().getStringArray("env.resources", "resources");
for (String resource : resources) {
String fileOrDir = getBundle().getSubstitutor().replace(resource);
addLocal(getBundle(), (String) event.getPropertyValue(),
fileOrDir);
}
}
// step provider package re-load
if (key.equalsIgnoreCase(ApplicationProperties.STEP_PROVIDER_PKG.key)) {
// has loaded steps and adding more or override java
// steps....
// for example suite level parameter has common steps and
// test level parameter has test specific steps
if (ConfigurationManager.getBundle()
.containsKey("teststep.mapping")) {
ConfigurationManager.getStepMapping()
.putAll(JavaStepFinder.getAllJavaSteps());
for (ScenarioFactory factory : getStepFactories()) {
if (event.getPropertyValue() instanceof ArrayList<?>) {
ArrayList<String> bundlesArray =
((ArrayList<String>) event.getPropertyValue());
bundles = bundlesArray
.toArray(new String[bundlesArray.size()]);
for (String pkg : bundlesArray) {
factory.process(pkg.replaceAll("\\.", "/"));
}
} else {
String resourcesBundle = (String) value;
if (StringUtil.isNotBlank(resourcesBundle)) {
factory.process(
resourcesBundle.replaceAll("\\.", "/"));
}
}
}
}
}
}
}
}
} |
package at.ac.tuwien.kr.alpha.grounder.transformation;
import at.ac.tuwien.kr.alpha.common.atoms.Atom;
import at.ac.tuwien.kr.alpha.common.atoms.Literal;
import at.ac.tuwien.kr.alpha.common.program.NormalProgram;
import at.ac.tuwien.kr.alpha.common.rule.NormalRule;
import at.ac.tuwien.kr.alpha.common.rule.head.NormalHead;
import at.ac.tuwien.kr.alpha.common.terms.FunctionTerm;
import at.ac.tuwien.kr.alpha.common.terms.IntervalTerm;
import at.ac.tuwien.kr.alpha.common.terms.Term;
import at.ac.tuwien.kr.alpha.common.terms.VariableTerm;
import at.ac.tuwien.kr.alpha.grounder.atoms.IntervalAtom;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class IntervalTermToIntervalAtom extends ProgramTransformation<NormalProgram, NormalProgram> {
private static final String INTERVAL_VARIABLE_PREFIX = "_Interval";
/**
* Rewrites intervals into a new variable and special IntervalAtom.
*
* @return true if some interval occurs in the rule.
*/
private static NormalRule rewriteIntervalSpecifications(NormalRule rule) {
// Collect all intervals and replace them with variables.
Map<VariableTerm, IntervalTerm> intervalReplacements = new LinkedHashMap<>();
List<Literal> rewrittenBody = new ArrayList<>();
for (Literal literal : rule.getBody()) {
rewrittenBody.add(rewriteLiteral(literal, intervalReplacements));
}
NormalHead rewrittenHead = rule.isConstraint() ? null :
new NormalHead(rewriteLiteral(rule.getHeadAtom().toLiteral(), intervalReplacements).getAtom());
// If intervalReplacements is empty, no IntervalTerms have been found, keep rule as is.
if (intervalReplacements.isEmpty()) {
return rule;
}
// Add new IntervalAtoms representing the interval specifications.
for (Map.Entry<VariableTerm, IntervalTerm> interval : intervalReplacements.entrySet()) {
rewrittenBody.add(new IntervalAtom(interval.getValue(), interval.getKey()).toLiteral());
}
return new NormalRule(rewrittenHead, rewrittenBody);
}
/**
* Replaces every IntervalTerm by a new variable and returns a mapping of the replaced VariableTerm -> IntervalTerm.
*/
private static Literal rewriteLiteral(Literal lit, Map<VariableTerm, IntervalTerm> intervalReplacement) {
Atom atom = lit.getAtom();
List<Term> termList = new ArrayList<>(atom.getTerms());
boolean didChange = false;
for (int i = 0; i < termList.size(); i++) {
Term term = termList.get(i);
if (term instanceof IntervalTerm) {
VariableTerm replacementVariable = VariableTerm.getInstance(INTERVAL_VARIABLE_PREFIX + intervalReplacement.size());
intervalReplacement.put(replacementVariable, (IntervalTerm) term);
termList.set(i, replacementVariable);
didChange = true;
}
if (term instanceof FunctionTerm) {
// Rewrite function terms recursively.
FunctionTerm rewrittenFunctionTerm = rewriteFunctionTerm((FunctionTerm) term, intervalReplacement);
termList.set(i, rewrittenFunctionTerm);
didChange = true;
}
}
if (didChange) {
Atom rewrittenAtom = atom.withTerms(termList);
return lit.isNegated() ? rewrittenAtom.toLiteral().negate() : rewrittenAtom.toLiteral();
}
return lit;
}
private static FunctionTerm rewriteFunctionTerm(FunctionTerm functionTerm, Map<VariableTerm, IntervalTerm> intervalReplacement) {
List<Term> termList = new ArrayList<>(functionTerm.getTerms());
boolean didChange = false;
for (int i = 0; i < termList.size(); i++) {
Term term = termList.get(i);
if (term instanceof IntervalTerm) {
VariableTerm replacementVariable = VariableTerm.getInstance("_Interval" + intervalReplacement.size());
intervalReplacement.put(replacementVariable, (IntervalTerm) term);
termList.set(i, replacementVariable);
didChange = true;
}
if (term instanceof FunctionTerm) {
// Recursively rewrite function terms.
FunctionTerm rewrittenFunctionTerm = rewriteFunctionTerm((FunctionTerm) term, intervalReplacement);
if (rewrittenFunctionTerm != term) {
termList.set(i, rewrittenFunctionTerm);
didChange = true;
}
}
}
if (didChange) {
return FunctionTerm.getInstance(functionTerm.getSymbol(), termList);
}
return functionTerm;
}
@Override
public NormalProgram apply(NormalProgram inputProgram) {
boolean didChange = false;
List<NormalRule> rewrittenRules = new ArrayList<>();
for (NormalRule rule : inputProgram.getRules()) {
NormalRule rewrittenRule = rewriteIntervalSpecifications(rule);
rewrittenRules.add(rewrittenRule);
// If no rewriting occurred, the output rule is the same as the input to the rewriting.
if (rewrittenRule != rule) {
didChange = true;
}
}
// Return original program if no rule was actually rewritten.
if (!didChange) {
return inputProgram;
}
return new NormalProgram(rewrittenRules, inputProgram.getFacts(), inputProgram.getInlineDirectives());
}
} |
package com.bullhornsdk.data.model.entity.core.customobject;
import com.bullhornsdk.data.model.entity.core.type.AbstractEntity;
import com.bullhornsdk.data.model.entity.core.type.CreateEntity;
import com.bullhornsdk.data.model.entity.core.type.DateLastModifiedEntity;
import com.bullhornsdk.data.model.entity.core.type.HardDeleteEntity;
import com.bullhornsdk.data.model.entity.core.type.QueryEntity;
import com.bullhornsdk.data.model.entity.core.type.UpdateEntity;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.joda.time.DateTime;
import java.math.BigDecimal;
public abstract class CustomObjectInstance extends AbstractEntity implements QueryEntity, DateLastModifiedEntity, CreateEntity, UpdateEntity, HardDeleteEntity {
private Integer id;
private String text1;
private String text2;
private String text3;
private String text4;
private String text5;
private String text6;
private String text7;
private String text8;
private String text9;
private String text10;
private String text11;
private String text12;
private String text13;
private String text14;
private String text15;
private String text16;
private String text17;
private String text18;
private String text19;
private String text20;
private Integer int1;
private Integer int2;
private Integer int3;
private Integer int4;
private Integer int5;
private Integer int6;
private Integer int7;
private Integer int8;
private Integer int9;
private Integer int10;
private BigDecimal float1;
private BigDecimal float2;
private BigDecimal float3;
private BigDecimal float4;
private BigDecimal float5;
private BigDecimal float6;
private BigDecimal float7;
private BigDecimal float8;
private BigDecimal float9;
private BigDecimal float10;
private String textBlock1;
private String textBlock2;
private String textBlock3;
private String textBlock4;
private String textBlock5;
private DateTime date1;
private DateTime date2;
private DateTime date3;
private DateTime date4;
private DateTime date5;
private DateTime date6;
private DateTime date7;
private DateTime date8;
private DateTime date9;
private DateTime date10;
private DateTime dateAdded;
private DateTime dateLastModified;
public CustomObjectInstance() {
super();
}
@JsonProperty("id")
public Integer getId() {
return id;
}
@JsonProperty("id")
public void setId(Integer id) {
this.id = id;
}
@JsonProperty("text1")
public String getText1() {
return text1;
}
@JsonProperty("text1")
public void setText1(String text1) {
this.text1 = text1;
}
@JsonProperty("text2")
public String getText2() {
return text2;
}
@JsonProperty("text2")
public void setText2(String text2) {
this.text2 = text2;
}
@JsonProperty("text3")
public String getText3() {
return text3;
}
@JsonProperty("text3")
public void setText3(String text3) {
this.text3 = text3;
}
@JsonProperty("text4")
public String getText4() {
return text4;
}
@JsonProperty("text4")
public void setText4(String text4) {
this.text4 = text4;
}
@JsonProperty("text5")
public String getText5() {
return text5;
}
@JsonProperty("text5")
public void setText5(String text5) {
this.text5 = text5;
}
@JsonProperty("text6")
public String getText6() {
return text6;
}
@JsonProperty("text6")
public void setText6(String text6) {
this.text6 = text6;
}
@JsonProperty("text7")
public String getText7() {
return text7;
}
@JsonProperty("text7")
public void setText7(String text7) {
this.text7 = text7;
}
@JsonProperty("text8")
public String getText8() {
return text8;
}
@JsonProperty("text8")
public void setText8(String text8) {
this.text8 = text8;
}
@JsonProperty("text9")
public String getText9() {
return text9;
}
@JsonProperty("text9")
public void setText9(String text9) {
this.text9 = text9;
}
@JsonProperty("text10")
public String getText10() {
return text10;
}
@JsonProperty("text10")
public void setText10(String text10) {
this.text10 = text10;
}
@JsonProperty("text11")
public String getText11() {
return text11;
}
@JsonProperty("text11")
public void setText11(String text11) {
this.text11 = text11;
}
@JsonProperty("text12")
public String getText12() {
return text12;
}
@JsonProperty("text12")
public void setText12(String text12) {
this.text12 = text12;
}
@JsonProperty("text13")
public String getText13() {
return text13;
}
@JsonProperty("text13")
public void setText13(String text13) {
this.text13 = text13;
}
@JsonProperty("text14")
public String getText14() {
return text14;
}
@JsonProperty("text14")
public void setText14(String text14) {
this.text14 = text14;
}
@JsonProperty("text15")
public String getText15() {
return text15;
}
@JsonProperty("text15")
public void setText15(String text15) {
this.text15 = text15;
}
@JsonProperty("text16")
public String getText16() {
return text16;
}
@JsonProperty("text16")
public void setText16(String text16) {
this.text16 = text16;
}
@JsonProperty("text17")
public String getText17() {
return text17;
}
@JsonProperty("text17")
public void setText17(String text17) {
this.text17 = text17;
}
@JsonProperty("text18")
public String getText18() {
return text18;
}
@JsonProperty("text18")
public void setText18(String text18) {
this.text18 = text18;
}
@JsonProperty("text19")
public String getText19() {
return text19;
}
@JsonProperty("text19")
public void setText19(String text19) {
this.text19 = text19;
}
@JsonProperty("text20")
public String getText20() {
return text20;
}
@JsonProperty("text20")
public void setText20(String text20) {
this.text20 = text20;
}
@JsonProperty("int1")
public Integer getInt1() {
return int1;
}
@JsonProperty("int1")
public void setInt1(Integer int1) {
this.int1 = int1;
}
@JsonProperty("int2")
public Integer getInt2() {
return int2;
}
@JsonProperty("int2")
public void setInt2(Integer int2) {
this.int2 = int2;
}
@JsonProperty("int3")
public Integer getInt3() {
return int3;
}
@JsonProperty("int3")
public void setInt3(Integer int3) {
this.int3 = int3;
}
@JsonProperty("int4")
public Integer getInt4() {
return int4;
}
@JsonProperty("int4")
public void setInt4(Integer int4) {
this.int4 = int4;
}
@JsonProperty("int5")
public Integer getInt5() {
return int5;
}
@JsonProperty("int5")
public void setInt5(Integer int5) {
this.int5 = int5;
}
@JsonProperty("int6")
public Integer getInt6() {
return int6;
}
@JsonProperty("int6")
public void setInt6(Integer int6) {
this.int6 = int6;
}
@JsonProperty("int7")
public Integer getInt7() {
return int7;
}
@JsonProperty("int7")
public void setInt7(Integer int7) {
this.int7 = int7;
}
@JsonProperty("int8")
public Integer getInt8() {
return int8;
}
@JsonProperty("int8")
public void setInt8(Integer int8) {
this.int8 = int8;
}
@JsonProperty("int9")
public Integer getInt9() {
return int9;
}
@JsonProperty("int9")
public void setInt9(Integer int9) {
this.int9 = int9;
}
@JsonProperty("int10")
public Integer getInt10() {
return int10;
}
@JsonProperty("int10")
public void setInt10(Integer int10) {
this.int10 = int10;
}
@JsonProperty("float1")
public BigDecimal getFloat1() {
return float1;
}
@JsonProperty("float1")
public void setFloat1(BigDecimal float1) {
this.float1 = float1;
}
@JsonProperty("float2")
public BigDecimal getFloat2() {
return float2;
}
@JsonProperty("float2")
public void setFloat2(BigDecimal float2) {
this.float2 = float2;
}
@JsonProperty("float3")
public BigDecimal getFloat3() {
return float3;
}
@JsonProperty("float3")
public void setFloat3(BigDecimal float3) {
this.float3 = float3;
}
@JsonProperty("float4")
public BigDecimal getFloat4() {
return float4;
}
@JsonProperty("float4")
public void setFloat4(BigDecimal float4) {
this.float4 = float4;
}
@JsonProperty("float5")
public BigDecimal getFloat5() {
return float5;
}
@JsonProperty("float5")
public void setFloat5(BigDecimal float5) {
this.float5 = float5;
}
@JsonProperty("float6")
public BigDecimal getFloat6() {
return float6;
}
@JsonProperty("float6")
public void setFloat6(BigDecimal float6) {
this.float6 = float6;
}
@JsonProperty("float7")
public BigDecimal getFloat7() {
return float7;
}
@JsonProperty("float7")
public void setFloat7(BigDecimal float7) {
this.float7 = float7;
}
@JsonProperty("float8")
public BigDecimal getFloat8() {
return float8;
}
@JsonProperty("float8")
public void setFloat8(BigDecimal float8) {
this.float8 = float8;
}
@JsonProperty("float9")
public BigDecimal getFloat9() {
return float9;
}
@JsonProperty("float9")
public void setFloat9(BigDecimal float9) {
this.float9 = float9;
}
@JsonProperty("float10")
public BigDecimal getFloat10() {
return float10;
}
@JsonProperty("float10")
public void setFloat10(BigDecimal float10) {
this.float10 = float10;
}
@JsonProperty("textBlock1")
public String getTextBlock1() {
return textBlock1;
}
@JsonProperty("textBlock1")
public void setTextBlock1(String textBlock1) {
this.textBlock1 = textBlock1;
}
@JsonProperty("textBlock2")
public String getTextBlock2() {
return textBlock2;
}
@JsonProperty("textBlock2")
public void setTextBlock2(String textBlock2) {
this.textBlock2 = textBlock2;
}
@JsonProperty("textBlock3")
public String getTextBlock3() {
return textBlock3;
}
@JsonProperty("textBlock3")
public void setTextBlock3(String textBlock3) {
this.textBlock3 = textBlock3;
}
@JsonProperty("textBlock4")
public String getTextBlock4() {
return textBlock4;
}
@JsonProperty("textBlock4")
public void setTextBlock4(String textBlock4) {
this.textBlock4 = textBlock4;
}
@JsonProperty("textBlock5")
public String getTextBlock5() {
return textBlock5;
}
@JsonProperty("textBlock5")
public void setTextBlock5(String textBlock5) {
this.textBlock5 = textBlock5;
}
@JsonProperty("date1")
public DateTime getDate1() {
return date1;
}
@JsonProperty("date1")
public void setDate1(DateTime date1) {
this.date1 = date1;
}
@JsonProperty("date2")
public DateTime getDate2() {
return date2;
}
@JsonProperty("date2")
public void setDate2(DateTime date2) {
this.date2 = date2;
}
@JsonProperty("date3")
public DateTime getDate3() {
return date3;
}
@JsonProperty("date3")
public void setDate3(DateTime date3) {
this.date3 = date3;
}
@JsonProperty("date4")
public DateTime getDate4() {
return date4;
}
@JsonProperty("date4")
public void setDate4(DateTime date4) {
this.date4 = date4;
}
@JsonProperty("date5")
public DateTime getDate5() {
return date5;
}
@JsonProperty("date5")
public void setDate5(DateTime date5) {
this.date5 = date5;
}
@JsonProperty("date6")
public DateTime getDate6() {
return date6;
}
@JsonProperty("date6")
public void setDate6(DateTime date6) {
this.date6 = date6;
}
@JsonProperty("date7")
public DateTime getDate7() {
return date7;
}
@JsonProperty("date7")
public void setDate7(DateTime date7) {
this.date7 = date7;
}
@JsonProperty("date8")
public DateTime getDate8() {
return date8;
}
@JsonProperty("date8")
public void setDate8(DateTime date8) {
this.date8 = date8;
}
@JsonProperty("date9")
public DateTime getDate9() {
return date9;
}
@JsonProperty("date9")
public void setDate9(DateTime date9) {
this.date9 = date9;
}
@JsonProperty("date10")
public DateTime getDate10() {
return date10;
}
@JsonProperty("date10")
public void setDate10(DateTime date10) {
this.date10 = date10;
}
@JsonProperty("dateAdded")
public DateTime getDateAdded() {
return dateAdded;
}
@JsonProperty("dateAdded")
public void setDateAdded(DateTime dateAdded) {
this.dateAdded = dateAdded;
}
@JsonProperty("dateLastModified")
public DateTime getDateLastModified() {
return dateLastModified;
}
@JsonProperty("dateLastModified")
public void setDateLastModified(DateTime dateLastModified) {
this.dateLastModified = dateLastModified;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CustomObjectInstance that = (CustomObjectInstance) o;
if (id != null ? !id.equals(that.id) : that.id != null) return false;
if (text1 != null ? !text1.equals(that.text1) : that.text1 != null) return false;
if (text2 != null ? !text2.equals(that.text2) : that.text2 != null) return false;
if (text3 != null ? !text3.equals(that.text3) : that.text3 != null) return false;
if (text4 != null ? !text4.equals(that.text4) : that.text4 != null) return false;
if (text5 != null ? !text5.equals(that.text5) : that.text5 != null) return false;
if (text6 != null ? !text6.equals(that.text6) : that.text6 != null) return false;
if (text7 != null ? !text7.equals(that.text7) : that.text7 != null) return false;
if (text8 != null ? !text8.equals(that.text8) : that.text8 != null) return false;
if (text9 != null ? !text9.equals(that.text9) : that.text9 != null) return false;
if (text10 != null ? !text10.equals(that.text10) : that.text10 != null) return false;
if (text11 != null ? !text11.equals(that.text11) : that.text11 != null) return false;
if (text12 != null ? !text12.equals(that.text12) : that.text12 != null) return false;
if (text13 != null ? !text13.equals(that.text13) : that.text13 != null) return false;
if (text14 != null ? !text14.equals(that.text14) : that.text14 != null) return false;
if (text15 != null ? !text15.equals(that.text15) : that.text15 != null) return false;
if (text16 != null ? !text16.equals(that.text16) : that.text16 != null) return false;
if (text17 != null ? !text17.equals(that.text17) : that.text17 != null) return false;
if (text18 != null ? !text18.equals(that.text18) : that.text18 != null) return false;
if (text19 != null ? !text19.equals(that.text19) : that.text19 != null) return false;
if (text20 != null ? !text20.equals(that.text20) : that.text20 != null) return false;
if (int1 != null ? !int1.equals(that.int1) : that.int1 != null) return false;
if (int2 != null ? !int2.equals(that.int2) : that.int2 != null) return false;
if (int3 != null ? !int3.equals(that.int3) : that.int3 != null) return false;
if (int4 != null ? !int4.equals(that.int4) : that.int4 != null) return false;
if (int5 != null ? !int5.equals(that.int5) : that.int5 != null) return false;
if (int6 != null ? !int6.equals(that.int6) : that.int6 != null) return false;
if (int7 != null ? !int7.equals(that.int7) : that.int7 != null) return false;
if (int8 != null ? !int8.equals(that.int8) : that.int8 != null) return false;
if (int9 != null ? !int9.equals(that.int9) : that.int9 != null) return false;
if (int10 != null ? !int10.equals(that.int10) : that.int10 != null) return false;
if (float1 != null ? !float1.equals(that.float1) : that.float1 != null) return false;
if (float2 != null ? !float2.equals(that.float2) : that.float2 != null) return false;
if (float3 != null ? !float3.equals(that.float3) : that.float3 != null) return false;
if (float4 != null ? !float4.equals(that.float4) : that.float4 != null) return false;
if (float5 != null ? !float5.equals(that.float5) : that.float5 != null) return false;
if (float6 != null ? !float6.equals(that.float6) : that.float6 != null) return false;
if (float7 != null ? !float7.equals(that.float7) : that.float7 != null) return false;
if (float8 != null ? !float8.equals(that.float8) : that.float8 != null) return false;
if (float9 != null ? !float9.equals(that.float9) : that.float9 != null) return false;
if (float10 != null ? !float10.equals(that.float10) : that.float10 != null) return false;
if (textBlock1 != null ? !textBlock1.equals(that.textBlock1) : that.textBlock1 != null) return false;
if (textBlock2 != null ? !textBlock2.equals(that.textBlock2) : that.textBlock2 != null) return false;
if (textBlock3 != null ? !textBlock3.equals(that.textBlock3) : that.textBlock3 != null) return false;
if (textBlock4 != null ? !textBlock4.equals(that.textBlock4) : that.textBlock4 != null) return false;
if (textBlock5 != null ? !textBlock5.equals(that.textBlock5) : that.textBlock5 != null) return false;
if (date1 != null ? !date1.equals(that.date1) : that.date1 != null) return false;
if (date2 != null ? !date2.equals(that.date2) : that.date2 != null) return false;
if (date3 != null ? !date3.equals(that.date3) : that.date3 != null) return false;
if (date4 != null ? !date4.equals(that.date4) : that.date4 != null) return false;
if (date5 != null ? !date5.equals(that.date5) : that.date5 != null) return false;
if (date6 != null ? !date6.equals(that.date6) : that.date6 != null) return false;
if (date7 != null ? !date7.equals(that.date7) : that.date7 != null) return false;
if (date8 != null ? !date8.equals(that.date8) : that.date8 != null) return false;
if (date9 != null ? !date9.equals(that.date9) : that.date9 != null) return false;
if (date10 != null ? !date10.equals(that.date10) : that.date10 != null) return false;
if (dateAdded != null ? !dateAdded.equals(that.dateAdded) : that.dateAdded != null) return false;
return !(dateLastModified != null ? !dateLastModified.equals(that.dateLastModified) : that.dateLastModified != null);
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (text1 != null ? text1.hashCode() : 0);
result = 31 * result + (text2 != null ? text2.hashCode() : 0);
result = 31 * result + (text3 != null ? text3.hashCode() : 0);
result = 31 * result + (text4 != null ? text4.hashCode() : 0);
result = 31 * result + (text5 != null ? text5.hashCode() : 0);
result = 31 * result + (text6 != null ? text6.hashCode() : 0);
result = 31 * result + (text7 != null ? text7.hashCode() : 0);
result = 31 * result + (text8 != null ? text8.hashCode() : 0);
result = 31 * result + (text9 != null ? text9.hashCode() : 0);
result = 31 * result + (text10 != null ? text10.hashCode() : 0);
result = 31 * result + (text11 != null ? text11.hashCode() : 0);
result = 31 * result + (text12 != null ? text12.hashCode() : 0);
result = 31 * result + (text13 != null ? text13.hashCode() : 0);
result = 31 * result + (text14 != null ? text14.hashCode() : 0);
result = 31 * result + (text15 != null ? text15.hashCode() : 0);
result = 31 * result + (text16 != null ? text16.hashCode() : 0);
result = 31 * result + (text17 != null ? text17.hashCode() : 0);
result = 31 * result + (text18 != null ? text18.hashCode() : 0);
result = 31 * result + (text19 != null ? text19.hashCode() : 0);
result = 31 * result + (text20 != null ? text20.hashCode() : 0);
result = 31 * result + (int1 != null ? int1.hashCode() : 0);
result = 31 * result + (int2 != null ? int2.hashCode() : 0);
result = 31 * result + (int3 != null ? int3.hashCode() : 0);
result = 31 * result + (int4 != null ? int4.hashCode() : 0);
result = 31 * result + (int5 != null ? int5.hashCode() : 0);
result = 31 * result + (int6 != null ? int6.hashCode() : 0);
result = 31 * result + (int7 != null ? int7.hashCode() : 0);
result = 31 * result + (int8 != null ? int8.hashCode() : 0);
result = 31 * result + (int9 != null ? int9.hashCode() : 0);
result = 31 * result + (int10 != null ? int10.hashCode() : 0);
result = 31 * result + (float1 != null ? float1.hashCode() : 0);
result = 31 * result + (float2 != null ? float2.hashCode() : 0);
result = 31 * result + (float3 != null ? float3.hashCode() : 0);
result = 31 * result + (float4 != null ? float4.hashCode() : 0);
result = 31 * result + (float5 != null ? float5.hashCode() : 0);
result = 31 * result + (float6 != null ? float6.hashCode() : 0);
result = 31 * result + (float7 != null ? float7.hashCode() : 0);
result = 31 * result + (float8 != null ? float8.hashCode() : 0);
result = 31 * result + (float9 != null ? float9.hashCode() : 0);
result = 31 * result + (float10 != null ? float10.hashCode() : 0);
result = 31 * result + (textBlock1 != null ? textBlock1.hashCode() : 0);
result = 31 * result + (textBlock2 != null ? textBlock2.hashCode() : 0);
result = 31 * result + (textBlock3 != null ? textBlock3.hashCode() : 0);
result = 31 * result + (textBlock4 != null ? textBlock4.hashCode() : 0);
result = 31 * result + (textBlock5 != null ? textBlock5.hashCode() : 0);
result = 31 * result + (date1 != null ? date1.hashCode() : 0);
result = 31 * result + (date2 != null ? date2.hashCode() : 0);
result = 31 * result + (date3 != null ? date3.hashCode() : 0);
result = 31 * result + (date4 != null ? date4.hashCode() : 0);
result = 31 * result + (date5 != null ? date5.hashCode() : 0);
result = 31 * result + (date6 != null ? date6.hashCode() : 0);
result = 31 * result + (date7 != null ? date7.hashCode() : 0);
result = 31 * result + (date8 != null ? date8.hashCode() : 0);
result = 31 * result + (date9 != null ? date9.hashCode() : 0);
result = 31 * result + (date10 != null ? date10.hashCode() : 0);
result = 31 * result + (dateAdded != null ? dateAdded.hashCode() : 0);
result = 31 * result + (dateLastModified != null ? dateLastModified.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "CustomObjectInstance{" +
"id=" + id +
", text1='" + text1 + '\'' +
", text2='" + text2 + '\'' +
", text3='" + text3 + '\'' +
", text4='" + text4 + '\'' +
", text5='" + text5 + '\'' +
", text6='" + text6 + '\'' +
", text7='" + text7 + '\'' +
", text8='" + text8 + '\'' +
", text9='" + text9 + '\'' +
", text10='" + text10 + '\'' +
", text11='" + text11 + '\'' +
", text12='" + text12 + '\'' +
", text13='" + text13 + '\'' +
", text14='" + text14 + '\'' +
", text15='" + text15 + '\'' +
", text16='" + text16 + '\'' +
", text17='" + text17 + '\'' +
", text18='" + text18 + '\'' +
", text19='" + text19 + '\'' +
", text20='" + text20 + '\'' +
", int1=" + int1 +
", int2=" + int2 +
", int3=" + int3 +
", int4=" + int4 +
", int5=" + int5 +
", int6=" + int6 +
", int7=" + int7 +
", int8=" + int8 +
", int9=" + int9 +
", int10=" + int10 +
", float1=" + float1 +
", float2=" + float2 +
", float3=" + float3 +
", float4=" + float4 +
", float5=" + float5 +
", float6=" + float6 +
", float7=" + float7 +
", float8=" + float8 +
", float9=" + float9 +
", float10=" + float10 +
", textBlock1='" + textBlock1 + '\'' +
", textBlock2='" + textBlock2 + '\'' +
", textBlock3='" + textBlock3 + '\'' +
", textBlock4='" + textBlock4 + '\'' +
", textBlock5='" + textBlock5 + '\'' +
", date1=" + date1 +
", date2=" + date2 +
", date3=" + date3 +
", date4=" + date4 +
", date5=" + date5 +
", date6=" + date6 +
", date7=" + date7 +
", date8=" + date8 +
", date9=" + date9 +
", date10=" + date10 +
", dateAdded=" + dateAdded +
", dateLastModified=" + dateLastModified +
'}';
}
} |
package com.github.aesteve.vertx.nubes.reflections.injectors.typed;
import io.vertx.ext.web.RoutingContext;
@FunctionalInterface
public interface ParamInjector<T> {
public T resolve(RoutingContext context);
} |
package com.pearson.statsagg.database_objects.metric_last_seen;
import com.google.common.collect.Lists;
import com.pearson.statsagg.database_engine.DatabaseInterface;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import com.pearson.statsagg.database_engine.DatabaseObjectDao;
import com.pearson.statsagg.globals.DatabaseConfiguration;
import com.pearson.statsagg.utilities.StackTrace;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Jeffrey Schmidt
*/
public class MetricLastSeenDao extends DatabaseObjectDao<MetricLastSeen> {
private static final Logger logger = LoggerFactory.getLogger(MetricLastSeenDao.class.getName());
private final String tableName_ = "METRIC_LAST_SEEN";
public MetricLastSeenDao(){}
public MetricLastSeenDao(boolean closeConnectionAfterOperation) {
databaseInterface_.setCloseConnectionAfterOperation(closeConnectionAfterOperation);
}
public MetricLastSeenDao(DatabaseInterface databaseInterface) {
super(databaseInterface);
}
public boolean dropTable() {
return dropTable(MetricLastSeenSql.DropTable_MetricLastSeen);
}
public boolean createTable() {
List<String> databaseCreationSqlStatements = new ArrayList<>();
if (DatabaseConfiguration.getType() == DatabaseConfiguration.MYSQL) {
databaseCreationSqlStatements.add(MetricLastSeenSql.CreateTable_MetricLastSeen_MySQL);
}
else {
databaseCreationSqlStatements.add(MetricLastSeenSql.CreateTable_MetricLastSeen_Derby);
}
databaseCreationSqlStatements.add(MetricLastSeenSql.CreateIndex_MetricLastSeen_PrimaryKey);
return createTable(databaseCreationSqlStatements);
}
@Override
public MetricLastSeen getDatabaseObject(MetricLastSeen metricLastSeen) {
if (metricLastSeen == null) return null;
return getDatabaseObject(MetricLastSeenSql.Select_MetricLastSeen_ByPrimaryKey,
metricLastSeen.getMetricKeySha1());
}
@Override
public boolean insert(MetricLastSeen metricLastSeen) {
if (metricLastSeen == null) return false;
return insert(MetricLastSeenSql.Insert_MetricLastSeen,
metricLastSeen.getMetricKeySha1(), metricLastSeen.getMetricKey(), metricLastSeen.getLastModified());
}
@Override
public boolean update(MetricLastSeen metricLastSeen) {
if (metricLastSeen == null) return false;
return update(MetricLastSeenSql.Update_MetricLastSeen_ByPrimaryKey,
metricLastSeen.getMetricKey(), metricLastSeen.getLastModified(), metricLastSeen.getMetricKeySha1());
}
@Override
public boolean delete(MetricLastSeen metricLastSeen) {
if (metricLastSeen == null) return false;
return delete(MetricLastSeenSql.Delete_MetricLastSeen_ByPrimaryKey,
metricLastSeen.getMetricKeySha1());
}
@Override
public MetricLastSeen processSingleResultAllColumns(ResultSet resultSet) {
try {
if ((resultSet == null) || resultSet.isClosed()) {
return null;
}
String metricKeySha1 = resultSet.getString("METRIC_KEY_SHA1");
if (resultSet.wasNull()) metricKeySha1 = null;
String metricKey = resultSet.getString("METRIC_KEY");
if (resultSet.wasNull()) metricKey = null;
Timestamp lastModified = resultSet.getTimestamp("LAST_MODIFIED");
if (resultSet.wasNull()) lastModified = null;
MetricLastSeen metricLastSeen = new MetricLastSeen(metricKeySha1, metricKey, lastModified);
return metricLastSeen;
}
catch (Exception e) {
logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
return null;
}
}
@Override
public String getTableName() {
return tableName_;
}
public MetricLastSeen getMetricLastSeen(String metricKeySha1) {
return getDatabaseObject(MetricLastSeenSql.Select_MetricLastSeen_ByPrimaryKey,
metricKeySha1);
}
public boolean delete(String metricKeySha1) {
return delete(MetricLastSeenSql.Delete_MetricLastSeen_ByPrimaryKey,
metricKeySha1);
}
public boolean batchUpsert(List<MetricLastSeen> metricLastSeens) {
if ((metricLastSeens == null) || metricLastSeens.isEmpty()) {
return false;
}
if (DatabaseConfiguration.getType() == DatabaseConfiguration.MYSQL) {
boolean wasAllUpsertSuccess = true;
List<List<MetricLastSeen>> metricLastSeenPartitions = Lists.partition(metricLastSeens, 1000);
for (List<MetricLastSeen> metricLastSeenPartition : metricLastSeenPartitions) {
List<Object> parameters = new ArrayList<>();
for (MetricLastSeen metricLastSeen : metricLastSeenPartition) {
parameters.add(metricLastSeen.getMetricKeySha1());
parameters.add(metricLastSeen.getMetricKey());
parameters.add(metricLastSeen.getLastModified());
}
boolean wasUpsertSuccess = genericDmlStatement(MetricLastSeenSql.generateBatchUpsert(metricLastSeenPartition.size()), parameters);
if (!wasUpsertSuccess) wasAllUpsertSuccess = false;
}
return wasAllUpsertSuccess;
}
else if (!databaseInterface_.isManualTransactionControl()) {
return upsert(metricLastSeens, true);
}
else {
boolean wasAllUpsertSuccess = true;
for (MetricLastSeen metricLastSeen : metricLastSeens) {
boolean wasUpsertSuccess = upsert(metricLastSeen);
if (!wasUpsertSuccess) wasAllUpsertSuccess = false;
}
return wasAllUpsertSuccess;
}
}
} |
package fi.otavanopisto.kuntaapi.server.integrations.ptv;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.AccessTimeout;
import javax.ejb.Singleton;
import javax.ejb.TimerService;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.event.Event;
import javax.inject.Inject;
import fi.metatavu.kuntaapi.server.rest.model.LocalizedValue;
import fi.metatavu.kuntaapi.server.rest.model.Service;
import fi.metatavu.kuntaapi.server.rest.model.ServiceOrganization;
import fi.metatavu.ptv.client.ApiResponse;
import fi.metatavu.ptv.client.model.V4VmOpenApiService;
import fi.metatavu.ptv.client.model.V4VmOpenApiServiceOrganization;
import fi.metatavu.ptv.client.model.V4VmOpenApiServiceServiceChannel;
import fi.otavanopisto.kuntaapi.server.cache.ModificationHashCache;
import fi.otavanopisto.kuntaapi.server.controllers.IdentifierController;
import fi.otavanopisto.kuntaapi.server.discover.EntityUpdater;
import fi.otavanopisto.kuntaapi.server.id.ElectronicServiceChannelId;
import fi.otavanopisto.kuntaapi.server.id.IdController;
import fi.otavanopisto.kuntaapi.server.id.OrganizationId;
import fi.otavanopisto.kuntaapi.server.id.PhoneServiceChannelId;
import fi.otavanopisto.kuntaapi.server.id.PrintableFormServiceChannelId;
import fi.otavanopisto.kuntaapi.server.id.ServiceId;
import fi.otavanopisto.kuntaapi.server.id.ServiceLocationServiceChannelId;
import fi.otavanopisto.kuntaapi.server.id.WebPageServiceChannelId;
import fi.otavanopisto.kuntaapi.server.index.IndexRemoveRequest;
import fi.otavanopisto.kuntaapi.server.index.IndexRemoveService;
import fi.otavanopisto.kuntaapi.server.index.IndexRequest;
import fi.otavanopisto.kuntaapi.server.index.IndexableService;
import fi.otavanopisto.kuntaapi.server.integrations.KuntaApiConsts;
import fi.otavanopisto.kuntaapi.server.integrations.KuntaApiIdFactory;
import fi.otavanopisto.kuntaapi.server.integrations.management.ManagementConsts;
import fi.otavanopisto.kuntaapi.server.integrations.ptv.client.PtvApi;
import fi.otavanopisto.kuntaapi.server.integrations.ptv.tasks.ServiceIdTaskQueue;
import fi.otavanopisto.kuntaapi.server.persistence.model.Identifier;
import fi.otavanopisto.kuntaapi.server.settings.SystemSettingController;
import fi.otavanopisto.kuntaapi.server.tasks.IdTask;
import fi.otavanopisto.kuntaapi.server.tasks.IdTask.Operation;
import fi.otavanopisto.kuntaapi.server.utils.LocalizationUtils;
@ApplicationScoped
@Singleton
@AccessTimeout (unit = TimeUnit.HOURS, value = 1l)
@SuppressWarnings ("squid:S3306")
public class PtvServiceEntityUpdater extends EntityUpdater {
@Inject
private Logger logger;
@Inject
private SystemSettingController systemSettingController;
@Inject
private PtvApi ptvApi;
@Inject
private PtvIdFactory ptvIdFactory;
@Inject
private KuntaApiIdFactory kuntaApiIdFactory;
@Inject
private PtvTranslator ptvTranslator;
@Inject
private IdController idController;
@Inject
private IdentifierController identifierController;
@Inject
private PtvServiceResourceContainer ptvServiceResourceContainer;
@Inject
private ModificationHashCache modificationHashCache;
@Inject
private ServiceIdTaskQueue serviceIdTaskQueue;
@Inject
private Event<IndexRequest> indexRequest;
@Inject
private Event<IndexRemoveRequest> indexRemoveRequest;
@Resource
private TimerService timerService;
@Override
public String getName() {
return "ptv-services";
}
@Override
public void timeout() {
executeNextTask();
}
@Override
public TimerService getTimerService() {
return timerService;
}
private void executeNextTask() {
IdTask<ServiceId> task = serviceIdTaskQueue.next();
if (task != null) {
if (task.getOperation() == Operation.UPDATE) {
updatePtvService(task.getId(), task.getOrderIndex());
} else if (task.getOperation() == Operation.REMOVE) {
deletePtvService(task.getId());
}
}
}
private void updatePtvService(ServiceId ptvServiceId, Long orderIndex) {
if (!systemSettingController.hasSettingValue(PtvConsts.SYSTEM_SETTING_BASEURL)) {
logger.log(Level.INFO, "Ptv system setting not defined, skipping update.");
return;
}
ApiResponse<V4VmOpenApiService> response = ptvApi.getServiceApi().apiV4ServiceByIdGet(ptvServiceId.getId());
if (response.isOk()) {
Identifier identifier = identifierController.acquireIdentifier(orderIndex, ptvServiceId);
V4VmOpenApiService ptvService = response.getResponse();
ServiceId kuntaApiServiceId = kuntaApiIdFactory.createFromIdentifier(ServiceId.class, identifier);
fi.metatavu.kuntaapi.server.rest.model.Service service = translateService(ptvService, kuntaApiServiceId);
if (service != null) {
ptvServiceResourceContainer.put(kuntaApiServiceId, service);
modificationHashCache.put(identifier.getKuntaApiId(), createPojoHash(service));
index(identifier.getKuntaApiId(), service, orderIndex);
}
} else {
logger.warning(String.format("Service %s processing failed on [%d] %s", ptvServiceId.getId(), response.getStatus(), response.getMessage()));
}
}
private fi.metatavu.kuntaapi.server.rest.model.Service translateService(V4VmOpenApiService ptvService, ServiceId kuntaApiServiceId) {
List<V4VmOpenApiServiceServiceChannel> serviceChannels = ptvService.getServiceChannels();
List<ElectronicServiceChannelId> kuntaApiElectronicServiceChannelIds = new ArrayList<>();
List<PhoneServiceChannelId> kuntaApiPhoneServiceChannelIds = new ArrayList<>();
List<PrintableFormServiceChannelId> kuntaApiPrintableFormServiceChannelIds = new ArrayList<>();
List<ServiceLocationServiceChannelId> kuntaApiServiceLocationServiceChannelIds = new ArrayList<>();
List<WebPageServiceChannelId> kuntaApiWebPageServiceChannelIds = new ArrayList<>();
for (V4VmOpenApiServiceServiceChannel serviceChannel : serviceChannels) {
sortServiceChannel(kuntaApiElectronicServiceChannelIds, kuntaApiPhoneServiceChannelIds,
kuntaApiPrintableFormServiceChannelIds, kuntaApiServiceLocationServiceChannelIds,
kuntaApiWebPageServiceChannelIds, serviceChannel);
}
List<ServiceOrganization> serviceOrganizations = translateServiceOrganizations(ptvService.getOrganizations());
return ptvTranslator.translateService(kuntaApiServiceId,
kuntaApiElectronicServiceChannelIds,
kuntaApiPhoneServiceChannelIds,
kuntaApiPrintableFormServiceChannelIds,
kuntaApiServiceLocationServiceChannelIds,
kuntaApiWebPageServiceChannelIds,
serviceOrganizations,
ptvService);
}
private void sortServiceChannel(List<ElectronicServiceChannelId> kuntaApiElectronicServiceChannelIds,
List<PhoneServiceChannelId> kuntaApiPhoneServiceChannelIds,
List<PrintableFormServiceChannelId> kuntaApiPrintableFormServiceChannelIds,
List<ServiceLocationServiceChannelId> kuntaApiServiceLocationServiceChannelIds,
List<WebPageServiceChannelId> kuntaApiWebPageServiceChannelIds, V4VmOpenApiServiceServiceChannel serviceChannel) {
String serviceChannelId = serviceChannel.getServiceChannelId();
ElectronicServiceChannelId kuntaApiElectronicServiceChannelId = idController.translateElectronicServiceChannelId(ptvIdFactory.createElectronicServiceChannelId(serviceChannelId), KuntaApiConsts.IDENTIFIER_NAME);
if (kuntaApiElectronicServiceChannelId != null) {
kuntaApiElectronicServiceChannelIds.add(kuntaApiElectronicServiceChannelId);
return;
}
PhoneServiceChannelId kuntaApiPhoneServiceChannelId = idController.translatePhoneServiceChannelId(ptvIdFactory.createPhoneServiceChannelId(serviceChannelId), KuntaApiConsts.IDENTIFIER_NAME);
if (kuntaApiPhoneServiceChannelId != null) {
kuntaApiPhoneServiceChannelIds.add(kuntaApiPhoneServiceChannelId);
return;
}
PrintableFormServiceChannelId kuntaApiPrintableFormServiceChannelId = idController.translatePrintableFormServiceChannelId(ptvIdFactory.createPrintableFormServiceChannelId(serviceChannelId), KuntaApiConsts.IDENTIFIER_NAME);
if (kuntaApiPrintableFormServiceChannelId != null) {
kuntaApiPrintableFormServiceChannelIds.add(kuntaApiPrintableFormServiceChannelId);
return;
}
ServiceLocationServiceChannelId kuntaApiServiceLocationServiceChannelId = idController.translateServiceLocationServiceChannelId(ptvIdFactory.createServiceLocationServiceChannelId(serviceChannelId), KuntaApiConsts.IDENTIFIER_NAME);
if (kuntaApiServiceLocationServiceChannelId != null) {
kuntaApiServiceLocationServiceChannelIds.add(kuntaApiServiceLocationServiceChannelId);
return;
}
WebPageServiceChannelId kuntaApiWebPageServiceChannelId = idController.translateWebPageServiceChannelId(ptvIdFactory.createWebPageServiceChannelId(serviceChannelId), KuntaApiConsts.IDENTIFIER_NAME);
if (kuntaApiWebPageServiceChannelId != null) {
kuntaApiWebPageServiceChannelIds.add(kuntaApiWebPageServiceChannelId);
return;
}
logger.log(Level.WARNING, () -> String.format("Failed to resolve service channel %s type", serviceChannelId));
}
private List<ServiceOrganization> translateServiceOrganizations(List<V4VmOpenApiServiceOrganization> ptvServiceOrganizations) {
if (ptvServiceOrganizations == null) {
return Collections.emptyList();
}
List<ServiceOrganization> result = new ArrayList<>(ptvServiceOrganizations.size());
for (V4VmOpenApiServiceOrganization ptvServiceOrganization : ptvServiceOrganizations) {
OrganizationId ptvOrganizationId = ptvIdFactory.createOrganizationId(ptvServiceOrganization.getOrganizationId());
OrganizationId kuntaApiOrganizationId = idController.translateOrganizationId(ptvOrganizationId, KuntaApiConsts.IDENTIFIER_NAME);
if (kuntaApiOrganizationId != null) {
result.add(ptvTranslator.translateServiceOrganization(kuntaApiOrganizationId, ptvServiceOrganization));
} else {
logger.log(Level.SEVERE, () -> String.format("Failed to translate organization %s into Kunta API id", ptvOrganizationId));
}
}
return result;
}
private void index(String serviceId, Service service, Long orderIndex) {
List<LocalizedValue> descriptions = service.getDescriptions();
List<LocalizedValue> names = service.getNames();
List<String> organizationIds = new ArrayList<>(service.getOrganizations().size());
for (ServiceOrganization serviceOrganization : service.getOrganizations()) {
organizationIds.add(serviceOrganization.getOrganizationId());
}
for (String language : LocalizationUtils.getListsLanguages(names, descriptions)) {
IndexableService indexableService = new IndexableService();
indexableService.setShortDescription(LocalizationUtils.getBestMatchingValue("ShortDescription", descriptions, language, PtvConsts.DEFAULT_LANGUAGE));
indexableService.setDescription(LocalizationUtils.getBestMatchingValue("Description", descriptions, language, PtvConsts.DEFAULT_LANGUAGE));
indexableService.setUserInstruction(LocalizationUtils.getBestMatchingValue("ServiceUserInstruction", descriptions, language, PtvConsts.DEFAULT_LANGUAGE));
indexableService.setKeywords(LocalizationUtils.getLocaleValues(service.getKeywords(), PtvConsts.DEFAULT_LANGUAGE));
indexableService.setLanguage(language);
indexableService.setName(LocalizationUtils.getBestMatchingValue("Name", names, language, PtvConsts.DEFAULT_LANGUAGE));
indexableService.setAlternativeName(LocalizationUtils.getBestMatchingValue("AlternativeName", names, language, PtvConsts.DEFAULT_LANGUAGE));
indexableService.setServiceId(serviceId);
indexableService.setOrganizationIds(organizationIds);
indexableService.setOrderIndex(orderIndex);
indexRequest.fire(new IndexRequest(indexableService));
}
}
private void deletePtvService(ServiceId ptvServiceId) {
Identifier serviceIdentifier = identifierController.findIdentifierById(ptvServiceId);
if (serviceIdentifier != null) {
ServiceId kuntaApiServiceId = new ServiceId(KuntaApiConsts.IDENTIFIER_NAME, serviceIdentifier.getKuntaApiId());
modificationHashCache.clear(serviceIdentifier.getKuntaApiId());
ptvServiceResourceContainer.clear(kuntaApiServiceId);
identifierController.deleteIdentifier(serviceIdentifier);
IndexRemoveService indexRemove = new IndexRemoveService();
indexRemove.setServiceId(kuntaApiServiceId.getId());
indexRemove.setLanguage(ManagementConsts.DEFAULT_LOCALE);
indexRemoveRequest.fire(new IndexRemoveRequest(indexRemove));
}
}
} |
package de.st_ddt.crazyutil.databases;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import org.bukkit.Bukkit;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.plugin.java.JavaPlugin;
public class ConfigurationDatabase<S extends ConfigurationDatabaseEntry> extends BasicDatabase<S>
{
private final JavaPlugin plugin;
final ConfigurationSection config;
final String path;
final String[] columnNames;
private final Runnable delayedSave = new Runnable()
{
@Override
public void run()
{
if (requireSave)
saveDatabaseDelayed();
}
};
private boolean requireSave = false;
public ConfigurationDatabase(final Class<S> clazz, final String[] defaultColumnNames, final String defaultPath, final JavaPlugin plugin, final ConfigurationSection config)
{
super(DatabaseType.CONFIG, clazz, defaultColumnNames);
this.plugin = plugin;
this.config = plugin.getConfig();
if (config == null)
{
this.path = defaultPath;
this.columnNames = defaultColumnNames;
}
else
{
this.path = config.getString("CONFIG.path", defaultPath);
this.columnNames = new String[defaultColumnNames.length];
for (int i = 0; i < defaultColumnNames.length; i++)
columnNames[i] = config.getString("CONFIG.columns." + defaultColumnNames[i], defaultColumnNames[i]);
}
}
public ConfigurationDatabase(final Class<S> clazz, final String[] defaultColumnNames, final JavaPlugin plugin, final String path, final String[] columnNames)
{
super(DatabaseType.CONFIG, clazz, defaultColumnNames);
this.plugin = plugin;
this.config = plugin.getConfig();
this.path = path;
this.columnNames = columnNames;
}
@Override
Constructor<S> getConstructor(final Class<S> clazz)
{
try
{
return clazz.getConstructor(ConfigurationSection.class, String[].class);
}
catch (final Exception e)
{
e.printStackTrace();
return null;
}
}
@Override
public void initialize()
{
loadAllEntries();
}
@Override
public final boolean isStaticDatabase()
{
return true;
}
@Override
public final boolean isCachedDatabase()
{
return true;
}
@Override
public final S updateEntry(final String key)
{
return getEntry(key);
}
@Override
public S loadEntry(final String key)
{
ConfigurationSection section = config.getConfigurationSection(path + "." + key.toLowerCase());
final boolean nameCase;
if (section == null)
{
section = config.getConfigurationSection(path + "." + key);
nameCase = true;
}
else
nameCase = false;
if (section == null)
return null;
try
{
final S data = constructor.newInstance(section, columnNames);
if (data.getName() == null)
{
System.err.println("Entry " + key + " was corrupted and could be fixed.");
if (nameCase)
config.set(path + "." + key + "." + columnNames[0], key);
else
config.set(path + "." + key.toLowerCase() + "." + columnNames[0], key);
return loadEntry(key);
}
datas.put(data.getName().toLowerCase(), data);
if (nameCase || !key.equals(data.getName()))
{
config.set(path + "." + key, null);
save(data);
}
return data;
}
catch (final InvocationTargetException e)
{
System.err.println("Error occured while trying to load entry: " + key);
shortPrintStackTrace(e, e.getCause());
return null;
}
catch (final Exception e)
{
System.err.println("Error occured while trying to load entry: " + key);
e.printStackTrace();
return null;
}
}
@Override
public void loadAllEntries()
{
if (config.getConfigurationSection(path) == null)
return;
for (final String key : config.getConfigurationSection(path).getKeys(false))
loadEntry(key);
}
@Override
public boolean deleteEntry(final String key)
{
config.set(path + "." + key.toLowerCase(), null);
final boolean res = super.deleteEntry(key);
asyncSaveDatabase();
return res;
}
@Override
public void save(final S entry)
{
if (entry == null)
return;
super.save(entry);
entry.saveToConfigDatabase(config, path + "." + entry.getName().toLowerCase() + ".", columnNames);
asyncSaveDatabase();
}
@Override
public void saveAll(final Collection<S> entries)
{
for (final S entry : entries)
{
super.save(entry);
entry.saveToConfigDatabase(config, path + "." + entry.getName().toLowerCase() + ".", columnNames);
}
asyncSaveDatabase();
}
@Override
public void purgeDatabase()
{
config.set(path, null);
super.purgeDatabase();
}
@Override
public void saveDatabase()
{
synchronized (getDatabaseLock())
{
for (final S entry : datas.values())
if (entry != null)
entry.saveToConfigDatabase(config, path + "." + entry.getName().toLowerCase() + ".", columnNames);
}
plugin.saveConfig();
}
@SuppressWarnings("deprecation")
final void asyncSaveDatabase()
{
if (!requireSave)
{
requireSave = true;
Bukkit.getScheduler().scheduleAsyncDelayedTask(plugin, delayedSave);
}
}
private void saveDatabaseDelayed()
{
plugin.saveConfig();
requireSave = false;
}
@Override
public void save(final ConfigurationSection config, final String path)
{
super.save(config, path);
config.set(path + "CONFIG.path", this.path);
for (int i = 0; i < defaultColumnNames.length; i++)
config.set(path + "CONFIG.columns." + defaultColumnNames[i], columnNames[i]);
}
} |
package dr.evomodelxml.coalescent;
import dr.evolution.util.Units;
import dr.evomodel.coalescent.ExponentialGrowthModel;
import dr.evomodel.coalescent.PowerLawGrowthModel;
import dr.evoxml.util.XMLUnits;
import dr.inference.model.Parameter;
import dr.xml.*;
/**
* Parses an element from an DOM document into a ExponentialGrowth.
*/
public class PowerLawGrowthModelParser extends AbstractXMLObjectParser {
public static String N0 = "n0";
public static String POWER_LAW_GROWTH_MODEL = "powerLawGrowth";
public static String POWER = "power";
public String getParserName() {
return POWER_LAW_GROWTH_MODEL;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
Units.Type units = XMLUnits.Utils.getUnitsAttr(xo);
XMLObject cxo = xo.getChild(N0);
Parameter N0Param = (Parameter) cxo.getChild(Parameter.class);
Parameter rParam;
cxo = xo.getChild(POWER);
rParam = (Parameter) cxo.getChild(Parameter.class);
return new PowerLawGrowthModel(N0Param, rParam, units);
} |
package fh.prog.lab.it.samples.dbServices;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import static java.lang.System.out;
/**
* @author NET
*
*/
public class DBServicesInvoker {
//Credentials will be taken from here |
package org.mtransit.parser.ca_l_assomption_mrclasso_bus;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.mtransit.parser.DefaultAgencyTools;
import org.mtransit.parser.Utils;
import org.mtransit.parser.gtfs.data.GCalendar;
import org.mtransit.parser.gtfs.data.GCalendarDate;
import org.mtransit.parser.gtfs.data.GRoute;
import org.mtransit.parser.gtfs.data.GSpec;
import org.mtransit.parser.gtfs.data.GStop;
import org.mtransit.parser.gtfs.data.GTrip;
import org.mtransit.parser.mt.data.MAgency;
import org.mtransit.parser.mt.data.MRoute;
import org.mtransit.parser.CleanUtils;
import org.mtransit.parser.mt.data.MTrip;
public class LAssomptionMRCLASSOBusAgencyTools extends DefaultAgencyTools {
public static void main(String[] args) {
if (args == null || args.length == 0) {
args = new String[3];
args[0] = "input/gtfs.zip";
args[1] = "../../mtransitapps/ca-l-assomption-mrclasso-bus-android/res/raw/";
args[2] = ""; // files-prefix
}
new LAssomptionMRCLASSOBusAgencyTools().start(args);
}
private HashSet<String> serviceIds;
@Override
public void start(String[] args) {
System.out.printf("\nGenerating MRCLASSO bus data...");
long start = System.currentTimeMillis();
this.serviceIds = extractUsefulServiceIds(args, this);
super.start(args);
System.out.printf("\nGenerating MRCLASSO bus data... DONE in %s.\n", Utils.getPrettyDuration(System.currentTimeMillis() - start));
}
@Override
public boolean excludeCalendar(GCalendar gCalendar) {
if (this.serviceIds != null) {
return excludeUselessCalendar(gCalendar, this.serviceIds);
}
return super.excludeCalendar(gCalendar);
}
@Override
public boolean excludeCalendarDate(GCalendarDate gCalendarDates) {
if (this.serviceIds != null) {
return excludeUselessCalendarDate(gCalendarDates, this.serviceIds);
}
return super.excludeCalendarDate(gCalendarDates);
}
@Override
public boolean excludeTrip(GTrip gTrip) {
if (this.serviceIds != null) {
return excludeUselessTrip(gTrip, this.serviceIds);
}
return super.excludeTrip(gTrip);
}
@Override
public Integer getAgencyRouteType() {
return MAgency.ROUTE_TYPE_BUS;
}
private static final Pattern SECTEUR = Pattern.compile("(secteur[s]? )", Pattern.CASE_INSENSITIVE);
private static final String SECTEUR_REPLACEMENT = "";
@Override
public String getRouteLongName(GRoute gRoute) {
String routeLongName = gRoute.getRouteLongName();
routeLongName = CleanUtils.SAINT.matcher(routeLongName).replaceAll(CleanUtils.SAINT_REPLACEMENT);
routeLongName = SECTEUR.matcher(routeLongName).replaceAll(SECTEUR_REPLACEMENT);
return CleanUtils.cleanLabel(routeLongName);
}
private static final String AGENCY_COLOR = "00718F";
@Override
public String getAgencyColor() {
return AGENCY_COLOR;
}
private static final String COLOR_E680AD = "E680AD";
private static final String COLOR_A1A1A4 = "A1A1A4";
private static final String COLOR_99CB9A = "99CB9A";
private static final String COLOR_EF3B3A = "EF3B3A";
private static final String COLOR_E8B909 = "E8B909";
private static final String COLOR_067650 = "067650";
private static final String COLOR_1DA1DC = "1DA1DC";
private static final String COLOR_AAB41C = "AAB41C";
private static final String COLOR_D68119 = "D68119";
private static final String COLOR_A686AA = "A686AA";
private static final String COLOR_A74232 = "A74232";
private static final String COLOR_FDE900 = "FDE900";
private static final String COLOR_623F99 = "623F99";
private static final String RSN_1 = "1";
private static final String RSN_2 = "2";
private static final String RSN_5 = "5";
private static final String RSN_6 = "6";
private static final String RSN_8 = "8";
private static final String RSN_9 = "9";
private static final String RSN_11 = "11";
private static final String RSN_14 = "14";
private static final String RSN_15 = "15";
private static final String RSN_100 = "100";
private static final String RSN_101 = "101";
private static final String RSN_200 = "200";
private static final String RSN_300 = "300";
private static final String RSN_400 = "400";
@Override
public String getRouteColor(GRoute gRoute) {
if (RSN_1.equals(gRoute.getRouteShortName())) return COLOR_AAB41C;
if (RSN_2.equals(gRoute.getRouteShortName())) return COLOR_E680AD;
if (RSN_5.equals(gRoute.getRouteShortName())) return COLOR_A1A1A4;
if (RSN_6.equals(gRoute.getRouteShortName())) return COLOR_99CB9A;
if (RSN_8.equals(gRoute.getRouteShortName())) return COLOR_EF3B3A;
if (RSN_9.equals(gRoute.getRouteShortName())) return COLOR_E8B909;
if (RSN_11.equals(gRoute.getRouteShortName())) return COLOR_067650;
if (RSN_14.equals(gRoute.getRouteShortName())) return COLOR_1DA1DC;
if (RSN_15.equals(gRoute.getRouteShortName())) return COLOR_AAB41C;
if (RSN_100.equals(gRoute.getRouteShortName())) return COLOR_D68119;
if (RSN_101.equals(gRoute.getRouteShortName())) return COLOR_A686AA;
if (RSN_200.equals(gRoute.getRouteShortName())) return COLOR_A74232;
if (RSN_300.equals(gRoute.getRouteShortName())) return COLOR_FDE900;
if (RSN_400.equals(gRoute.getRouteShortName())) return COLOR_623F99;
return super.getRouteColor(gRoute);
}
@Override
public void setTripHeadsign(MRoute mRoute, MTrip mTrip, GTrip gTrip, GSpec gtfs) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), gTrip.getDirectionId());
}
@Override
public boolean mergeHeadsign(MTrip mTrip, MTrip mTripToMerge) {
List<String> headsignsValues = Arrays.asList(mTrip.getHeadsignValue(), mTripToMerge.getHeadsignValue());
if (mTrip.getRouteId() == 2L) {
if (Arrays.asList(
"St-Sulpice",
"Lavaltrie"
).containsAll(headsignsValues)) {
mTrip.setHeadsignString("Lavaltrie", mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 6L) {
if (Arrays.asList(
"Repentigny",
"Épiphanie"
).containsAll(headsignsValues)) {
mTrip.setHeadsignString("Épiphanie", mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 400L) {
if (Arrays.asList(
"Repentigny",
"Montréal"
).containsAll(headsignsValues)) {
mTrip.setHeadsignString("Montréal", mTrip.getHeadsignId());
return true;
} else if (Arrays.asList(
"Repentigny",
"Assomption"
).containsAll(headsignsValues)) {
mTrip.setHeadsignString("Assomption", mTrip.getHeadsignId());
return true;
}
}
System.out.printf("\nUnexpected trips to merge %s & %s!\n", mTrip, mTripToMerge);
System.exit(-1);
return false;
}
private static final Pattern DIRECTION = Pattern.compile("(direction )", Pattern.CASE_INSENSITIVE);
private static final String DIRECTION_REPLACEMENT = "";
@Override
public String cleanTripHeadsign(String tripHeadsign) {
tripHeadsign = DIRECTION.matcher(tripHeadsign).replaceAll(DIRECTION_REPLACEMENT);
return CleanUtils.cleanLabelFR(tripHeadsign);
}
private static final Pattern START_WITH_FACE_A = Pattern.compile("^(face à )", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
private static final Pattern START_WITH_FACE_AU = Pattern.compile("^(face au )", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
private static final Pattern START_WITH_FACE = Pattern.compile("^(face )", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
private static final Pattern SPACE_FACE_A = Pattern.compile("( face à )", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
private static final Pattern SPACE_WITH_FACE_AU = Pattern.compile("( face au )", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
private static final Pattern SPACE_WITH_FACE = Pattern.compile("( face )", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
private static final Pattern[] START_WITH_FACES = new Pattern[] { START_WITH_FACE_A, START_WITH_FACE_AU, START_WITH_FACE };
private static final Pattern[] SPACE_FACES = new Pattern[] { SPACE_FACE_A, SPACE_WITH_FACE_AU, SPACE_WITH_FACE };
private static final Pattern AVENUE = Pattern.compile("( avenue)", Pattern.CASE_INSENSITIVE);
private static final String AVENUE_REPLACEMENT = " av.";
@Override
public String cleanStopName(String gStopName) {
gStopName = AVENUE.matcher(gStopName).replaceAll(AVENUE_REPLACEMENT);
gStopName = Utils.replaceAll(gStopName, START_WITH_FACES, CleanUtils.SPACE);
gStopName = Utils.replaceAll(gStopName, SPACE_FACES, CleanUtils.SPACE);
return CleanUtils.cleanLabelFR(gStopName);
}
private static final String ZERO = "0";
@Override
public String getStopCode(GStop gStop) {
if (ZERO.equals(gStop.getStopCode())) {
return null;
}
return super.getStopCode(gStop);
}
private static final Pattern DIGITS = Pattern.compile("[\\d]+");
@Override
public int getStopId(GStop gStop) {
String stopCode = getStopCode(gStop);
if (stopCode != null && stopCode.length() > 0) {
return Integer.valueOf(stopCode); // using stop code as stop ID
}
Matcher matcher = DIGITS.matcher(gStop.getStopId());
if (matcher.find()) {
int digits = Integer.parseInt(matcher.group());
int stopId;
System.out.printf("\nStop doesn't have an ID (start with) %s!\n", gStop);
System.exit(-1);
stopId = -1;
System.out.printf("\nStop doesn't have an ID (end with) %s!\n", gStop);
System.exit(-1);
return stopId + digits;
}
System.out.printf("\nUnexpected stop ID for %s!\n", gStop);
System.exit(-1);
return -1;
}
} |
package org.jembi.rhea.flows;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static org.junit.Assert.*;
import java.io.IOException;
import java.util.Map;
import org.jembi.Util;
import org.jembi.rhea.RestfulHttpRequest;
import org.jembi.rhea.RestfulHttpResponse;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.mule.api.MuleException;
import org.mule.api.MuleMessage;
import org.mule.module.client.MuleClient;
import org.mule.tck.junit4.FunctionalTestCase;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
public class mediationSaveencounterDenormalizationOpenMRSSHRTest extends FunctionalTestCase {
@Rule
public WireMockRule wireMockRule = new WireMockRule(8003);
private void setupWebserviceStub(int httpStatus) {
stubFor(post(urlEqualTo("/openmrs/ws/rest/RHEA/patient/encounters?idType=NID&patientId=1234567890123"))
.willReturn(aResponse()
.withStatus(httpStatus)));
}
@Override
protected String getConfigResources() {
return "src/main/app/saveencounter-denormalization-openmrsshr.xml";
}
@Test
public void testSaveEncounterValidResponse() throws MuleException, IOException{
setupWebserviceStub(201);
MuleClient client = new MuleClient(muleContext);
Map<String, Object> properties = null;
RestfulHttpRequest req = new RestfulHttpRequest();
req.setHttpMethod(RestfulHttpRequest.HTTP_POST);
req.setPath("openmrs/ws/rest/v1/patient/NID-1234567890123/encounters");
req.setBody(Util.getResourceAsString("oru_r01.xml"));
MuleMessage result = client.send("vm://saveEncounters-De-normailization-OpenMRSSHR", (Object) req, properties);
Assert.assertTrue(result.getPayload() instanceof RestfulHttpResponse);
RestfulHttpResponse resp = (RestfulHttpResponse) result.getPayload();
assertEquals(201, resp.getHttpStatus());
}
@Test
public void testSaveEncounterResourceNotFound() throws MuleException, IOException{
setupWebserviceStub(404);
MuleClient client = new MuleClient(muleContext);
Map<String, Object> properties = null;
RestfulHttpRequest req = new RestfulHttpRequest();
req.setHttpMethod(RestfulHttpRequest.HTTP_POST);
req.setPath("openmrs/ws/rest/v1/patient/NID-1234567890123/encounters");
req.setBody(Util.getResourceAsString("oru_r01.xml"));
MuleMessage result = client.send("vm://saveEncounters-De-normailization-OpenMRSSHR", (Object) req, properties);
Assert.assertTrue(result.getPayload() instanceof RestfulHttpResponse);
RestfulHttpResponse resp = (RestfulHttpResponse) result.getPayload();
assertEquals(404, resp.getHttpStatus());
}
} |
package stroom.config.common;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import stroom.util.shared.AbstractConfig;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import java.util.Objects;
public class ApiGatewayConfig extends AbstractConfig {
public static final String PROP_NAME_HOST_NAME = "hostname";
public static final String PROP_NAME_SCHEME = "scheme";
public static final String PROP_NAME_PORT = "port";
private String hostname;
private String scheme = "https";
private Integer port;
@JsonProperty(PROP_NAME_HOST_NAME)
@JsonPropertyDescription("The hostname, DNS name or IP address of the " +
"Stroom API gateway, i.e. Nginx.")
@NotNull
public String getHostname() {
return hostname;
}
public void setHostname(final String hostname) {
this.hostname = hostname;
}
@JsonProperty(PROP_NAME_SCHEME)
@JsonPropertyDescription("The scheme to use when passing requests to the API gateway, " +
" i.e. https")
@Pattern(regexp = "^https?$")
@NotNull
public String getScheme() {
return scheme;
}
public void setScheme(final String scheme) {
this.scheme = scheme;
}
@JsonProperty(PROP_NAME_PORT)
@JsonPropertyDescription("The port to use when passing requests to the API gateway. " +
"If no port is supplied then no port will be used in the resulting URL and it will " +
"be inferred from the scheme.")
@Min(1)
@Max(65535)
public Integer getPort() {
return port;
}
public void setPort(final Integer port) {
this.port = port;
}
@JsonIgnore
public String getBasePath() {
return buildBasePath().toString();
}
/**
* Helper method to build a URL on the API Gateway using the supplied
* path
* @param path e.g. /users
*/
@JsonIgnore
public String buildApiGatewayUrl(final String path) {
StringBuilder stringBuilder = buildBasePath();
if (path != null && !path.isEmpty()) {
stringBuilder.append(path);
}
return stringBuilder.toString();
}
@Override
public String toString() {
return "ApiGatewayConfig{" +
"hostname='" + hostname + '\'' +
", scheme='" + scheme + '\'' +
", port=" + port +
'}';
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final ApiGatewayConfig that = (ApiGatewayConfig) o;
return Objects.equals(hostname, that.hostname) &&
Objects.equals(scheme, that.scheme) &&
Objects.equals(port, that.port);
}
@Override
public int hashCode() {
return Objects.hash(hostname, scheme, port);
}
private StringBuilder buildBasePath() {
Objects.requireNonNull(hostname,
"stroom.apiGateway.hostname must be configured");
// TODO could consider building this on any call to the setters and
// then holding it to save re-computing all the time
final StringBuilder stringBuilder = new StringBuilder()
.append(scheme)
.append(":
.append(hostname);
if (port != null) {
stringBuilder.append(":")
.append(port.toString());
}
return stringBuilder;
}
} |
package com.evolveum.midpoint.testing.selenium;
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.WebDriver;
import org.junit.*;
import com.evolveum.midpoint.testing.Selenium;
import com.evolveum.midpoint.api.logging.Trace;
import com.evolveum.midpoint.logging.TraceManager;
import static org.junit.Assert.*;
public class Test002basicUser {
Selenium se;
static String baseUrl = "http://localhost:8080/idm";
private static final transient Trace logger = TraceManager.getTrace(Test002basicUser.class);
@Before
/***
* Do login as Admin for each test
*/
public void start() {
WebDriver driver = new FirefoxDriver();
// WebDriver driver = new ChromeDriver();
se = new Selenium(driver, baseUrl);
se.setBrowserLogLevel("5");
se.open("/");
se.waitForText("Login", 10);
se.type("loginForm:userName", "administrator");
se.type("loginForm:password", "secret");
se.click("loginForm:loginButton");
se.waitForText("Administrator", 10);
assertEquals(baseUrl + "/index.iface", se.getLocation());
}
/*
* close browser
*/
@After
public void stop() {
se.stop();
}
// Based on MID-2 jira scenarios
// TODO description
@Test
public void test01addUser() {
se.click(se.findLink("topAccount"));
se.waitForPageToLoad("30000");
assertEquals(baseUrl + "/account/index.iface", se.getLocation());
assertTrue(se.isTextPresent("New User"));
se.click(se.findLink("leftCreate"));
se.waitForText("Web access enabled");
assertEquals(baseUrl + "/account/userCreate.iface", se.getLocation());
logger.info("Minimal requirements");
se.type("createUserForm:name", "barbossa");
se.type("createUserForm:givenName", "Hector");
se.type("createUserForm:familyName", "Barbossa");
se.type("createUserForm:fullName", "Hector Barbossa");
se.type("createUserForm:email", "");
se.type("createUserForm:locality", "");
se.type("createUserForm:password1", "qwe123.Q");
se.type("createUserForm:password2", "qwe123.Q");
se.click("createUserForm:enabled");
se.click("createUserForm:webAccessEnabled"); // disable
se.click("createUserForm:createUser"); // enable
se.waitForText("User created successfully");
assertTrue(se.isTextPresent("Hector Barbossa"));
se.click(se.findLink("leftCreate"));
se.waitForText("Web access enabled");
assertEquals(baseUrl + "/account/userCreate.iface", se.getLocation());
logger.info("All fields filled");
se.type("createUserForm:name", "elizabeth");
se.type("createUserForm:givenName", "Elizabeth");
se.type("createUserForm:familyName", "Swann");
se.type("createUserForm:fullName", "Elizabeth Swann");
se.type("createUserForm:email", "elizabeth@blackpearl.pir");
se.type("createUserForm:locality", "Empress");
se.type("createUserForm:password1", "qwe123.Q");
se.type("createUserForm:password2", "qwe123.Q");
se.click("createUserForm:webAccessEnabled");
se.click("createUserForm:createUser");
se.waitForText("User created successfully");
assertTrue(se.isTextPresent("Elizabeth Swann"));
se.click(se.findLink("leftCreate"));
se.waitForText("Web access enabled");
assertEquals(baseUrl + "/account/userCreate.iface", se.getLocation());
logger.info("try to insert twice");
se.type("createUserForm:name", "elizabeth");
se.type("createUserForm:givenName", "Elizabeth");
se.type("createUserForm:familyName", "Swann");
se.type("createUserForm:fullName", "Elizabeth Swann Turner");
se.type("createUserForm:email", "elizabeth@empress.pir");
se.type("createUserForm:locality", "Empress");
se.type("createUserForm:password1", "qwe123.Q");
se.type("createUserForm:password2", "qwe123.Q");
se.click("createUserForm:webAccessEnabled");
se.click("createUserForm:createUser");
se.waitForText("Failed to create user");
assertTrue(se.isTextPresent("could not insert"));
assertTrue(se.isTextPresent("ConstraintViolationException"));
// test missing name and password not match
logger.info("missing: name");
se.type("createUserForm:name", "");
se.type("createUserForm:givenName", "Joshamee");
se.type("createUserForm:familyName", "Gibbs");
se.type("createUserForm:fullName", "Joshamee Gibbs");
se.type("createUserForm:email", "elizabeth@Swann.com");
se.type("createUserForm:locality", "nowhere");
se.type("createUserForm:password1", "qwe123.Q");
se.type("createUserForm:password2", "qwe213.Q");
se.click("createUserForm:webAccessEnabled");
se.click("createUserForm:createUser");
se.waitForText("Value is required");
assertTrue(se.isTextPresent("Please check password fields."));
assertTrue(se.isTextPresent("Passwords doesn't match"));
logger.info("missing: password");
se.type("createUserForm:name", "Joshamee");
se.type("createUserForm:givenName", "Joshamee");
se.type("createUserForm:familyName", "Gibbs");
se.type("createUserForm:fullName", "Joshamee Gibbs");
se.type("createUserForm:email", "elizabeth@Swann.com");
se.type("createUserForm:locality", "nowhere");
se.type("createUserForm:password1", "");
se.type("createUserForm:password2", "");
se.click("createUserForm:webAccessEnabled");
se.click("createUserForm:createUser");
se.waitForText("Value is required");
logger.info("missing: givenname");
se.type("createUserForm:name", "Joshamee");
se.type("createUserForm:givenName", "");
se.type("createUserForm:familyName", "Gibbs");
se.type("createUserForm:fullName", "Joshamee Gibbs");
se.type("createUserForm:email", "elizabeth@Swann.com");
se.type("createUserForm:locality", "nowhere");
se.type("createUserForm:password1", "qwe123.Q");
se.type("createUserForm:password2", "qwe213.Q");
se.click("createUserForm:webAccessEnabled");
se.click("createUserForm:createUser");
se.waitForText("Value is required");
logger.info("missing: familyname");
se.type("createUserForm:name", "Joshamee");
se.type("createUserForm:givenName", "Joshamee");
se.type("createUserForm:familyName", "");
se.type("createUserForm:fullName", "Joshamee Gibbs");
se.type("createUserForm:email", "elizabeth@Swann.com");
se.type("createUserForm:locality", "nowhere");
se.type("createUserForm:password1", "qwe123.Q");
se.type("createUserForm:password2", "qwe213.Q");
se.click("createUserForm:webAccessEnabled");
se.click("createUserForm:createUser");
se.waitForText("Value is required");
logger.info("missing: fullname");
se.type("createUserForm:name", "Joshamee");
se.type("createUserForm:givenName", "Joshamee");
se.type("createUserForm:familyName", "Gibbs");
se.type("createUserForm:fullName", "");
se.type("createUserForm:email", "elizabeth@Swann.com");
se.type("createUserForm:locality", "nowhere");
se.type("createUserForm:password1", "qwe123.Q");
se.type("createUserForm:password2", "qwe213.Q");
se.click("createUserForm:webAccessEnabled");
se.click("createUserForm:createUser");
se.waitForText("Value is required");
}
//TODO description
@Test
public void test02searchUser() throws InterruptedException {
logger.info("searchTest()");
se.click(se.findLink("topAccount"));
se.waitForPageToLoad("30000");
assertEquals(baseUrl + "/account/index.iface", se.getLocation());
assertTrue(se.isTextPresent("New User"));
// get hashmap and login
HashMap<String, String> h = new HashMap<String, String>();
for (String l : se.getAllLinks()) {
if (!l.contains("Table") || !l.contains("name"))
continue;
h.put(se.getText(l), l.replace(":name", ""));
}
for (String k : h.keySet()) {
logger.info(k + " -> " + h.get(k));
}
assertTrue(se.isTextPresent("Elizabeth Swann"));
assertTrue(se.isTextPresent("Hector Barbossa"));
se.type("admin-content:searchName", "elizabeth");
se.click("admin-content:searchButton");
se.waitForText("List Users");
assertTrue(se.isTextPresent("Elizabeth Swann"));
assertFalse(se.isTextPresent("Hector Barbossa"));
se.type("admin-content:searchName", "barbossa");
se.click("admin-content:searchButton");
se.waitForText("List Users");
se.type("admin-content:searchName", "");
se.click("admin-content:searchButton");
se.waitForText("List Users");
assertTrue(se.isTextPresent("Elizabeth Swann"));
assertTrue(se.isTextPresent("Hector Barbossa"));
}
/***
* Modify user via debug pages
*
* Actions:
* 1. login as admin
* 2. click to Configuration
* 3. click to Import objects
* 4. fill editor with proper XML (new user jack)
* 5. click Accounts
* 6. check if user is there
*/
@Test
public void test03importUser() {
se.click(se.findLink("topConfiguration"));
se.waitForPageToLoad("30000");
assertEquals(baseUrl + "/config/index.iface", se.getLocation());
assertTrue(se.isTextPresent("Import And Export"));
se.click(se.findLink("leftImport"));
String xmlUser = "<?xml version= '1.0' encoding='UTF-8'?>\n"
+ "<i:user oid='c0c010c0-d34d-b33f-f00d-111111111111' xmlns:xsi='http:
+ "xmlns:i='http://midpoint.evolveum.com/xml/ns/public/common/common-1.xsd'\n"
+ "xmlns:c='http://midpoint.evolveum.com/xml/ns/public/common/common-1.xsd'\n"
+ "xmlns:piracy='http://midpoint.evolveum.com/xml/ns/samples/piracy'>\n"
+ "<c:name>jack</c:name>\n" + "<c:extension>\n" + "<piracy:ship>Black Pearl</piracy:ship>\n"
+ "</c:extension>\n" + "<i:fullName>Cpt. Jack Sparrow</i:fullName>\n"
+ "<i:givenName>Jack</i:givenName>\n" + "<i:familyName>Sparrow</i:familyName>\n"
+ "<i:additionalNames>yet another name</i:additionalNames>\n"
+ "<i:honorificPrefix>Cpt.</i:honorificPrefix>\n"
+ " <i:honorificSuffix>PhD.</i:honorificSuffix>\n"
+ "<i:eMailAddress>jack.sparrow@evolveum.com</i:eMailAddress>\n"
+ "<i:telephoneNumber>555-1234</i:telephoneNumber>\n"
+ "<i:employeeNumber>emp1234</i:employeeNumber>\n"
+ "<i:employeeType>CAPTAIN</i:employeeType>\n"
+ "<i:organizationalUnit>Leaders</i:organizationalUnit>\n"
+ "<i:locality>Black Pearl</i:locality>\n" + "<i:credentials>\n" + "<i:password>\n"
+ " <i:cleartextPassword>Gibbsmentellnotales</i:cleartextPassword>\n"
+ "</i:password>\n" + "</i:credentials>\n" + "</i:user>";
se.type("importForm:editor", xmlUser);
se.click("importForm:uploadButton");
assertTrue(se.waitForText("Added object: jack"));
se.click(se.findLink("topAccount"));
se.waitForPageToLoad("30000");
assertEquals(baseUrl + "/account/index.iface", se.getLocation());
assertTrue(se.isTextPresent("New User"));
assertTrue(se.isTextPresent("Cpt. Jack Sparrow"));
}
/***
* Modify user via debug pages
*
* Actions:
* 1. login as admin
* 2. click to Configuration
* 3. click to Import objects
* 4. fill editor with proper modified XML (user jack)
* 5. click to Upload object
* a) overwrite is not selected -> FAIL
* b) overwrite is selected -> PASS
* 6. click Accounts
* 7. check if user full name is changed
*/
@Test
public void test04importModifyUser() {
// failing import allready exists
se.click(se.findLink("topConfiguration"));
se.waitForPageToLoad("30000");
assertEquals(baseUrl + "/config/index.iface", se.getLocation());
assertTrue(se.isTextPresent("Import And Export"));
se.click(se.findLink("leftImport"));
String xmlUser = "<?xml version= '1.0' encoding='UTF-8'?>\n"
+ "<i:user oid=\"c0c010c0-d34d-b33f-f00d-111111111111\" xmlns:xsi='http:
+ "xmlns:i='http://midpoint.evolveum.com/xml/ns/public/common/common-1.xsd'\n"
+ "xmlns:c='http://midpoint.evolveum.com/xml/ns/public/common/common-1.xsd'\n"
+ "xmlns:piracy='http://midpoint.evolveum.com/xml/ns/samples/piracy'>\n"
+ "<c:name>jack</c:name>\n" + "<c:extension>\n" + "<piracy:ship>Black Pearl</piracy:ship>\n"
+ "</c:extension>\n" + "<i:fullName>Com. Jack Sparrow</i:fullName>\n"
+ "<i:givenName>Jack</i:givenName>\n" + "<i:familyName>Sparrow</i:familyName>\n"
+ "<i:additionalNames>yet another name</i:additionalNames>\n"
+ "<i:honorificPrefix>Cpt.</i:honorificPrefix>\n"
+ " <i:honorificSuffix>PhD.</i:honorificSuffix>\n"
+ "<i:eMailAddress>jack.sparrow@evolveum.com</i:eMailAddress>\n"
+ "<i:telephoneNumber>555-1234</i:telephoneNumber>\n"
+ "<i:employeeNumber>emp1234</i:employeeNumber>\n"
+ "<i:employeeType>CAPTAIN</i:employeeType>\n"
+ "<i:organizationalUnit>Leaders</i:organizationalUnit>\n"
+ "<i:locality>Black Pearl</i:locality>\n" + "<i:credentials>\n" + "<i:password>\n"
+ " <i:cleartextPassword>deadmentellnotales</i:cleartextPassword>\n"
+ "</i:password>\n" + "</i:credentials>\n" + "</i:user>";
se.type("importForm:editor", xmlUser);
se.click("importForm:uploadButton");
assertTrue(se.waitForText("Failed to add object jack"));
assertTrue(se.isTextPresent("already exists in store"));
//overwrite enabled
se.click(se.findLink("topConfiguration"));
se.waitForPageToLoad("30000");
assertEquals(baseUrl + "/config/index.iface", se.getLocation());
assertTrue(se.isTextPresent("Import And Export"));
se.click(se.findLink("leftImport"));
se.type("importForm:editor", xmlUser);
se.click("importForm:enableOverwrite");
se.click("importForm:uploadButton");
assertTrue(se.waitForText("Added object: jack"));
se.click(se.findLink("topAccount"));
se.waitForPageToLoad("30000");
assertEquals(baseUrl + "/account/index.iface", se.getLocation());
assertTrue(se.isTextPresent("New User"));
assertTrue(se.isTextPresent("Com. Jack Sparrow"));
}
/***
* modify user via GUI
*
* 1. login as admin
* 2. click to Accounts
* 3. select and click user jack
* 4. click to edit button
* 5. change full name
* 6. change locality
* 7. click to save changes
* 8. check if user fullname is changed
* 9. click to user
* 10. check if locality is changed
*/
@Test
public void test05modifyUser() {
//modify jack (demote)
se.click(se.findLink("topAccount"));
se.waitForPageToLoad("30000");
assertEquals(baseUrl + "/account/index.iface", se.getLocation());
assertTrue(se.isTextPresent("New User"));
se.click(se.findLink("jack"));
se.waitForPageToLoad("30000");
assertEquals(baseUrl + "/account/userDetails.iface", se.getLocation());
assertTrue(se.isTextPresent("Black Pearl"));
se.click("admin-content:editButton");
se.waitForText("Save changes",30);
for (String s: se.getAllFields() ) {
if (s.contains("fullNameText")) {
se.type(s, "SR. Jack Sparrow");
}
if (s.contains("localityText")) {
se.type(s, "Queen Anne's Revenge");
}
}
se.click("admin-content:saveButton");
se.waitForPageToLoad("30000");
assertEquals(baseUrl + "/account/index.iface", se.getLocation());
assertTrue(se.isTextPresent("New User"));
assertTrue(se.isTextPresent("SR. Jack Sparrow"));
se.click(se.findLink("Jack"));
se.waitForPageToLoad("30000");
assertEquals(baseUrl + "/account/userDetails.iface", se.getLocation());
assertTrue(se.isTextPresent("Queen Anne"));
}
//TODO
@Test
public void test06modifyUserViaDebug() {
}
//TODO
@Test
public void test07deleteUserViaDebug() {
}
/***
* Search user and delete it form midPoint
*
* Actions:
* 1. login as admin
* 2. click to accounts
* 3. find user
* 4. mark user to delete
* 5. click Delete button
* a) click NO -> FAIL
* b) click YES -> PASS
*
* Do for user:
* * Elizabeth
* * barbossa
*
* Validation:
* * user not exists after remove
*/
@Test
public void test99deleteUser() {
//delete elizabeth
se.click(se.findLink("topAccount"));
se.waitForPageToLoad("30000");
assertEquals(baseUrl + "/account/index.iface", se.getLocation());
assertTrue(se.isTextPresent("New User"));
// get hashmap and login
HashMap<String, String> h = new HashMap<String, String>();
for (String l : se.getAllLinks()) {
if (!l.contains("Table") || !l.contains("name"))
continue;
h.put(se.getText(l), l.replace("name", ""));
}
se.click(h.get("elizabeth") + "deleteCheckbox");
se.click("admin-content:deleteUser");
se.waitForText("Confirm delete");
se.click("admin-content:deleteUserNo");
se.waitForText("List Users");
se.click("admin-content:deleteUser");
se.waitForText("Confirm delete");
se.click("admin-content:deleteUserYes");
se.waitForText("List Users");
assertFalse(se.isTextPresent("Elizabeth Swann"));
//delete barbossa
se.click(se.findLink("topHome"));
se.waitForPageToLoad("30000");
se.click(se.findLink("topAccount"));
se.waitForPageToLoad("30000");
assertTrue(se.isTextPresent("New User"));
for (String l : se.getAllLinks()) {
if (!l.contains("Table") || !l.contains("name"))
continue;
logger.info("Adding:" + se.getText(l), l.replace("name", ""));
h.put(se.getText(l), l.replace("name", ""));
}
se.click(h.get("barbossa") + "deleteCheckbox");
se.click("admin-content:deleteUser");
se.waitForText("Confirm delete");
se.click("admin-content:deleteUserYes");
se.waitForText("List Users");
assertFalse(se.isTextPresent("barbossa"));
//delete jack
se.click(se.findLink("topHome"));
se.waitForPageToLoad("30000");
se.click(se.findLink("topAccount"));
se.waitForPageToLoad("30000");
assertTrue(se.isTextPresent("New User"));
for (String l : se.getAllLinks()) {
if (!l.contains("Table") || !l.contains("name"))
continue;
logger.info("Adding:" + se.getText(l), l.replace("name", ""));
h.put(se.getText(l), l.replace("name", ""));
}
se.click(h.get("jack") + "deleteCheckbox");
se.click("admin-content:deleteUser");
se.waitForText("Confirm delete");
se.click("admin-content:deleteUserYes");
se.waitForText("List Users");
assertFalse(se.isTextPresent("Jack"));
}
} |
package com.evolveum.midpoint.schema.xjc.schema;
import com.evolveum.midpoint.prism.PrismContainer;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.schema.xjc.PrefixMapper;
import com.evolveum.midpoint.schema.xjc.PrismForJAXBUtil;
import com.evolveum.midpoint.schema.xjc.Processor;
import com.sun.codemodel.*;
import com.sun.tools.xjc.Options;
import com.sun.tools.xjc.model.CClassInfo;
import com.sun.tools.xjc.model.nav.NClass;
import com.sun.tools.xjc.outline.ClassOutline;
import com.sun.tools.xjc.outline.Outline;
import com.sun.xml.xsom.XSElementDecl;
import com.sun.xml.xsom.XSSchema;
import com.sun.xml.xsom.XSSchemaSet;
import com.sun.xml.xsom.XSType;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.namespace.QName;
import java.util.*;
import java.util.Map.Entry;
import static com.evolveum.midpoint.schema.xjc.util.ProcessorUtils.*;
/**
* Simple proof of concept for our custom XJC plugin.
*
* @author lazyman
*/
public class SchemaProcessor implements Processor {
//annotations for schema processor
private static final QName PROPERTY_CONTAINER = new QName(PrefixMapper.A.getNamespace(), "propertyContainer");
private static final QName MIDPOINT_CONTAINER = new QName(PrefixMapper.A.getNamespace(), "midPointContainer");
//fields and methods for prism containers/prism objects
private static final String COMPLEX_TYPE_FIELD = "COMPLEX_TYPE";
private static final String CONTAINER_FIELD_NAME = "container";
private static final String METHOD_GET_CONTAINER = "getContainer";
private static final String METHOD_SET_CONTAINER = "setContainer";
private static final String METHOD_GET_CONTAINER_NAME = "getContainerName";
//methods in PrismForJAXBUtil
private static final String METHOD_GET_PROPERTY_VALUE = "getPropertyValue";
private static final String METHOD_GET_PROPERTY_VALUES = "getPropertyValues";
private static final String METHOD_SET_PROPERTY_VALUE = "setPropertyValue";
//equals, toString, hashCode methods
private static final String METHOD_TO_STRING = "toString";
private static final String METHOD_DEBUG_DUMP = "debugDump";
private static final int METHOD_DEBUG_DUMP_INDENT = 3;
private static final String METHOD_EQUALS = "equals";
private static final String METHOD_EQUIVALENT = "equivalent";
private static final String METHOD_HASH_CODE = "hashCode";
//prism container handling
private static final String METHOD_ADD_REPLACE_EXISTING = "addReplaceExisting";
//map which contains mapping from complex type qnames to element names
private Map<QName, List<QName>> complexTypeToElementName;
//todo change annotation on ObjectType in common-1.xsd to a:midPointContainer
@Override
public boolean run(Outline outline, Options options, ErrorHandler errorHandler) throws SAXException {
try {
StepSchemaConstants stepSchemaConstants = new StepSchemaConstants();
stepSchemaConstants.run(outline, options, errorHandler);
Map<String, JFieldVar> namespaceFields = stepSchemaConstants.getNamespaceFields();
addComplextType(outline, namespaceFields);
addContainerName(outline, namespaceFields);
addFieldQNames(outline, namespaceFields);
Set<JDefinedClass> containers = updateMidPointContainer(outline);
containers.addAll(updatePropertyContainer(outline));
updateFields(outline, containers);
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException("Couldn't process MidPoint JAXB customisation, reason: "
+ ex.getMessage() + ", " + ex.getClass(), ex);
}
return true;
}
private Set<JDefinedClass> updatePropertyContainer(Outline outline) {
return updateContainer(outline, PROPERTY_CONTAINER, PrismContainer.class);
}
private Set<JDefinedClass> updateMidPointContainer(Outline outline) {
return updateContainer(outline, MIDPOINT_CONTAINER, PrismObject.class);
}
private Set<JDefinedClass> updateContainer(Outline outline, QName annotation,
Class<? extends PrismContainer> containerClass) {
Set<JDefinedClass> containers = new HashSet<JDefinedClass>();
Set<Map.Entry<NClass, CClassInfo>> set = outline.getModel().beans().entrySet();
for (Map.Entry<NClass, CClassInfo> entry : set) {
ClassOutline classOutline = outline.getClazz(entry.getValue());
QName qname = entry.getValue().getTypeName();
if (qname == null || !hasAnnotation(classOutline, annotation)) {
continue;
}
//todo remove, only till propertyContainer annotation is on ObjectType
if (hasAnnotation(classOutline, MIDPOINT_CONTAINER) && hasAnnotation(classOutline, PROPERTY_CONTAINER)
&& annotation.equals(PROPERTY_CONTAINER)) {
continue;
}
JDefinedClass definedClass = classOutline.implClass;
containers.add(definedClass);
//inserting MidPointObject field into ObjectType class
JVar container = definedClass.field(JMod.PRIVATE, containerClass, CONTAINER_FIELD_NAME);
//adding XmlTransient annotation
container.annotate((JClass) outline.getModel().codeModel._ref(XmlTransient.class));
//create getContainer
createGetContainerMethod(classOutline, container, containerClass);
//create setContainer
createSetContainerMethod(definedClass, container, containerClass, outline);
System.out.println("Creating toString, equals, hashCode methods.");
//create toString, equals, hashCode
createToStringMethod(definedClass, outline);
createEqualsMethod(definedClass, outline);
createHashCodeMethod(definedClass, outline);
}
return containers;
}
private void createHashCodeMethod(JDefinedClass definedClass, Outline outline) {
JMethod hashCode = definedClass.method(JMod.PUBLIC, int.class, METHOD_HASH_CODE);
hashCode.annotate((JClass) outline.getModel().codeModel._ref(Override.class));
JBlock body = hashCode.body();
body._return(JExpr.invoke(METHOD_GET_CONTAINER).invoke(METHOD_HASH_CODE));
}
private void createEqualsMethod(JDefinedClass definedClass, Outline outline) {
JClass object = (JClass) outline.getModel().codeModel._ref(Object.class);
JMethod equals = definedClass.method(JMod.PUBLIC, boolean.class, METHOD_EQUALS);
JVar obj = equals.param(object, "obj");
equals.annotate((JClass) outline.getModel().codeModel._ref(Override.class));
JBlock body = equals.body();
JBlock ifNull = body._if(obj._instanceof(definedClass).not())._then();
ifNull._return(JExpr.lit(false));
JVar other = body.decl(definedClass, "other", JExpr.cast(definedClass, obj));
JInvocation invocation = JExpr.invoke(METHOD_GET_CONTAINER).invoke(METHOD_EQUIVALENT);
invocation.arg(other.invoke(METHOD_GET_CONTAINER));
body._return(invocation);
}
private void createToStringMethod(JDefinedClass definedClass, Outline outline) {
JClass clazz = (JClass) outline.getModel().codeModel._ref(String.class);
JMethod toString = definedClass.method(JMod.PUBLIC, clazz, METHOD_TO_STRING);
toString.annotate((JClass) outline.getModel().codeModel._ref(Override.class));
JBlock body = toString.body();
JInvocation invocation = JExpr.invoke(METHOD_GET_CONTAINER).invoke(METHOD_DEBUG_DUMP);
invocation.arg(JExpr.lit(METHOD_DEBUG_DUMP_INDENT));
body._return(invocation);
}
private void createGetContainerMethod(ClassOutline classOutline, JVar container,
Class<? extends PrismContainer> containerClass) {
JDefinedClass definedClass = classOutline.implClass;
JClass clazz = (JClass) classOutline.parent().getModel().codeModel._ref(containerClass);
JMethod getContainer = definedClass.method(JMod.PUBLIC, clazz, METHOD_GET_CONTAINER);
//create method body
JBlock body = getContainer.body();
JBlock then = body._if(container.eq(JExpr._null()))._then();
JInvocation newContainer = (JInvocation) JExpr._new(clazz);
newContainer.arg(JExpr.invoke(METHOD_GET_CONTAINER_NAME));
then.assign(container, newContainer);
body._return(container);
}
private void createSetContainerMethod(JDefinedClass definedClass, JVar container,
Class<? extends PrismContainer> containerClass, Outline outline) {
JMethod setContainer = definedClass.method(JMod.PUBLIC, void.class, METHOD_SET_CONTAINER);
JVar methodContainer = setContainer.param(containerClass, "container");
//create method body
JBlock body = setContainer.body();
JBlock then = body._if(methodContainer.eq(JExpr._null()))._then();
then.assign(JExpr._this().ref(container), JExpr._null());
then._return();
JInvocation equals = JExpr.invoke(JExpr.invoke(METHOD_GET_CONTAINER_NAME), "equals");
equals.arg(methodContainer.invoke("getName"));
then = body._if(equals.not())._then();
JClass illegalArgumentClass = (JClass) outline.getModel().codeModel._ref(IllegalArgumentException.class);
JInvocation exception = JExpr._new(illegalArgumentClass);
JExpression message = JExpr.lit("Container qname '").plus(JExpr.invoke(methodContainer, "getName"))
.plus(JExpr.lit("' doesn't equals to '")).plus(JExpr.ref(COMPLEX_TYPE_FIELD))
.plus(JExpr.lit("'."));
exception.arg(message);
then._throw(exception);
body.assign(JExpr._this().ref(container), methodContainer);
}
private void addContainerName(Outline outline, Map<String, JFieldVar> namespaceFields) {
Set<Map.Entry<NClass, CClassInfo>> set = outline.getModel().beans().entrySet();
for (Map.Entry<NClass, CClassInfo> entry : set) {
ClassOutline classOutline = outline.getClazz(entry.getValue());
QName qname = entry.getValue().getTypeName();
if (qname == null) {
continue;
}
//element name
List<QName> qnames = getComplexTypeToElementName(classOutline).get(qname);
if (qnames == null || qnames.size() != 1) {
System.out.println("Found zero or more than one element names for type '"
+ qname + "', " + qnames + ".");
continue;
}
qname = qnames.get(0);
JDefinedClass definedClass = classOutline.implClass;
JMethod getContainerName = definedClass.method(JMod.NONE, QName.class, METHOD_GET_CONTAINER_NAME);
JBlock body = getContainerName.body();
JFieldVar var = namespaceFields.get(qname.getNamespaceURI());
JClass clazz = (JClass) outline.getModel().codeModel._ref(QName.class);
JInvocation invocation = (JInvocation) JExpr._new(clazz);
if (var != null) {
JClass schemaClass = (JClass) outline.getModel().codeModel._getClass(StepSchemaConstants.CLASS_NAME);
invocation.arg(schemaClass.staticRef(var));
invocation.arg(qname.getLocalPart());
} else {
invocation.arg(qname.getNamespaceURI());
invocation.arg(qname.getLocalPart());
}
body._return(invocation);
}
}
private void addComplextType(Outline outline, Map<String, JFieldVar> namespaceFields) {
Set<Map.Entry<NClass, CClassInfo>> set = outline.getModel().beans().entrySet();
for (Map.Entry<NClass, CClassInfo> entry : set) {
ClassOutline classOutline = outline.getClazz(entry.getValue());
QName qname = entry.getValue().getTypeName();
if (qname == null) {
continue;
}
JFieldVar var = namespaceFields.get(qname.getNamespaceURI());
if (var != null) {
createQNameDefinition(outline, classOutline.implClass, COMPLEX_TYPE_FIELD, var, qname);
} else {
createPSFField(outline, classOutline.implClass, COMPLEX_TYPE_FIELD, qname);
}
}
}
private Map<QName, List<QName>> getComplexTypeToElementName(ClassOutline classOutline) {
if (complexTypeToElementName != null) {
return complexTypeToElementName;
} else {
complexTypeToElementName = new HashMap<QName, List<QName>>();
}
XSSchemaSet schemaSet = classOutline.target.getSchemaComponent().getRoot();
for (XSSchema schema : schemaSet.getSchemas()) {
Map<String, XSElementDecl> elemDecls = schema.getElementDecls();
for (Entry<String, XSElementDecl> entry : elemDecls.entrySet()) {
XSElementDecl decl = entry.getValue();
XSType xsType = decl.getType();
if (xsType.getName() == null) {
continue;
}
QName type = new QName(xsType.getTargetNamespace(), xsType.getName());
List<QName> qnames = complexTypeToElementName.get(type);
if (qnames == null) {
qnames = new ArrayList<QName>();
complexTypeToElementName.put(type, qnames);
}
qnames.add(new QName(decl.getTargetNamespace(), decl.getName()));
}
}
return complexTypeToElementName;
}
private JFieldVar createQNameDefinition(Outline outline, JDefinedClass definedClass, String fieldName,
JFieldVar namespaceField, QName reference) {
JClass clazz = (JClass) outline.getModel().codeModel._ref(QName.class);
JClass schemaClass = (JClass) outline.getModel().codeModel._getClass(StepSchemaConstants.CLASS_NAME);
JInvocation invocation = (JInvocation) JExpr._new(clazz);
invocation.arg(schemaClass.staticRef(namespaceField));
invocation.arg(reference.getLocalPart());
int psf = JMod.PUBLIC | JMod.STATIC | JMod.FINAL;
return definedClass.field(psf, QName.class, fieldName, invocation);
}
private void addFieldQNames(Outline outline, Map<String, JFieldVar> namespaceFields) {
Set<Map.Entry<NClass, CClassInfo>> set = outline.getModel().beans().entrySet();
for (Map.Entry<NClass, CClassInfo> entry : set) {
ClassOutline classOutline = outline.getClazz(entry.getValue());
QName qname = entry.getValue().getTypeName();
if (qname == null) {
continue;
}
JDefinedClass implClass = classOutline.implClass;
Map<String, JFieldVar> fields = implClass.fields();
if (fields == null) {
continue;
}
List<FieldBox<QName>> boxes = new ArrayList<FieldBox<QName>>();
for (String field : fields.keySet()) {
if ("serialVersionUID".equals(field) || "oid".equals(field) || COMPLEX_TYPE_FIELD.equals(field)) {
continue;
}
String fieldName = fieldFPrefixUnderscoredUpperCase(field);
boxes.add(new FieldBox(fieldName, new QName(qname.getNamespaceURI(), field)));
}
for (FieldBox<QName> box : boxes) {
JFieldVar var = namespaceFields.get(qname.getNamespaceURI());
if (var != null) {
createQNameDefinition(outline, implClass, box.getFieldName(), var, box.getValue());
} else {
createPSFField(outline, implClass, box.getFieldName(), box.getValue());
}
}
}
}
private void updateFields(Outline outline, Set<JDefinedClass> containers) {
Set<Map.Entry<NClass, CClassInfo>> set = outline.getModel().beans().entrySet();
for (Map.Entry<NClass, CClassInfo> entry : set) {
ClassOutline classOutline = outline.getClazz(entry.getValue());
QName qname = entry.getValue().getTypeName();
if (qname == null) {
continue;
}
JDefinedClass implClass = classOutline.implClass;
Map<String, JFieldVar> fields = implClass.fields();
if (fields == null || !isPropertyContainer(classOutline.implClass, outline)) {
//it's PropertyContainer, MidPointObject class or doesn't have fields
continue;
}
System.out.println("Updating fields and get/set methods: " + classOutline.implClass.fullName());
List<JFieldVar> fieldsToBeRemoved = new ArrayList<JFieldVar>();
boolean remove;
for (String field : fields.keySet()) {
if ("serialVersionUID".equals(field) || COMPLEX_TYPE_FIELD.equals(field)
|| CONTAINER_FIELD_NAME.equals(field)) {
continue;
}
JFieldVar fieldVar = fields.get(field);
boolean isPublicStaticFinal = (fieldVar.mods().getValue() & (JMod.STATIC | JMod.FINAL)) != 0;
if (field.startsWith("F_") && isPublicStaticFinal) {
//our QName constant fields
continue;
}
remove = false;
if ("oid".equals(field)) {
System.out.println("Updating oid field: " + fieldVar.name());
remove = updateOidField(fieldVar, classOutline);
} else if (isFieldTypeContainer(fieldVar, classOutline)) {
System.out.println("Updating container field: " + fieldVar.name());
remove = updateContainerFieldType(fieldVar, classOutline);
} else {
System.out.println("Updating field: " + fieldVar.name());
remove = updateField(fieldVar, classOutline);
}
if (remove) {
fieldsToBeRemoved.add(fieldVar);
}
}
for (JFieldVar field : fieldsToBeRemoved) {
implClass.removeField(field);
}
}
}
/**
* adding Deprecation annotation and small comment to method
*/
@Deprecated
private void addDeprecation(Outline outline, JMethod method) {
method.annotate((JClass) outline.getModel().codeModel._ref(Deprecated.class));
JDocComment comment = method.javadoc();
comment.append("DO NOT USE! For testing purposes only.");
}
@Deprecated
private void notYetImplementedException(Outline outline, JMethod method) {
//adding deprecation
addDeprecation(outline, method);
//comment and not yet implemented exception
JBlock body = method.body();
body.directStatement("//todo implement in xjc processing with using XmlUtil");
JClass illegalAccess = (JClass) outline.getModel().codeModel._ref(UnsupportedOperationException.class);
JInvocation exception = JExpr._new(illegalAccess);
exception.arg(JExpr.lit("Not yet implemented."));
body._throw(exception);
}
private boolean isPropertyContainer(JDefinedClass definedClass, Outline outline) {
if (definedClass == null) {
return false;
}
ClassOutline classOutline = null;
for (ClassOutline clazz : outline.getClasses()) {
if (definedClass.equals(clazz.implClass)) {
classOutline = clazz;
break;
}
}
if (classOutline == null) {
return false;
}
boolean isContainer = hasAnnotation(classOutline, PROPERTY_CONTAINER)
|| hasAnnotation(classOutline, MIDPOINT_CONTAINER);
if (isContainer) {
return true;
}
if (!(definedClass._extends() instanceof JDefinedClass)) {
return false;
}
return isPropertyContainer((JDefinedClass) definedClass._extends(), outline);
}
private boolean isFieldTypeContainer(JFieldVar field, ClassOutline classOutline) {
Outline outline = classOutline.parent();
JType type = field.type();
if (type instanceof JDefinedClass) {
return isPropertyContainer((JDefinedClass) type, outline);
}
return false;
}
private boolean updateOidField(JFieldVar field, ClassOutline classOutline) {
JDefinedClass definedClass = classOutline.implClass;
Outline outline = classOutline.parent();
JClass string = (JClass) outline.getModel().codeModel._ref(String.class);
JMethod oldMethod = definedClass.getMethod("getOid", new JType[]{});
JMethod method = recreateMethod(oldMethod, definedClass);
JBlock body = method.body();
body._return(JExpr.invoke(METHOD_GET_CONTAINER).invoke("getOid"));
copyAnnotations(method, field, oldMethod);
method = definedClass.getMethod("setOid", new JType[]{string});
method = recreateMethod(method, definedClass);
body = method.body();
JInvocation invocation = body.invoke(JExpr.invoke(METHOD_GET_CONTAINER), method.name());
invocation.arg(method.listParams()[0]);
return true;
}
private boolean updateContainerFieldType(JFieldVar field, ClassOutline classOutline) {
//only setter method must be updated
String methodName = getSetterMethod(classOutline, field);
JDefinedClass definedClass = classOutline.implClass;
JMethod method = definedClass.getMethod(methodName, new JType[]{field.type()});
method = recreateMethod(method, definedClass);
JBlock body = method.body();
JVar param = method.listParams()[0];
body.assign(JExpr._this().ref(field), param);
JConditional condition = body._if(param.eq(JExpr._null()));
JBlock thenBlock = condition._then();
thenBlock.directStatement("//todo how do we remove property container from parent container???");
JBlock elseBlock = condition._else();
JInvocation addReplace = elseBlock.invoke(JExpr.invoke(METHOD_GET_CONTAINER), METHOD_ADD_REPLACE_EXISTING);
addReplace.arg(JExpr.invoke(param, METHOD_GET_CONTAINER));
return false;
}
private boolean updateField(JFieldVar field, ClassOutline classOutline) {
JDefinedClass definedClass = classOutline.implClass;
//update getter
String methodName = getGetterMethod(classOutline, field);
JMethod oldMethod = definedClass.getMethod(methodName, new JType[]{});
JMethod method = recreateMethod(oldMethod, definedClass);
copyAnnotations(method, field, oldMethod);
JClass list = (JClass) classOutline.parent().getModel().codeModel._ref(List.class);
JType type = field.type();
boolean isList = false;
if (type instanceof JClass) {
isList = list.equals(((JClass) type).erasure());
}
createFieldGetterBody(method, field, classOutline, isList);
//update setter
if (isList) {
//setter for list field members was not created
return true;
}
methodName = getSetterMethod(classOutline, field);
method = definedClass.getMethod(methodName, new JType[]{field.type()});
method = recreateMethod(method, definedClass);
createFieldSetterBody(method, field, classOutline);
return true;
}
private void createFieldSetterBody(JMethod method, JFieldVar field, ClassOutline classOutline) {
JBlock body = method.body();
JClass prismUtil = (JClass) classOutline.parent().getModel().codeModel._ref(PrismForJAXBUtil.class);
JInvocation invocation = body.staticInvoke(prismUtil, METHOD_SET_PROPERTY_VALUE);
//push arguments
invocation.arg(JExpr.invoke(METHOD_GET_CONTAINER));
invocation.arg(JExpr.ref(fieldFPrefixUnderscoredUpperCase(field.name())));
invocation.arg(method.listParams()[0]);
}
private void createFieldGetterBody(JMethod method, JFieldVar field, ClassOutline classOutline, boolean isList) {
JBlock body = method.body();
JClass prismUtil = (JClass) classOutline.parent().getModel().codeModel._ref(PrismForJAXBUtil.class);
JInvocation invocation;
if (isList) {
invocation = prismUtil.staticInvoke(METHOD_GET_PROPERTY_VALUES);
} else {
invocation = prismUtil.staticInvoke(METHOD_GET_PROPERTY_VALUE);
}
//push arguments
invocation.arg(JExpr.invoke(METHOD_GET_CONTAINER));
invocation.arg(JExpr.ref(fieldFPrefixUnderscoredUpperCase(field.name())));
JType type = field.type();
if (type.isPrimitive()) {
JPrimitiveType primitive = (JPrimitiveType) type;
invocation.arg(JExpr.dotclass(primitive.boxify()));
} else {
JClass clazz = (JClass) type;
if (isList) {
invocation.arg(JExpr.dotclass(clazz.getTypeParameters().get(0)));
} else {
invocation.arg(JExpr.dotclass(clazz));
}
}
body._return(invocation);
}
} |
package org.mwc.cmap.core.DataTypes.TrackData;
import java.util.*;
import Debrief.Tools.Tote.WatchableList;
import Debrief.Wrappers.TrackWrapper;
import MWC.GUI.*;
import MWC.TacticalData.Track;
/**
* embedded class which manages the primary & secondary tracks
*/
public class TrackManager implements TrackDataProvider
// TrackDataProvider.TrackDataListener
{
private WatchableList _thePrimary;
private WatchableList[] _theSecondaries;
private Vector _myDataListeners;
private Layers _theLayers;
private Vector _myShiftListeners;
/**
* set a limit for the maximum number of secondary tracks we will plot
*/
private static final int MAX_SECONDARIES = 10;
/**
* and the message to display
*/
private static final String MAX_MESSAGE = "Too many tracks. Only the first "
+ MAX_SECONDARIES + " secondary tracks have been assigned";
public TrackManager(Layers parentLayers)
{
_theLayers = parentLayers;
}
/**
* pass through the data, and assign any watchables as primary and secondary
*
* @param onlyAssignTracks
* only put TracksWrappers on the tote
*/
public void autoAssign(boolean onlyAssignTracks)
{
// check we have some data to search
if (_theLayers != null)
{
// pass through the data to find the WatchableLists
for (int l = 0; l < _theLayers.size(); l++)
{
final Layer layer = _theLayers.elementAt(l);
if (layer instanceof WatchableList)
{
if (_theSecondaries != null)
{
// have we got our full set of secondarires yet?
if (_theSecondaries.length >= MAX_SECONDARIES)
{
MWC.GUI.Dialogs.DialogFactory.showMessage("Secondary limit reached",
MAX_MESSAGE);
return;
}
}
processWatchableList((WatchableList) layer, onlyAssignTracks);
}
else
{
final Enumeration iter = layer.elements();
while (iter.hasMoreElements())
{
final Plottable p = (Plottable) iter.nextElement();
if (p instanceof WatchableList)
{
if (_theSecondaries != null)
{
// have we got our full set of secondarires yet?
if (_theSecondaries.length >= MAX_SECONDARIES)
{
MWC.GUI.Dialogs.DialogFactory.showMessage("Secondary limit reached",
MAX_MESSAGE);
return;
}
}
processWatchableList((WatchableList) p, onlyAssignTracks);
}
}
}
}
}
}
/**
* @param list
* the list of items to process
* @param onlyAssignTracks
* whether only TrackWrapper items should be placed on the list
*/
private void processWatchableList(final WatchableList list, boolean onlyAssignTracks)
{
// check this isn't the primary
if (list != getPrimaryTrack())
{
final WatchableList w = (WatchableList) list;
// see if we need a primary setting
if (getPrimaryTrack() == null)
{
if (w.getVisible())
if ((!onlyAssignTracks) || (onlyAssignTracks) && (w instanceof TrackWrapper))
setPrimary(w);
}
else
{
boolean haveAlready = false;
// check that this isn't one of our secondaries
for (int i = 0; i < _theSecondaries.length; i++)
{
WatchableList secW = _theSecondaries[i];
if (secW == w)
{
// don't bother with it, we've got it already
haveAlready = true;
continue;
}
}
if (!haveAlready)
{
if (w.getVisible())
if ((!onlyAssignTracks) || (onlyAssignTracks) && (w instanceof TrackWrapper))
addSecondary(w);
}
}
}
}
public void assignTracks(String primaryTrack, Vector secondaryTracks)
{
// ok - find the matching tracks/
Object theP = _theLayers.findLayer(primaryTrack);
if (theP != null)
{
if (theP instanceof WatchableList)
{
_thePrimary = (WatchableList) theP;
}
}
// do we have secondaries?
if (secondaryTracks != null)
{
// and now the secs
Vector secs = new Vector(0, 1);
Iterator iter = secondaryTracks.iterator();
while (iter.hasNext())
{
String thisS = (String) iter.next();
Object theS = _theLayers.findLayer(thisS);
if (theS != null)
if (theS instanceof WatchableList)
{
secs.add(theS);
}
}
if (secs.size() > 0)
{
_theSecondaries = new WatchableList[] { null };
_theSecondaries = (WatchableList[]) secs.toArray(_theSecondaries);
}
}
}
public void addTrackDataListener(TrackDataListener listener)
{
if (_myDataListeners == null)
_myDataListeners = new Vector();
// do we already contain this one?
if (!_myDataListeners.contains(listener))
_myDataListeners.add(listener);
}
public void addTrackShiftListener(TrackShiftListener listener)
{
if (_myShiftListeners == null)
_myShiftListeners = new Vector();
// do we already contain this one?
if (!_myShiftListeners.contains(listener))
_myShiftListeners.add(listener);
}
public WatchableList getPrimaryTrack()
{
return _thePrimary;
}
public WatchableList[] getSecondaryTracks()
{
return _theSecondaries;
}
public void setPrimary(WatchableList primary)
{
// ok - set it as the primary
setPrimaryImpl(primary);
// now remove it as a secondary
removeSecondaryImpl(primary);
fireTracksChanged();
}
private void setPrimaryImpl(WatchableList primary)
{
_thePrimary = primary;
// and inform the listeners
if (_myDataListeners != null)
{
Iterator iter = _myDataListeners.iterator();
while (iter.hasNext())
{
TrackDataListener list = (TrackDataListener) iter.next();
list.tracksUpdated(_thePrimary, _theSecondaries);
}
}
}
public void secondariesUpdated(WatchableList[] secondaries)
{
_theSecondaries = secondaries;
// and inform the listeners
fireTracksChanged();
}
private void fireTracksChanged()
{
if (_myDataListeners != null)
{
Iterator iter = _myDataListeners.iterator();
while (iter.hasNext())
{
TrackDataListener list = (TrackDataListener) iter.next();
list.tracksUpdated(_thePrimary, _theSecondaries);
}
}
}
public void addSecondary(WatchableList secondary)
{
// right, insert this as a secondary track
addSecondaryImpl(secondary);
// was it the primary?
if (secondary == _thePrimary)
setPrimaryImpl(null);
fireTracksChanged();
}
private void addSecondaryImpl(WatchableList secondary)
{
// store the new list
Vector newList = new Vector(1, 1);
// copy in the old list
if (_theSecondaries != null)
{
for (int i = 0; i < _theSecondaries.length; i++)
{
newList.add(_theSecondaries[i]);
}
}
// and add the new item
newList.add(secondary);
WatchableList[] demo = new WatchableList[] { null };
_theSecondaries = (WatchableList[]) newList.toArray(demo);
}
// testing for this class
static public final class testTrackManager extends junit.framework.TestCase
{
static public final String TEST_ALL_TEST_TYPE = "UNIT";
public testTrackManager(final String val)
{
super(val);
}
public void testLists()
{
TrackWrapper ta = new TrackWrapper();
ta.setTrack(new Track());
ta.setName("ta");
TrackWrapper tb = new TrackWrapper();
tb.setTrack(new Track());
tb.setName("tb");
TrackWrapper tc = new TrackWrapper();
tc.setTrack(new Track());
tc.setName("tc");
Layers theLayers = new Layers();
theLayers.addThisLayer(ta);
theLayers.addThisLayer(tb);
theLayers.addThisLayer(tc);
String pri_a = "ta";
String pri_b = "tz";
String sec_b = "tb";
String sec_c = "tc";
String sec_d = "tz";
Vector secs = new Vector(0, 1);
secs.add(sec_b);
secs.add(sec_c);
// create the mgr
TrackManager tm = new TrackManager(theLayers);
// do some checks
assertNull("pri empty", tm._thePrimary);
assertNull("secs empty", tm._theSecondaries);
assertNotNull("layers assigned", tm._theLayers);
// now get going
tm.assignTracks(pri_a, secs);
// and do the tests
assertNotNull("pri assigned", tm._thePrimary);
assertEquals("pri matches", tm._thePrimary, ta);
// and the secs
assertNotNull("sec assigned", tm._theSecondaries);
assertEquals("correct num", 2, tm._theSecondaries.length);
// setup duff data
secs.clear();
secs.add(sec_b);
secs.add(sec_d);
// assign duff data
tm.assignTracks(pri_b, secs);
// and test duff data
assertNotNull("pri still assigned", tm._thePrimary);
assertEquals("pri matches", tm._thePrimary, ta);
assertNotNull("sec assigned", tm._theSecondaries);
assertEquals("correct num", 1, tm._theSecondaries.length);
// assign more real data
tm.assignTracks(sec_c, secs);
// and test duff data
assertNotNull("pri still assigned", tm._thePrimary);
assertEquals("pri matches", tm._thePrimary, tc);
assertNotNull("sec assigned", tm._theSecondaries);
assertEquals("correct num", 1, tm._theSecondaries.length);
}
}
public void removeTrackDataListener(TrackDataListener listener)
{
if (_myDataListeners != null)
_myDataListeners.remove(listener);
}
public void removeTrackShiftListener(TrackShiftListener listener)
{
if (_myShiftListeners != null)
_myShiftListeners.remove(listener);
}
/**
* remove the indicated secondary track
*
* @param thisSec
*/
public void removeSecondary(WatchableList thisSec)
{
removeSecondaryImpl(thisSec);
// and now fire updates
fireTracksChanged();
}
private void removeSecondaryImpl(WatchableList thisSec)
{
// store the new list
Vector newList = new Vector(1, 1);
// copy in the old list
if (_theSecondaries != null)
{
for (int i = 0; i < _theSecondaries.length; i++)
{
WatchableList curSec = _theSecondaries[i];
if (curSec == thisSec)
{
// hey, just ignore it
}
else
{
newList.add(_theSecondaries[i]);
}
}
}
if (newList.size() > 0)
{
WatchableList[] demo = new WatchableList[] { null };
_theSecondaries = (WatchableList[]) newList.toArray(demo);
}
else
_theSecondaries = new WatchableList[0];
}
/**
* ok - tell anybody that wants to know that it's moved
*
* @param target
*/
public void fireTrackShift(TrackWrapper target)
{
if (_myShiftListeners != null)
{
Iterator iter = _myShiftListeners.iterator();
while (iter.hasNext())
{
TrackShiftListener list = (TrackShiftListener) iter.next();
list.trackShifted(target);
}
}
}
} |
package arjdbc.postgresql;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.sql.Array;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.List;
import java.util.UUID;
import org.jruby.Ruby;
import org.jruby.RubyArray;
import org.jruby.RubyBoolean;
import org.jruby.RubyClass;
import org.jruby.RubyFloat;
import org.jruby.RubyIO;
import org.jruby.RubyString;
import org.jruby.anno.JRubyMethod;
import org.jruby.javasupport.JavaUtil;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.ByteList;
import org.postgresql.PGConnection;
import org.postgresql.PGStatement;
import org.postgresql.util.PGInterval;
import org.postgresql.util.PGobject;
/**
*
* @author enebo
*/
public class PostgreSQLRubyJdbcConnection extends arjdbc.jdbc.RubyJdbcConnection {
protected PostgreSQLRubyJdbcConnection(Ruby runtime, RubyClass metaClass) {
super(runtime, metaClass);
}
public static RubyClass createPostgreSQLJdbcConnectionClass(Ruby runtime, RubyClass jdbcConnection) {
final RubyClass clazz = getConnectionAdapters(runtime).
defineClassUnder("PostgreSQLJdbcConnection", jdbcConnection, POSTGRESQL_JDBCCONNECTION_ALLOCATOR);
clazz.defineAnnotatedMethods(PostgreSQLRubyJdbcConnection.class);
getConnectionAdapters(runtime).setConstant("PostgresJdbcConnection", clazz); // backwards-compat
return clazz;
}
private static ObjectAllocator POSTGRESQL_JDBCCONNECTION_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
return new PostgreSQLRubyJdbcConnection(runtime, klass);
}
};
// enables testing if the bug is fixed (please run our test-suite)
// using `rake test_postgresql JRUBY_OPTS="-J-Darjdbc.postgresql.generated.keys=true"`
protected static final boolean generatedKeys = Boolean.getBoolean("arjdbc.postgresql.generated.keys");
@Override
protected IRubyObject mapGeneratedKeys(
final Ruby runtime, final Connection connection,
final Statement statement, final Boolean singleResult)
throws SQLException {
if ( generatedKeys ) {
super.mapGeneratedKeys(runtime, connection, statement, singleResult);
}
// NOTE: PostgreSQL driver supports generated keys but does not work
// correctly for all cases e.g. for tables whene no keys are generated
// during an INSERT getGeneratedKeys return all inserted rows instead
// of an empty result set ... thus disabled until issue is resolved !
return null; // not supported
}
@Override
protected String caseConvertIdentifierForJdbc(final DatabaseMetaData metaData, final String value)
throws SQLException {
if ( value != null ) {
if ( metaData.storesUpperCaseIdentifiers() ) {
return value.toUpperCase();
}
// for PostgreSQL we do not care about storesLowerCaseIdentifiers()
}
return value;
}
@Override
protected void setStatementParameters(final ThreadContext context,
final Connection connection, final PreparedStatement statement,
final List<?> binds) throws SQLException {
((PGConnection) connection).addDataType("daterange", DateRangeType.class);
((PGConnection) connection).addDataType("tsrange", TsRangeType.class);
((PGConnection) connection).addDataType("tstzrange", TstzRangeType.class);
((PGConnection) connection).addDataType("int4range", Int4RangeType.class);
((PGConnection) connection).addDataType("int8range", Int8RangeType.class);
((PGConnection) connection).addDataType("numrange", NumRangeType.class);
super.setStatementParameters(context, connection, statement, binds);
}
@Override // due statement.setNull(index, Types.BLOB) not working :
// org.postgresql.util.PSQLException: ERROR: column "sample_binary" is of type bytea but expression is of type oid
protected void setBlobParameter(final ThreadContext context,
final Connection connection, final PreparedStatement statement,
final int index, final Object value,
final IRubyObject column, final int type) throws SQLException {
if ( value instanceof IRubyObject ) {
setBlobParameter(context, connection, statement, index, (IRubyObject) value, column, type);
}
else {
if ( value == null ) statement.setNull(index, Types.BINARY);
else {
statement.setBinaryStream(index, (InputStream) value);
}
}
}
@Override // due statement.setNull(index, Types.BLOB) not working :
// org.postgresql.util.PSQLException: ERROR: column "sample_binary" is of type bytea but expression is of type oid
protected void setBlobParameter(final ThreadContext context,
final Connection connection, final PreparedStatement statement,
final int index, final IRubyObject value,
final IRubyObject column, final int type) throws SQLException {
if ( value.isNil() ) {
statement.setNull(index, Types.BINARY);
}
else {
if ( value instanceof RubyIO ) { // IO/File
statement.setBinaryStream(index, ((RubyIO) value).getInStream());
}
else { // should be a RubyString
final ByteList blob = value.asString().getByteList();
statement.setBinaryStream(index,
new ByteArrayInputStream(blob.unsafeBytes(), blob.getBegin(), blob.getRealSize()),
blob.getRealSize() // length
);
}
}
}
@Override // to handle infinity timestamp values
protected void setTimestampParameter(final ThreadContext context,
final Connection connection, final PreparedStatement statement,
final int index, IRubyObject value,
final IRubyObject column, final int type) throws SQLException {
if ( value instanceof RubyFloat ) {
final double _value = ( (RubyFloat) value ).getValue();
if ( Double.isInfinite(_value) ) {
final Timestamp timestamp;
if ( _value < 0 ) {
timestamp = new Timestamp(PGStatement.DATE_NEGATIVE_INFINITY);
}
else {
timestamp = new Timestamp(PGStatement.DATE_POSITIVE_INFINITY);
}
statement.setTimestamp( index, timestamp );
return;
}
}
super.setTimestampParameter(context, connection, statement, index, value, column, type);
}
private static final ByteList INTERVAL =
new ByteList( new byte[] { 'i','n','t','e','r','v','a','l' }, false );
@Override
protected void setStringParameter(final ThreadContext context,
final Connection connection, final PreparedStatement statement,
final int index, final IRubyObject value,
final IRubyObject column, final int type) throws SQLException {
if ( value.isNil() ) statement.setNull(index, Types.VARCHAR);
else {
if ( column != null && ! column.isNil() ) {
final RubyString sqlType = column.callMethod(context, "sql_type").asString();
if ( sqlType.getByteList().startsWith( INTERVAL ) ) {
statement.setObject( index, new PGInterval( value.asString().toString() ) );
return;
}
}
statement.setString( index, value.asString().toString() );
}
}
@Override
protected void setObjectParameter(final ThreadContext context,
final Connection connection, final PreparedStatement statement,
final int index, Object value,
final IRubyObject column, final int type) throws SQLException {
final String columnType = column.callMethod(context, "type").asJavaString();
if ( columnType != null && columnType.endsWith("range") ) {
if ( value instanceof IRubyObject ) {
final IRubyObject rubyValue = (IRubyObject) value;
if ( rubyValue.isNil() ) {
statement.setNull(index, Types.OTHER); return;
}
else {
final String rangeValue = column.getMetaClass().
callMethod("range_to_string", rubyValue).toString();
final Object rangeObject;
if ( columnType == (Object) "daterange" ) {
rangeObject = new DateRangeType(rangeValue);
}
else if ( columnType == (Object) "tsrange" ) {
rangeObject = new TsRangeType(rangeValue);
}
else if ( columnType == (Object) "tstzrange" ) {
rangeObject = new TstzRangeType(rangeValue);
}
else if ( columnType == (Object) "int4range" ) {
rangeObject = new Int4RangeType(rangeValue);
}
else if ( columnType == (Object) "int8range" ) {
rangeObject = new Int8RangeType(rangeValue);
}
else { // if ( columnType == (Object) "numrange" )
rangeObject = new NumRangeType(rangeValue);
}
statement.setObject(index, rangeObject);
}
}
else {
if ( value == null ) {
statement.setNull(index, Types.JAVA_OBJECT);
}
else { // NOTE: this won't work with 9.2.1003
statement.setString(index, value.toString());
}
}
return;
}
super.setObjectParameter(context, connection, statement, index, value, column, type);
}
@Override
protected String resolveArrayBaseTypeName(final ThreadContext context,
final Object value, final IRubyObject column, final int type) {
String sqlType = column.callMethod(context, "sql_type").toString();
if ( sqlType.startsWith("character varying") ) return "text";
final int index = sqlType.indexOf('('); // e.g. "character varying(255)"
if ( index > 0 ) sqlType = sqlType.substring(0, index);
return sqlType;
}
@Override
protected int jdbcTypeFor(final ThreadContext context, final Ruby runtime,
final IRubyObject column, final Object value) throws SQLException {
// NOTE: likely wrong but native adapters handles this thus we should
// too - used from #table_exists? `binds << [ nil, schema ] if schema`
if ( column == null || column.isNil() ) return Types.VARCHAR; // assume type == :string
return super.jdbcTypeFor(context, runtime, column, value);
}
/**
* Override jdbcToRuby type conversions to handle infinite timestamps.
* Handing timestamp off to ruby as string so adapter can perform type
* conversion to timestamp
*/
@Override
protected IRubyObject jdbcToRuby(
final ThreadContext context, final Ruby runtime,
final int column, final int type, final ResultSet resultSet)
throws SQLException {
switch ( type ) {
case Types.BIT:
// we do get BIT for 't' 'f' as well as BIT strings e.g. "0110" :
final String bits = resultSet.getString(column);
if ( bits == null ) return runtime.getNil();
if ( bits.length() > 1 ) {
return RubyString.newUnicodeString(runtime, bits);
}
return booleanToRuby(context, runtime, resultSet, column);
//case Types.JAVA_OBJECT: case Types.OTHER:
//return objectToRuby(runtime, resultSet, resultSet.getObject(column));
}
return super.jdbcToRuby(context, runtime, column, type, resultSet);
}
@Override
protected IRubyObject timestampToRuby(final ThreadContext context,
final Ruby runtime, final ResultSet resultSet, final int column)
throws SQLException {
// NOTE: using Timestamp we loose information such as BC :
// Timestamp: '0001-12-31 22:59:59.0' String: '0001-12-31 22:59:59 BC'
final String value = resultSet.getString(column);
if ( value == null ) {
if ( resultSet.wasNull() ) return runtime.getNil();
return runtime.newString();
}
final RubyString strValue = timestampToRubyString(runtime, value.toString());
if ( rawDateTime != null && rawDateTime.booleanValue() ) return strValue;
final IRubyObject adapter = callMethod(context, "adapter"); // self.adapter
if ( adapter.isNil() ) return strValue; // NOTE: we warn on init_connection
return adapter.callMethod(context, "_string_to_timestamp", strValue);
}
@Override
protected IRubyObject arrayToRuby(final ThreadContext context,
final Ruby runtime, final ResultSet resultSet, final int column)
throws SQLException {
// NOTE: avoid `finally { array.free(); }` on PostgreSQL due :
// java.sql.SQLFeatureNotSupportedException:
// Method org.postgresql.jdbc4.Jdbc4Array.free() is not yet implemented.
final Array value = resultSet.getArray(column);
if ( value == null && resultSet.wasNull() ) return runtime.getNil();
final RubyArray array = runtime.newArray();
final ResultSet arrayResult = value.getResultSet(); // 1: index, 2: value
final int baseType = value.getBaseType();
while ( arrayResult.next() ) {
array.append( jdbcToRuby(context, runtime, 2, baseType, arrayResult) );
}
return array;
}
@Override
protected IRubyObject objectToRuby(final ThreadContext context,
final Ruby runtime, final ResultSet resultSet, final int column)
throws SQLException {
final Object object = resultSet.getObject(column);
if ( object == null && resultSet.wasNull() ) return runtime.getNil();
final Class<?> objectClass = object.getClass();
if ( objectClass == UUID.class ) {
return runtime.newString( object.toString() );
}
if ( objectClass == PGInterval.class ) {
return runtime.newString( formatInterval(object) );
}
if ( object instanceof PGobject ) {
// PG 9.2 JSON type will be returned here as well
return runtime.newString( object.toString() );
}
return JavaUtil.convertJavaToRuby(runtime, object);
}
@Override
protected TableName extractTableName(
final Connection connection, String catalog, String schema,
final String tableName) throws IllegalArgumentException, SQLException {
// The postgres JDBC driver will default to searching every schema if no
// schema search path is given. Default to the 'public' schema instead:
if ( schema == null ) schema = "public";
return super.extractTableName(connection, catalog, schema, tableName);
}
// NOTE: do not use PG classes in the API so that loading is delayed !
private String formatInterval(final Object object) {
final PGInterval interval = (PGInterval) object;
if ( rawIntervalType ) return interval.getValue();
final StringBuilder str = new StringBuilder(32);
final int years = interval.getYears();
if ( years != 0 ) str.append(years).append(" years ");
final int months = interval.getMonths();
if ( months != 0 ) str.append(months).append(" months ");
final int days = interval.getDays();
if ( days != 0 ) str.append(days).append(" days ");
final int hours = interval.getHours();
final int mins = interval.getMinutes();
final int secs = (int) interval.getSeconds();
if ( hours != 0 || mins != 0 || secs != 0 ) { // xx:yy:zz if not all 00
if ( hours < 10 ) str.append('0');
str.append(hours).append(':');
if ( mins < 10 ) str.append('0');
str.append(mins).append(':');
if ( secs < 10 ) str.append('0');
str.append(secs);
}
else {
if ( str.length() > 1 ) str.deleteCharAt( str.length() - 1 ); // " " at the end
}
return str.toString();
}
// whether to use "raw" interval values off by default - due native adapter compatibilty :
// RAW values :
// - 2 years 0 mons 0 days 0 hours 3 mins 0.00 secs
// - -1 years 0 mons -2 days 0 hours 0 mins 0.00 secs
// Rails style :
// - 2 years 00:03:00
// - -1 years -2 days
protected static boolean rawIntervalType = Boolean.getBoolean("arjdbc.postgresql.iterval.raw");
@JRubyMethod(name = "raw_interval_type?")
public static IRubyObject useRawIntervalType(final ThreadContext context, final IRubyObject self) {
return context.getRuntime().newBoolean(rawIntervalType);
}
@JRubyMethod(name = "raw_interval_type=")
public static IRubyObject setRawIntervalType(final IRubyObject self, final IRubyObject value) {
if ( value instanceof RubyBoolean ) {
rawIntervalType = ((RubyBoolean) value).isTrue();
}
else {
rawIntervalType = value.isNil();
}
return value;
}
// NOTE: without these custom registered Postgre (driver) types
// ... we can not set range parameters in prepared statements !
public static class DateRangeType extends PGobject {
public DateRangeType() {
setType("daterange");
}
public DateRangeType(final String value) throws SQLException {
this();
setValue(value);
}
}
public static class TsRangeType extends PGobject {
public TsRangeType() {
setType("tsrange");
}
public TsRangeType(final String value) throws SQLException {
this();
setValue(value);
}
}
public static class TstzRangeType extends PGobject {
public TstzRangeType() {
setType("tstzrange");
}
public TstzRangeType(final String value) throws SQLException {
this();
setValue(value);
}
}
public static class Int4RangeType extends PGobject {
public Int4RangeType() {
setType("int4range");
}
public Int4RangeType(final String value) throws SQLException {
this();
setValue(value);
}
}
public static class Int8RangeType extends PGobject {
public Int8RangeType() {
setType("int8range");
}
public Int8RangeType(final String value) throws SQLException {
this();
setValue(value);
}
}
public static class NumRangeType extends PGobject {
public NumRangeType() {
setType("numrange");
}
public NumRangeType(final String value) throws SQLException {
this();
setValue(value);
}
}
} |
// Vilya library - tools for developing networked games
// This library is free software; you can redistribute it and/or modify it
// (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.ezgame.server;
import com.samskivert.util.Invoker;
import com.samskivert.util.ResultListener;
import com.threerings.crowd.server.CrowdServer;
import com.threerings.presents.client.InvocationService;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;
import java.lang.reflect.Array;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Level;
import com.samskivert.util.CountHashMap;
import com.samskivert.util.RandomUtil;
import static com.threerings.ezgame.server.Log.log;
/**
* Manages loading and querying word dictionaries in multiple languages.
*
* NOTE: the service supports lazy loading of language files, but does not
* _unload_ them from memory, leading to increasing memory usage.
*
* NOTE: the dictionary service has not yet been tested with language
* files written in non-default character encodings.
*/
public class DictionaryManager
{
/**
* Helper class, encapsulates a sorted array of word hashes,
* which can be used to look up the existence of a word.
*/
private class Dictionary
{
/**
* Constructor, loads up the word list and initializes storage.
* This naive version assumes language files are simple list of words,
* with one word per line.
*/
public Dictionary (File wordfile)
{
try
{
if (wordfile.exists() && wordfile.isFile() && wordfile.canRead())
{
// File length will give us a rough starting point for the word array
long bytecount = wordfile.length();
int approxWords = (int) (bytecount / 5); // just a heuristic,
// Read it line by line
BufferedReader reader = new BufferedReader (new FileReader (wordfile));
String line = null;
while ((line = reader.readLine()) != null) {
String word = line.toLowerCase();
// Add the word to the dictionary
_words.add(word);
// count characters
for (int ii = word.length() - 1; ii >= 0; ii
char ch = word.charAt(ii);
_letters.incrementCount(ch, 1);
}
}
log.log (Level.INFO,
"Loaded dictionary file " + wordfile.getName () +
" with " + _words.size () + " entries, " +
_letters.size () + " letters.");
}
else
{
log.log (Level.WARNING,
"Could not access dictionary file " + wordfile.getAbsolutePath ());
}
}
catch (Exception ex)
{
log.log (Level.WARNING, "Failed to load dictionary file", ex);
_words.clear(); // dump everything
_letters.clear();
}
}
/** Checks if the specified word exists in the word list */
public boolean contains (String word)
{
return (word != null) && _words.contains(word.toLowerCase());
}
/** Gets an array of random letters for the language, with uniform distribution. */
public char[] randomLetters (int count)
{
Set<Character> letterSet = _letters.keySet();
int letterCount = letterSet.size();
Character[] letters = new Character[letterCount];
letterSet.toArray(letters);
char[] results = new char[count];
for (int ii = 0; ii < count; ii++) {
results[ii] = letters[RandomUtil.getInt(letterCount)];
}
return results;
}
// PRIVATE STORAGE
/** The words. */
protected HashSet<String> _words = new HashSet<String>();
/** Letter frequency. */
protected CountHashMap<Character> _letters = new CountHashMap<Character>();
}
/**
* Creates the singleton instance of the dictionary service.
*/
public static void init (File dictionaryRoot)
{
_singleton = new DictionaryManager (dictionaryRoot);
}
/**
* Get an instance of the dictionary service.
*/
public static DictionaryManager getInstance ()
{
return _singleton;
}
/**
* Protected constructor.
*/
protected DictionaryManager (File dictionaryRoot)
{
_dictionaryRoot = dictionaryRoot;
}
/**
* Returns true if the language is known to be supported by the
* dictionary service (would it be better to return a whole list
* of supported languages instead?)
*/
public void isLanguageSupported (
final String locale, final InvocationService.ResultListener listener)
{
// TODO: once we have file paths set up, change this to match
// against dictionary files
listener.requestProcessed (locale.toLowerCase().startsWith("en"));
}
/**
* Retrieves a set of letters from a language definition file,
* and returns a random sampling of /count/ elements.
*/
public void getLetterSet (
final String locale, final int count, final InvocationService.ResultListener listener)
{
// Create a new unit of work
Invoker.Unit work = new Invoker.Unit ("DictionaryManager.getLetterSet") {
public boolean invoke ()
{
Dictionary dict = getDictionary (locale);
char[] chars = dict.randomLetters (count);
StringBuilder sb = new StringBuilder ();
for (char c : chars)
{
sb.append (c);
sb.append (',');
}
sb.deleteCharAt (sb.length() - 1);
listener.requestProcessed (sb.toString());
return true;
}
};
// Do the work!
CrowdServer.invoker.postUnit (work);
}
/**
* Checks if the specified word exists in the given language
*/
public void checkWord (
final String locale, final String word, final InvocationService.ResultListener listener)
{
// Create a new unit of work
Invoker.Unit work = new Invoker.Unit ("DictionaryManager.checkWord") {
public boolean invoke ()
{
Dictionary dict = getDictionary (locale);
boolean result = (dict != null && dict.contains (word));
listener.requestProcessed (result);
return true;
}
};
// ...and off we go.
CrowdServer.invoker.postUnit (work);
}
/**
* Retrieves the dictionary object for a given locale.
* Forces the dictionary file to be loaded, if it hasn't already.
*/
private Dictionary getDictionary (String locale)
{
locale = locale.toLowerCase ();
if (! _dictionaries.containsKey (locale))
{
try
{
// Make a file name
String filename = locale + ".wordlist";
File file = new File (_dictionaryRoot, filename);
_dictionaries.put (locale, new Dictionary (file));
}
catch (Exception e)
{
log.log (Level.WARNING, "Failed to load language file", e);
}
}
return _dictionaries.get (locale);
}
// PRIVATE VARIABLES
/** Singleton instance pointer */
private static DictionaryManager _singleton;
/** Root directory where we find dictionary files */
private File _dictionaryRoot;
/** Map from locale name to Dictionary object */
private HashMap <String, Dictionary> _dictionaries = new HashMap <String, Dictionary> ();
} |
// $Id: PuzzleManagerDelegate.java 209 2007-02-24 00:37:33Z mdb $
// Vilya library - tools for developing networked games
// This library is free software; you can redistribute it and/or modify it
// (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.stats.server.persist;
import com.samskivert.jdbc.depot.Key;
import com.samskivert.jdbc.depot.PersistentRecord;
import com.samskivert.jdbc.depot.annotation.Column;
import com.samskivert.jdbc.depot.annotation.Entity;
import com.samskivert.jdbc.depot.annotation.Id;
import com.samskivert.jdbc.depot.expression.ColumnExp;
@Entity(name="STATS")
public class StatRecord extends PersistentRecord
{
// AUTO-GENERATED: FIELDS START
/** The column identifier for the {@link #playerId} field. */
public static final String PLAYER_ID = "playerId";
/** The qualified column identifier for the {@link #playerId} field. */
public static final ColumnExp PLAYER_ID_C =
new ColumnExp(StatRecord.class, PLAYER_ID);
/** The column identifier for the {@link #statCode} field. */
public static final String STAT_CODE = "statCode";
/** The qualified column identifier for the {@link #statCode} field. */
public static final ColumnExp STAT_CODE_C =
new ColumnExp(StatRecord.class, STAT_CODE);
/** The column identifier for the {@link #statData} field. */
public static final String STAT_DATA = "statData";
/** The qualified column identifier for the {@link #statData} field. */
public static final ColumnExp STAT_DATA_C =
new ColumnExp(StatRecord.class, STAT_DATA);
// AUTO-GENERATED: FIELDS END
public static final int SCHEMA_VERSION = 2;
/** The identifier of the player this is a stat for. */
@Id
@Column(name="PLAYER_ID")
public int playerId;
/** The code of the stat. */
@Id
@Column(name="STAT_CODE")
public int statCode;
/** The data associated with the stat. */
@Column(name="STAT_DATA")
public byte[] statData;
/**
* An empty constructor for unmarshalling.
*/
public StatRecord ()
{
super();
}
/**
* A constructor that populates all our fields.
*/
public StatRecord (int playerId, int statCode, byte[] data)
{
super();
this.playerId = playerId;
this.statCode = statCode;
this.statData = data;
}
// AUTO-GENERATED: METHODS START
/**
* Create and return a primary {@link Key} to identify a {@link #StatRecord}
* with the supplied key values.
*/
public static Key<StatRecord> getKey (int playerId, int statCode)
{
return new Key<StatRecord>(
StatRecord.class,
new String[] { PLAYER_ID, STAT_CODE },
new Comparable[] { playerId, statCode });
}
// AUTO-GENERATED: METHODS END
} |
package org.jaxen.function;
import java.util.List;
import org.jaxen.Context;
import org.jaxen.Function;
import org.jaxen.FunctionCallException;
import org.jaxen.Navigator;
public class NormalizeSpaceFunction implements Function
{
public Object call(Context context,
List args) throws FunctionCallException
{
if (args.size() >= 1)
{
return evaluate( args.get(0),
context.getNavigator() );
}
throw new FunctionCallException( "normalize-space() requires one argument" );
}
public static String evaluate(Object strArg,
Navigator nav)
{
String str = StringFunction.evaluate( strArg,
nav );
char[] buffer = str.toCharArray();
int write = 0;
int lastWrite = 0;
boolean wroteOne = false;
int read = 0;
while (read < buffer.length)
{
if (Character.isWhitespace(buffer[read]))
{
if (wroteOne)
{
buffer[write++] = ' ';
}
do
{
read++;
}
while(read < buffer.length && Character.isWhitespace(buffer[read]));
}
else
{
buffer[write++] = buffer[read++];
wroteOne = true;
lastWrite = write;
}
}
return new String(buffer, 0, lastWrite);
}
} |
package org.xwiki.rendering.wikimodel.util;
import java.util.ArrayList;
import java.util.List;
/**
* This is an internal utility class used as a context to keep in memory the
* current state of parsed trees (list items).
*
* @version $Id$
* @since 4.0M1
*/
public class ListBuilder
{
static class CharPos implements TreeBuilder.IPos<CharPos>
{
private int fPos;
private char fRowChar;
private char fTreeChar;
public CharPos(char treeChar, char rowChar, int pos)
{
fPos = pos;
fTreeChar = treeChar;
fRowChar = rowChar;
}
@Override
public boolean equals(Object obj)
{
if (obj == this) {
return true;
}
if (!(obj instanceof CharPos)) {
return false;
}
CharPos pos = (CharPos) obj;
return equalsData(pos) && pos.fPos == fPos;
}
public boolean equalsData(CharPos pos)
{
return pos.fTreeChar == fTreeChar;
}
public int getPos()
{
return fPos;
}
}
TreeBuilder<CharPos> fBuilder = new TreeBuilder<CharPos>(
new TreeBuilder.ITreeListener<CharPos>()
{
public void onBeginRow(CharPos pos)
{
fListener.beginRow(pos.fTreeChar, pos.fRowChar);
}
public void onBeginTree(CharPos pos)
{
fListener.beginTree(pos.fTreeChar);
}
public void onEndRow(CharPos pos)
{
fListener.endRow(pos.fTreeChar, pos.fRowChar);
}
public void onEndTree(CharPos pos)
{
fListener.endTree(pos.fTreeChar);
}
});
private IListListener fListener;
public ListBuilder(IListListener listener)
{
fListener = listener;
}
/**
* @param row the parameters of the row
*/
public void alignContext(String row)
{
List<CharPos> list = getCharPositions(row);
fBuilder.align(list);
}
private List<CharPos> getCharPositions(String s)
{
List<CharPos> list = new ArrayList<CharPos>();
char[] array = s.toCharArray();
int pos = 0;
for (int i = 0; i < array.length; i++) {
char ch = array[i];
if (ch == '\r' || ch == '\n') {
continue;
}
if (!Character.isSpaceChar(ch)) {
char treeChar = getTreeType(ch);
list.add(new CharPos(treeChar, ch, pos));
}
pos++;
}
return list;
}
/**
* @param rowType the type of the row
* @return the type of the tree corresponding to the given row type
*/
protected char getTreeType(char rowType)
{
return rowType;
}
} |
package com.salesforce.dva.argus.service.metric.transform;
import com.salesforce.dva.argus.entity.Metric;
import com.salesforce.dva.argus.service.metric.MetricReader;
import com.salesforce.dva.argus.system.SystemAssert;
import com.salesforce.dva.argus.system.SystemException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
/**
* Creates additional data points to fill gaps.<br>
* <tt>FILL(<expr>, <interval>, <interval>, <constant>)</tt>
*
* @author Ruofan Zhang(rzhang@salesforce.com)
*/
public class FillTransform implements Transform {
/** The default metric name for results. */
public static final String DEFAULT_METRIC_NAME = "result";
/** The default metric scope for results. */
public static final String DEFAULT_SCOPE_NAME = "scope";
private static Map<Long, Double> _fillMetricTransform(Metric metric, long windowSizeInSeconds, long offsetInSeconds, double value) {
if(metric == null || metric.getDatapoints() == null || metric.getDatapoints().isEmpty()) {
return Collections.emptyMap();
}
Map<Long, Double> filledDatapoints = new TreeMap<>();
Map<Long, Double> sortedDatapoints = new TreeMap<>(metric.getDatapoints());
Long[] sortedTimestamps = new Long[sortedDatapoints.size()];
sortedDatapoints.keySet().toArray(sortedTimestamps);
Long startTimestamp = sortedTimestamps[0];
Long endTimestamp = sortedTimestamps[sortedTimestamps.length - 1];
// create a new datapoints map propagateDatpoints, which have all the
// expected timestamps, then fill the missing value
int index = 1;
while (startTimestamp <= endTimestamp) {
filledDatapoints.put(startTimestamp, sortedDatapoints.containsKey(startTimestamp) ? sortedDatapoints.get(startTimestamp) : null);
if (index >= sortedDatapoints.size()) {
break;
}
if ((startTimestamp + windowSizeInSeconds * 1000) < sortedTimestamps[index]) {
startTimestamp = startTimestamp + windowSizeInSeconds * 1000;
} else {
startTimestamp = sortedTimestamps[index];
index++;
}
}
int newLength = filledDatapoints.size();
List<Long> newTimestamps = new ArrayList<Long>();
List<Double> newValues = new ArrayList<>();
for (Map.Entry<Long, Double> entry : filledDatapoints.entrySet()) {
newTimestamps.add(entry.getKey());
newValues.add(entry.getValue());
}
for (int i = 0; i < newLength; i++) {
if (newValues.get(i) != null) {
continue;
} else {
filledDatapoints.put(newTimestamps.get(i) + offsetInSeconds * 1000, value);
}
}
Map<Long, Double> cleanFilledDatapoints = new TreeMap<>();
for (Map.Entry<Long, Double> entry : filledDatapoints.entrySet()) {
if (entry.getValue() != null) {
cleanFilledDatapoints.put(entry.getKey(), entry.getValue());
}
}
return cleanFilledDatapoints;
}
private static long _parseTimeIntervalInSeconds(String interval) {
MetricReader.TimeUnit timeunit = null;
try {
long intervalInSeconds = 0;
timeunit = MetricReader.TimeUnit.fromString(interval.substring(interval.length() - 1));
long timeDigits = Long.parseLong(interval.substring(0, interval.length() - 1));
intervalInSeconds = timeDigits * timeunit.getValue() / 1000;
return intervalInSeconds;
} catch (Exception t) {
throw new SystemException("Please input a valid time interval!");
}
}
private List<Metric> _fillLine(List<String> constants, long relativeTo) {
SystemAssert.requireArgument(constants != null && constants.size() == 5,
"Line Filling Transform needs 5 constants (start, end, interval, offset, value)!");
long startTimestamp = _parseStartAndEndTimestamps(constants.get(0), relativeTo);
long endTimestamp = _parseStartAndEndTimestamps(constants.get(1), relativeTo);
long windowSizeInSeconds = _parseTimeIntervalInSeconds(constants.get(2));
long offsetInSeconds = _parseTimeIntervalInSeconds(constants.get(3));
double value = Double.parseDouble(constants.get(4));
SystemAssert.requireArgument(startTimestamp < endTimestamp, "End time must occure later than start time!");
SystemAssert.requireArgument(windowSizeInSeconds >= 0, "Window size must be greater than ZERO!");
boolean isDivisible = ((startTimestamp - endTimestamp) % (windowSizeInSeconds * 1000)) == 0;
// snapping start and end time if range is not a multiple of windowSize.
if (!isDivisible) {
long startSnapping = startTimestamp % (windowSizeInSeconds * 1000);
startTimestamp = startTimestamp - startSnapping;
long endSnapping = endTimestamp % (windowSizeInSeconds * 1000);
endTimestamp = endTimestamp - endSnapping;
}
Metric metric = new Metric(DEFAULT_SCOPE_NAME, DEFAULT_METRIC_NAME);
Map<Long, Double> filledDatapoints = new TreeMap<>();
while (startTimestamp < endTimestamp) {
filledDatapoints.put(startTimestamp, value);
startTimestamp += windowSizeInSeconds * 1000;
}
filledDatapoints.put(endTimestamp, value);
Map<Long, Double> newFilledDatapoints = new TreeMap<>();
for (Map.Entry<Long, Double> entry : filledDatapoints.entrySet()) {
newFilledDatapoints.put(entry.getKey() + offsetInSeconds * 1000, entry.getValue());
}
metric.setDatapoints(newFilledDatapoints);
List<Metric> lineMetrics = new ArrayList<Metric>();
lineMetrics.add(metric);
return lineMetrics;
}
private long _parseStartAndEndTimestamps(String timeStr, long relativeTo) {
if (timeStr == null || timeStr.isEmpty()) {
return relativeTo;
}
try {
if (timeStr.charAt(0) == '-') {
long timeToDeductInSeconds = _parseTimeIntervalInSeconds(timeStr.substring(1));
return (relativeTo - timeToDeductInSeconds * 1000);
}
return Long.parseLong(timeStr);
} catch (NumberFormatException nfe) {
throw new SystemException("Could not parse time.", nfe);
}
}
@Override
public List<Metric> transform(List<Metric> metrics) {
throw new UnsupportedOperationException("Fill Transform needs interval, offset and value!");
}
@Override
public List<Metric> transform(List<Metric> metrics, List<String> constants) {
// Last 2 constants for FILL Transform are added by MetricReader.
// The last constant is used to distinguish between FILL(expr, #constants#) and FILL(#constants#).
// The second last constant is the timestamp using which relative start and end timestamps
// should be calculated for fillLine ( FILL(#constants#) ).
boolean constantsOnly = false;
if(constants != null && !constants.isEmpty()) {
constantsOnly = Boolean.parseBoolean(constants.get(constants.size()-1));
constants.remove(constants.size()-1);
}
long relativeTo = System.currentTimeMillis();
if(constants != null && !constants.isEmpty()) {
relativeTo = Long.parseLong(constants.get(constants.size()-1));
constants.remove(constants.size() - 1);
}
if (constantsOnly) {
return _fillLine(constants, relativeTo);
}
SystemAssert.requireArgument(metrics != null, "Cannot transform null metrics list!");
SystemAssert.requireArgument(constants != null && constants.size() == 3,
"Fill Transform needs exactly three constants: interval, offset, value");
String interval = constants.get(0);
long windowSizeInSeconds = _parseTimeIntervalInSeconds(interval);
SystemAssert.requireArgument(windowSizeInSeconds >= 0, "Window size must be greater than ZERO!");
String offset = constants.get(1);
long offsetInSeconds = _parseTimeIntervalInSeconds(offset);
double value = Double.parseDouble(constants.get(2));
List<Metric> fillMetricList = new ArrayList<Metric>();
for (Metric metric : metrics) {
Metric newMetric = new Metric(metric);
newMetric.setDatapoints(_fillMetricTransform(metric, windowSizeInSeconds, offsetInSeconds, value));
fillMetricList.add(newMetric);
}
return fillMetricList;
}
@Override
public String getResultScopeName() {
return TransformFactory.Function.FILL.name();
}
@Override
public List<Metric> transform(List<Metric>... listOfList) {
throw new UnsupportedOperationException("Fill doesb't need list of list!");
}
} |
package org.jdesktop.swingx.plaf.basic.core;
import javax.swing.DefaultListSelectionModel;
import javax.swing.ListModel;
import javax.swing.ListSelectionModel;
import javax.swing.RowSorter;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.RowSorterEvent;
import javax.swing.event.RowSorterListener;
import org.jdesktop.swingx.JXList;
import org.jdesktop.swingx.util.Contract;
import sun.swing.SwingUtilities2;
/**
* ListSortUI provides support for managing the synchronization between
* RowSorter, SelectionModel and ListModel if a JXList is sortable.<p>
*
* This implementation is an adaption of JTable.SortManager fit to the
* needs of a ListUI. In contrast to JTable tradition, the ui delegate has
* full control about listening to model/selection changes and updating
* the list accordingly. So it's role is that of a helper to the ui-delgate
* (vs. as a helper of the JTable). It's still up to the ListUI itself to
* listen to model/selection and propagate the notification to this class, if
* a sorter is installed, but still do the usual updates (layout, repaint) itself.
* On the other hand, listening to the sorter and updating list state accordingly
* is completely done by this.
*
*/
public final class ListSortUI {
private RowSorter<? extends ListModel> sorter;
private JXList list;
// Selection, in terms of the model. This is lazily created
// as needed.
private ListSelectionModel modelSelection;
private int modelLeadIndex;
// Set to true while in the process of changing the selection.
// If this is true the selection change is ignored.
private boolean syncingSelection;
// Temporary cache of selection, in terms of model. This is only used
// if we don't need the full weight of modelSelection.
private int[] lastModelSelection;
private boolean sorterChanged;
private boolean ignoreSortChange;
private RowSorterListener sorterListener;
public ListSortUI(JXList list, RowSorter<? extends ListModel> sorter) {
this.sorter = Contract.asNotNull(sorter, "RowSorter must not be null");
this.list = Contract.asNotNull(list, "list must not be null");
if (sorter != list.getRowSorter()) throw
new IllegalStateException("sorter must be same as the one on list");
sorterListener = createRowSorterListener();
sorter.addRowSorterListener(sorterListener);
}
/**
* Disposes any resources used by this SortManager.
* Note: this instance must not be used after dispose!
*/
public void dispose() {
if (sorter != null) {
sorter.removeRowSorterListener(sorterListener);
}
sorter = null;
list = null;
}
/**
* Called after notification from ListModel.
* @param e the change event from the listModel.
*/
public void modelChanged(ListDataEvent e) {
ModelChange change = new ModelChange(e);
prepareForChange(change);
notifySorter(change);
if (change.type != ListDataEvent.CONTENTS_CHANGED) {
// If the Sorter is unsorted we will not have received
// notification, force treating insert/delete as a change.
sorterChanged = true;
}
processChange(change);
}
/**
* Called after notification from selectionModel.
*
* Invoked when the selection, on the view, has changed.
*/
public void viewSelectionChanged(ListSelectionEvent e) {
if (!syncingSelection && modelSelection != null) {
modelSelection = null;
}
}
/**
* Called after notification from RowSorter.
*
* @param e RowSorter event of type SORTED.
*/
protected void sortedChanged(RowSorterEvent e) {
sorterChanged = true;
if (!ignoreSortChange) {
prepareForChange(e);
processChange(null);
// PENDING Jw: this is fix of 1161-swingx - not updated after setting
// rowFilter
// potentially costly? but how to distinguish a mere sort from a
// filterchanged? (only the latter requires a revalidate)
list.revalidate();
list.repaint();
}
}
/**
* Invoked when the RowSorter has changed.
* Updates the internal cache of the selection based on the change.
*
* @param sortEvent the notification
* @throws NullPointerException if the given event is null.
*/
private void prepareForChange(RowSorterEvent sortEvent) {
Contract.asNotNull(sortEvent, "sorter event not null");
// sort order changed. If modelSelection is null and filtering
// is enabled we need to cache the selection in terms of the
// underlying model, this will allow us to correctly restore
// the selection even if rows are filtered out.
if (modelSelection == null &&
sorter.getViewRowCount() != sorter.getModelRowCount()) {
modelSelection = new DefaultListSelectionModel();
ListSelectionModel viewSelection = getViewSelectionModel();
int min = viewSelection.getMinSelectionIndex();
int max = viewSelection.getMaxSelectionIndex();
int modelIndex;
for (int viewIndex = min; viewIndex <= max; viewIndex++) {
if (viewSelection.isSelectedIndex(viewIndex)) {
modelIndex = convertRowIndexToModel(
sortEvent, viewIndex);
if (modelIndex != -1) {
modelSelection.addSelectionInterval(
modelIndex, modelIndex);
}
}
}
modelIndex = convertRowIndexToModel(sortEvent,
viewSelection.getLeadSelectionIndex());
SwingUtilities2.setLeadAnchorWithoutSelection(
modelSelection, modelIndex, modelIndex);
} else if (modelSelection == null) {
// Sorting changed, haven't cached selection in terms
// of model and no filtering. Temporarily cache selection.
cacheModelSelection(sortEvent);
}
}
/**
* Invoked when the list model has changed. This is invoked prior to
* notifying the sorter of the change.
* Updates the internal cache of the selection based on the change.
*
* @param change the notification
* @throws NullPointerException if the given event is null.
*/
private void prepareForChange(ModelChange change) {
Contract.asNotNull(change, "table event not null");
if (change.allRowsChanged) {
// All the rows have changed, chuck any cached selection.
modelSelection = null;
} else if (modelSelection != null) {
// Table changed, reflect changes in cached selection model.
switch (change.type) {
case ListDataEvent.INTERVAL_REMOVED:
modelSelection.removeIndexInterval(change.startModelIndex,
change.endModelIndex);
break;
case ListDataEvent.INTERVAL_ADDED:
modelSelection.insertIndexInterval(change.startModelIndex,
change.endModelIndex, true);
break;
default:
break;
}
} else {
// table changed, but haven't cached rows, temporarily
// cache them.
cacheModelSelection(null);
}
}
private void cacheModelSelection(RowSorterEvent sortEvent) {
lastModelSelection = convertSelectionToModel(sortEvent);
modelLeadIndex = convertRowIndexToModel(sortEvent,
getViewSelectionModel().getLeadSelectionIndex());
}
/**
* Inovked when either the table has changed or the sorter has changed
* and after the sorter has been notified. If necessary this will
* reapply the selection and variable row heights.
*/
private void processChange(ModelChange change) {
if (change != null && change.allRowsChanged) {
allChanged();
getViewSelectionModel().clearSelection();
} else if (sorterChanged) {
restoreSelection(change);
}
}
/**
* Restores the selection from that in terms of the model.
*/
private void restoreSelection(ModelChange change) {
syncingSelection = true;
if (lastModelSelection != null) {
restoreSortingSelection(lastModelSelection,
modelLeadIndex, change);
lastModelSelection = null;
} else if (modelSelection != null) {
ListSelectionModel viewSelection = getViewSelectionModel();
viewSelection.setValueIsAdjusting(true);
viewSelection.clearSelection();
int min = modelSelection.getMinSelectionIndex();
int max = modelSelection.getMaxSelectionIndex();
int viewIndex;
for (int modelIndex = min; modelIndex <= max; modelIndex++) {
if (modelSelection.isSelectedIndex(modelIndex)) {
viewIndex = sorter.convertRowIndexToView(modelIndex);
if (viewIndex != -1) {
viewSelection.addSelectionInterval(viewIndex,
viewIndex);
}
}
}
// Restore the lead
int viewLeadIndex = modelSelection.getLeadSelectionIndex();
if (viewLeadIndex != -1) {
viewLeadIndex = sorter.convertRowIndexToView(viewLeadIndex);
}
SwingUtilities2.setLeadAnchorWithoutSelection(
viewSelection, viewLeadIndex, viewLeadIndex);
viewSelection.setValueIsAdjusting(false);
}
syncingSelection = false;
}
/**
* Restores the selection after a model event/sort order changes.
* All coordinates are in terms of the model.
*/
private void restoreSortingSelection(int[] selection, int lead,
ModelChange change) {
// Convert the selection from model to view
for (int i = selection.length - 1; i >= 0; i
selection[i] = convertRowIndexToView(change, selection[i]);
}
lead = convertRowIndexToView(change, lead);
// Check for the common case of no change in selection for 1 row
if (selection.length == 0 ||
(selection.length == 1 && selection[0] == list.getSelectedIndex())) {
return;
}
ListSelectionModel selectionModel = getViewSelectionModel();
// And apply the new selection
selectionModel.setValueIsAdjusting(true);
selectionModel.clearSelection();
for (int i = selection.length - 1; i >= 0; i
if (selection[i] != -1) {
selectionModel.addSelectionInterval(selection[i],
selection[i]);
}
}
SwingUtilities2.setLeadAnchorWithoutSelection(
selectionModel, lead, lead);
selectionModel.setValueIsAdjusting(false);
}
/**
* Converts a model index to view index. This is called when the
* sorter or model changes and sorting is enabled.
*
* @param change describes the TableModelEvent that initiated the change;
* will be null if called as the result of a sort
*/
private int convertRowIndexToView(ModelChange change, int modelIndex) {
if (modelIndex < 0) {
return -1;
}
// Contract.asNotNull(change, "change must not be null?");
if (change != null && modelIndex >= change.startModelIndex) {
if (change.type == ListDataEvent.INTERVAL_ADDED) {
if (modelIndex + change.length >= change.modelRowCount) {
return -1;
}
return sorter.convertRowIndexToView(
modelIndex + change.length);
}
else if (change.type == ListDataEvent.INTERVAL_REMOVED) {
if (modelIndex <= change.endModelIndex) {
// deleted
return -1;
}
else {
if (modelIndex - change.length >= change.modelRowCount) {
return -1;
}
return sorter.convertRowIndexToView(
modelIndex - change.length);
}
}
// else, updated
}
if (modelIndex >= sorter.getModelRowCount()) {
return -1;
}
return sorter.convertRowIndexToView(modelIndex);
}
private int convertRowIndexToModel(RowSorterEvent e, int viewIndex) {
// JW: the event is null if the selection is cached in prepareChange
// after model notification. Then the conversion from the
// sorter is still valid as the prepare is called before
// notifying the sorter.
if (e != null) {
if (e.getPreviousRowCount() == 0) {
return viewIndex;
}
// range checking handled by RowSorterEvent
return e.convertPreviousRowIndexToModel(viewIndex);
}
// Make sure the viewIndex is valid
if (viewIndex < 0 || viewIndex >= sorter.getViewRowCount()) {
return -1;
}
return sorter.convertRowIndexToModel(viewIndex);
}
/**
* Converts the selection to model coordinates. This is used when
* the model changes or the sorter changes.
*/
private int[] convertSelectionToModel(RowSorterEvent e) {
int[] selection = list.getSelectedIndices();
for (int i = selection.length - 1; i >= 0; i
selection[i] = convertRowIndexToModel(e, selection[i]);
}
return selection;
}
/**
* Notifies the sorter of a change in the underlying model.
*/
private void notifySorter(ModelChange change) {
try {
ignoreSortChange = true;
sorterChanged = false;
if (change.allRowsChanged) {
sorter.allRowsChanged();
} else {
switch (change.type) {
case ListDataEvent.CONTENTS_CHANGED:
sorter.rowsUpdated(change.startModelIndex,
change.endModelIndex);
break;
case ListDataEvent.INTERVAL_ADDED:
sorter.rowsInserted(change.startModelIndex,
change.endModelIndex);
break;
case ListDataEvent.INTERVAL_REMOVED:
sorter.rowsDeleted(change.startModelIndex,
change.endModelIndex);
break;
}
}
} finally {
ignoreSortChange = false;
}
}
private ListSelectionModel getViewSelectionModel() {
return list.getSelectionModel();
}
/**
* Invoked when the underlying model has completely changed.
*/
private void allChanged() {
modelLeadIndex = -1;
modelSelection = null;
}
/**
* Creates and returns a RowSorterListener. This implementation
* calls sortedChanged if the event is of type SORTED.
*
* @return rowSorterListener to install on sorter.
*/
protected RowSorterListener createRowSorterListener() {
RowSorterListener l = new RowSorterListener() {
@Override
public void sorterChanged(RowSorterEvent e) {
if (e.getType() == RowSorterEvent.Type.SORTED) {
sortedChanged(e);
}
}
};
return l;
}
/**
* ModelChange is used when sorting to restore state, it corresponds
* to data from a TableModelEvent. The values are precalculated as
* they are used extensively.<p>
*
* PENDING JW: this is not yet fully adapted to ListDataEvent.
*/
final static class ModelChange {
// JW: if we received a dataChanged, there _is no_ notion
// of end/start/length of change
// Starting index of the change, in terms of the model, -1 if dataChanged
int startModelIndex;
// Ending index of the change, in terms of the model, -1 if dataChanged
int endModelIndex;
// Length of the change (end - start + 1), - 1 if dataChanged
int length;
// Type of change
int type;
// Number of rows in the model
int modelRowCount;
// True if the event indicates all the contents have changed
boolean allRowsChanged;
public ModelChange(ListDataEvent e) {
type = e.getType();
modelRowCount = ((ListModel) e.getSource()).getSize();
startModelIndex = e.getIndex0();
endModelIndex = e.getIndex1();
allRowsChanged = startModelIndex < 0;
length = allRowsChanged ? -1 : endModelIndex - startModelIndex + 1;
}
}
} |
package org.orbeon.oxf.xforms;
import org.apache.commons.pool.ObjectPool;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.Element;
import org.orbeon.oxf.common.OXFException;
import org.orbeon.oxf.common.ValidationException;
import org.orbeon.oxf.pipeline.api.ExternalContext;
import org.orbeon.oxf.pipeline.api.PipelineContext;
import org.orbeon.oxf.util.IndentedLogger;
import org.orbeon.oxf.util.LoggerFactory;
import org.orbeon.oxf.util.NetUtils;
import org.orbeon.oxf.util.PropertyContext;
import org.orbeon.oxf.xforms.action.XFormsActions;
import org.orbeon.oxf.xforms.control.XFormsControl;
import org.orbeon.oxf.xforms.control.XFormsSingleNodeControl;
import org.orbeon.oxf.xforms.control.XFormsValueControl;
import org.orbeon.oxf.xforms.control.controls.*;
import org.orbeon.oxf.xforms.event.XFormsEvent;
import org.orbeon.oxf.xforms.event.XFormsEventFactory;
import org.orbeon.oxf.xforms.event.XFormsEventTarget;
import org.orbeon.oxf.xforms.event.XFormsEvents;
import org.orbeon.oxf.xforms.event.events.*;
import org.orbeon.oxf.xforms.processor.XFormsServer;
import org.orbeon.oxf.xforms.processor.XFormsURIResolver;
import org.orbeon.oxf.xforms.state.XFormsState;
import org.orbeon.oxf.xforms.submission.SubmissionResult;
import org.orbeon.oxf.xforms.submission.XFormsModelSubmission;
import org.orbeon.oxf.xforms.xbl.XBLContainer;
import org.orbeon.oxf.xml.dom4j.Dom4jUtils;
import org.orbeon.oxf.xml.dom4j.ExtendedLocationData;
import org.orbeon.saxon.om.Item;
import org.orbeon.saxon.value.BooleanValue;
import org.orbeon.saxon.value.SequenceExtent;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.*;
/**
* Represents an XForms containing document.
*
* The containing document:
*
* o Is the container for root XForms models (including multiple instances)
* o Contains XForms controls
* o Handles event handlers hierarchy
*/
public class XFormsContainingDocument extends XBLContainer {
// Special id name for the top-level containing document
public static final String CONTAINING_DOCUMENT_PSEUDO_ID = "$containing-document$";
// Per-document current logging indentation
private final IndentedLogger.Indentation indentation = new IndentedLogger.Indentation();
private static final String LOGGING_CATEGORY = "document";
private static final Logger logger = LoggerFactory.createLogger(XFormsContainingDocument.class);
private final Map<String, IndentedLogger> loggersMap = new HashMap<String, IndentedLogger>();
{
final Logger globalLogger = XFormsServer.getLogger();
final Set<String> debugConfig = XFormsProperties.getDebugLogging();
registerLogger(XFormsContainingDocument.logger, globalLogger, debugConfig, XFormsContainingDocument.LOGGING_CATEGORY);
registerLogger(XFormsModel.logger, globalLogger, debugConfig, XFormsModel.LOGGING_CATEGORY);
registerLogger(XFormsModelSubmission.logger, globalLogger, debugConfig, XFormsModelSubmission.LOGGING_CATEGORY);
registerLogger(XFormsControls.logger, globalLogger, debugConfig, XFormsControls.LOGGING_CATEGORY);
registerLogger(XFormsEvents.logger, globalLogger, debugConfig, XFormsEvents.LOGGING_CATEGORY);
registerLogger(XFormsActions.logger, globalLogger, debugConfig, XFormsActions.LOGGING_CATEGORY);
}
private void registerLogger(Logger localLogger, Logger globalLogger, Set<String> debugConfig, String category) {
if (XFormsServer.USE_SEPARATE_LOGGERS) {
loggersMap.put(category, new IndentedLogger(localLogger, indentation, category));
} else {
loggersMap.put(category, new IndentedLogger(globalLogger, debugConfig.contains(category), indentation, category));
}
}
private final IndentedLogger indentedLogger = getIndentedLogger(LOGGING_CATEGORY);
// Global XForms function library
private static XFormsFunctionLibrary functionLibrary = new XFormsFunctionLibrary();
// Object pool this object must be returned to, if any
private ObjectPool sourceObjectPool;
// Whether this document is currently being initialized
private boolean isInitializing;
// Transient URI resolver for initialization
private XFormsURIResolver uriResolver;
// Transient OutputStream for xforms:submission[@replace = 'all'], or null if not available
private ExternalContext.Response response;
// A document refers to the static state and controls
private XFormsStaticState xformsStaticState;
private XFormsControls xformsControls;
// Client state
private XFormsModelSubmission activeSubmission;
private List<AsynchronousSubmission> backgroundAsynchronousSubmissions;
private List<AsynchronousSubmission> foregroundAsynchronousSubmissions;
private boolean gotSubmission;
private boolean gotSubmissionSecondPass;
private boolean gotSubmissionReplaceAll;
private List<Message> messagesToRun;
private List<Load> loadsToRun;
private List<Script> scriptsToRun;
private String focusEffectiveControlId;
private String helpEffectiveControlId;
private List<DelayedEvent> delayedEvents;
private boolean goingOffline;
// private boolean goingOnline; // never used at the moment
// Global flag used during initialization only
private boolean mustPerformInitializationFirstRefresh;
// Event information
private static final Set<String> ignoredXFormsOutputExternalEvents = new HashSet<String>();
private static final Set<String> allowedXFormsOutputExternalEvents = new HashSet<String>();
private static final Set<String> allowedXFormsUploadExternalEvents = new HashSet<String>();
private static final Set<String> allowedXFormsControlsExternalEvents = new HashSet<String>();
private static final Set<String> allowedXFormsRepeatExternalEvents = new HashSet<String>();
private static final Set<String> allowedXFormsSubmissionExternalEvents = new HashSet<String>();
private static final Set<String> allowedXFormsContainingDocumentExternalEvents = new HashSet<String>();
private static final Set<String> allowedXXFormsDialogExternalEvents = new HashSet<String>();
static {
// External events ignored on xforms:output
ignoredXFormsOutputExternalEvents.add(XFormsEvents.XFORMS_DOM_FOCUS_IN);
ignoredXFormsOutputExternalEvents.add(XFormsEvents.XFORMS_DOM_FOCUS_OUT);
// External events allowed on xforms:output
allowedXFormsOutputExternalEvents.addAll(ignoredXFormsOutputExternalEvents);
allowedXFormsOutputExternalEvents.add(XFormsEvents.XFORMS_HELP);
// External events allowed on xforms:upload
allowedXFormsUploadExternalEvents.addAll(allowedXFormsOutputExternalEvents);
allowedXFormsUploadExternalEvents.add(XFormsEvents.XFORMS_SELECT);
allowedXFormsUploadExternalEvents.add(XFormsEvents.XXFORMS_VALUE_CHANGE_WITH_FOCUS_CHANGE);
// External events allowed on other controls
allowedXFormsControlsExternalEvents.addAll(allowedXFormsOutputExternalEvents);
allowedXFormsControlsExternalEvents.add(XFormsEvents.XFORMS_DOM_ACTIVATE);
allowedXFormsControlsExternalEvents.add(XFormsEvents.XXFORMS_VALUE_CHANGE_WITH_FOCUS_CHANGE);
allowedXFormsControlsExternalEvents.add(XFormsEvents.XXFORMS_VALUE_OR_ACTIVATE);// for noscript mode
// External events allowed on xforms:repeat
allowedXFormsRepeatExternalEvents.add(XFormsEvents.XXFORMS_DND);
// External events allowed on xforms:submission
allowedXFormsSubmissionExternalEvents.add(XFormsEvents.XXFORMS_SUBMIT);
// External events allowed on containing document
allowedXFormsContainingDocumentExternalEvents.add(XFormsEvents.XXFORMS_LOAD);
allowedXFormsContainingDocumentExternalEvents.add(XFormsEvents.XXFORMS_OFFLINE);
allowedXFormsContainingDocumentExternalEvents.add(XFormsEvents.XXFORMS_ONLINE);
// External events allowed on xxforms:dialog
allowedXXFormsDialogExternalEvents.add(XFormsEvents.XXFORMS_DIALOG_CLOSE);
}
// For testing only
// private static int testAjaxToggleValue = 0;
/**
* Return the global function library.
*/
public static XFormsFunctionLibrary getFunctionLibrary() {
return functionLibrary;
}
/**
* Create an XFormsContainingDocument from an XFormsEngineStaticState object.
*
* @param pipelineContext current pipeline context
* @param xformsStaticState static state object
* @param uriResolver optional URIResolver for loading instances during initialization (and possibly more, such as schemas and "GET" submissions upon initialization)
*/
public XFormsContainingDocument(PipelineContext pipelineContext, XFormsStaticState xformsStaticState, XFormsURIResolver uriResolver) {
super(CONTAINING_DOCUMENT_PSEUDO_ID, CONTAINING_DOCUMENT_PSEUDO_ID, CONTAINING_DOCUMENT_PSEUDO_ID, "", null);
setLocationData(xformsStaticState.getLocationData());
indentedLogger.startHandleOperation("initialization", "creating new ContainingDocument (static state object provided).");
// Remember static state
this.xformsStaticState = xformsStaticState;
// Remember URI resolver for initialization
this.uriResolver = uriResolver;
this.isInitializing = true;
// Initialize the containing document
try {
initialize(pipelineContext);
} catch (Exception e) {
throw ValidationException.wrapException(e, new ExtendedLocationData(getLocationData(), "initializing XForms containing document"));
}
// Clear URI resolver, since it is of no use after initialization, and it may keep dangerous references (PipelineContext)
this.uriResolver = null;
// NOTE: we clear isInitializing when Ajax requests come in
indentedLogger.endHandleOperation();
}
/**
* Restore an XFormsContainingDocument from XFormsState and XFormsStaticState.
*
* @param pipelineContext current pipeline context
* @param xformsState static and dynamic state information
* @param xformsStaticState static state object, or null if not available
*/
public XFormsContainingDocument(PipelineContext pipelineContext, XFormsState xformsState, XFormsStaticState xformsStaticState) {
super(CONTAINING_DOCUMENT_PSEUDO_ID, CONTAINING_DOCUMENT_PSEUDO_ID, CONTAINING_DOCUMENT_PSEUDO_ID, "", null);
if (xformsStaticState != null) {
// Use passed static state object
indentedLogger.startHandleOperation("initialization", "restoring containing document (static state object provided).");
this.xformsStaticState = xformsStaticState;
} else {
// Create static state object
// TODO: Handle caching of XFormsStaticState object? Anything that can be done here?
indentedLogger.startHandleOperation("initialization", "restoring containing document (static state object not provided).");
this.xformsStaticState = new XFormsStaticState(pipelineContext, xformsState.getStaticState());
}
// Make sure there is location data
setLocationData(this.xformsStaticState.getLocationData());
// Restore the containing document's dynamic state
final String encodedDynamicState = xformsState.getDynamicState();
try {
if (encodedDynamicState == null || encodedDynamicState.equals("")) {
// Just for tests, we allow the dynamic state to be empty
initialize(pipelineContext);
xformsControls.evaluateControlValuesIfNeeded(pipelineContext);
} else {
// Regular case
restoreDynamicState(pipelineContext, encodedDynamicState);
}
} catch (Exception e) {
throw ValidationException.wrapException(e, new ExtendedLocationData(getLocationData(), "re-initializing XForms containing document"));
}
indentedLogger.endHandleOperation();
}
/**
* Restore an XFormsContainingDocument from XFormsState only.
*
* @param pipelineContext current pipeline context
* @param xformsState XFormsState containing static and dynamic state
*/
public XFormsContainingDocument(PipelineContext pipelineContext, XFormsState xformsState) {
this(pipelineContext, xformsState, null);
}
public XFormsState getXFormsState(PipelineContext pipelineContext) {
// Make sure we have up to date controls before creating state below
xformsControls.updateControlBindingsIfNeeded(pipelineContext);
// Encode state
return new XFormsState(xformsStaticState.getEncodedStaticState(pipelineContext), createEncodedDynamicState(pipelineContext, false));
}
public void setSourceObjectPool(ObjectPool sourceObjectPool) {
this.sourceObjectPool = sourceObjectPool;
}
public ObjectPool getSourceObjectPool() {
return sourceObjectPool;
}
public XFormsURIResolver getURIResolver() {
return uriResolver;
}
public boolean isInitializing() {
return isInitializing;
}
/**
* Whether the document is currently in a mode where it must handle differences. This is the case when the document
* is initializing and producing the initial output.
*
* @return true iif the document must handle differences
*/
public boolean isHandleDifferences() {
return !isInitializing;
}
/**
* Return the controls.
*/
public XFormsControls getControls() {
return xformsControls;
}
/**
* Whether the document is dirty since the last request.
*
* @return whether the document is dirty since the last request
*/
public boolean isDirtySinceLastRequest() {
return xformsControls.isDirtySinceLastRequest();
}
/**
* Return the XFormsEngineStaticState.
*/
public XFormsStaticState getStaticState() {
return xformsStaticState;
}
/**
* Return a map of script id -> script text.
*/
public Map<String, String> getScripts() {
return xformsStaticState.getScripts();
}
/**
* Return the document base URI.
*/
public String getBaseURI() {
return xformsStaticState.getBaseURI();
}
/**
* Return the container type that generate the XForms page, either "servlet" or "portlet".
*/
public String getContainerType() {
return xformsStaticState.getContainerType();
}
/**
* Return the container namespace that generate the XForms page. Always "" for servlets.
*/
public String getContainerNamespace() {
return xformsStaticState.getContainerNamespace();
}
/**
* Return external-events configuration attribute.
*/
private Map<String, String> getExternalEventsMap() {
return xformsStaticState.getExternalEventsMap();
}
/**
* Return whether an external event name is explicitly allowed by the configuration.
*
* @param eventName event name to check
* @return true if allowed, false otherwise
*/
private boolean isExplicitlyAllowedExternalEvent(String eventName) {
return !XFormsEventFactory.isBuiltInEvent(eventName) && getExternalEventsMap() != null && getExternalEventsMap().get(eventName) != null;
}
/**
* Get object with the effective id specified.
*
* @param effectiveId effective id of the target
* @return object, or null if not found
*/
public Object getObjectByEffectiveId(String effectiveId) {
// Search in parent (models and this)
{
final Object resultObject = super.getObjectByEffectiveId(effectiveId);
if (resultObject != null)
return resultObject;
}
// Search in controls
{
final Object resultObject = xformsControls.getObjectByEffectiveId(effectiveId);
if (resultObject != null)
return resultObject;
}
// Check container id
if (effectiveId.equals(getEffectiveId()))
return this;
return null;
}
/**
* Return the active submission if any or null.
*/
public XFormsModelSubmission getClientActiveSubmission() {
return activeSubmission;
}
/**
* Clear current client state.
*/
private void clearClientState() {
this.isInitializing = false;
this.activeSubmission = null;
this.gotSubmission = false;
this.gotSubmissionSecondPass = false;
this.gotSubmissionReplaceAll = false;
this.backgroundAsynchronousSubmissions = null;
this.foregroundAsynchronousSubmissions = null;
this.messagesToRun = null;
this.loadsToRun = null;
this.scriptsToRun = null;
this.focusEffectiveControlId = null;
this.helpEffectiveControlId = null;
this.delayedEvents = null;
this.goingOffline = false;
// this.goingOnline = false;
}
/**
* Set the active submission.
*
* This can be called with a non-null value at most once.
*/
public void setClientActiveSubmission(XFormsModelSubmission activeSubmission) {
if (this.activeSubmission != null)
throw new ValidationException("There is already an active submission.", activeSubmission.getLocationData());
if (loadsToRun != null)
throw new ValidationException("Unable to run a two-pass submission and xforms:load within a same action sequence.", activeSubmission.getLocationData());
if (messagesToRun != null)
throw new ValidationException("Unable to run a two-pass submission and xforms:message within a same action sequence.", activeSubmission.getLocationData());
if (scriptsToRun != null)
throw new ValidationException("Unable to run a two-pass submission and xxforms:script within a same action sequence.", activeSubmission.getLocationData());
if (focusEffectiveControlId != null)
throw new ValidationException("Unable to run a two-pass submission and xforms:setfocus within a same action sequence.", activeSubmission.getLocationData());
if (helpEffectiveControlId != null)
throw new ValidationException("Unable to run a two-pass submission and xforms-help within a same action sequence.", activeSubmission.getLocationData());
this.activeSubmission = activeSubmission;
}
public boolean isGotSubmission() {
return gotSubmission;
}
public void setGotSubmission() {
this.gotSubmission = true;
}
public boolean isGotSubmissionSecondPass() {
return gotSubmissionSecondPass;
}
public void setGotSubmissionSecondPass() {
this.gotSubmissionSecondPass = true;
}
public void setGotSubmissionReplaceAll() {
if (this.gotSubmissionReplaceAll)
throw new ValidationException("Unable to run a second submission with replace=\"all\" within a same action sequence.", getLocationData());
this.gotSubmissionReplaceAll = true;
}
public boolean isGotSubmissionReplaceAll() {
return gotSubmissionReplaceAll;
}
private static class AsynchronousSubmission {
public Future<SubmissionResult> future;
public String submissionEffectiveId;
public AsynchronousSubmission(Future<SubmissionResult> future, String submissionEffectiveId) {
this.future = future;
this.submissionEffectiveId = submissionEffectiveId;
}
}
// Global thread pool
private static ExecutorService threadPool = Executors.newCachedThreadPool();
private CompletionService<SubmissionResult> completionService = new ExecutorCompletionService<SubmissionResult>(threadPool);
public void addAsynchronousSubmission(final Callable<SubmissionResult> callable, String submissionEffectiveId, boolean isBackground) {
// Add submission future
if (isBackground) {
// Background async submission
final Future<SubmissionResult> future = completionService.submit(callable);
if (backgroundAsynchronousSubmissions == null)
backgroundAsynchronousSubmissions = new ArrayList<AsynchronousSubmission>();
backgroundAsynchronousSubmissions.add(new AsynchronousSubmission(future, submissionEffectiveId));
} else {
// Foreground async submission
final Future<SubmissionResult> future = new Future<SubmissionResult>() {
private boolean isDone;
private boolean isCanceled;
private SubmissionResult result;
public boolean cancel(boolean b) {
if (isDone)
return false;
isCanceled = true;
return true;
}
public boolean isCancelled() {
return isCanceled;
}
public boolean isDone() {
return isDone;
}
public SubmissionResult get() throws InterruptedException, ExecutionException {
if (isCanceled)
throw new CancellationException();
if (!isDone) {
try {
result = callable.call();
} catch (Exception e) {
throw new ExecutionException(e);
}
isDone = true;
}
return result;
}
public SubmissionResult get(long l, TimeUnit timeUnit) throws InterruptedException, ExecutionException, TimeoutException {
return get();
}
};
if (foregroundAsynchronousSubmissions == null)
foregroundAsynchronousSubmissions = new ArrayList<AsynchronousSubmission>();
foregroundAsynchronousSubmissions.add(new AsynchronousSubmission(future, submissionEffectiveId));
// NOTE: In this very basic level of support, we don't support
// xforms-submit-done / xforms-submit-error handlers
// TODO: Do something with result, e.g. log?
// final ConnectionResult connectionResult = ...
}
}
public boolean hasBackgroundAsynchronousSubmissions() {
return backgroundAsynchronousSubmissions != null && backgroundAsynchronousSubmissions.size() > 0;
}
private boolean hasForegroundAsynchronousSubmissions() {
return foregroundAsynchronousSubmissions != null && foregroundAsynchronousSubmissions.size() > 0;
}
public void processBackgroundAsynchronousSubmissions(PropertyContext propertyContext) {
// Processing a series of background asynchronous submission might in turn trigger the creation of new
// background asynchronous submissions. We need to process until no submissions are left.
while (hasBackgroundAsynchronousSubmissions())
processBackgroundAsynchronousSubmissionsBatch(propertyContext);
}
/**
* Process all current background submissions if any. Submissions are processed in the order in which they are made
* available upon termination by the completion service.
*
* @param propertyContext current context
*/
private void processBackgroundAsynchronousSubmissionsBatch(PropertyContext propertyContext) {
// Get then reset current batch list
final List<AsynchronousSubmission> submissionsToProcess = backgroundAsynchronousSubmissions;
backgroundAsynchronousSubmissions = null;
final IndentedLogger indentedLogger = getIndentedLogger(XFormsModelSubmission.LOGGING_CATEGORY);
indentedLogger.startHandleOperation("", "processing background asynchronous submissions");
int count = 0;
try {
final int size = submissionsToProcess.size();
for (; count < size; count++) {
try {
// Handle next completed task
final SubmissionResult result = completionService.take().get();
// Process response by dispatching an event to the submission
final XFormsModelSubmission submission = (XFormsModelSubmission) getObjectByEffectiveId(result.getSubmissionEffectiveId());
final XBLContainer container = submission.getXBLContainer(this);
// NOTE: not clear whether we should use an event for this as there doesn't seem to be a benefit
container.dispatchEvent(propertyContext, new XXFormsSubmitReplaceEvent(this, submission, result));
} catch (Throwable throwable) {
// Something bad happened
throw new OXFException(throwable);
}
}
} finally {
indentedLogger.endHandleOperation("count", Integer.toString(count));
}
}
/**
* Process all current foreground submissions if any. Submissions are processed in the order in which they were
* executed.
*/
public void processForegroundAsynchronousSubmissions() {
if (hasForegroundAsynchronousSubmissions()) {
final IndentedLogger indentedLogger = getIndentedLogger(XFormsModelSubmission.LOGGING_CATEGORY);
indentedLogger.startHandleOperation("", "processing foreground asynchronous submissions");
int count = 0;
try {
for (Iterator<AsynchronousSubmission> i = foregroundAsynchronousSubmissions.iterator(); i.hasNext(); count++) {
final AsynchronousSubmission asyncSubmission = i.next();
try {
// Submission is run at this point
asyncSubmission.future.get();
// NOTE: We do not process the response at all
} catch (Throwable throwable) {
// Something happened but we swallow the exception and keep going
indentedLogger.logError("", "asynchronous submission: throwable caught", throwable);
}
// Remove submission from list of submission so we can gc the Runnable
i.remove();
}
} finally {
indentedLogger.endHandleOperation("count", Integer.toString(count));
}
}
}
/**
* Add an XForms message to send to the client.
*/
public void addMessageToRun(String message, String level) {
if (activeSubmission != null)
throw new ValidationException("Unable to run a two-pass submission and xforms:message within a same action sequence.", activeSubmission.getLocationData());
if (messagesToRun == null)
messagesToRun = new ArrayList<Message>();
messagesToRun.add(new Message(message, level));
}
/**
* Return the list of messages to send to the client, null if none.
*/
public List<Message> getMessagesToRun() {
return messagesToRun;
}
/**
* Schedule an event for delayed execution, following xforms:dispatch/@delay semantics.
*
* @param eventName name of the event to dispatch
* @param targetStaticId static id of the target to dispatch to
* @param bubbles whether the event bubbles
* @param cancelable whether the event is cancelable
* @param delay delay after which to dispatch the event
* @param showProgress whether to show the progress indicator when submitting the event
* @param progressMessage message to show if the progress indicator is visible
*/
public void addDelayedEvent(String eventName, String targetStaticId, boolean bubbles, boolean cancelable, int delay, boolean showProgress, String progressMessage) {
if (delayedEvents == null)
delayedEvents = new ArrayList<DelayedEvent>();
delayedEvents.add(new DelayedEvent(eventName, targetStaticId, bubbles, cancelable, System.currentTimeMillis() + delay, showProgress, progressMessage));
}
public List<DelayedEvent> getDelayedEvents() {
return delayedEvents;
}
public static class DelayedEvent {
private String eventName;
private String targetStaticId;
private boolean bubbles;
private boolean cancelable;
private long time;
private boolean showProgress;
private String progressMessage;
public DelayedEvent(String eventName, String targetStaticId, boolean bubbles, boolean cancelable, long time, boolean showProgress, String progressMessage) {
this.eventName = eventName;
this.targetStaticId = targetStaticId;
this.bubbles = bubbles;
this.cancelable = cancelable;
this.time = time;
this.showProgress = showProgress;
this.progressMessage = progressMessage;
}
public String getEncodedDocument(PipelineContext pipelineContext) {
final Document eventsDocument = Dom4jUtils.createDocument();
final Element eventsElement = eventsDocument.addElement(XFormsConstants.XXFORMS_EVENTS_QNAME);
final Element eventElement = eventsElement.addElement(XFormsConstants.XXFORMS_EVENT_QNAME);
eventElement.addAttribute("name", eventName);
eventElement.addAttribute("source-control-id", targetStaticId);
eventElement.addAttribute("bubbles", Boolean.toString(bubbles));
eventElement.addAttribute("cancelable", Boolean.toString(cancelable));
return XFormsUtils.encodeXML(pipelineContext, eventsDocument, false);
}
public boolean isShowProgress() {
return showProgress;
}
public String getProgressMessage() {
return progressMessage;
}
public long getTime() {
return time;
}
}
public static class Message {
private String message;
private String level;
public Message(String message, String level) {
this.message = message;
this.level = level;
}
public String getMessage() {
return message;
}
public String getLevel() {
return level;
}
}
public void addScriptToRun(String scriptId, String eventTargetId, String eventObserverId) {
if (activeSubmission != null)
throw new ValidationException("Unable to run a two-pass submission and xxforms:script within a same action sequence.", activeSubmission.getLocationData());
// Warn that scripts won't run in noscript mode (duh)
if (XFormsProperties.isNoscript(this))
indentedLogger.logWarning("noscript", "script won't run in noscript mode", "script id", scriptId);
if (scriptsToRun == null)
scriptsToRun = new ArrayList<Script>();
scriptsToRun.add(new Script(XFormsUtils.scriptIdToScriptName(scriptId), eventTargetId, eventObserverId));
}
public static class Script {
private String functionName;
private String eventTargetId;
private String eventObserverId;
public Script(String functionName, String eventTargetId, String eventObserverId) {
this.functionName = functionName;
this.eventTargetId = eventTargetId;
this.eventObserverId = eventObserverId;
}
public String getFunctionName() {
return functionName;
}
public String getEventTargetId() {
return eventTargetId;
}
public String getEventObserverId() {
return eventObserverId;
}
}
public List<Script> getScriptsToRun() {
return scriptsToRun;
}
/**
* Add an XForms load to send to the client.
*/
public void addLoadToRun(String resource, String target, String urlType, boolean isReplace, boolean isPortletLoad, boolean isShowProgress) {
if (activeSubmission != null)
throw new ValidationException("Unable to run a two-pass submission and xforms:load within a same action sequence.", activeSubmission.getLocationData());
if (loadsToRun == null)
loadsToRun = new ArrayList<Load>();
loadsToRun.add(new Load(resource, target, urlType, isReplace, isPortletLoad, isShowProgress));
}
/**
* Return the list of loads to send to the client, null if none.
*/
public List<Load> getLoadsToRun() {
return loadsToRun;
}
public static class Load {
private String resource;
private String target;
private String urlType;
private boolean isReplace;
private boolean isPortletLoad;
private boolean isShowProgress;
public Load(String resource, String target, String urlType, boolean isReplace, boolean isPortletLoad, boolean isShowProgress) {
this.resource = resource;
this.target = target;
this.urlType = urlType;
this.isReplace = isReplace;
this.isPortletLoad = isPortletLoad;
this.isShowProgress = isShowProgress;
}
public String getResource() {
return resource;
}
public String getTarget() {
return target;
}
public String getUrlType() {
return urlType;
}
public boolean isReplace() {
return isReplace;
}
public boolean isPortletLoad() {
return isPortletLoad;
}
public boolean isShowProgress() {
return isShowProgress;
}
}
/**
* Tell the client that focus must be changed to the given effective control id.
*
* This can be called several times, but only the last control id is remembered.
*
* @param effectiveControlId
*/
public void setClientFocusEffectiveControlId(String effectiveControlId) {
if (activeSubmission != null)
throw new ValidationException("Unable to run a two-pass submission and xforms:setfocus within a same action sequence.", activeSubmission.getLocationData());
this.focusEffectiveControlId = effectiveControlId;
}
/**
* Return the effective control id of the control to set the focus to, or null.
*/
public String getClientFocusEffectiveControlId() {
if (focusEffectiveControlId == null)
return null;
final XFormsControl xformsControl = (XFormsControl) getObjectByEffectiveId(focusEffectiveControlId);
// It doesn't make sense to tell the client to set the focus to an element that is non-relevant or readonly
if (xformsControl != null && xformsControl instanceof XFormsSingleNodeControl) {
final XFormsSingleNodeControl xformsSingleNodeControl = (XFormsSingleNodeControl) xformsControl;
if (xformsSingleNodeControl.isRelevant() && !xformsSingleNodeControl.isReadonly())
return focusEffectiveControlId;
else
return null;
} else {
return null;
}
}
/**
* Tell the client that help must be shown for the given effective control id.
*
* This can be called several times, but only the last controld id is remembered.
*
* @param effectiveControlId
*/
public void setClientHelpEffectiveControlId(String effectiveControlId) {
if (activeSubmission != null)
throw new ValidationException("Unable to run a two-pass submission and xforms-help within a same action sequence.", activeSubmission.getLocationData());
this.helpEffectiveControlId = effectiveControlId;
}
/**
* Return the effective control id of the control to help for, or null.
*/
public String getClientHelpEffectiveControlId() {
if (helpEffectiveControlId == null)
return null;
final XFormsControl xformsControl = (XFormsControl) getObjectByEffectiveId(helpEffectiveControlId);
// It doesn't make sense to tell the client to show help for an element that is non-relevant, but we allow readonly
if (xformsControl != null && xformsControl instanceof XFormsSingleNodeControl) {
final XFormsSingleNodeControl xformsSingleNodeControl = (XFormsSingleNodeControl) xformsControl;
if (xformsSingleNodeControl.isRelevant())
return helpEffectiveControlId;
else
return null;
} else {
return null;
}
}
/**
* Execute an external event and ensure deferred event handling.
*
* @param pipelineContext current PipelineContext
* @param isTrustedEvent whether this event is trusted
* @param eventName name of the event
* @param targetEffectiveId effective id of the target to dispatch to
* @param bubbles whether the event bubbles (for custom events)
* @param cancelable whether the event is cancelable (for custom events)
* @param otherControlEffectiveId other effective control id if any
* @param valueString optional context string
* @param filesElement optional files elements for upload
* @param dndStart optional DnD start information
* @param dndEnd optional DnD end information
* @param handleGoingOnline whether we are going online and therefore using optimized event handling
*/
public void executeExternalEvent(PipelineContext pipelineContext, boolean isTrustedEvent, String eventName, String targetEffectiveId,
boolean bubbles, boolean cancelable,
String otherControlEffectiveId, String valueString, Element filesElement,
String dndStart, String dndEnd, boolean handleGoingOnline) {
final IndentedLogger indentedLogger = getIndentedLogger(XFormsEvents.LOGGING_CATEGORY);
final String LOG_TYPE = "executeExternalEvent";
try {
indentedLogger.startHandleOperation(LOG_TYPE, "handling external event", "target id", targetEffectiveId, "event name", eventName);
// Get event target object
XFormsEventTarget eventTarget;
{
final Object eventTargetObject = getObjectByEffectiveId(targetEffectiveId);
if (!(eventTargetObject instanceof XFormsEventTarget)) {
if (XFormsProperties.isExceptionOnInvalidClientControlId(this)) {
throw new ValidationException("Event target id '" + targetEffectiveId + "' is not an XFormsEventTarget.", getLocationData());
} else {
if (indentedLogger.isDebugEnabled()) {
indentedLogger.logDebug(LOG_TYPE, "ignoring client event with invalid target id", "target id", targetEffectiveId, "event name", eventName);
}
return;
}
}
eventTarget = (XFormsEventTarget) eventTargetObject;
}
if (isTrustedEvent) {
// Event is trusted, don't check if it is allowed
if (indentedLogger.isDebugEnabled()) {
indentedLogger.logDebug(LOG_TYPE, "processing trusted event", "target id", targetEffectiveId, "event name", eventName);
}
} else if (!checkForAllowedEvents(pipelineContext, indentedLogger, eventName, eventTarget, handleGoingOnline)) {
// Event is not trusted and is not allowed
return;
}
// Get other event target
final XFormsEventTarget otherEventTarget;
{
final Object otherEventTargetObject = (otherControlEffectiveId == null) ? null : getObjectByEffectiveId(otherControlEffectiveId);
if (otherEventTargetObject == null) {
otherEventTarget = null;
} else if (!(otherEventTargetObject instanceof XFormsEventTarget)) {
if (XFormsProperties.isExceptionOnInvalidClientControlId(this)) {
throw new ValidationException("Other event target id '" + otherControlEffectiveId + "' is not an XFormsEventTarget.", getLocationData());
} else {
if (indentedLogger.isDebugEnabled()) {
indentedLogger.logDebug(LOG_TYPE, "ignoring invalid client event with invalid second control id", "target id", targetEffectiveId, "event name", eventName, "second control id", otherControlEffectiveId);
}
return;
}
} else {
otherEventTarget = (XFormsEventTarget) otherEventTargetObject;
}
}
// Rewrite event type. This is special handling of xxforms-value-or-activate for noscript mode.
if (XFormsEvents.XXFORMS_VALUE_OR_ACTIVATE.equals(eventName)) {
// In this case, we translate the event depending on the control type
if (eventTarget instanceof XFormsTriggerControl) {
// Triggers get a DOM activation
if ("".equals(valueString)) {
// Handler produces:
// <button type="submit" name="foobar" value="activate">...
// <input type="submit" name="foobar" value="Hi There">...
// <input type="image" name="foobar" value="Hi There" src="...">...
// IE 6/7 are terminally broken: they don't send the value back, but the contents of the label. So
// we must test for any empty content here instead of "!activate".equals(valueString). (Note that
// this means that empty labels won't work.) Further, with IE 6, all buttons are present when
// using <button>, so we use <input> instead, either with type="submit" or type="image". Bleh.
return;
}
eventName = XFormsEvents.XFORMS_DOM_ACTIVATE;
} else {
// Other controls get a value change
eventName = XFormsEvents.XXFORMS_VALUE_CHANGE_WITH_FOCUS_CHANGE;
}
}
// For testing only
if (XFormsProperties.isAjaxTest()) {
if (eventName.equals(XFormsEvents.XXFORMS_VALUE_CHANGE_WITH_FOCUS_CHANGE)) {
valueString = "value" + System.currentTimeMillis();
}
}
if (!handleGoingOnline) {
// When not going online, each event is within its own start/end outermost action handler
startOutermostActionHandler();
}
{
// Create event
final XFormsEvent xformsEvent = XFormsEventFactory.createEvent(this, eventName, eventTarget, otherEventTarget,
true, bubbles, cancelable, valueString, filesElement, new String[] { dndStart, dndEnd} );
// Handle repeat focus. Don't dispatch event on DOMFocusOut however.
if (targetEffectiveId.indexOf(XFormsConstants.REPEAT_HIERARCHY_SEPARATOR_1) != -1
&& !XFormsEvents.XFORMS_DOM_FOCUS_OUT.equals(eventName)) {
// Check if the value to set will be different from the current value
if (eventTarget instanceof XFormsValueControl && xformsEvent instanceof XXFormsValueChangeWithFocusChangeEvent) {
final XXFormsValueChangeWithFocusChangeEvent valueChangeWithFocusChangeEvent = (XXFormsValueChangeWithFocusChangeEvent) xformsEvent;
if (valueChangeWithFocusChangeEvent.getOtherTargetObject() == null) {
// We only get a value change with this event
final String currentExternalValue = ((XFormsValueControl) eventTarget).getExternalValue(pipelineContext);
if (currentExternalValue != null) {
// We completely ignore the event if the value in the instance is the same. This also saves dispatching xxforms-repeat-focus below.
final boolean isIgnoreValueChangeEvent = currentExternalValue.equals(valueChangeWithFocusChangeEvent.getNewValue());
if (isIgnoreValueChangeEvent) {
indentedLogger.logDebug(LOG_TYPE, "ignoring value change event as value is the same",
"control id", eventTarget.getEffectiveId(), "event name", eventName, "value", currentExternalValue);
// Ensure deferred event handling
// NOTE: Here this will do nothing, but out of consistency we better have matching startOutermostActionHandler/endOutermostActionHandler
endOutermostActionHandler(pipelineContext);
return;
}
} else {
// shouldn't happen really, but just in case let's log this
indentedLogger.logDebug(LOG_TYPE, "got null currentExternalValue", "control id", eventTarget.getEffectiveId(), "event name", eventName);
}
} else {
// There will be a focus event too, so don't ignore
}
}
// Dispatch repeat focus event
{
// The event target is in a repeated structure, so make sure it gets repeat focus
dispatchEvent(pipelineContext, new XXFormsRepeatFocusEvent(this, eventTarget));
// Get a fresh reference
eventTarget = (XFormsControl) getObjectByEffectiveId(eventTarget.getEffectiveId());
}
}
// Interpret event
if (eventTarget instanceof XFormsOutputControl) {
// Special xforms:output case
if (XFormsEvents.XFORMS_DOM_FOCUS_IN.equals(eventName)) {
// First, dispatch DOMFocusIn
dispatchEvent(pipelineContext, xformsEvent);
// Then, dispatch DOMActivate unless the control is read-only
final XFormsOutputControl xformsOutputControl = (XFormsOutputControl) getObjectByEffectiveId(eventTarget.getEffectiveId());
if (!xformsOutputControl.isReadonly()) {
dispatchEvent(pipelineContext, new XFormsDOMActivateEvent(this, xformsOutputControl));
}
} else if (!ignoredXFormsOutputExternalEvents.contains(eventName)) {
// Dispatch other event
dispatchEvent(pipelineContext, xformsEvent);
}
} else if (xformsEvent instanceof XXFormsValueChangeWithFocusChangeEvent) {
// 4.6.7 Sequence: Value Change
// What we want to do here is set the value on the initial controls tree, as the value has already been
// changed on the client. This means that this event(s) must be the first to come!
final XXFormsValueChangeWithFocusChangeEvent valueChangeWithFocusChangeEvent = (XXFormsValueChangeWithFocusChangeEvent) xformsEvent;
{
// Store value into instance data through the control
final XFormsValueControl valueXFormsControl = (XFormsValueControl) eventTarget;
// NOTE: filesElement is only used by the upload control at the moment
valueXFormsControl.storeExternalValue(pipelineContext, valueChangeWithFocusChangeEvent.getNewValue(), null, filesElement);
}
{
// NOTE: Recalculate and revalidate are done with the automatic deferred updates
// Handle focus change DOMFocusOut / DOMFocusIn
if (valueChangeWithFocusChangeEvent.getOtherTargetObject() != null) {
// We have a focus change (otherwise, the focus is assumed to remain the same)
// Dispatch DOMFocusOut
// NOTE: setExternalValue() above may cause e.g. xforms-select / xforms-deselect events to be
// dispatched, so we get the control again to have a fresh reference
final XFormsControl sourceXFormsControl = (XFormsControl) getObjectByEffectiveId(eventTarget.getEffectiveId());
if (sourceXFormsControl != null) {
dispatchEvent(pipelineContext, new XFormsDOMFocusOutEvent(this, sourceXFormsControl));
}
// Dispatch DOMFocusIn
final XFormsControl otherTargetXFormsControl
= (XFormsControl) getObjectByEffectiveId(((XFormsControl) valueChangeWithFocusChangeEvent.getOtherTargetObject()).getEffectiveId());
if (otherTargetXFormsControl != null) {
dispatchEvent(pipelineContext, new XFormsDOMFocusInEvent(this, otherTargetXFormsControl));
}
}
// NOTE: Refresh is done with the automatic deferred updates
}
} else {
// Dispatch any other allowed event
dispatchEvent(pipelineContext, xformsEvent);
}
}
// When not going online, each event is within its own start/end outermost action handler
if (!handleGoingOnline) {
endOutermostActionHandler(pipelineContext);
}
} finally {
indentedLogger.endHandleOperation();
}
}
public void dispatchEvent(PipelineContext pipelineContext, XFormsEvent event) {
// Ensure that the event uses the proper container to dispatch the event
final XBLContainer targetContainer = event.getTargetObject().getXBLContainer(this);
if (targetContainer == this) {
super.dispatchEvent(pipelineContext, event);
} else {
targetContainer.dispatchEvent(pipelineContext, event);
}
}
/**
* Check whether the external event is allowed on the gtiven target/
*
* @param pipelineContext pipeline context
* @param indentedLogger logger
* @param eventName event name
* @param eventTarget event target
* @param handleGoingOnline whether we are going online and therefore using optimized event handling
* @return true iif the event is allowed
*/
private boolean checkForAllowedEvents(PipelineContext pipelineContext, IndentedLogger indentedLogger, String eventName, XFormsEventTarget eventTarget, boolean handleGoingOnline) {
// Don't allow for events on non-relevant, readonly or xforms:output controls (we accept focus events on
// xforms:output though).
// This is also a security measure that also ensures that somebody is not able to change values in an instance
// by hacking external events.
final String LOG_TYPE = "checkForAllowedEvents";
if (eventTarget instanceof XFormsControl) {
// Target is a control
if (eventTarget instanceof XXFormsDialogControl) {
// Target is a dialog
// Check for implicitly allowed events
if (!allowedXXFormsDialogExternalEvents.contains(eventName)) {
if (indentedLogger.isDebugEnabled()) {
indentedLogger.logDebug(LOG_TYPE, "ignoring invalid client event on xxforms:dialog", "control id", eventTarget.getEffectiveId(), "event name", eventName);
}
return false;
}
} else if (eventTarget instanceof XFormsRepeatControl) {
// Target is a repeat
if (!allowedXFormsRepeatExternalEvents.contains(eventName)) {
if (indentedLogger.isDebugEnabled()) {
indentedLogger.logDebug(LOG_TYPE, "ignoring invalid client event on xforms:repeat", "control id", eventTarget.getEffectiveId(), "event name", eventName);
}
return false;
}
} else {
// Target is a regular control
// Only single-node controls accept events from the client
if (!(eventTarget instanceof XFormsSingleNodeControl)) {// NOTE: This includes xforms:trigger/xforms:submit
if (indentedLogger.isDebugEnabled()) {
indentedLogger.logDebug(LOG_TYPE, "ignoring invalid client event on non-single-node control", "control id", eventTarget.getEffectiveId(), "event name", eventName);
}
return false;
}
final XFormsSingleNodeControl xformsControl = (XFormsSingleNodeControl) eventTarget;
if (handleGoingOnline) {
// When going online, ensure rebuild/revalidate before each event
rebuildRecalculateIfNeeded(pipelineContext);
// Mark the control as dirty, because we may have done a rebuild/recalculate earlier, and this means
// the MIPs need to be re-evaluated before being checked below
getControls().cloneInitialStateIfNeeded();
xformsControl.markDirty();
}
if (!xformsControl.isRelevant() || (xformsControl.isReadonly() && !(xformsControl instanceof XFormsOutputControl))) {
// Controls accept event only if they are relevant and not readonly, except for xforms:output which may be readonly
if (indentedLogger.isDebugEnabled()) {
indentedLogger.logDebug(LOG_TYPE, "ignoring invalid client event on non-relevant or read-only control", "control id", eventTarget.getEffectiveId(), "event name", eventName);
}
return false;
}
if (!isExplicitlyAllowedExternalEvent(eventName)) {
// The event is not explicitly allowed: check for implicitly allowed events
if (xformsControl instanceof XFormsOutputControl) {
if (!allowedXFormsOutputExternalEvents.contains(eventName)) {
if (indentedLogger.isDebugEnabled()) {
indentedLogger.logDebug(LOG_TYPE, "ignoring invalid client event on xforms:output", "control id", eventTarget.getEffectiveId(), "event name", eventName);
}
return false;
}
} else if (xformsControl instanceof XFormsUploadControl) {
if (!allowedXFormsUploadExternalEvents.contains(eventName)) {
if (indentedLogger.isDebugEnabled()) {
indentedLogger.logDebug(LOG_TYPE, "ignoring invalid client event on xforms:upload", "control id", eventTarget.getEffectiveId(), "event name", eventName);
}
return false;
}
} else {
if (!allowedXFormsControlsExternalEvents.contains(eventName)) {
if (indentedLogger.isDebugEnabled()) {
indentedLogger.logDebug(LOG_TYPE, "ignoring invalid client event", "control id", eventTarget.getEffectiveId(), "event name", eventName);
}
return false;
}
}
}
}
} else if (eventTarget instanceof XFormsModelSubmission) {
// Target is a submission
if (!isExplicitlyAllowedExternalEvent(eventName)) {
// The event is not explicitly allowed: check for implicitly allowed events
if (!allowedXFormsSubmissionExternalEvents.contains(eventName)) {
if (indentedLogger.isDebugEnabled()) {
indentedLogger.logDebug(LOG_TYPE, "ignoring invalid client event on xforms:submission", "submission id", eventTarget.getEffectiveId(), "event name", eventName);
}
return false;
}
}
} else if (eventTarget instanceof XFormsContainingDocument) {
// Target is the containing document
// Check for implicitly allowed events
if (!allowedXFormsContainingDocumentExternalEvents.contains(eventName)) {
if (indentedLogger.isDebugEnabled()) {
indentedLogger.logDebug(LOG_TYPE, "ignoring invalid client event on containing document", "target id", eventTarget.getEffectiveId(), "event name", eventName);
}
return false;
}
} else {
// Target is not a control
if (!isExplicitlyAllowedExternalEvent(eventName)) {
// The event is not explicitly allowed
if (indentedLogger.isDebugEnabled()) {
indentedLogger.logDebug(LOG_TYPE, "ignoring invalid client event", "target id", eventTarget.getEffectiveId(), "event name", eventName);
}
return false;
}
}
return true;
}
/**
* Prepare the ContainingDocument for a sequence of external events.
*
* @param pipelineContext current PipelineContext
* @param response ExternalContext.Response for xforms:submission[@replace = 'all'], or null
* @param handleGoingOnline whether we are going online and therefore using optimized event handling
*/
public void startExternalEventsSequence(PipelineContext pipelineContext, ExternalContext.Response response, boolean handleGoingOnline) {
// Clear containing document state
clearClientState();
// Remember OutputStream
this.response = response;
// Initialize controls
xformsControls.initialize(pipelineContext);
// Start outermost action handler here if going online
if (handleGoingOnline)
startOutermostActionHandler();
}
/**
* End a sequence of external events.
*
* @param pipelineContext current PipelineContext
* @param handleGoingOnline whether we are going online and therefore using optimized event handling
*/
public void endExternalEventsSequence(PipelineContext pipelineContext, boolean handleGoingOnline) {
// End outermost action handler here if going online
if (handleGoingOnline)
endOutermostActionHandler(pipelineContext);
this.response = null;
}
/**
* Return an OutputStream for xforms:submission[@replace = 'all']. Used by submission.
*
* @return OutputStream
*/
public ExternalContext.Response getResponse() {
return response;
}
public void performDefaultAction(PropertyContext propertyContext, XFormsEvent event) {
final String eventName = event.getEventName();
if (XFormsEvents.XXFORMS_LOAD.equals(eventName)) {
// Internal load event
final XXFormsLoadEvent xxformsLoadEvent = (XXFormsLoadEvent) event;
final ExternalContext externalContext = (ExternalContext) propertyContext.getAttribute(PipelineContext.EXTERNAL_CONTEXT);
try {
final String resource = xxformsLoadEvent.getResource();
final String pathInfo;
final Map<String, String[]> parameters;
final int qmIndex = resource.indexOf('?');
if (qmIndex != -1) {
pathInfo = resource.substring(0, qmIndex);
parameters = NetUtils.decodeQueryString(resource.substring(qmIndex + 1), false);
} else {
pathInfo = resource;
parameters = null;
}
externalContext.getResponse().sendRedirect(pathInfo, parameters, false, false, false);
} catch (IOException e) {
throw new ValidationException(e, getLocationData());
}
} else if (XFormsEvents.XXFORMS_ONLINE.equals(eventName)) {
// Internal event for going online
goOnline(propertyContext);
} else if (XFormsEvents.XXFORMS_OFFLINE.equals(eventName)) {
// Internal event for going offline
goOffline(propertyContext);
}
}
public void goOnline(PropertyContext propertyContext) {
// Dispatch to all models
for (XFormsModel currentModel: getModels()) {
// TODO: Dispatch to children containers?
dispatchEvent(propertyContext, new XXFormsOnlineEvent(this, currentModel));
}
// this.goingOnline = true;
this.goingOffline = false;
}
public void goOffline(PropertyContext propertyContext) {
// Handle inserts of controls marked as "offline insert triggers"
final List<String> offlineInsertTriggerPrefixedIds = getStaticState().getOfflineInsertTriggerIds();
if (offlineInsertTriggerPrefixedIds != null) {
for (String currentPrefixedId: offlineInsertTriggerPrefixedIds) {
final Object o = getObjectByEffectiveId(currentPrefixedId);// NOTE: won't work for triggers within repeats
if (o instanceof XFormsTriggerControl) {
final XFormsTriggerControl trigger = (XFormsTriggerControl) o;
final XFormsEvent event = new XFormsDOMActivateEvent(this, trigger);
// This attribute is a temporary HACK, used to improve performance when going offline. It causes
// the insert action to not rebuild controls to adjust indexes after insertion, as well as always
// inserting based on the last node of the insert nodes-set. This probably wouldn't be needed if
// insert performance was good from the get go.
// TODO: check above now that repeat/insert/delete has been improved
event.setAttribute(XFormsConstants.NO_INDEX_ADJUSTMENT, new SequenceExtent(new Item[] { BooleanValue.TRUE }));
// Dispatch event n times
final int repeatCount = XFormsProperties.getOfflineRepeatCount(this);
for (int j = 0; j < repeatCount; j++)
dispatchEvent(propertyContext, event);
}
}
}
// Dispatch xxforms-offline to all models
for (XFormsModel currentModel: getModels()) {
// TODO: Dispatch to children containers
dispatchEvent(propertyContext, new XXFormsOfflineEvent(this, currentModel));
}
// this.goingOnline = false;
this.goingOffline = true;
}
public boolean goingOffline() {
return goingOffline;
}
/**
* Create an encoded dynamic state that represents the dynamic state of this XFormsContainingDocument.
*
* @param pipelineContext current PipelineContext
* @param isForceEncryption whether to force encryption or not
* @return encoded dynamic state
*/
public String createEncodedDynamicState(PipelineContext pipelineContext, boolean isForceEncryption) {
return XFormsUtils.encodeXML(pipelineContext, createDynamicStateDocument(),
(isForceEncryption || XFormsProperties.isClientStateHandling(this)) ? XFormsProperties.getXFormsPassword() : null, false);
}
private Document createDynamicStateDocument() {
final Document dynamicStateDocument;
indentedLogger.startHandleOperation("", "encoding state");
{
dynamicStateDocument = Dom4jUtils.createDocument();
final Element dynamicStateElement = dynamicStateDocument.addElement("dynamic-state");
// Serialize instances
{
final Element instancesElement = dynamicStateElement.addElement("instances");
serializeInstances(instancesElement);
}
// Serialize controls
xformsControls.serializeControls(dynamicStateElement);
}
indentedLogger.endHandleOperation();
return dynamicStateDocument;
}
/**
* Restore the document's dynamic state given a serialized version of the dynamic state.
*
* @param pipelineContext current PipelineContext
* @param encodedDynamicState serialized dynamic state
*/
private void restoreDynamicState(PipelineContext pipelineContext, String encodedDynamicState) {
// Get dynamic state document
final Document dynamicStateDocument = XFormsUtils.decodeXML(pipelineContext, encodedDynamicState);
// Restore models state
{
// Store instances state in PipelineContext for use down the line
final Element instancesElement = dynamicStateDocument.getRootElement().element("instances");
pipelineContext.setAttribute(XFORMS_DYNAMIC_STATE_RESTORE_INSTANCES, instancesElement);
// Create XForms controls and models
createControlsAndModels(pipelineContext);
// Restore top-level models state, including instances
restoreModelsState(pipelineContext);
}
// Restore controls state
{
// Store serialized control state for retrieval later
final Map serializedControlStateMap = xformsControls.getSerializedControlStateMap(dynamicStateDocument.getRootElement());
pipelineContext.setAttribute(XFORMS_DYNAMIC_STATE_RESTORE_CONTROLS, serializedControlStateMap);
xformsControls.initializeState(pipelineContext, true);
xformsControls.evaluateControlValuesIfNeeded(pipelineContext);
pipelineContext.setAttribute(XFORMS_DYNAMIC_STATE_RESTORE_CONTROLS, null);
}
// Indicate that instance restoration process is over
pipelineContext.setAttribute(XFORMS_DYNAMIC_STATE_RESTORE_INSTANCES, null);
}
/**
* Whether the containing document is in a phase of restoring the dynamic state.
*
* @param propertyContext current context
* @return true iif restore is in process
*/
public boolean isRestoringDynamicState(PropertyContext propertyContext) {
return propertyContext.getAttribute(XFormsContainingDocument.XFORMS_DYNAMIC_STATE_RESTORE_INSTANCES) != null;
}
public Map getSerializedControlStatesMap(PropertyContext propertyContext) {
return (Map) propertyContext.getAttribute(XFormsContainingDocument.XFORMS_DYNAMIC_STATE_RESTORE_CONTROLS);
}
/**
* Whether, during initialization, this is the first refresh. The flag is automatically cleared during this call so
* that only the first call returns true.
*
* @return true if this is the first refresh, false otherwise
*/
public boolean isInitializationFirstRefreshClear() {
boolean result = mustPerformInitializationFirstRefresh;
mustPerformInitializationFirstRefresh = false;
return result;
}
private void initialize(PipelineContext pipelineContext) {
// This is called upon the first creation of the XForms engine only
// Create XForms controls and models
createControlsAndModels(pipelineContext);
// Before dispatching initialization events, remember that first refresh must be performed
this.mustPerformInitializationFirstRefresh = XFormsProperties.isDispatchInitialEvents(this);
// Group all xforms-model-construct-done and xforms-ready events within a single outermost action handler in
// order to optimize events
// Perform deferred updates only for xforms-ready
startOutermostActionHandler();
// Initialize models
initializeModels(pipelineContext);
// Check for background asynchronous submissions
processBackgroundAsynchronousSubmissions(pipelineContext);
// End deferred behavior
endOutermostActionHandler(pipelineContext);
// In case there is no model or no controls, make sure the flag is cleared as it is only relevant during
// initialization
this.mustPerformInitializationFirstRefresh = false;
}
private void createControlsAndModels(PipelineContext pipelineContext) {
// Gather static analysis information
xformsStaticState.analyzeIfNecessary(pipelineContext);
// Create XForms controls
xformsControls = new XFormsControls(this);
// Add models
addAllModels();
}
protected void initializeNestedControls(PropertyContext propertyContext) {
// Call-back from super class models initialization
// This is important because if controls use binds, those must be up to date
rebuildRecalculateIfNeeded(propertyContext);
// Initialize controls
xformsControls.initialize(propertyContext);
}
private Stack<XFormsEvent> eventStack = new Stack<XFormsEvent>();
public void startHandleEvent(XFormsEvent event) {
eventStack.push(event);
}
public void endHandleEvent() {
eventStack.pop();
}
/**
* Return the event being processed by the current event handler, null if no event is being processed.
*/
public XFormsEvent getCurrentEvent() {
return (eventStack.size() == 0) ? null : eventStack.peek();
}
public List getEventHandlers(XBLContainer container) {
return getStaticState().getEventHandlers(XFormsUtils.getEffectiveIdNoSuffix(getEffectiveId()));
}
public static void logWarningStatic(String type, String message, String... parameters) {
final Logger globalLogger = XFormsServer.getLogger();
IndentedLogger.logWarningStatic(globalLogger, "XForms", type, message, parameters);
}
public static void logErrorStatic(String type, String message, Throwable throwable) {
final Logger globalLogger = XFormsServer.getLogger();
IndentedLogger.logErrorStatic(globalLogger, "XForms", type, message, throwable);
}
/**
* Return a logger given a category.
*
* @param loggingCategory category
* @return logger
*/
public IndentedLogger getIndentedLogger(String loggingCategory) {
return loggersMap.get(loggingCategory);
}
private static final Map<String, IndentedLogger> STATIC_LOGGERS_MAP = new HashMap<String, IndentedLogger>();
/**
* Return a static logger given all the details.
*
* @param localLogger local logger, used only if separate loggers are configured
* @param globalLogger global logger, usually XFormsServer.getLogger()
* @param category category
* @return logger
*/
public static IndentedLogger getIndentedLogger(Logger localLogger, Logger globalLogger, String category) {
final IndentedLogger existingIndentedLogger = STATIC_LOGGERS_MAP.get(category);
if (existingIndentedLogger != null) {
return existingIndentedLogger;
}
final IndentedLogger indentedLogger;
final Logger logger;
final boolean isDebugEnabled;
if (XFormsServer.USE_SEPARATE_LOGGERS) {
logger = localLogger;
isDebugEnabled = logger.isDebugEnabled();
} else {
logger = globalLogger;
isDebugEnabled = XFormsProperties.getDebugLogging().contains(category);
}
indentedLogger = new IndentedLogger(logger, isDebugEnabled, category);
STATIC_LOGGERS_MAP.put(category, indentedLogger);
return indentedLogger;
}
} |
package org.orbeon.oxf.xforms.processor;
import org.orbeon.oxf.xforms.control.controls.XFormsSelect1Control;
import org.orbeon.oxf.xforms.XFormsProperties;
import org.orbeon.oxf.xforms.XFormsContainingDocument;
import org.orbeon.oxf.common.Version;
import org.orbeon.saxon.om.FastStringBuffer;
import java.util.*;
public class XFormsFeatures {
private static final FeatureConfig[] features = {
new FeatureConfig("range", "range"),
new FeatureConfig("tree", new String[] { "select", "select1" }, XFormsSelect1Control.TREE_APPEARANCE),
new FeatureConfig("menu", "select1", XFormsSelect1Control.MENU_APPEARANCE),
new FeatureConfig("autocomplete", "select1", XFormsSelect1Control.AUTOCOMPLETE_APPEARANCE),
new FeatureConfig("htmlarea", "textarea", "text/html"),
new FeatureConfig("dialog", "dialog"),
new FeatureConfig("offline") {
public boolean isInUse(XFormsContainingDocument containingDocument, Map appearancesMap) {
return XFormsProperties.isOfflineMode(containingDocument);
}
},
new FeatureConfig("jscalendar") {
public boolean isInUse(XFormsContainingDocument containingDocument, Map appearancesMap) {
return "jscalendar".equals(XFormsProperties.getDatePicker(containingDocument));
}
},
new FeatureConfig("yuicalendar") {
public boolean isInUse(XFormsContainingDocument containingDocument, Map appearancesMap) {
return !"jscalendar".equals(XFormsProperties.getDatePicker(containingDocument));
}
}
};
public static class FeatureConfig {
private String name;
// private String id;
private String[] controlNames;
private String[] controlAppearanceOrMediatypes;
public FeatureConfig(String name) {
this(name, (String[]) null, (String[]) null);
}
public FeatureConfig(String name, String controlName) {
this(name, new String[] { controlName }, (String[]) null);
}
public FeatureConfig(String name, String controlName, String controlAppearanceOrMediatype) {
this(name, new String[] { controlName }, new String[] { controlAppearanceOrMediatype });
}
public FeatureConfig(String name, String[] controlNames, String controlAppearanceOrMediatype) {
this(name, controlNames, new String[] { controlAppearanceOrMediatype });
}
public FeatureConfig(String name, String[] controlNames, String[] controlAppearanceOrMediatypes) {
this.name = name;
// this.id = SecureUtils.digestString(name, "md5", "base64");
this.controlNames = controlNames;
this.controlAppearanceOrMediatypes = controlAppearanceOrMediatypes;
}
public String getName() {
return name;
}
public String getId() {
// return id;
return name;
}
public boolean isInUse(XFormsContainingDocument containingDocument, Map appearancesMap) {
if (controlAppearanceOrMediatypes != null && controlAppearanceOrMediatypes.length > 0) {
// Test by control name and appearance/mediatype
for (int i = 0; i < controlNames.length; i++) {
for (int j = 0; j < controlAppearanceOrMediatypes.length; j++) {
if (ResourceConfig.isInUse(appearancesMap, controlNames[i], controlAppearanceOrMediatypes[j])) {
return true;
}
}
}
} else {
// Test by control name only
for (int i = 0; i < controlNames.length; i++) {
if (ResourceConfig.isInUse(appearancesMap, controlNames[i]))
return true;
}
}
return false;
}
}
private static Map featuresByIdMap = new HashMap();
static {
for (int i = 0; i < features.length; i++) {
final FeatureConfig currentFeatureConfig = features[i];
featuresByIdMap.put(currentFeatureConfig.getId(), currentFeatureConfig);
}
}
private static final ResourceConfig[] stylesheets = {
// Calendar stylesheets
new ResourceConfig("/ops/javascript/jscalendar/calendar-blue.css", null) {
public boolean isInUse(XFormsContainingDocument containingDocument, Map appearancesMap) {
return "jscalendar".equals(XFormsProperties.getDatePicker(containingDocument));
}
protected String getFeatureName() { return "jscalendar"; }
},
new ResourceConfig("/ops/yui/container/assets/container.css", null) {
public boolean isInUse(XFormsContainingDocument containingDocument, Map appearancesMap) {
return "jscalendar".equals(XFormsProperties.getDatePicker(containingDocument));
}
protected String getFeatureName() { return "jscalendar"; }
},
new ResourceConfig("/ops/yui/calendar/assets/calendar.css", null) {
public boolean isInUse(XFormsContainingDocument containingDocument, Map appearancesMap) {
return !"jscalendar".equals(XFormsProperties.getDatePicker(containingDocument));
}
protected String getFeatureName() { return "yuicalendar"; }
},
// Yahoo! UI Library
new ResourceConfig("/ops/yui/treeview/assets/treeview.css", null) {
public boolean isInUse(XFormsContainingDocument containingDocument, Map appearancesMap) {
return isTreeInUse(appearancesMap);
}
public String getFeatureName() { return "tree"; }
},
new ResourceConfig("/ops/yui/examples/treeview/assets/css/check/tree.css", null) {
public boolean isInUse(XFormsContainingDocument containingDocument, Map appearancesMap) {
return isTreeInUse(appearancesMap);
}
public String getFeatureName() { return "tree"; }
},
new ResourceConfig("/ops/yui/menu/assets/menu.css", null) {
public boolean isInUse(XFormsContainingDocument containingDocument, Map appearancesMap) {
return isMenuInUse(appearancesMap);
}
public String getFeatureName() { return "menu"; }
},
// NOTE: This doesn't work, probably because FCK editor files must be loaded in an iframe
// new ResourceConfig("/ops/fckeditor/editor/skins/default/fck_editor.css", null) {
// public boolean isInUse(Map appearancesMap) {
// return isHtmlAreaInUse(appearancesMap);
// public String getFeatureName() { return "htmlarea"; }
// Other standard stylesheets
new ResourceConfig("/config/theme/xforms.css", null),
new ResourceConfig("/config/theme/error.css", null)
};
private static final ResourceConfig[] scripts = {
// Calendar scripts
new ResourceConfig("/ops/javascript/jscalendar/calendar.js", "/ops/javascript/jscalendar/calendar-min.js") {
public boolean isInUse(XFormsContainingDocument containingDocument, Map appearancesMap) {
return "jscalendar".equals(XFormsProperties.getDatePicker(containingDocument));
}
protected String getFeatureName() { return "jscalendar"; }
},
new ResourceConfig("/ops/javascript/jscalendar/lang/calendar-en.js", "/ops/javascript/jscalendar/lang/calendar-en-min.js") {
public boolean isInUse(XFormsContainingDocument containingDocument, Map appearancesMap) {
return "jscalendar".equals(XFormsProperties.getDatePicker(containingDocument));
}
protected String getFeatureName() { return "jscalendar"; }
},
new ResourceConfig("/ops/javascript/jscalendar/calendar-setup.js", "/ops/javascript/jscalendar/calendar-setup-min.js") {
public boolean isInUse(XFormsContainingDocument containingDocument, Map appearancesMap) {
return "jscalendar".equals(XFormsProperties.getDatePicker(containingDocument));
}
protected String getFeatureName() { return "jscalendar"; }
},
// Yahoo UI Library
new ResourceConfig("/ops/yui/yahoo/yahoo.js", "/ops/yui/yahoo/yahoo-min.js"),
new ResourceConfig("/ops/yui/selector/selector-beta.js", "/ops/yui/selector/selector-beta-min.js") {
public boolean isInUse(XFormsContainingDocument containingDocument, Map appearancesMap) {
return XFormsProperties.isOfflineMode(containingDocument);
}
public String getFeatureName() { return "offline"; }
},
new ResourceConfig("/ops/yui/event/event.js", "/ops/yui/event/event-min.js"),
new ResourceConfig("/ops/yui/dom/dom.js", "/ops/yui/dom/dom-min.js"),
new ResourceConfig("/ops/yui/connection/connection.js", "/ops/yui/connection/connection-min.js"),
new ResourceConfig("/ops/yui/animation/animation.js", "/ops/yui/animation/animation-min.js"),
new ResourceConfig("/ops/yui/dragdrop/dragdrop.js", "/ops/yui/dragdrop/dragdrop-min.js"),
new ResourceConfig("/ops/yui/container/container.js", "/ops/yui/container/container-min.js"),
new ResourceConfig("/ops/yui/calendar/calendar.js", "/ops/yui/calendar/calendar-min.js") {
public boolean isInUse(XFormsContainingDocument containingDocument, Map appearancesMap) {
return !"jscalendar".equals(XFormsProperties.getDatePicker(containingDocument));
}
protected String getFeatureName() { return "yuicalendar"; }
},
new ResourceConfig("/ops/yui/slider/slider.js", "/ops/yui/slider/slider-min.js") {
public boolean isInUse(XFormsContainingDocument containingDocument, Map appearancesMap) {
return isRangeInUse(appearancesMap);
}
public String getFeatureName() { return "range"; }
},
new ResourceConfig("/ops/yui/treeview/treeview.js", "/ops/yui/treeview/treeview-min.js") {
public boolean isInUse(XFormsContainingDocument containingDocument, Map appearancesMap) {
return isTreeInUse(appearancesMap);
}
public String getFeatureName() { return "tree"; }
},
new ResourceConfig("/ops/yui/examples/treeview/assets/js/TaskNode.js", "/ops/yui/examples/treeview/assets/js/TaskNode-min.js") {
public boolean isInUse(XFormsContainingDocument containingDocument, Map appearancesMap) {
return isTreeInUse(appearancesMap);
}
public String getFeatureName() { return "tree"; }
},
new ResourceConfig("/ops/yui/examples/treeview/assets/js/CheckOnClickNode.js", "/ops/yui/examples/treeview/assets/js/CheckOnClickNode-min.js") {
public boolean isInUse(XFormsContainingDocument containingDocument, Map appearancesMap) {
return isTreeInUse(appearancesMap);
}
public String getFeatureName() { return "tree"; }
},
new ResourceConfig("/ops/yui/menu/menu.js", "/ops/yui/menu/menu-min.js") {
public boolean isInUse(XFormsContainingDocument containingDocument, Map appearancesMap) {
return isMenuInUse(appearancesMap);
}
public String getFeatureName() { return "menu"; }
},
// HTML area
new ResourceConfig("/ops/fckeditor/fckeditor.js", null) {
public boolean isInUse(XFormsContainingDocument containingDocument, Map appearancesMap) {
return isHtmlAreaInUse(appearancesMap);
}
public String getFeatureName() { return "htmlarea"; }
},
// Autocomplete
new ResourceConfig("/ops/javascript/suggest-common.js", "/ops/javascript/suggest-common-min.js") {
public boolean isInUse(XFormsContainingDocument containingDocument, Map appearancesMap) {
return isAutocompleteInUse(appearancesMap);
}
public String getFeatureName() { return "autocomplete"; }
},
new ResourceConfig("/ops/javascript/suggest-actb.js", "/ops/javascript/suggest-actb-min.js") {
public boolean isInUse(XFormsContainingDocument containingDocument, Map appearancesMap) {
return isAutocompleteInUse(appearancesMap);
}
public String getFeatureName() { return "autocomplete"; }
},
// Selector is so far only used offline
new ResourceConfig("/ops/yui/selector/selector-beta.js", "/ops/yui/selector/selector-beta-min.js") {
public boolean isInUse(XFormsContainingDocument containingDocument, Map appearancesMap) {
return XFormsProperties.isOfflineMode(containingDocument);
}
public String getFeatureName() { return "offline"; }
},
// ajaxxslt (to compute XPath expressions on the client-side when offline)
new ResourceConfig("/ops/javascript/ajaxxslt/util.js", "/ops/javascript/ajaxxslt/util-min.js") {
public boolean isInUse(XFormsContainingDocument containingDocument, Map appearancesMap) {
return XFormsProperties.isOfflineMode(containingDocument);
}
public String getFeatureName() { return "offline"; }
},
new ResourceConfig("/ops/javascript/ajaxxslt/xmltoken.js", "/ops/javascript/ajaxxslt/xmltoken-min.js") {
public boolean isInUse(XFormsContainingDocument containingDocument, Map appearancesMap) {
return XFormsProperties.isOfflineMode(containingDocument);
}
public String getFeatureName() { return "offline"; }
},
new ResourceConfig("/ops/javascript/ajaxxslt/dom.js", "/ops/javascript/ajaxxslt/dom-min.js") {
public boolean isInUse(XFormsContainingDocument containingDocument, Map appearancesMap) {
return XFormsProperties.isOfflineMode(containingDocument);
}
public String getFeatureName() { return "offline"; }
},
new ResourceConfig("/ops/javascript/ajaxxslt/xpath.js", "/ops/javascript/ajaxxslt/xpath-min.js") {
public boolean isInUse(XFormsContainingDocument containingDocument, Map appearancesMap) {
return XFormsProperties.isOfflineMode(containingDocument);
}
public String getFeatureName() { return "offline"; }
},
// Encrytion library to encrypt data stored in the Gears store
new ResourceConfig("/ops/javascript/encryption/encryption.js", "/ops/javascript/encryption/encryption-min.js") {
public boolean isInUse(XFormsContainingDocument containingDocument, Map appearancesMap) {
return XFormsProperties.isOfflineMode(containingDocument);
}
public String getFeatureName() { return "offline"; }
},
new ResourceConfig("/ops/javascript/encryption/md5.js", "/ops/javascript/encryption/md5-min.js") {
public boolean isInUse(XFormsContainingDocument containingDocument, Map appearancesMap) {
return XFormsProperties.isOfflineMode(containingDocument);
}
public String getFeatureName() { return "offline"; }
},
new ResourceConfig("/ops/javascript/encryption/utf-8.js", "/ops/javascript/encryption/utf-8-min.js") {
public boolean isInUse(XFormsContainingDocument containingDocument, Map appearancesMap) {
return XFormsProperties.isOfflineMode(containingDocument);
}
public String getFeatureName() { return "offline"; }
},
// XForms client
new ResourceConfig("/ops/javascript/xforms.js", "/ops/javascript/xforms-min.js")
};
public static class ResourceConfig {
private String fullResource;
private String minResource;
public ResourceConfig(String fullResource, String minResource) {
this.fullResource = fullResource;
this.minResource = minResource;
}
public String getResourcePath(boolean tryMinimal) {
// Load minimal resource if requested and there exists a minimal resource
return (tryMinimal && minResource != null) ? minResource : fullResource;
}
public boolean isInUse(XFormsContainingDocument containingDocument, Map appearancesMap) {
// Default to true but can be overridden
return true;
}
public boolean isInUseByFeatureMap(Map featureMap) {
// Default to true but can be overridden
final String featureName = getFeatureName();
if (featureName == null)
return true;
final FeatureConfig featureConfig = (FeatureConfig) featureMap.get(featureName);
return featureConfig != null;
}
protected String getFeatureName() {
return null;
}
public static boolean isInUse(Map appearancesMap, String controlName) {
final Map controlMap = (Map) appearancesMap.get(controlName);
return controlMap != null;
}
public static boolean isInUse(Map appearancesMap, String controlName, String appearanceOrMediatypeName) {
final Map controlMap = (Map) appearancesMap.get(controlName);
if (controlMap == null) return false;
final Object controlAppearanceOrMediatypeList = controlMap.get(appearanceOrMediatypeName);
return controlAppearanceOrMediatypeList != null;
}
protected boolean isRangeInUse(Map appearancesMap) {
return isInUse(appearancesMap, "range");
}
protected boolean isTreeInUse(Map appearancesMap) {
return isInUse(appearancesMap, "select1", XFormsSelect1Control.TREE_APPEARANCE) || isInUse(appearancesMap, "select", XFormsSelect1Control.TREE_APPEARANCE);
}
protected boolean isMenuInUse(Map appearancesMap) {
return isInUse(appearancesMap, "select1", XFormsSelect1Control.MENU_APPEARANCE) || isInUse(appearancesMap, "select", XFormsSelect1Control.MENU_APPEARANCE);
}
protected boolean isAutocompleteInUse(Map appearancesMap) {
return isInUse(appearancesMap, "select1", XFormsSelect1Control.AUTOCOMPLETE_APPEARANCE);
}
protected boolean isHtmlAreaInUse(Map appearancesMap) {
return isInUse(appearancesMap, "textarea", "text/html");
}
protected boolean isDialogInUse(Map appearancesMap) {
return isInUse(appearancesMap, "dialog");
}
}
public static String getCombinedResourcesPrefix(XFormsContainingDocument containingDocument, Map appearancesMap, boolean isMinimal, boolean isVersioned) {
if (XFormsProperties.isCombinedResources(containingDocument)) {
final FastStringBuffer sb = new FastStringBuffer("/xforms-server/");
// Make the Orbeon Forms version part of the path if requested
if (isVersioned) {
sb.append(Version.getVersion());
sb.append('/');
}
sb.append("xforms");
for (int i = 0; i < features.length; i++) {
final FeatureConfig currentFeature = features[i];
if (currentFeature.isInUse(containingDocument, appearancesMap)) {
sb.append('-');
sb.append(currentFeature.getId());
}
}
if (isMinimal)
sb.append("-min");
return sb.toString();
} else {
return null;
}
}
public static List getCSSResources(XFormsContainingDocument containingDocument, Map appearancesMap) {
final List result = new ArrayList();
for (int i = 0; i < stylesheets.length; i++) {
final ResourceConfig resourceConfig = stylesheets[i];
if (resourceConfig.isInUse(containingDocument, appearancesMap)) {
// Only include stylesheet if needed
result.add(resourceConfig);
}
}
return result;
}
public static List getCSSResourcesByFeatureMap(Map featureMap) {
final List result = new ArrayList();
for (int i = 0; i < stylesheets.length; i++) {
final ResourceConfig resourceConfig = stylesheets[i];
if (resourceConfig.isInUseByFeatureMap(featureMap)) {
// Only include stylesheet if needed
result.add(resourceConfig);
}
}
return result;
}
public static List getJavaScriptResources(XFormsContainingDocument containingDocument, Map appearancesMap) {
final List result = new ArrayList();
for (int i = 0; i < scripts.length; i++) {
final ResourceConfig resourceConfig = scripts[i];
if (resourceConfig.isInUse(containingDocument, appearancesMap)) {
// Only include script if needed
result.add(resourceConfig);
}
}
return result;
}
public static List getJavaScriptResourcesByFeatureMap(Map featureMap) {
final List result = new ArrayList();
for (int i = 0; i < scripts.length; i++) {
final ResourceConfig resourceConfig = scripts[i];
if (resourceConfig.isInUseByFeatureMap(featureMap)) {
// Only include script if needed
result.add(resourceConfig);
}
}
return result;
}
public static FeatureConfig getFeatureById(String featureId) {
return (FeatureConfig) featuresByIdMap.get(featureId);
}
} |
package com.strengthcoach.strengthcoach.activities;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseInstallation;
import com.parse.ParsePush;
import com.parse.ParseQuery;
import com.parse.SendCallback;
import com.strengthcoach.strengthcoach.R;
import com.strengthcoach.strengthcoach.adapters.ChatItemAdapter;
import com.strengthcoach.strengthcoach.adapters.ICurrentUserProvider;
import com.strengthcoach.strengthcoach.models.Message;
import com.strengthcoach.strengthcoach.models.Trainer;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class ChatActivity extends ActionBarActivity implements ICurrentUserProvider {
Trainer m_trainer;
ArrayList<Message> messages;
ChatItemAdapter messagesAdapter;
String currentUserId;
EditText etMessage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
messages = new ArrayList<>();
messagesAdapter = new ChatItemAdapter(this, messages, this);
ListView lvMessages = (ListView) findViewById(R.id.lvMessages);
lvMessages.setAdapter(messagesAdapter);
etMessage = (EditText) findViewById(R.id.etMessage);
// Get the m_trainer object from parse and setup the view
String trainerId = getIntent().getStringExtra("trainerId");
ParseQuery<Trainer> query = ParseQuery.getQuery("Trainer");
query.whereEqualTo("objectId", trainerId);
query.findInBackground(new FindCallback<Trainer>() {
@Override
public void done(List<Trainer> list, com.parse.ParseException e) {
Log.d("DEBUG", ((Trainer) list.get(0)).getName());
m_trainer = list.get(0);
messagesAdapter.setTrainer(m_trainer);
}
});
if (getLoggedInUserId().equals("")) {
// Start login activity
Intent intent = new Intent(this, LoginActivity.class);
startActivityForResult(intent, 20);
}
else {
currentUserId = getLoggedInUserId();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_chat, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onSendClicked(View view) {
Message message = new Message();
message.setFromObjectId(currentUserId);
message.setToObjectId(m_trainer.getObjectId());
message.setText(etMessage.getText().toString());
message.saveInBackground();
messagesAdapter.add(message);
try {
JSONObject jsonObject = new JSONObject(String.format("{\"from\":\"%s\", \"to\":\"%s\", \"message\":\"%s\"}", currentUserId, m_trainer.getObjectId(), etMessage.getText().toString()));
ParseQuery pushQuery = ParseInstallation.getQuery();
pushQuery.whereEqualTo("channels", "");
ParsePush push = new ParsePush();
push.setQuery(pushQuery);
push.setData(jsonObject);
push.sendInBackground(new SendCallback() {
@Override
public void done(ParseException e) {
Toast.makeText(getBaseContext(), "sent", Toast.LENGTH_SHORT);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
etMessage.setText("");
// TODO: Remove fake message once trainer view is in place.
addFakeMessageFromTrainer();
}
private void addFakeMessageFromTrainer() {
Message message = new Message();
message.setToObjectId(currentUserId);
message.setFromObjectId(m_trainer.getObjectId());
message.setText("Hello. I would love to work with you");
message.saveInBackground();
messagesAdapter.add(message);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 20) {
if(resultCode != RESULT_OK){
// User didn't login cancel book slot
Intent returnIntent = new Intent();
setResult(RESULT_CANCELED, returnIntent);
finish();
}
else {
currentUserId = getLoggedInUserId();
}
}
}
private String getLoggedInUserId() {
SharedPreferences pref =
PreferenceManager.getDefaultSharedPreferences(this);
String userId = pref.getString("userId", "");
return userId;
}
@Override
public String currentUserId() {
return currentUserId;
}
} |
package org.orbeon.oxf.xforms.state;
import org.orbeon.oxf.common.OXFException;
import org.orbeon.oxf.pipeline.api.ExternalContext;
import org.orbeon.oxf.pipeline.api.PipelineContext;
import org.orbeon.oxf.util.UUIDUtils;
import org.orbeon.oxf.xforms.XFormsContainingDocument;
import org.orbeon.oxf.xforms.XFormsProperties;
/**
* Centralize XForms state management.
*
* TODO: Get rid of the old "session" store code as it is replaced by the new persistent store.
*/
public class XFormsStateManager {
// All these must have the same length
public static final String SESSION_STATE_PREFIX = "sess:";
public static final String APPLICATION_STATE_PREFIX = "appl:";
public static final String PERSISTENT_STATE_PREFIX = "pers:";
private static final int PREFIX_COLON_POSITION = SESSION_STATE_PREFIX.length() - 1;
// Ideally we wouldn't want to force session creation, but it's hard to implement the more elaborate expiration
public static final boolean FORCE_SESSION_CREATION = true;
/**
* Get the initial encoded XForms state as it must be sent to the client within the (X)HTML.
*
* @param containingDocument containing document
* @param externalContext external context (for access to session and application scopes)
* @param xformsState post-initialization XFormsState
* @param staticStateUUID static state UUID (if static state was cached against input document)
* @param dynamicStateUUID dynamic state UUID (if dynamic state was cached against output document)
* @return XFormsState containing the encoded static and dynamic states
*/
public static XFormsState getInitialEncodedClientState(XFormsContainingDocument containingDocument, ExternalContext externalContext, XFormsState xformsState, String staticStateUUID, String dynamicStateUUID) {
final String currentPageGenerationId;
final String staticStateString;
{
if (containingDocument.isServerStateHandling()) {
if (containingDocument.isLegacyServerStateHandling()) {
// Legacy session server handling
// Produce UUID
if (staticStateUUID == null) {
currentPageGenerationId = UUIDUtils.createPseudoUUID();
staticStateString = SESSION_STATE_PREFIX + currentPageGenerationId;
} else {
// In this case, we first store in the application scope, so that multiple requests can use the
// same cached state.
currentPageGenerationId = staticStateUUID;
staticStateString = APPLICATION_STATE_PREFIX + currentPageGenerationId;
}
} else {
// New server state handling with persistent store
if (staticStateUUID == null) {
currentPageGenerationId = UUIDUtils.createPseudoUUID();
} else {
currentPageGenerationId = staticStateUUID;
}
staticStateString = PERSISTENT_STATE_PREFIX + currentPageGenerationId;
}
} else {
// Produce encoded static state
staticStateString = xformsState.getStaticState();
currentPageGenerationId = null;
}
}
final String dynamicStateString;
{
if (containingDocument.isServerStateHandling()) {
if (containingDocument.isLegacyServerStateHandling()) {
// Legacy session server handling
if (dynamicStateUUID == null) {
// In this case, we use session scope since not much sharing will occur, if at all.
// Produce dynamic state key
final String newRequestId = UUIDUtils.createPseudoUUID();
final XFormsStateStore stateStore = XFormsSessionStateStore.instance(externalContext, true);
stateStore.add(currentPageGenerationId, null, newRequestId, xformsState, null);
dynamicStateString = SESSION_STATE_PREFIX + newRequestId;
} else {
// In this case, we first store in the application scope, so that multiple requests can use the
// same cached state.
dynamicStateString = APPLICATION_STATE_PREFIX + dynamicStateUUID;
final XFormsStateStore applicationStateStore = XFormsApplicationStateStore.instance(externalContext);
applicationStateStore.add(currentPageGenerationId, null, dynamicStateUUID, xformsState, null);
}
} else {
// New server state handling with persistent store
// Get session id if needed
final ExternalContext.Session session = externalContext.getSession(FORCE_SESSION_CREATION);
final String sessionId = (session != null) ? session.getId() : null;
final XFormsStateStore stateStore = XFormsPersistentApplicationStateStore.instance(externalContext);
if (dynamicStateUUID == null) {
// In this case, we use session scope since not much sharing will occur, if at all.
// Produce dynamic state key
final String newRequestId = UUIDUtils.createPseudoUUID();
stateStore.add(currentPageGenerationId, null, newRequestId, xformsState, sessionId);
dynamicStateString = PERSISTENT_STATE_PREFIX + newRequestId;
} else {
// In this case, we first store in the application scope, so that multiple requests can use the
// same cached state.
dynamicStateString = PERSISTENT_STATE_PREFIX + dynamicStateUUID;
stateStore.add(currentPageGenerationId, null, dynamicStateUUID, xformsState, sessionId);
}
}
} else {
// Send state to the client
dynamicStateString = xformsState.getDynamicState();
}
}
return new XFormsState(staticStateString, dynamicStateString);
}
/**
* Decode static and dynamic state strings coming from the client.
*
* @param pipelineContext pipeline context
* @param staticStateString static state string as sent by client
* @param dynamicStateString dynamic state string as sent by client
* @return decoded state
*/
public static XFormsDecodedClientState decodeClientState(PipelineContext pipelineContext, String staticStateString, String dynamicStateString) {
final ExternalContext externalContext = (ExternalContext) pipelineContext.getAttribute(PipelineContext.EXTERNAL_CONTEXT);
final XFormsDecodedClientState xformsDecodedClientState;
if (staticStateString.length() > PREFIX_COLON_POSITION && staticStateString.charAt(PREFIX_COLON_POSITION) == ':') {
// State doesn't come directly with request
// Separate prefixes from UUIDs
final String staticStatePrefix = staticStateString.substring(0, PREFIX_COLON_POSITION + 1);
final String staticStateUUID = staticStateString.substring(PREFIX_COLON_POSITION + 1);
final String dynamicStatePrefix = dynamicStateString.substring(0, PREFIX_COLON_POSITION + 1);
final String dynamicStateUUID = dynamicStateString.substring(PREFIX_COLON_POSITION + 1);
// Both prefixes must be the same
if (!staticStatePrefix.equals(dynamicStatePrefix)) {
throw new OXFException("Inconsistent XForms state prefixes: " + staticStatePrefix + ", " + dynamicStatePrefix);
}
// Get relevant store
final XFormsStateStore stateStore;
if (staticStatePrefix.equals(PERSISTENT_STATE_PREFIX)) {
stateStore = XFormsPersistentApplicationStateStore.instance(externalContext);
} else if (staticStatePrefix.equals(SESSION_STATE_PREFIX)) {
// NOTE: Don't create session at this time if it is not found
stateStore = XFormsSessionStateStore.instance(externalContext, false);
} else if (staticStatePrefix.equals(APPLICATION_STATE_PREFIX)) {
stateStore = XFormsApplicationStateStore.instance(externalContext);
} else {
// Invalid prefix
throw new OXFException("Invalid state prefix: " + staticStatePrefix);
}
// Get state from store
final XFormsState xformsState = (stateStore == null) ? null : stateStore.find(staticStateUUID, dynamicStateUUID);
// This is not going to be good when it happens, and we must create a caching heuristic that minimizes this
if (xformsState == null) {
final String UNABLE_TO_RETRIEVE_XFORMS_STATE_MESSAGE = "Unable to retrieve XForms engine state.";
final String PLEASE_RELOAD_PAGE_MESSAGE = "Please reload the current page. Note that you will lose any unsaved changes.";
if (staticStatePrefix.equals(PERSISTENT_STATE_PREFIX)) {
final ExternalContext.Session currentSession = externalContext.getSession(false);
if (currentSession == null || currentSession.isNew()) {
// This means that no session is currently existing, or a session exists but it is newly created
throw new OXFException("Your session has expired. " + PLEASE_RELOAD_PAGE_MESSAGE);
} else {
// There is a session and it is still known by the client
throw new OXFException(UNABLE_TO_RETRIEVE_XFORMS_STATE_MESSAGE + " " + PLEASE_RELOAD_PAGE_MESSAGE);
}
} else {
throw new OXFException(UNABLE_TO_RETRIEVE_XFORMS_STATE_MESSAGE + " " + PLEASE_RELOAD_PAGE_MESSAGE);
}
}
xformsDecodedClientState = new XFormsDecodedClientState(xformsState, staticStateUUID, dynamicStateUUID);
} else {
// State comes directly with request
xformsDecodedClientState = new XFormsDecodedClientState(new XFormsState(staticStateString, dynamicStateString), null, null);
}
return xformsDecodedClientState;
}
/**
* Get the encoded XForms state as it must be sent to the client within an Ajax response.
*
* @param containingDocument containing document
* @param pipelineContext pipeline context
* @param xformsDecodedClientState decoded state as received in Ajax request
* @param isAllEvents whether this is a special "all events" request
* @return XFormsState containing the encoded static and dynamic states
*/
public static XFormsState getEncodedClientStateDoCache(XFormsContainingDocument containingDocument, PipelineContext pipelineContext,
XFormsDecodedClientState xformsDecodedClientState, boolean isAllEvents) {
final ExternalContext externalContext = (ExternalContext) pipelineContext.getAttribute(PipelineContext.EXTERNAL_CONTEXT);
// Output static state (FOR TESTING ONLY)
final String staticStateString = xformsDecodedClientState.getXFormsState().getStaticState();
// Output dynamic state
final String dynamicStateString;
{
// Produce page generation id if needed
final String currentPageGenerationId = (xformsDecodedClientState.getStaticStateUUID() != null) ? xformsDecodedClientState.getStaticStateUUID() : UUIDUtils.createPseudoUUID();
// Create and encode dynamic state
final String newEncodedDynamicState = containingDocument.createEncodedDynamicState(pipelineContext);
final XFormsState newXFormsState = new XFormsState(staticStateString, newEncodedDynamicState);
if (containingDocument.isServerStateHandling()) {
final String requestId = xformsDecodedClientState.getDynamicStateUUID();
// Get session id if needed
final ExternalContext.Session session = externalContext.getSession(FORCE_SESSION_CREATION);
final String sessionId = (session != null) ? session.getId() : null;
// Produce dynamic state key (keep the same when allEvents!)
final String newRequestId = isAllEvents ? requestId : UUIDUtils.createPseudoUUID();
if (containingDocument.isLegacyServerStateHandling()) {
// Legacy session server handling
final XFormsStateStore stateStore = XFormsSessionStateStore.instance(externalContext, true);
stateStore.add(currentPageGenerationId, requestId, newRequestId, newXFormsState, sessionId);
dynamicStateString = SESSION_STATE_PREFIX + newRequestId;
} else {
// New server state handling with persistent store
final XFormsStateStore stateStore = XFormsPersistentApplicationStateStore.instance(externalContext);
stateStore.add(currentPageGenerationId, requestId, newRequestId, newXFormsState, sessionId);
dynamicStateString = PERSISTENT_STATE_PREFIX + newRequestId;
}
} else {
// Send state directly to the client
dynamicStateString = newEncodedDynamicState;
}
// Cache document if requested and possible
if (XFormsProperties.isCacheDocument()) {
XFormsDocumentCache.instance().add(pipelineContext, newXFormsState, containingDocument);
}
}
return new XFormsState(staticStateString, dynamicStateString);
}
/**
* Represent a decoded client state, i.e. a decoded XFormsState with some information extracted from the Ajax
* request.
*/
public static class XFormsDecodedClientState {
private XFormsState xformsState;
private String staticStateUUID;
private String dynamicStateUUID;
public XFormsDecodedClientState(XFormsState xformsState, String staticStateUUID, String dynamicStateUUID) {
this.xformsState = xformsState;
this.staticStateUUID = staticStateUUID;
this.dynamicStateUUID = dynamicStateUUID;
}
public XFormsState getXFormsState() {
return xformsState;
}
public String getStaticStateUUID() {
return staticStateUUID;
}
public String getDynamicStateUUID() {
return dynamicStateUUID;
}
}
} |
package ru.yandex.market.graphouse.search;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import ru.yandex.common.util.db.BulkUpdater;
import ru.yandex.market.clickhouse.ClickhouseTemplate;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author Dmitry Andreev <a href="mailto:AndreevDm@yandex-team.ru"/>
* @date 07/04/15
*/
public class MetricSearch implements InitializingBean, Runnable {
private static final Logger log = LogManager.getLogger();
private JdbcTemplate graphouseJdbcTemplate;
private final MetricTree metricTree = new MetricTree();
private final Queue<String> newMetricQueue = new ConcurrentLinkedQueue<>();
private int lastUpdatedTimestampSeconds = 0;
private int saveIntervalSeconds = 300;
private int updateDelaySeconds = 120;
@Override
public void afterPropertiesSet() throws Exception {
initDatabase();
new Thread(this, "MetricSearch thread").start();
}
private void initDatabase() {
graphouseJdbcTemplate.update(
"CREATE TABLE IF NOT EXISTS metric (" +
" `name` VARCHAR(200) NOT NULL, " +
" `ban` BIT NOT NULL DEFAULT 0, " +
" `updated` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, " +
" PRIMARY KEY (`name`), " +
" INDEX (`updated`)" +
") "
);
}
private void loadMetrics(int startTimestampSeconds) {
log.info("Loading metric names from db");
final AtomicInteger metricCount = new AtomicInteger();
final AtomicInteger banCount = new AtomicInteger();
graphouseJdbcTemplate.query(
"SELECT name, ban FROM metric WHERE updated >= ? ORDER BY ban DESC",
new RowCallbackHandler() {
@Override
public void processRow(ResultSet rs) throws SQLException {
String metric = rs.getString("name");
boolean ban = rs.getBoolean("ban");
if (ban) {
metricTree.ban(metric);
banCount.incrementAndGet();
} else {
metricTree.add(metric);
metricCount.incrementAndGet();
}
}
},
startTimestampSeconds
);
log.info("Loaded " + metricCount.get() + " metrics and " + banCount.get() + " bans");
}
private void saveNewMetrics() {
if (!newMetricQueue.isEmpty()) {
log.info("Saving new metric names to db");
int count = 0;
BulkUpdater bulkUpdater = new BulkUpdater(
graphouseJdbcTemplate,
"INSERT IGNORE INTO metric (name) values (?)",
100000
);
String metric;
while ((metric = newMetricQueue.poll()) != null) {
bulkUpdater.submit(metric);
count++;
}
bulkUpdater.done();
log.info("Saved " + count + " metric names");
} else {
log.info("No new metric names to save");
}
}
@Override
public void run() {
while (!Thread.interrupted()) {
try {
update();
saveNewMetrics();
} catch (Exception e) {
log.error("Failed to update metric search", e);
}
try {
Thread.sleep(TimeUnit.SECONDS.toMillis(saveIntervalSeconds));
} catch (InterruptedException ignored) {
}
}
}
private void update() {
int timeSeconds = (int) (System.currentTimeMillis() / 1000) - updateDelaySeconds;
loadMetrics(lastUpdatedTimestampSeconds);
lastUpdatedTimestampSeconds = timeSeconds;
}
public MetricStatus add(String metric) {
MetricStatus status = metricTree.add(metric);
if (status == MetricStatus.NEW) {
newMetricQueue.add(metric);
}
return status;
}
public void ban(String metric) {
graphouseJdbcTemplate.update(
"INSERT INTO metric (name, ban) VALUES (?, 1) " +
"ON DUPLICATE KEY UPDATE ban = 1, updated = CURRENT_TIMESTAMP",
metric
);
metricTree.ban(metric);
}
public void search(String query, Appendable result) throws IOException {
metricTree.search(query, result);
}
@Required
public void setGraphouseJdbcTemplate(JdbcTemplate graphouseJdbcTemplate) {
this.graphouseJdbcTemplate = graphouseJdbcTemplate;
}
public void setSaveIntervalSeconds(int saveIntervalSeconds) {
this.saveIntervalSeconds = saveIntervalSeconds;
}
public void setUpdateDelaySeconds(int updateDelaySeconds) {
this.updateDelaySeconds = updateDelaySeconds;
}
} |
package voldemort.client.rebalance;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import voldemort.VoldemortException;
import voldemort.client.protocol.admin.AdminClient;
import voldemort.cluster.Cluster;
import voldemort.cluster.Node;
import voldemort.server.rebalance.AlreadyRebalancingException;
import voldemort.server.rebalance.VoldemortRebalancingException;
import voldemort.store.UnreachableStoreException;
import voldemort.store.metadata.MetadataStore;
import voldemort.store.metadata.MetadataStore.VoldemortState;
import voldemort.store.rebalancing.RedirectingStore;
import voldemort.utils.RebalanceUtils;
import voldemort.versioning.VectorClock;
import voldemort.versioning.Versioned;
public class RebalanceController {
private static final int MAX_TRIES = 2;
private static Logger logger = Logger.getLogger(RebalanceController.class);
private final AdminClient adminClient;
RebalanceClientConfig rebalanceConfig;
public RebalanceController(String bootstrapUrl, RebalanceClientConfig rebalanceConfig) {
this.adminClient = new AdminClient(bootstrapUrl, rebalanceConfig);
this.rebalanceConfig = rebalanceConfig;
}
public RebalanceController(Cluster cluster, RebalanceClientConfig config) {
this.adminClient = new AdminClient(cluster, config);
this.rebalanceConfig = config;
}
private ExecutorService createExecutors(int numThreads) {
return Executors.newFixedThreadPool(numThreads, new ThreadFactory() {
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setName(r.getClass().getName());
return thread;
}
});
}
/**
* Voldemort dynamic cluster membership rebalancing mechanism. <br>
* Migrate partitions across nodes to managed changes in cluster
* memberships. <br>
* Takes targetCluster as parameters, fetches the current cluster
* configuration from the cluster compares and makes a list of partitions
* need to be transferred.<br>
* The cluster is kept consistent during rebalancing using a proxy mechanism
* via {@link RedirectingStore}<br>
*
*
* @param targetCluster: target Cluster configuration
*/
public void rebalance(final Cluster targetCluster) {
Versioned<Cluster> currentVersionedCluster = RebalanceUtils.getLatestCluster(new ArrayList<Integer>(),
adminClient);
rebalance(currentVersionedCluster.getValue(), targetCluster);
}
/**
* Voldemort dynamic cluster membership rebalancing mechanism. <br>
* Migrate partitions across nodes to managed changes in cluster
* memberships. <br>
* Takes targetCluster as parameters, fetches the current cluster
* configuration from the cluster compares and makes a list of partitions
* need to be transferred.<br>
* The cluster is kept consistent during rebalancing using a proxy mechanism
* via {@link RedirectingStore}<br>
*
*
* @param targetCluster: target Cluster configuration
*/
public void rebalance(Cluster currentCluster, final Cluster targetCluster) {
logger.info("Current Cluster configuration:" + currentCluster);
logger.info("Target Cluster configuration:" + targetCluster);
adminClient.setAdminClientCluster(currentCluster);
List<String> storeList = RebalanceUtils.getStoreNameList(currentCluster, adminClient);
final RebalanceClusterPlan rebalanceClusterPlan = new RebalanceClusterPlan(currentCluster,
targetCluster,
storeList,
rebalanceConfig.isDeleteAfterRebalancingEnabled());
logger.info(rebalanceClusterPlan);
// add all new nodes to currentCluster and propagate to all
currentCluster = getClusterWithNewNodes(currentCluster, targetCluster);
adminClient.setAdminClientCluster(currentCluster);
Node firstNode = currentCluster.getNodes().iterator().next();
VectorClock latestClock = (VectorClock) RebalanceUtils.getLatestCluster(new ArrayList<Integer>(),
adminClient)
.getVersion();
RebalanceUtils.propagateCluster(adminClient,
currentCluster,
latestClock.incremented(firstNode.getId(),
System.currentTimeMillis()),
new ArrayList<Integer>());
ExecutorService executor = createExecutors(rebalanceConfig.getMaxParallelRebalancing());
// start all threads
for(int nThreads = 0; nThreads < this.rebalanceConfig.getMaxParallelRebalancing(); nThreads++) {
executor.execute(new Runnable() {
public void run() {
// pick one node to rebalance from queue
while(!rebalanceClusterPlan.getRebalancingTaskQueue().isEmpty()) {
RebalanceNodePlan rebalanceTask = rebalanceClusterPlan.getRebalancingTaskQueue()
.poll();
if(null != rebalanceTask) {
int stealerNodeId = rebalanceTask.getStealerNode();
List<RebalancePartitionsInfo> rebalanceSubTaskList = rebalanceTask.getRebalanceTaskList();
// seed random with different seeds
Random random = new Random(stealerNodeId);
while(rebalanceSubTaskList.size() > 0) {
int index = (int) random.nextDouble() * rebalanceSubTaskList.size();
RebalancePartitionsInfo rebalanceSubTask = rebalanceSubTaskList.remove(index);
logger.info("Starting rebalancing for stealerNode:" + stealerNodeId
+ " with rebalanceInfo:" + rebalanceSubTask);
try {
int rebalanceAsyncId = startNodeRebalancing(rebalanceSubTask);
try {
commitClusterChanges(adminClient.getAdminClientCluster()
.getNodeById(stealerNodeId),
rebalanceSubTask);
} catch(Exception e) {
if(-1 != rebalanceAsyncId) {
adminClient.stopAsyncRequest(rebalanceSubTask.getStealerId(),
rebalanceAsyncId);
}
throw e;
}
adminClient.waitForCompletion(rebalanceSubTask.getStealerId(),
rebalanceAsyncId,
rebalanceConfig.getRebalancingClientTimeoutSeconds(),
TimeUnit.SECONDS);
logger.info("Successfully finished rebalance attempt:"
+ rebalanceSubTask);
} catch(UnreachableStoreException e) {
logger.error("StealerNode "
+ stealerNodeId
+ " is unreachable, please make sure it is up and running.",
e);
} catch(VoldemortRebalancingException e) {
logger.error(e);
for(Exception cause: e.getCauses()) {
logger.error(cause);
}
} catch(Exception e) {
logger.error("Rebalancing task failed with exception", e);
}
}
}
}
logger.info("Thread run() finished:\n");
}
});
}// for (nThreads ..
executorShutDown(executor);
}
private int startNodeRebalancing(RebalancePartitionsInfo rebalanceSubTask) {
int nTries = 0;
AlreadyRebalancingException exception = null;
while(nTries < MAX_TRIES) {
nTries++;
try {
return adminClient.rebalanceNode(rebalanceSubTask);
} catch(AlreadyRebalancingException e) {
logger.info("Node " + rebalanceSubTask.getStealerId()
+ " is currently rebalancing will wait till it finish.");
adminClient.waitForCompletion(rebalanceSubTask.getStealerId(),
MetadataStore.SERVER_STATE_KEY,
VoldemortState.NORMAL_SERVER.toString(),
rebalanceConfig.getRebalancingClientTimeoutSeconds(),
TimeUnit.SECONDS);
exception = e;
}
}
throw new VoldemortException("Failed to start rebalancing at node "
+ rebalanceSubTask.getStealerId() + " with rebalanceInfo:"
+ rebalanceSubTask, exception);
}
private void executorShutDown(ExecutorService executorService) {
try {
executorService.shutdown();
executorService.awaitTermination(rebalanceConfig.getRebalancingClientTimeoutSeconds(),
TimeUnit.SECONDS);
} catch(Exception e) {
logger.warn("Error while stoping executor service.", e);
}
}
public AdminClient getAdminClient() {
return adminClient;
}
public void stop() {
adminClient.stop();
}
/* package level function to ease of unit testing */
/**
* Does an atomic commit or revert for the intended partitions ownership
* changes and modify adminClient with the updatedCluster.<br>
* creates a new cluster metadata by moving partitions list passed in
* parameter rebalanceStealInfo and propagates it to all nodes.<br>
* Revert all changes if failed to copy on required copies (stealerNode and
* donorNode).<br>
* holds a lock untill the commit/revert finishes.
*
* @param stealPartitionsMap
* @param stealerNodeId
* @param rebalanceStealInfo
* @throws Exception
*/
void commitClusterChanges(Node stealerNode, RebalancePartitionsInfo rebalanceStealInfo)
throws Exception {
synchronized(adminClient) {
Cluster currentCluster = adminClient.getAdminClientCluster();
Node donorNode = currentCluster.getNodeById(rebalanceStealInfo.getDonorId());
VectorClock latestClock = (VectorClock) RebalanceUtils.getLatestCluster(Arrays.asList(stealerNode.getId(),
rebalanceStealInfo.getDonorId()),
adminClient)
.getVersion();
// apply changes and create new updated cluster.
Cluster updatedCluster = RebalanceUtils.createUpdatedCluster(currentCluster,
stealerNode,
donorNode,
rebalanceStealInfo.getPartitionList());
// increment clock version on stealerNodeId
latestClock.incrementVersion(stealerNode.getId(), System.currentTimeMillis());
try {
// propogates changes to all nodes.
RebalanceUtils.propagateCluster(adminClient,
updatedCluster,
latestClock,
Arrays.asList(stealerNode.getId(),
rebalanceStealInfo.getDonorId()));
// set new cluster in adminClient
adminClient.setAdminClientCluster(updatedCluster);
} catch(Exception e) {
// revert cluster changes.
updatedCluster = currentCluster;
latestClock.incrementVersion(stealerNode.getId(), System.currentTimeMillis());
RebalanceUtils.propagateCluster(adminClient,
updatedCluster,
latestClock,
new ArrayList<Integer>());
throw e;
}
adminClient.setAdminClientCluster(updatedCluster);
}
}
private Cluster getClusterWithNewNodes(Cluster currentCluster, Cluster targetCluster) {
ArrayList<Node> newNodes = new ArrayList<Node>();
for(Node node: targetCluster.getNodes()) {
if(!RebalanceUtils.containsNode(currentCluster, node.getId())) {
// add stealerNode with empty partitions list
newNodes.add(RebalanceUtils.updateNode(node, new ArrayList<Integer>()));
}
}
return RebalanceUtils.updateCluster(currentCluster, newNodes);
}
} |
package com.krishagni.catissueplus.core.biospecimen.services.impl;
import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import com.krishagni.catissueplus.core.administrative.domain.User;
import com.krishagni.catissueplus.core.biospecimen.domain.CollectionProtocol;
import com.krishagni.catissueplus.core.biospecimen.domain.CpReportSettings;
import com.krishagni.catissueplus.core.biospecimen.events.CollectionProtocolDetail;
import com.krishagni.catissueplus.core.biospecimen.services.CollectionProtocolService;
import com.krishagni.catissueplus.core.biospecimen.services.CollectionProtocolService.DataSource;
import com.krishagni.catissueplus.core.common.events.RequestEvent;
import com.krishagni.catissueplus.core.common.events.ResponseEvent;
import com.krishagni.catissueplus.core.common.service.EmailService;
import com.krishagni.catissueplus.core.common.util.ConfigUtil;
import com.krishagni.catissueplus.core.common.util.LogUtil;
import com.krishagni.catissueplus.core.de.events.ExecuteQueryEventOp;
import com.krishagni.catissueplus.core.de.events.QueryDataExportResult;
import com.krishagni.catissueplus.core.de.events.QueryExecResult;
import com.krishagni.catissueplus.core.de.services.QueryService;
import edu.common.dynamicextensions.query.WideRowMode;
@Configurable
public class CpReportGenerator {
private static final LogUtil logger = LogUtil.getLogger(CpReportGenerator.class);
private static final String RPTS_DIR = "cp-reports";
@Autowired
private EmailService emailSvc;
@Autowired
private QueryService querySvc;
public void generateReport(CollectionProtocol cp, CpReportSettings sysSettings, CpReportSettings rptSettings)
throws Exception {
if (sysSettings == null) {
sysSettings = new CpReportSettings();
}
if (rptSettings == null) {
rptSettings = new CpReportSettings();
rptSettings.setCp(cp);
}
String emailTmpl = rptSettings.getEmailTmpl();
if (StringUtils.isBlank(emailTmpl)) {
emailTmpl = sysSettings.getEmailTmpl();
}
String emailTmplKey = sysSettings.getEmailTmplKey();
if (StringUtils.isBlank(emailTmpl) && StringUtils.isBlank(emailTmplKey)) {
return;
}
List<String> rcptEmailIds = rptSettings.getRecipients().stream()
.map(User::getEmailAddress)
.collect(Collectors.toList());
if (rcptEmailIds.isEmpty()) {
rcptEmailIds = cp.getCoordinators().stream()
.map(User::getEmailAddress)
.collect(Collectors.toList());
rcptEmailIds.add(0, cp.getPrincipalInvestigator().getEmailAddress());
}
Map<String, Object> emailCtxt = new HashMap<>();
emailCtxt.putAll(getMetrics(cp, sysSettings, rptSettings));
emailCtxt.put("dataFile", getDataFile(cp, sysSettings, rptSettings));
emailCtxt.put("cp", CollectionProtocolDetail.from(cp)); // introduced in v4.0
emailCtxt.put("cpId", cp.getId()); // retaining this for backward compatibility
emailCtxt.put("cpShortTitle", cp.getShortTitle()); // retaining this for backward compatibility
emailCtxt.put("$subject", new String[] { cp.getShortTitle() });
if (StringUtils.isNotBlank(emailTmpl)) {
emailSvc.sendEmail("default_cp_report", emailTmpl, rcptEmailIds.toArray(new String[0]), emailCtxt);
} else {
emailSvc.sendEmail(emailTmplKey, rcptEmailIds.toArray(new String[0]), emailCtxt);
}
}
public File getDataFile(Long cpId, String fileId) {
return new File(getReportsDir(), cpId + "-" + fileId);
}
private Map<String, Object> getMetrics(CollectionProtocol cp, CpReportSettings sysSettings, CpReportSettings rptSettings)
throws Exception {
Map<String, Map<String, Object>> metricsCfg = rptSettings.getMetricsCfg();
if (metricsCfg == null || metricsCfg.isEmpty()) {
metricsCfg = sysSettings.getMetricsCfg();
}
if (metricsCfg == null || metricsCfg.isEmpty()) {
return Collections.emptyMap();
}
Map<String, Object> result = new HashMap<>();
for (Map.Entry<String, Map<String, Object>> metricCfg : metricsCfg.entrySet()) {
result.put(metricCfg.getKey(), getMetric(cp, metricCfg.getValue()));
}
return result;
}
private Object getMetric(CollectionProtocol cp, Map<String, Object> metricCfg)
throws Exception {
String type = (String) metricCfg.get("type");
CollectionProtocolService.DataSource source;
if (StringUtils.isBlank(type) || type.equalsIgnoreCase("AQL")) {
source = new CpAqlDataSource();
} else {
source = (CollectionProtocolService.DataSource) Class.forName(type).newInstance();
}
return source.getMetric(cp, metricCfg);
}
private String getDataFile(CollectionProtocol cp, CpReportSettings sysSettings, CpReportSettings cpSettings)
throws Exception {
File dataFile = null;
String aql = getDataAql(cpSettings);
if (StringUtils.isNotBlank(aql)) {
dataFile = new CpAqlDataSource().getDataFile(cp, Collections.singletonMap("aql", aql));
} else if (cpSettings.getDataCfg() != null && !cpSettings.getDataCfg().isEmpty()) {
String type = (String)cpSettings.getDataCfg().get("type");
if (type.equals("AQL")) {
dataFile = new CpAqlDataSource().getDataFile(cp, cpSettings.getDataCfg());
} else {
DataSource ds = (DataSource) Class.forName(type).newInstance();
dataFile = ds.getDataFile(cp, cpSettings.getDataCfg());
}
} else {
aql = getDataAql(sysSettings);
if (StringUtils.isNotBlank(aql)) {
dataFile = new CpAqlDataSource().getDataFile(cp, Collections.singletonMap("aql", aql));
}
}
if (dataFile != null) {
return moveFileToReportsDir(cp, dataFile);
}
return null;
}
private String getDataAql(CpReportSettings settings) {
String aql = null;
if (settings.getDataQuery() != null) {
aql = settings.getDataQuery().getAql();
} else if (StringUtils.isNotBlank(settings.getDataQueryAql())) {
aql = settings.getDataQueryAql();
}
return aql;
}
private String moveFileToReportsDir(CollectionProtocol cp, File file) {
String extn = ".csv";
int extnStartIdx = file.getName().lastIndexOf('.');
if (extnStartIdx != -1) {
extn = file.getName().substring(extnStartIdx);
}
String fileId = UUID.randomUUID().toString() + extn;
file.renameTo(new File(getReportsDir(), cp.getId() + "-" + fileId));
return fileId;
}
private File getReportsDir() {
File dir = new File(ConfigUtil.getInstance().getDataDir() + File.separator + RPTS_DIR);
if (!dir.exists()) {
synchronized (this) {
dir.mkdirs();
}
}
return dir;
}
private class CpAqlDataSource implements CollectionProtocolService.DataSource {
@Override
public Object getMetric(CollectionProtocol cp, Map<String, Object> input) {
String aql = (String)input.get("aql");
if (StringUtils.isBlank(aql)) {
return null;
}
ExecuteQueryEventOp op = new ExecuteQueryEventOp();
op.setRunType("Data");
op.setCpId(cp.getId());
op.setWideRowMode(WideRowMode.OFF.name());
op.setAql(aql);
op.setDisableAccessChecks(true);
String drivingForm = (String)input.get("drivingForm");
op.setDrivingForm(StringUtils.isBlank(drivingForm) ? "Participant" : drivingForm);
ResponseEvent<QueryExecResult> resp = querySvc.executeQuery(new RequestEvent<>(op));
return resp.isSuccessful() ? resp.getPayload() : null;
}
@Override
public File getDataFile(CollectionProtocol cp, Map<String, Object> input) {
ExecuteQueryEventOp op = new ExecuteQueryEventOp();
op.setCpId(cp.getId());
op.setDrivingForm("Participant");
op.setAql((String)input.get("aql"));
op.setRunType("Export");
op.setWideRowMode(WideRowMode.DEEP.name());
ResponseEvent<QueryDataExportResult> resp = querySvc.exportQueryData(new RequestEvent<>(op));
resp.throwErrorIfUnsuccessful();
QueryDataExportResult result = resp.getPayload();
String dataFile = result.getDataFile();
if (!result.isCompleted()) {
try {
result.getPromise().get();
} catch (Exception e) {
logger.error("Error retrieving CP report data file", e);
dataFile = null;
}
}
if (StringUtils.isBlank(dataFile)) {
return null;
}
ResponseEvent<File> fileResp = querySvc.getExportDataFile(new RequestEvent<>(dataFile));
fileResp.throwErrorIfUnsuccessful();
return fileResp.getPayload();
}
}
} |
package org.openehr.adl.serializer.constraints;
import org.openehr.adl.serializer.ArchetypeSerializeUtils;
import org.openehr.adl.serializer.ArchetypeSerializer;
import org.openehr.jaxb.am.ArchetypeSlot;
import org.openehr.jaxb.am.Assertion;
public class ArchetypeSlotSerializer extends ConstraintSerializer<ArchetypeSlot> {
public ArchetypeSlotSerializer(ArchetypeSerializer serializer) {
super(serializer);
}
@Override
public void serialize(ArchetypeSlot cobj) {
builder.indent().newline()
.append("allow_archetype")
.append(" ")
.append(cobj.getRmTypeName()).append("[").append(cobj.getNodeId()).append("]");
if (cobj.getOccurrences()!=null) {
builder.append(" occurrences matches {");
ArchetypeSerializeUtils.buildOccurrences(builder, cobj.getOccurrences());
builder.append("}");
}
if (cobj.isIsClosed()!=null && cobj.isIsClosed()) {
builder.append(" closed");
} else {
appendMatches(cobj);
}
builder.unindent();
}
private void appendMatches(ArchetypeSlot cobj) {
int mark = builder.mark();
builder.append(" matches { ");
boolean hasContent=false;
if (cobj.getIncludes() != null && cobj.getIncludes().size() > 0) {
hasContent=true;
builder.indent().newline()
.append("include")
.indent();
for (Assertion a : cobj.getIncludes()) {
builder.newline().append(a.getStringExpression());
}
builder.unindent().unindent();
}
if (cobj.getExcludes() != null && cobj.getExcludes().size() > 0) {
hasContent=true;
builder.indent().newline()
.append("exclude")
.indent();
for (Assertion a : cobj.getExcludes()) {
builder.newline().append(a.getStringExpression());
}
builder.unindent().unindent();
}
if (hasContent) {
builder.newline().append("}");
} else {
builder.revert(mark);
}
}
} |
package com.showlocationservicesdialogbox;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.LocationManager;
import android.text.Html;
import android.text.Spanned;
import com.facebook.react.bridge.*;
class LocationServicesDialogBoxModule extends ReactContextBaseJavaModule implements ActivityEventListener {
private Promise promiseCallback;
private ReadableMap map;
private Activity currentActivity;
private AlertDialog alertDialog;
private static final int ENABLE_LOCATION_SERVICES = 1009;
LocationServicesDialogBoxModule(ReactApplicationContext reactContext) {
super(reactContext);
reactContext.addActivityEventListener(this);
}
@Override
public void onNewIntent(Intent intent) {
}
@Override
public String getName() {
return "LocationServicesDialogBox";
}
@ReactMethod
public void checkLocationServicesIsEnabled(ReadableMap configMap, Promise promise) {
promiseCallback = promise;
map = configMap;
currentActivity = getCurrentActivity();
checkLocationService(false);
}
@ReactMethod
public void forceCloseDialog() {
if (alertDialog != null && promiseCallback != null) {
promiseCallback.reject(new Throwable("disabled"));
alertDialog.cancel();
}
}
private void checkLocationService(Boolean activityResult) {
if (currentActivity == null || map == null || promiseCallback == null) return;
LocationManager locationManager = (LocationManager) currentActivity.getSystemService(Context.LOCATION_SERVICE);
WritableMap result = Arguments.createMap();
Boolean isEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (map.hasKey("enableHighAccuracy") && map.getBoolean("enableHighAccuracy")) {
// High accuracy needed. Require NETWORK_PROVIDER.
isEnabled = isEnabled && locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} else {
// Either highAccuracy is not a must which means any location will suffice
// or it is not specified which means again that any location will do.
isEnabled = isEnabled || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
if (!isEnabled) {
if (activityResult || map.hasKey("openLocationServices") && !map.getBoolean("openLocationServices")) {
promiseCallback.reject(new Throwable("disabled"));
} else if (!map.hasKey("showDialog") || map.getBoolean("showDialog")) {
displayPromptForEnablingGPS(currentActivity, map, promiseCallback);
} else {
newActivity(currentActivity);
}
} else {
result.putString("status", "enabled");
result.putBoolean("enabled", true);
result.putBoolean("alreadyEnabled", !activityResult);
promiseCallback.resolve(result);
}
}
private void displayPromptForEnablingGPS(final Activity activity, final ReadableMap configMap, final Promise promise) {
final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
final Spanned message = (
android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N ?
Html.fromHtml(configMap.getString("message"), Html.FROM_HTML_MODE_LEGACY) :
Html.fromHtml(configMap.getString("message"))
);
builder.setMessage(message)
.setPositiveButton(configMap.getString("ok"),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int id) {
newActivity(activity);
dialogInterface.dismiss();
}
})
.setNegativeButton(configMap.getString("cancel"),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int id) {
promise.reject(new Throwable("disabled"));
dialogInterface.cancel();
}
});
alertDialog = builder.create();
if (!configMap.hasKey("preventOutSideTouch") || configMap.getBoolean("preventOutSideTouch")) {
alertDialog.setCanceledOnTouchOutside(false);
}
if (!configMap.hasKey("preventBackClick") || configMap.getBoolean("preventBackClick")) {
alertDialog.setCancelable(false);
}
alertDialog.show();
}
private void newActivity(final Activity activity) {
final String action = android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS;
activity.startActivityForResult(new Intent(action), ENABLE_LOCATION_SERVICES);
}
@Override
public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
if (requestCode == ENABLE_LOCATION_SERVICES) {
currentActivity = activity;
checkLocationService(true);
}
}
} |
package SPARQLParser.SPARQLStatements;
import SPARQLParser.SPARQL.InvalidSPARQLException;
import SPARQLParser.SPARQL.SplitQuery;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class SelectBlock implements IStatement
{
private String selectClause = "";
private Set<String> unknowns = new HashSet<String>();
private List<IStatement> statements = new ArrayList<IStatement>();
private String selectModifier = ""; // normally this is DISTINCT or REDUCED
private boolean inBlock = false; // denotes whether or not this select is a subselect (and thus has to be
// placed between a '{' and a '}'
private List<String> solutionModifier = new ArrayList<String>();
private List<String> graphs = new ArrayList<String>();
public SelectBlock(SplitQuery.SplitQueryIterator iterator, boolean inBlock) throws InvalidSPARQLException
{
calculateBlock(iterator);
this.inBlock = inBlock;
}
public SelectBlock()
{
}
public Set<String> getUnknowns()
{
Set<String> u = new HashSet<String>();
for(IStatement s : this.statements)
u.addAll(s.getUnknowns());
u.addAll(unknowns);
return u;
}
public void calculateBlock(SplitQuery.SplitQueryIterator iterator) throws InvalidSPARQLException
{
if(!iterator.hasNext())
{
throw new InvalidSPARQLException("Invalid SPARQL: on line " + iterator.getCurrentLine() + " near: " + iterator.getPrevious());
}
// https://www.w3.org/TR/rdf-sparql-query/#modDistinct
if(iterator.peekNext().toLowerCase().equals("distinct"))
{
this.selectModifier += iterator.next();
}
// https://www.w3.org/TR/rdf-sparql-query/#modReduced
if(iterator.peekNext().toLowerCase().equals("reduced"))
{
this.selectModifier += iterator.next();
}
while(iterator.hasNext() && (!iterator.peekNext().toLowerCase().equals("where") && (!iterator.peekNext().toLowerCase().equals("from"))))
{
String next = iterator.next();
this.selectClause += next + " ";
if(next.startsWith("?"))
{
unknowns.add(next.substring(1, next.length()));
}
}
this.selectClause = this.selectClause.substring(0, this.selectClause.length() - 1);
if(!(iterator.peekNext().toLowerCase().equals("where") || iterator.peekNext().toLowerCase().equals("from")))
{
throw new InvalidSPARQLException("Invalid SPARQL at line " + iterator.getCurrentLine() + " expected 'WHERE' or 'FROM' after " + iterator.getPrevious());
}
if(iterator.peekNext().toLowerCase().equals("from"))
{
iterator.next(); // the from
String graph = iterator.next(); // this should be <...>
if(!graph.startsWith("<") || !graph.endsWith(">"))
{
throw new InvalidSPARQLException("Invalid SPARQL at line " + iterator.getCurrentLine() + " not a valid graph URI: " + graph);
}
this.graphs.clear();
this.graphs.add(graph.substring(1, graph.length() - 1));
}
// the from has passed so now we MUST have a where
if(!iterator.next().toLowerCase().equals("where"))
{
throw new InvalidSPARQLException("Invalid SPARQL at line " + iterator.getCurrentLine() + " expected 'WHERE' after " + iterator.getPrevious());
}
if(!iterator.next().toLowerCase().equals("{"))
{
throw new InvalidSPARQLException("Invalid SPARQL at line " + iterator.getCurrentLine() + " expected '{' after " + iterator.getPrevious());
}
// read inner block now
this.parseBlock(iterator);
// now we might still have solution modifiers
while(iterator.hasNext() && (iterator.peekNext().toLowerCase().equals("limit") ||
iterator.peekNext().toLowerCase().equals("offset") ||
iterator.peekNext().toLowerCase().startsWith("order") ||
iterator.peekNext().toLowerCase().startsWith("group")))
{
if(iterator.peekNext().toLowerCase().startsWith("group"))
{
// group by clause
// for now I expect this to be of the form:
// GROUP BY ?uuid
String group = iterator.next();
if(!iterator.hasNext())
{
throw new InvalidSPARQLException("Invalid SPARQL on line: " + iterator.getCurrentLine() + " near: " + iterator.getPrevious());
}
String by = iterator.next();
if(!by.toLowerCase().equals("by"))
{
throw new InvalidSPARQLException("Invalid SPARQL on line: " + iterator.getCurrentLine() + " expected 'BY' near: " + iterator.getPrevious());
}
if(!iterator.hasNext())
{
throw new InvalidSPARQLException("Invalid SPARQL on line: " + iterator.getCurrentLine() + " near: " + iterator.getPrevious());
}
String variable = iterator.next();
if(!variable.startsWith("?"))
{
throw new InvalidSPARQLException("Invalid SPARQL on line: " + iterator.getCurrentLine() + " near: " + iterator.getPrevious());
}
this.solutionModifier.add(group + " " + by + " " + variable);
}
if(iterator.peekNext().toLowerCase().equals("limit") ||
iterator.peekNext().toLowerCase().equals("offset"))
{
this.solutionModifier.add(iterator.next() + " " + iterator.next());
}
else
{
String orderClause = iterator.next() + " " + iterator.next(); // this should be ORDER BY
if(!orderClause.toLowerCase().equals("order by"))
{
throw new InvalidSPARQLException("Invalid SPARQL at line : " + iterator.getCurrentLine() + " expected 'order by' instead of '" + orderClause + "' after " + iterator.getPrevious());
}
}
}
}
/**
* Parses a block between a '{' and a '}' token and returns the resulting block a single string
*
* @param iterator a valid SplitQueryIterator
* @throws InvalidSPARQLException
* @return everything between the next '{' and '}'
*/
private void parseBlock(SplitQuery.SplitQueryIterator iterator) throws InvalidSPARQLException
{
String block = "";
while (iterator.hasNextIncludingNewLines()) {
// do we get a new inner block
if (iterator.peekNext().startsWith("}")) {
int i = 0; // fu intellij
iterator.next();
iterator.breakOff("}");
statements.add(new SimpleStatement(block));
return;
}
// hooray we have a new inner block!
if(iterator.peekNext().startsWith("{") || iterator.peekNext().toLowerCase().startsWith("graph")) {
if(!block.trim().isEmpty())
{
statements.add(new SimpleStatement(block));
}
block = "";
statements.add(new ParenthesesBlock(iterator, true));
continue;
}
String nextPart = iterator.nextIncludingNewLines();
if (nextPart.trim().equals("\n")) {
block += nextPart;
} else {
block += " " + nextPart;
}
}
}
public String toString()
{
String toreturn = "";
if(this.inBlock) toreturn += "{";
toreturn += "SELECT " + this.selectClause + "\n";
for(String g : this.graphs)
{
if(!g.isEmpty() && !g.equals(""))toreturn += "FROM <" + g + ">\n";
}
toreturn += "WHERE\n{\n";
for(IStatement statement : statements)
toreturn += statement.toString();
toreturn += "\n}";
if(this.inBlock) toreturn += "}";
for(String smod : this.solutionModifier)
{
toreturn += smod + "\n";
}
return toreturn;
}
public String getSelectClause() {
return selectClause;
}
public void setSelectClause(String selectClause) {
this.selectClause = selectClause;
}
public void setUnknowns(Set<String> unknowns) {
this.unknowns = unknowns;
}
public String getSelectModifier() {
return selectModifier;
}
public void setSelectModifier(String selectModifier) {
this.selectModifier = selectModifier;
}
public List<IStatement> getStatements() {
return statements;
}
public void setStatements(List<IStatement> statements) {
this.statements = statements;
}
public boolean isInBlock() {
return inBlock;
}
public void setInBlock(boolean inBlock) {
this.inBlock = inBlock;
}
public List<String> getSolutionModifier() {
return solutionModifier;
}
public void setSolutionModifier(List<String> solutionModifier) {
this.solutionModifier = solutionModifier;
}
public String getGraph()
{
return null;
}
public List<String> getGraphs() {
return graphs;
}
public void setGraphs(List<String> graphs)
{
this.graphs = graphs;
}
public void setGraph(String graph) {
this.graphs.clear(); this.graphs.add(graph);
}
public void addGraph(String graph)
{
if(graph == null || graph.isEmpty() || graph.equals(""))
return;
if(!this.graphs.contains(graph))this.graphs.add(graph);
}
public StatementType getType() {
return StatementType.SELECTBLOCK;
}
public SelectBlock clone()
{
SelectBlock clone = new SelectBlock();
clone.setSelectClause(this.selectClause);
clone.setSelectModifier(this.selectModifier);
List<String> clonedGraphs = new ArrayList<String>();
for(String g:graphs)clonedGraphs.add(g);
clone.setGraphs(clonedGraphs);
clone.setInBlock(this.inBlock);
for(String u : this.unknowns)
clone.getUnknowns().add(u);
for(String s : this.solutionModifier)
clone.getSolutionModifier().add(s);
for(IStatement s : this.statements)
clone.getStatements().add(s.clone());
return this.clone();
}
/**
* this will propagate the replacement of ALL subsequent graph statements with the new
* graph name.
*
* note that to remove all graph statements you can just pass an empty string as parameter
*
* @param newGraph the name of the new graph
*/
public void replaceGraphStatements(String newGraph)
{
this.graphs.clear();
if(newGraph != null &&!newGraph.isEmpty() && newGraph != "")this.graphs.add(newGraph);
for(IStatement s : this.statements)
s.replaceGraphStatements(newGraph);
}
/**
* this will propagate the replacement of ALL subsequent graph statements which are
* equal to the oldGraph's name. All graph statements targetting other graphs will remain
* untouched.
*
* @param oldGraph the name of tha graph that needs be replaced
* @param newGraph the new graph name
*/
public void replaceGraphStatements(String oldGraph, String newGraph)
{
if(this.graphs.contains("oldGraph"))
{
this.graphs.remove(oldGraph);
if(newGraph != null &&!newGraph.isEmpty() && newGraph != "")this.graphs.add(newGraph);
}
if(oldGraph == null || oldGraph.isEmpty() || oldGraph.equals(""))
{
if(newGraph != null &&!newGraph.isEmpty() && newGraph != "")this.graphs.add(newGraph);
}
for(IStatement s : this.statements)
s.replaceGraphStatements(oldGraph, newGraph);
}
} |
package ch.ethz.geco.bass.server.auth;
import ch.ethz.geco.bass.server.AuthWebSocket;
import ch.ethz.geco.bass.util.ErrorHandler;
import ch.ethz.geco.bass.util.SQLite;
import org.mindrot.jbcrypt.BCrypt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
/**
* Manages the handling of users. This includes authorization, account management, and session handling.
*/
public class UserManager {
/**
* The logger of this class
*/
private static final Logger logger = LoggerFactory.getLogger(UserManager.class);
// Check database integrity
static {
try {
Connection con = SQLite.getConnection();
if (!SQLite.tableExists("Users")) {
logger.debug("User table does not exist, creating...");
PreparedStatement statement = con.prepareStatement("CREATE TABLE Users (ID INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT NOT NULL, Password TEXT NOT NULL);");
statement.execute();
logger.debug("User table created!");
} else {
logger.debug("User table already exists.");
}
if (!SQLite.tableExists("Sessions")) {
logger.debug("Sessions table does not exist, creating...");
PreparedStatement statement = con.prepareStatement("CREATE TABLE Sessions (UserID INTEGER NOT NULL, Token TEXT NOT NULL, Valid DATETIME NOT NULL, FOREIGN KEY(UserID) REFERENCES Users(ID));");
statement.execute();
logger.debug("Sessions table created!");
} else {
logger.debug("Sessions table already exists.");
}
} catch (SQLException e) {
ErrorHandler.handleLocal(e);
}
// Periodically remove old session tokens every minute
new Timer().schedule(new TimerTask() {
@Override
public void run() {
deleteExpiredSessions();
}
}, 60000, 60000);
logger.info("Started periodic session token cleanup!");
}
/**
* Tries to login a user with the given credentials and return a valid session token to the given web socket on success.
* If it fails, it will send appropriate error messages to the given web socket. This function will generate a new session token,
* which is valid for one day, for each call. Like this, you can connect multiple times with the same account.
*
* @param webSocket the web socket which wants to login
* @param userName the user name
* @param password the password
*/
public static void login(AuthWebSocket webSocket, String userName, String password) {
try {
Connection con = SQLite.getConnection();
// Get hashed password
PreparedStatement queryStatement = con.prepareStatement("SELECT * FROM Users WHERE Name = ?;");
queryStatement.setString(1, userName);
ResultSet queryResult = queryStatement.executeQuery();
// Check if we found any rows
if (queryResult.next()) {
String hash = queryResult.getString("Password");
if (BCrypt.checkpw(password, hash)) {
String token = UUID.randomUUID().toString();
Integer userID = queryResult.getInt("ID");
// Add a new session token to the database which is valid for one day
PreparedStatement insertStatement = con.prepareStatement("INSERT INTO Sessions VALUES (?,?, datetime('now', '+1 day'));");
insertStatement.setInt(1, userID);
insertStatement.setString(2, token);
insertStatement.executeUpdate();
User user = new User(userID, userName);
webSocket.setAuthorizedUser(user);
// TODO: Send session token to interface
} else {
// TODO: Send wrong password notification
}
} else {
// TODO: Send account not found notification
}
} catch (SQLException e) {
ErrorHandler.handleLocal(e);
}
}
/**
* Tries to login a user with the given session token. This can be used to resume old sessions.
*
* @param webSocket the web socket which wants to login
* @param token the session token
*/
public static void login(AuthWebSocket webSocket, String token) {
try {
Connection con = SQLite.getConnection();
PreparedStatement sessionQuery = con.prepareStatement("SELECT UserID FROM Sessions WHERE Token = ?;");
sessionQuery.setString(1, token);
ResultSet sessionResult = sessionQuery.executeQuery();
if (sessionResult.next()) {
int userID = sessionResult.getInt("UserID");
PreparedStatement userQuery = con.prepareStatement("SELECT Name FROM Users WHERE ID = ?;");
userQuery.setInt(1, userID);
ResultSet userResult = userQuery.executeQuery();
if (userResult.next()) {
String userName = userResult.getString("Name");
User user = new User(userID, userName);
webSocket.setAuthorizedUser(user);
// TODO: Resend session token to interface?
} else {
// No user found, but there was a session associated with it. This should not happen
}
} else {
// TODO: Send invalid session notification
}
} catch (SQLException e) {
ErrorHandler.handleLocal(e);
}
}
/**
* Tries to register a new user. Responds to the given web socket if the operation was successful.
* It could fail because of duplicate user names or internal errors.
*
* @param webSocket the web socket which wants to register a new user
* @param userName the user name
* @param password the password
*/
public static void register(AuthWebSocket webSocket, String userName, String password) {
try {
Connection con = SQLite.getConnection();
PreparedStatement queryStatement = con.prepareStatement("SELECT * FROM Users WHERE Name = ?;");
queryStatement.setString(1, userName);
ResultSet result = queryStatement.executeQuery();
// Check if there is already a user with that name
if (!result.next()) {
PreparedStatement insertStatement = con.prepareStatement("INSERT INTO Users VALUES (?, ?)");
insertStatement.setString(1, userName);
insertStatement.setString(2, password);
insertStatement.executeUpdate();
// TODO: Send registration successful notification
} else {
// TODO: Send name already taken notification
}
} catch (SQLException e) {
ErrorHandler.handleLocal(e);
}
}
/**
* Tries to delete the given user. Responds to the given web socket if the operation was successful.
*
* @param webSocket the web socket which wants to delete a user
* @param userID the user ID of the user to delete
*/
public static void delete(AuthWebSocket webSocket, String userID) {
try {
Connection con = SQLite.getConnection();
PreparedStatement deleteStatement = con.prepareStatement("DELETE FROM Users WHERE ID = ?;");
deleteStatement.setString(1, userID);
deleteStatement.executeUpdate();
// TODO: Send account successfully deleted notification
} catch (SQLException e) {
ErrorHandler.handleLocal(e);
}
}
/**
* Deletes a specific session token from the database.
*
* @param token the token to delete
*/
private static void deleteSessionToken(String token) {
try {
Connection con = SQLite.getConnection();
PreparedStatement deleteStatement = con.prepareStatement("DELETE FROM Sessions WHERE Token = ?;");
deleteStatement.setString(1, token);
deleteStatement.executeUpdate();
} catch (SQLException e) {
ErrorHandler.handleLocal(e);
}
}
/**
* Deletes old session tokens in the database.
*/
private static void deleteExpiredSessions() {
try {
Connection con = SQLite.getConnection();
PreparedStatement deleteStatement = con.prepareStatement("DELETE FROM Sessions WHERE Valid < datetime('now');");
int removedSessions = deleteStatement.executeUpdate();
if (removedSessions > 0) {
logger.info("Removed " + removedSessions + " expired Sessions.");
}
} catch (SQLException e) {
ErrorHandler.handleLocal(e);
}
}
} |
package org.ovirt.engine.core.bll;
import java.util.Arrays;
import java.util.List;
import org.ovirt.engine.core.common.AuditLogType;
import org.ovirt.engine.core.common.PermissionSubject;
import org.ovirt.engine.core.common.action.UpdateVmDiskParameters;
import org.ovirt.engine.core.common.businessentities.DiskImage;
import org.ovirt.engine.core.common.businessentities.DiskImageBase;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.businessentities.VmNetworkInterface;
import org.ovirt.engine.core.dal.VdcBllMessages;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
import org.ovirt.engine.core.dao.DiskImageDAO;
import org.ovirt.engine.core.utils.linq.LinqUtils;
import org.ovirt.engine.core.utils.linq.Predicate;
import org.ovirt.engine.core.utils.transaction.TransactionMethod;
import org.ovirt.engine.core.utils.transaction.TransactionSupport;
@NonTransactiveCommandAttribute
public class UpdateVmDiskCommand<T extends UpdateVmDiskParameters> extends AbstractDiskVmCommand<T> {
private static final long serialVersionUID = 5915267156998835363L;
private List<PermissionSubject> listPermissionSubjects;
private DiskImage _oldDisk;
private boolean shouldUpdateQuotaForDisk;
public UpdateVmDiskCommand(T parameters) {
super(parameters);
setQuotaId(parameters.getDiskInfo() != null ? parameters.getDiskInfo().getQuotaId() : null);
}
@Override
protected void ExecuteVmCommand() {
perforDiskUpdate();
}
@Override
protected boolean canDoAction() {
boolean retValue = isVmExist();
if (retValue) {
_oldDisk = getDiskImageDao().get(getParameters().getImageId());
// Set disk alias name in the disk retrieved from the parameters.
ImagesHandler.setDiskAlias(getParameters().getDiskInfo().getDisk(), getVm());
retValue = isDiskExist(_oldDisk) && checkCanPerformRegularUpdate();
}
return retValue;
}
@Override
protected void setActionMessageParameters() {
addCanDoActionMessage(VdcBllMessages.VAR__ACTION__UPDATE);
addCanDoActionMessage(VdcBllMessages.VAR__TYPE__VM_DISK);
}
@Override
protected DiskImageDAO getDiskImageDao() {
return DbFacade.getInstance().getDiskImageDAO();
}
@Override
protected boolean validateQuota() {
boolean quotaValid = true;
shouldUpdateQuotaForDisk = !_oldDisk.getQuotaId().equals(getQuotaId());
if (shouldUpdateQuotaForDisk) {
// Set default quota id if storage pool enforcement is disabled.
getParameters().setQuotaId(QuotaHelper.getInstance().getQuotaIdToConsume(getQuotaId(),
getStoragePool()));
setStorageDomainId(_oldDisk.getstorage_ids().get(0).getValue());
quotaValid = (QuotaManager.validateStorageQuota(getStorageDomainId().getValue(),
getParameters().getQuotaId(),
getStoragePool().getQuotaEnforcementType(),
new Double(getParameters().getDiskInfo().getSizeInGigabytes()),
getCommandId(),
getReturnValue().getCanDoActionMessages()));
}
return quotaValid;
}
private boolean checkCanPerformRegularUpdate() {
boolean retValue = true;
if (VM.isStatusUpOrPausedOrSuspended(getVm().getstatus())) {
retValue = false;
addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_VM_STATUS_ILLEGAL);
} else if (_oldDisk.getdisk_interface() != getParameters().getDiskInfo().getdisk_interface()) {
List<VmNetworkInterface> allVmInterfaces = DbFacade.getInstance()
.getVmNetworkInterfaceDAO().getAllForVm(getVmId());
List allVmDisks = getDiskImageDao().getAllForVm(getVmId());
allVmDisks.removeAll(LinqUtils.filter(allVmDisks, new Predicate<DiskImageBase>() {
@Override
public boolean eval(DiskImageBase o) {
return o.getinternal_drive_mapping().equals(
_oldDisk.getinternal_drive_mapping());
}
}));
allVmDisks.add(getParameters().getDiskInfo());
if (!CheckPCIAndIDELimit(getVm().getnum_of_monitors(),
allVmInterfaces,
allVmDisks,
getReturnValue().getCanDoActionMessages())) {
retValue = false;
}
}
if (retValue && getParameters().getDiskInfo().getboot()) {
VmHandler.updateDisksFromDb(getVm());
for (DiskImage disk : getVm().getDiskMap().values()) {
if (disk.getboot() && !getParameters().getImageId().equals(disk.getId())) {
retValue = false;
addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_DISK_BOOT_IN_USE);
getReturnValue().getCanDoActionMessages().add(
String.format("$DiskName %1$s", disk.getinternal_drive_mapping()));
break;
}
}
}
return retValue;
}
@Override
public List<PermissionSubject> getPermissionCheckSubjects() {
if (listPermissionSubjects == null) {
listPermissionSubjects = super.getPermissionCheckSubjects();
listPermissionSubjects =
QuotaHelper.getInstance().addQuotaPermissionSubject(listPermissionSubjects,
getStoragePool(),
getQuotaId());
}
return listPermissionSubjects;
}
@Override
protected void removeQuotaCommandLeftOver() {
if (shouldUpdateQuotaForDisk) {
QuotaManager.removeStorageDeltaQuotaCommand(getQuotaId(),
getStorageDomainId().getValue(),
getStoragePool().getQuotaEnforcementType(),
getCommandId());
}
}
private void perforDiskUpdate() {
TransactionSupport.executeInNewTransaction(new TransactionMethod<Object>() {
@Override
public Object runInTransaction() {
_oldDisk.setboot(getParameters().getDiskInfo().getboot());
_oldDisk.setdisk_interface(getParameters().getDiskInfo().getdisk_interface());
_oldDisk.setpropagate_errors(getParameters().getDiskInfo().getpropagate_errors());
_oldDisk.setwipe_after_delete(getParameters().getDiskInfo().getwipe_after_delete());
_oldDisk.setQuotaId(getQuotaId());
_oldDisk.getDisk().setDiskAlias(getParameters().getDiskInfo().getDisk().getDiskAlias());
DbFacade.getInstance().getDiskDao().update(_oldDisk.getDisk());
getDiskImageDao().update(_oldDisk);
setSucceeded(UpdateVmInSpm(getVm().getstorage_pool_id(),
Arrays.asList(getVm())));
return null;
}
});
}
@Override
public AuditLogType getAuditLogTypeValue() {
return getSucceeded() ? AuditLogType.USER_UPDATE_VM_DISK : AuditLogType.USER_FAILED_UPDATE_VM_DISK;
}
} |
package org.ovirt.engine.core.utils.ovf;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.ovirt.engine.core.common.businessentities.ArchitectureType;
import org.ovirt.engine.core.common.businessentities.Snapshot;
import org.ovirt.engine.core.common.businessentities.Snapshot.SnapshotStatus;
import org.ovirt.engine.core.common.businessentities.Snapshot.SnapshotType;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.businessentities.VmDevice;
import org.ovirt.engine.core.common.businessentities.VmStatic;
import org.ovirt.engine.core.common.businessentities.network.VmNetworkInterface;
import org.ovirt.engine.core.common.businessentities.storage.DiskImage;
import org.ovirt.engine.core.common.utils.customprop.VmPropertiesUtils;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.utils.ovf.xml.XmlDocument;
import org.ovirt.engine.core.utils.ovf.xml.XmlNode;
import org.ovirt.engine.core.utils.ovf.xml.XmlNodeList;
public class OvfVmReader extends OvfReader {
private static final String EXPORT_ONLY_PREFIX = "exportonly_";
protected VM _vm;
public OvfVmReader(XmlDocument document,
VM vm,
ArrayList<DiskImage> images,
ArrayList<VmNetworkInterface> interfaces) {
super(document, images, interfaces, vm.getStaticData());
_vm = vm;
_vm.setInterfaces(interfaces);
}
@Override
protected void readOsSection(XmlNode section) {
_vm.getStaticData().setId(new Guid(section.attributes.get("ovf:id").getValue()));
XmlNode node = selectSingleNode(section, "Description");
if (node != null) {
int osId = osRepository.getOsIdByUniqueName(node.innerText);
_vm.getStaticData().setOsId(osId);
_vm.setClusterArch(osRepository.getArchitectureFromOS(osId));
}
else {
_vm.setClusterArch(ArchitectureType.undefined);
}
}
@Override
protected void readDiskImageItem(XmlNode node) {
final Guid guid = new Guid(selectSingleNode(node, "rasd:InstanceId", _xmlNS).innerText);
DiskImage image = _images.stream().filter(d -> d.getImageId().equals(guid)).findFirst().orElse(null);
image.setId(OvfParser.getImageGroupIdFromImageFile(selectSingleNode(node,
"rasd:HostResource", _xmlNS).innerText));
if (StringUtils.isNotEmpty(selectSingleNode(node, "rasd:Parent", _xmlNS).innerText)) {
image.setParentId(new Guid(selectSingleNode(node, "rasd:Parent", _xmlNS).innerText));
}
if (StringUtils.isNotEmpty(selectSingleNode(node, "rasd:Template", _xmlNS).innerText)) {
image.setImageTemplateId(new Guid(selectSingleNode(node, "rasd:Template", _xmlNS).innerText));
}
image.setAppList(selectSingleNode(node, "rasd:ApplicationList", _xmlNS).innerText);
XmlNode storageNode = selectSingleNode(node, "rasd:StorageId", _xmlNS);
if (storageNode != null &&
StringUtils.isNotEmpty(storageNode.innerText)) {
image.setStorageIds(new ArrayList<>(Arrays.asList(new Guid(storageNode.innerText))));
}
if (StringUtils.isNotEmpty(selectSingleNode(node, "rasd:StoragePoolId", _xmlNS).innerText)) {
image.setStoragePoolId(new Guid(selectSingleNode(node, "rasd:StoragePoolId", _xmlNS).innerText));
}
final Date creationDate = OvfParser.utcDateStringToLocaDate(
selectSingleNode(node, "rasd:CreationDate", _xmlNS).innerText);
if (creationDate != null) {
image.setCreationDate(creationDate);
}
final Date lastModified = OvfParser.utcDateStringToLocaDate(
selectSingleNode(node, "rasd:LastModified", _xmlNS).innerText);
if (lastModified != null) {
image.setLastModified(lastModified);
}
final Date last_modified_date = OvfParser.utcDateStringToLocaDate(
selectSingleNode(node, "rasd:last_modified_date", _xmlNS).innerText);
if (last_modified_date != null) {
image.setLastModifiedDate(last_modified_date);
}
VmDevice readDevice = readManagedVmDevice(node, image.getId());
image.setPlugged(readDevice.getIsPlugged());
image.setReadOnly(readDevice.getIsReadOnly());
}
@Override
protected void updateSingleNic(XmlNode node, VmNetworkInterface iface) {
super.updateSingleNic(node, iface);
iface.setMacAddress((selectSingleNode(node, "rasd:MACAddress", _xmlNS) != null) ? selectSingleNode(node,
"rasd:MACAddress", _xmlNS).innerText : "");
}
@Override
protected void readGeneralData(XmlNode content) {
// General Vm
XmlNode node = selectSingleNode(content, OvfProperties.NAME);
if (node != null) {
_vm.getStaticData().setName(node.innerText);
name = _vm.getStaticData().getName();
}
node = selectSingleNode(content, OvfProperties.TEMPLATE_ID);
if (node != null) {
if (StringUtils.isNotEmpty(node.innerText)) {
_vm.getStaticData().setVmtGuid(new Guid(node.innerText));
}
}
node = selectSingleNode(content, OvfProperties.TEMPLATE_NAME);
if (node != null) {
if (StringUtils.isNotEmpty(node.innerText)) {
_vm.setVmtName(node.innerText);
}
}
node = selectSingleNode(content, OvfProperties.INSTANCE_TYPE_ID);
if (node != null) {
if (StringUtils.isNotEmpty(node.innerText)) {
_vm.setInstanceTypeId(new Guid(node.innerText));
}
}
node = selectSingleNode(content, OvfProperties.IMAGE_TYPE_ID);
if (node != null) {
if (StringUtils.isNotEmpty(node.innerText)) {
_vm.setImageTypeId(new Guid(node.innerText));
}
}
node = selectSingleNode(content, OvfProperties.IS_INITIALIZED);
if (node != null) {
_vm.getStaticData().setInitialized(Boolean.parseBoolean(node.innerText));
}
node = selectSingleNode(content, OvfProperties.QUOTA_ID);
if (node != null) {
Guid quotaId = new Guid(node.innerText);
if (!Guid.Empty.equals(quotaId)) {
_vm.getStaticData().setQuotaId(quotaId);
}
}
OvfLogEventHandler<VmStatic> handler = new VMStaticOvfLogHandler(_vm.getStaticData());
// Gets a list of all the aliases of the fields that should be logged in
// ovd For each one of these fields, the proper value will be read from
// the ovf and field in vm static
List<String> aliases = handler.getAliases();
for (String alias : aliases) {
String value = readEventLogValue(content, alias);
if (StringUtils.isNotEmpty(value)) {
handler.addValueForAlias(alias, value);
}
}
// {@link VM#predefinedProperties} and {@link VM#userDefinedProperties}
// are being set in the above alias handling, we need to update custom properties
// to keep them consistent
_vm.setCustomProperties(VmPropertiesUtils.getInstance().customProperties(_vm.getPredefinedProperties(), _vm.getUserDefinedProperties()));
node = selectSingleNode(content, OvfProperties.APPLICATIONS_LIST);
if (node != null) {
if (StringUtils.isNotEmpty(node.innerText)) {
_vm.setAppList(node.innerText);
}
}
// if no app list in VM, get it from one of the leafs
else if(_images != null && _images.size() > 0) {
int root = getFirstImage(_images, _images.get(0));
if (root != -1) {
for(int i=0; i<_images.size(); i++) {
int x = getNextImage(_images, _images.get(i));
if (x == -1) {
_vm.setAppList(_images.get(i).getAppList());
}
}
} else {
_vm.setAppList(_images.get(0).getAppList());
}
}
node = selectSingleNode(content, OvfProperties.TRUSTED_SERVICE);
if (node != null) {
_vm.setTrustedService(Boolean.parseBoolean(node.innerText));
}
node = selectSingleNode(content, OvfProperties.ORIGINAL_TEMPLATE_ID);
if (node != null) {
_vm.getStaticData().setOriginalTemplateGuid(new Guid(node.innerText));
}
node = selectSingleNode(content, OvfProperties.ORIGINAL_TEMPLATE_NAME);
if (node != null) {
_vm.getStaticData().setOriginalTemplateName(node.innerText);
}
node = selectSingleNode(content, OvfProperties.USE_LATEST_VERSION);
if (node != null) {
_vm.setUseLatestVersion(Boolean.parseBoolean(node.innerText));
}
node = selectSingleNode(content, OvfProperties.USE_HOST_CPU);
if (node != null) {
_vm.setUseHostCpuFlags(Boolean.parseBoolean(node.innerText));
}
}
@Override
protected String getDefaultDisplayTypeStringRepresentation() {
return OvfProperties.VM_DEFAULT_DISPLAY_TYPE;
}
// function returns the index of the image that has no parent
private static int getFirstImage(ArrayList<DiskImage> images, DiskImage curr) {
for (int i = 0; i < images.size(); i++) {
if (curr.getParentId().equals(images.get(i).getImageId())) {
return i;
}
}
return -1;
}
// function returns the index of image that is it's child
private static int getNextImage(ArrayList<DiskImage> images, DiskImage curr) {
for (int i = 0; i < images.size(); i++) {
if (images.get(i).getParentId().equals(curr.getImageId())) {
return i;
}
}
return -1;
}
private String readEventLogValue(XmlNode content, String name) {
StringBuilder fullNameSB = new StringBuilder(EXPORT_ONLY_PREFIX);
fullNameSB.append(name);
XmlNode node = selectSingleNode(content, fullNameSB.toString());
if (node != null) {
return node.innerText;
}
return null;
}
@Override
protected void readSnapshotsSection(XmlNode section) {
XmlNodeList list = selectNodes(section, "Snapshot");
ArrayList<Snapshot> snapshots = new ArrayList<>();
_vm.setSnapshots(snapshots);
for (XmlNode node : list) {
XmlNode vmConfiguration = selectSingleNode(node, "VmConfiguration", _xmlNS);
Snapshot snapshot = new Snapshot(vmConfiguration != null);
snapshot.setId(new Guid(node.attributes.get("ovf:id").getValue()));
snapshot.setVmId(_vm.getId());
snapshot.setType(SnapshotType.valueOf(selectSingleNode(node, "Type", _xmlNS).innerText));
snapshot.setStatus(SnapshotStatus.OK);
snapshot.setDescription(selectSingleNode(node, "Description", _xmlNS).innerText);
XmlNode memory = selectSingleNode(node, "Memory", _xmlNS);
if (memory != null) {
snapshot.setMemoryVolume(memory.innerText);
}
final Date creationDate = OvfParser.utcDateStringToLocaDate(selectSingleNode(node, "CreationDate", _xmlNS).innerText);
if (creationDate != null) {
snapshot.setCreationDate(creationDate);
}
snapshot.setVmConfiguration(vmConfiguration == null
? null : new String(Base64.decodeBase64(vmConfiguration.innerText)));
XmlNode appList = selectSingleNode(node, "ApplicationList", _xmlNS);
if (appList != null) {
snapshot.setAppList(appList.innerText);
}
snapshots.add(snapshot);
}
}
@Override
protected void buildNicReference() {
}
} |
package com.rackspacecloud.blueflood.service;
import com.google.common.base.Ticker;
import com.rackspacecloud.blueflood.rollup.Granularity;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.*;
public class ShardStateManagerTest {
private final int TEST_SHARD = 0;
private final int TEST_SLOT = 0;
private final Granularity TEST_GRANULARITY = Granularity.MIN_5;
private List<Integer> managedShards = new ArrayList<Integer>() {{ add(TEST_SHARD); }};
private ShardStateManager.SlotStateManager slotStateManager;
@Before
public void setup() {
ShardStateManager shardStateManager = new ShardStateManager(managedShards, Ticker.systemTicker());
slotStateManager = shardStateManager.getSlotStateManager(TEST_SHARD, TEST_GRANULARITY);
}
@Test
public void testUpdateSlotsOnReadForSlotsNeverRolled() {
//during startup
//This tests -> if (stamp == null)
final long lastIngestionTime = System.currentTimeMillis();
List<SlotState> slotStates = new ArrayList<SlotState>() {{
add(createSlotState(TEST_GRANULARITY, UpdateStamp.State.Active, lastIngestionTime, lastIngestionTime));
}};
for (SlotState slotState: slotStates) {
slotStateManager.updateSlotOnRead(slotState);
}
Map<Integer, UpdateStamp> slotStamps = slotStateManager.getSlotStamps();
UpdateStamp updateStamp = slotStamps.get(TEST_SLOT);
assertEquals("Unexpected state", UpdateStamp.State.Active, updateStamp.getState());
assertEquals("Invalid last ingestion timestamp", lastIngestionTime, updateStamp.getTimestamp());
assertEquals("Last rollup time should not be set", 0, updateStamp.getLastRollupTimestamp());
}
@Test
public void testUpdateSlotsOnReadForRolledSlots() {
//during startup
//This tests -> if (stamp.getTimestamp() == timestamp && state.equals(UpdateStamp.State.Rolled))
final long lastIngestionTime = System.currentTimeMillis() - 10 * 60 * 1000; //minus 10 mins
final long rolledSlotLastUpdatedTime = System.currentTimeMillis() - 5 * 60 * 1000; //minus 5 mins
//Both active and rolled states have same last ingested timestamp
List<SlotState> slotStates = new ArrayList<SlotState>() {{
add(createSlotState(TEST_GRANULARITY, UpdateStamp.State.Active, lastIngestionTime, lastIngestionTime));
add(createSlotState(TEST_GRANULARITY, UpdateStamp.State.Rolled, lastIngestionTime, rolledSlotLastUpdatedTime));
}};
for (SlotState slotState: slotStates) {
slotStateManager.updateSlotOnRead(slotState);
}
Map<Integer, UpdateStamp> slotStamps = slotStateManager.getSlotStamps();
UpdateStamp updateStamp = slotStamps.get(TEST_SLOT);
assertEquals("Unexpected state", UpdateStamp.State.Rolled, updateStamp.getState());
assertEquals("Last ingestion timestamp is incorrect", lastIngestionTime, updateStamp.getTimestamp());
assertEquals("Last rollup timestamp is incorrect", rolledSlotLastUpdatedTime, updateStamp.getLastRollupTimestamp());
}
@Test
public void testUpdateSlotsOnReadForRolledSlotsButGotDelayedMetrics() {
//during startup
//This tests -> if (state.equals(UpdateStamp.State.Rolled))
final long lastIngestionTime = System.currentTimeMillis() - 10 * 60 * 1000; //minus 10 mins
final long rolledSlotLastUpdatedTime = System.currentTimeMillis() - 5 * 60 * 1000; //minus 5 mins
final long delayedMetricIngestionTime = lastIngestionTime - 1; //it just has to be different than lastIngestionTime
final long activeSlotLastUpdatedTime = System.currentTimeMillis(); //means we ingested delayed metric recently
//Both active and rolled states have different last ingested timestamp.
//The slot last update time is also different as we got a delayed metric later and "Active" got updated cos of that.
List<SlotState> slotStates = new ArrayList<SlotState>() {{
add(createSlotState(TEST_GRANULARITY, UpdateStamp.State.Active, delayedMetricIngestionTime, activeSlotLastUpdatedTime));
add(createSlotState(TEST_GRANULARITY, UpdateStamp.State.Rolled, lastIngestionTime, rolledSlotLastUpdatedTime));
}};
for (SlotState slotState: slotStates) {
slotStateManager.updateSlotOnRead(slotState);
}
Map<Integer, UpdateStamp> slotStamps = slotStateManager.getSlotStamps();
UpdateStamp updateStamp = slotStamps.get(TEST_SLOT);
assertEquals("Unexpected state", UpdateStamp.State.Active, updateStamp.getState());
assertEquals("Last ingestion timestamp is incorrect", delayedMetricIngestionTime, updateStamp.getTimestamp());
assertEquals("Last rollup timestamp is incorrect", rolledSlotLastUpdatedTime, updateStamp.getLastRollupTimestamp());
}
private void establishCurrentState() {
final long existingIngestionTime = System.currentTimeMillis() - 60 * 1000; //minus 1 min
final long lastRolledIngestionTime = existingIngestionTime - 14 * 24 * 60 * 60 * 1000; //minus 14 days
final long rolledSlotLastUpdatedTime = lastRolledIngestionTime + 5 * 60 * 1000;
List<SlotState> slotStates = new ArrayList<SlotState>() {{
add(createSlotState(TEST_GRANULARITY, UpdateStamp.State.Active, existingIngestionTime, existingIngestionTime));
add(createSlotState(TEST_GRANULARITY, UpdateStamp.State.Rolled, lastRolledIngestionTime, rolledSlotLastUpdatedTime));
}};
//establishing state as active (with in-memory current state as Active)
for (SlotState slotState: slotStates) {
slotStateManager.updateSlotOnRead(slotState);
}
}
@Test
public void testUpdateSlotsOnReadWithIncomingActiveState() {
//updating existing in-memory map (current state: active, incoming: active state)
//This tests -> if (stamp.getTimestamp() != timestamp && state.equals(UpdateStamp.State.Active))
//This tests -> if (!(stamp.getState().equals(UpdateStamp.State.Active) && (stamp.getTimestamp() > timestamp || stamp.isDirty())))
establishCurrentState();
long lastRollupTime = slotStateManager.getSlotStamps().get(TEST_SLOT).getLastRollupTimestamp();
long lastIngestionTime = System.currentTimeMillis();
long lastUpdatedTime = System.currentTimeMillis();
SlotState newUpdateForActiveSlot = createSlotState(Granularity.MIN_5, UpdateStamp.State.Active, lastIngestionTime, lastUpdatedTime);
//new incoming slot state
slotStateManager.updateSlotOnRead(newUpdateForActiveSlot);
Map<Integer, UpdateStamp> slotStamps = slotStateManager.getSlotStamps();
UpdateStamp updateStamp = slotStamps.get(TEST_SLOT);
assertEquals("Unexpected state", UpdateStamp.State.Active, updateStamp.getState());
assertEquals("Last ingestion timestamp is incorrect", lastIngestionTime, updateStamp.getTimestamp());
assertEquals("Last rollup timestamp is incorrect", lastRollupTime, updateStamp.getLastRollupTimestamp());
}
@Test
public void testUpdateSlotsOnReadWithIncomingActiveStateButOlderData() {
//updating existing in-memory map (current state: active, incoming: active state but with old ingest timestamp)
//This tests -> if (stamp.getTimestamp() != timestamp && state.equals(UpdateStamp.State.Active))
//This tests -> else part of if (!(stamp.getState().equals(UpdateStamp.State.Active) && (stamp.getTimestamp() > timestamp || stamp.isDirty())))
establishCurrentState();
long lastRollupTime = slotStateManager.getSlotStamps().get(TEST_SLOT).getLastRollupTimestamp();
long existingLastIngestionTime = slotStateManager.getSlotStamps().get(TEST_SLOT).getTimestamp();
long lastIngestionTime = existingLastIngestionTime - 60 * 1000; //minus 1 min
long lastUpdatedTime = System.currentTimeMillis();
SlotState newUpdateForActiveSlot = createSlotState(Granularity.MIN_5, UpdateStamp.State.Active, lastIngestionTime, lastUpdatedTime);
//new incoming slot state
slotStateManager.updateSlotOnRead(newUpdateForActiveSlot);
Map<Integer, UpdateStamp> slotStamps = slotStateManager.getSlotStamps();
UpdateStamp updateStamp = slotStamps.get(TEST_SLOT);
assertEquals("Unexpected state", UpdateStamp.State.Active, updateStamp.getState());
assertEquals("Last ingestion timestamp is incorrect", existingLastIngestionTime, updateStamp.getTimestamp());
assertEquals("Last rollup timestamp is incorrect", lastRollupTime, updateStamp.getLastRollupTimestamp());
assertEquals("Dirty flag is incorrect", true, updateStamp.isDirty());
}
@Test
public void testUpdateSlotsOnReadIncomingRolledStateSameTimestamp() {
//updating existing in-memory map (current state:active, incoming: rolled state with same ingest timestamp)
//This tests -> if (stamp.getTimestamp() == timestamp && state.equals(UpdateStamp.State.Rolled))
establishCurrentState();
long existingLastIngestionTime = slotStateManager.getSlotStamps().get(TEST_SLOT).getTimestamp();
long newRolledSlotLastUpdatedTime = System.currentTimeMillis();
SlotState newUpdateForActiveSlot = createSlotState(Granularity.MIN_5, UpdateStamp.State.Rolled, existingLastIngestionTime, newRolledSlotLastUpdatedTime);
//new incoming slot state
slotStateManager.updateSlotOnRead(newUpdateForActiveSlot);
Map<Integer, UpdateStamp> slotStamps = slotStateManager.getSlotStamps();
UpdateStamp updateStamp = slotStamps.get(TEST_SLOT);
assertEquals("Unexpected state", UpdateStamp.State.Rolled, updateStamp.getState());
assertEquals("Last ingestion timestamp is incorrect", existingLastIngestionTime, updateStamp.getTimestamp());
assertEquals("Last rollup timestamp is incorrect", newRolledSlotLastUpdatedTime, updateStamp.getLastRollupTimestamp());
}
@Test
public void testUpdateSlotsOnReadIncomingRolledStateDifferentTimestamp() {
//updating existing in-memory map (current state: active, incoming: rolled state with different ingest timestamp)
//This tests -> if (state.equals(UpdateStamp.State.Rolled))
establishCurrentState();
long existingLastIngestionTime = slotStateManager.getSlotStamps().get(TEST_SLOT).getTimestamp();
long newLastRolledIngestionTime = existingLastIngestionTime - 1; //making it different from the ingest time we already have in "Active"
long newRolledSlotLastUpdatedTime = System.currentTimeMillis();
SlotState newUpdateForActiveSlot = createSlotState(Granularity.MIN_5, UpdateStamp.State.Rolled, newLastRolledIngestionTime, newRolledSlotLastUpdatedTime);
//new incoming slot state
slotStateManager.updateSlotOnRead(newUpdateForActiveSlot);
Map<Integer, UpdateStamp> slotStamps = slotStateManager.getSlotStamps();
UpdateStamp updateStamp = slotStamps.get(TEST_SLOT);
assertEquals("Unexpected state", UpdateStamp.State.Active, updateStamp.getState());
assertEquals("Last ingestion timestamp is incorrect", existingLastIngestionTime, updateStamp.getTimestamp());
assertEquals("Last rollup timestamp is incorrect", newRolledSlotLastUpdatedTime, updateStamp.getLastRollupTimestamp());
}
private SlotState createSlotState(Granularity granularity, UpdateStamp.State state, long lastIngestionTimeStamp, long lastUpdatedTimestamp) {
return new SlotState(granularity, TEST_SLOT, state).withTimestamp(lastIngestionTimeStamp).withLastUpdatedTimestamp(lastUpdatedTimestamp);
}
@Test
public void createOrUpdateCreatesWhenSlotNotPresent() {
// precondition
assertFalse(slotStateManager.getSlotStamps().containsKey(0));
// when
slotStateManager.createOrUpdateForSlotAndMillisecond(0, 1234L);
// then
assertTrue("The slot should be present in the map", slotStateManager.getSlotStamps().containsKey(0));
UpdateStamp stamp = slotStateManager.getSlotStamps().get(0);
assertTrue("The slot should be marked dirty", stamp.isDirty());
assertEquals("The timestamp should be set", 1234L, stamp.getTimestamp());
assertEquals("The state should be Active", UpdateStamp.State.Active, stamp.getState());
assertEquals("The last rollup timestamp should be uninitialized", 0, stamp.getLastRollupTimestamp());
}
@Test
public void createOrUpdateUpdatesWhenSlotAlreadyPresent() {
// given
slotStateManager.createOrUpdateForSlotAndMillisecond(0, 1234L);
UpdateStamp _stamp = slotStateManager.getSlotStamps().get(0);
_stamp.setDirty(false);
_stamp.setState(UpdateStamp.State.Rolled);
// precondition
assertEquals(1234L, _stamp.getTimestamp());
assertFalse(_stamp.isDirty());
assertEquals(UpdateStamp.State.Rolled, _stamp.getState());
assertEquals(0, _stamp.getLastRollupTimestamp());
// when
slotStateManager.createOrUpdateForSlotAndMillisecond(0, 1235L);
// then
assertTrue("The slot should still be present in the map", slotStateManager.getSlotStamps().containsKey(0));
UpdateStamp stamp = slotStateManager.getSlotStamps().get(0);
assertEquals("The timestamp should have changed", 1235L, _stamp.getTimestamp());
assertTrue("The slot should be marked dirty", stamp.isDirty());
assertEquals("The state should be Active", UpdateStamp.State.Active, stamp.getState());
assertEquals("The last rollup timestamp should be uninitialized", 0, stamp.getLastRollupTimestamp());
}
@Test
public void getDirtySlotsWhenEmptyReturnsEmpty() {
// precondition
assertTrue(slotStateManager.getSlotStamps().isEmpty());
// when
Map dirtySlots = slotStateManager.getDirtySlotStampsAndMarkClean();
// then
assertNotNull(dirtySlots);
assertTrue("No slots should be included", dirtySlots.isEmpty());
}
@Test
public void getDirtySlotsWhenContainsOnlyCleanSlotsReturnsEmpty() {
// given
slotStateManager.createOrUpdateForSlotAndMillisecond(0, 1234L);
UpdateStamp _stamp = slotStateManager.getSlotStamps().get(0);
_stamp.setDirty(false);
// when
Map dirtySlots = slotStateManager.getDirtySlotStampsAndMarkClean();
// then
assertNotNull(dirtySlots);
assertTrue("No slots should be included", dirtySlots.isEmpty());
}
@Test
public void getDirtySlotsWhenContainsOnlyDirtySlotsReturnsThoseSlotsAndMarksClean() {
// given
slotStateManager.createOrUpdateForSlotAndMillisecond(0, 1234L);
slotStateManager.createOrUpdateForSlotAndMillisecond(1, 1234L);
// when
Map<Integer, UpdateStamp> dirtySlots = slotStateManager.getDirtySlotStampsAndMarkClean();
// then
assertNotNull(dirtySlots);
assertEquals("Both slots should be returned", 2, dirtySlots.size());
assertTrue("The first slot should be included", dirtySlots.containsKey(0));
UpdateStamp stamp = dirtySlots.get(0);
assertFalse("The first slot should be clean", stamp.isDirty());
assertTrue("The second slot should be included", dirtySlots.containsKey(1));
stamp = dirtySlots.get(1);
assertFalse("The second slot should be clean", stamp.isDirty());
}
@Test
public void getDirtySlotsWhenContainsCleanAndDirtySlotsReturnsOnlyDirtySlotsAndMarksClean() {
// given
slotStateManager.createOrUpdateForSlotAndMillisecond(0, 1234L);
slotStateManager.getSlotStamps().get(0).setDirty(false);
slotStateManager.createOrUpdateForSlotAndMillisecond(1, 1234L);
// when
Map<Integer, UpdateStamp> dirtySlots = slotStateManager.getDirtySlotStampsAndMarkClean();
// then
assertNotNull(dirtySlots);
assertEquals("Only one slot should be returned", 1, dirtySlots.size());
assertFalse("Slot 0 should not be included", dirtySlots.containsKey(0));
assertFalse("Slot 0 should still be clean", slotStateManager.getSlotStamps().get(0).isDirty());
assertTrue("Slot 1 should be included", dirtySlots.containsKey(1));
assertFalse("Slot 1 should now be clean", dirtySlots.get(1).isDirty());
}
@Test
public void getAndSetStateGetsAndSetsState() {
// given
slotStateManager.createOrUpdateForSlotAndMillisecond(0, 1234L);
// precondition
assertEquals(UpdateStamp.State.Active, slotStateManager.getSlotStamps().get(0).getState());
// when
UpdateStamp stamp = slotStateManager.getAndSetState(0, UpdateStamp.State.Rolled);
// then
assertNotNull(stamp);
assertSame("The stamp returned should be the same one for slot 0", slotStateManager.getSlotStamps().get(0), stamp);
assertEquals("The state should be changed to Rolled", UpdateStamp.State.Rolled, stamp.getState());
}
@Test
public void getAndSetStateDoesNotAffectUnspecifiedSlot() {
// given
slotStateManager.createOrUpdateForSlotAndMillisecond(0, 1234L);
slotStateManager.createOrUpdateForSlotAndMillisecond(1, 1235L);
// precondition
assertEquals(UpdateStamp.State.Active, slotStateManager.getSlotStamps().get(0).getState());
assertEquals(UpdateStamp.State.Active, slotStateManager.getSlotStamps().get(1).getState());
// when
UpdateStamp stamp = slotStateManager.getAndSetState(0, UpdateStamp.State.Rolled);
// then
assertNotNull(stamp);
assertSame(slotStateManager.getSlotStamps().get(0), stamp);
assertEquals("Slot 0 should now be Rolled", UpdateStamp.State.Rolled, stamp.getState());
assertEquals("Slot 0 should still be Active", UpdateStamp.State.Active, slotStateManager.getSlotStamps().get(1).getState());
}
@Test(expected = NullPointerException.class)
public void getAndSetStateUninitializedSlotThrowsException() {
// precondition
assertEquals(0, slotStateManager.getSlotStamps().size());
// when
UpdateStamp stamp = slotStateManager.getAndSetState(0, UpdateStamp.State.Rolled);
// then
// the exception is thrown
}
@Test
public void getSlotsEligibleUninitializedReturnsEmpty() {
// precondition
assertEquals(0, slotStateManager.getSlotStamps().size());
// when
List<Integer> slots = slotStateManager.getSlotsEligibleForRollup(0, 0, 0);
// then
assertNotNull(slots);
assertTrue("No slots should be returned", slots.isEmpty());
}
@Test
public void getSlotsEligibleDoesNotReturnRolledSlots() {
// given
slotStateManager.createOrUpdateForSlotAndMillisecond(0, 1234L);
slotStateManager.getAndSetState(0, UpdateStamp.State.Rolled);
// when
List<Integer> slots = slotStateManager.getSlotsEligibleForRollup(0, 0, 0);
// then
assertNotNull(slots);
assertTrue("No slots should be returned", slots.isEmpty());
}
@Test
public void getSlotsEligibleDoesNotReturnSlotsThatAreTooYoung() {
// given
slotStateManager.createOrUpdateForSlotAndMillisecond(0, 1234L);
slotStateManager.getAndSetState(0, UpdateStamp.State.Active);
// when
List<Integer> slots = slotStateManager.getSlotsEligibleForRollup(1235L, 30000, 0);
// then
assertNotNull(slots);
assertTrue("No slots should be returned", slots.isEmpty());
}
@Test
public void getSlotsEligibleDoesNotReturnSlotsThatWereRolledRecently() {
// given
slotStateManager.createOrUpdateForSlotAndMillisecond(0, 1234L);
UpdateStamp stamp = slotStateManager.getSlotStamps().get(0);
stamp.setLastRollupTimestamp(2345L);
// when
List<Integer> slots = slotStateManager.getSlotsEligibleForRollup(2346L, 0, 70000);
// then
assertNotNull(slots);
assertTrue("No slots should be returned", slots.isEmpty());
}
@Test
public void getSlotsEligibleReturnsSlotsThatWereRolledButNotRecently() {
// given
slotStateManager.createOrUpdateForSlotAndMillisecond(0, 1234L);
UpdateStamp stamp = slotStateManager.getSlotStamps().get(0);
stamp.setLastRollupTimestamp(2345L);
// when
List<Integer> slots = slotStateManager.getSlotsEligibleForRollup(2346L, 0, 1);
// then
assertNotNull(slots);
assertEquals("Only one slot should be returned", 1, slots.size());
assertEquals("Slot zero should be included", 0, slots.get(0).intValue());
}
@Test
public void getSlotsEligibleReturnsSlotsThatWereNotRolled() {
// given
slotStateManager.createOrUpdateForSlotAndMillisecond(0, 1234L);
// when
List<Integer> slots = slotStateManager.getSlotsEligibleForRollup(2346L, 0, 1);
// then
assertNotNull(slots);
assertEquals("Only one slot should be returned", 1, slots.size());
assertEquals("Slot zero should be included", 0, slots.get(0).intValue());
}
} |
package com.amee.restlet.resource;
import com.amee.base.resource.ValidationResult;
import com.amee.restlet.AMEESpringServer;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.data.MediaType;
import org.restlet.data.Preference;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.data.Status;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.resource.DomRepresentation;
import org.restlet.resource.Representation;
public class ResourceManager {
private final Log log = LogFactory.getLog(getClass());
private GenericResource resource;
public void init(GenericResource resource) {
this.resource = resource;
}
/**
* This is how we tell if the request came via HTTPS as SSL is terminated at the load balancer.
*
* @return true if the current request has come through the secure connector
*/
protected boolean isSecure() {
return getActiveServer().isSecure();
}
protected boolean isOk(JSONObject result) {
return isStatus(result, "OK");
}
protected boolean isNotFound(JSONObject result) {
return isStatus(result, "NOT_FOUND");
}
protected boolean isNotAuthenticated(JSONObject result) {
return isStatus(result, "NOT_AUTHENTICATED");
}
protected boolean isNotAuthorized(JSONObject result) {
return isStatus(result, "NOT_AUTHORIZED");
}
protected boolean isInternalError(JSONObject result) {
return isStatus(result, "INTERNAL_ERROR");
}
protected boolean isInvalid(JSONObject result) {
return isStatus(result, "INVALID");
}
protected boolean isTimedOut(JSONObject result) {
return isStatus(result, "TIMED_OUT");
}
protected boolean isMediaTypeNotSupported(JSONObject result) {
return isStatus(result, "MEDIA_TYPE_NOT_SUPPORTED");
}
protected boolean isStatus(JSONObject result, String status) {
try {
return (result != null) && result.has("status") && result.getString("status").equals(status);
} catch (JSONException e) {
// Swallow.
return false;
}
}
protected Map<String, String> getAttributes() {
Map<String, String> attributes = new HashMap<String, String>();
for (String attributeName : getAttributeNames()) {
if (getRequest().getAttributes().containsKey(attributeName)) {
Object a = getRequest().getAttributes().get(attributeName);
if (a instanceof String) {
// This removes any matrix parameters.
String value = ((String) a).split(";")[0];
try {
// URLDecoder decodes application/x-www-form-urlencoded Strings, which should only appear in the body of a POST.
// It decodes "+" symbols to spaces, which breaks ISO time formats that include a "+", so we manually encode them
// here and immediately decode them again in order to preserve them.
value = URLDecoder.decode(value.replace("+", "%2B"), "UTF-8").replace("%2B", "+");
} catch (UnsupportedEncodingException e) {
log.warn("getAttributes() Caught UnsupportedEncodingException: " + e.getMessage());
}
attributes.put(attributeName, value);
} else {
log.warn("getAttributes() Attribute value is not a String: " + attributeName);
}
} else {
log.warn("getAttributes() Attribute value not found: " + attributeName);
}
}
return attributes;
}
protected Map<String, String> getMatrixParameters() {
return getRequest().getResourceRef().getMatrixAsForm().getValuesMap();
}
protected Map<String, String> getQueryParameters() {
/*
* The query parameters could be retrieved by calling:
*
* getRequest().getResourceRef().getQueryAsForm().getValuesMap();
*
* The problem with that is that the Reference.getQueryAsForm() method calls a Form constructor which decodes the query string with
* URLDecoder.decode, which is appropriate only for application/x-www-form-urlencoded strings in POST bodies. It decodes "+" symbols
* to spaces, which breaks ISO time formats that include a "+", so we manually encode them here before passing them to the Form
* constructor, and immediately decode them again in order to preserve them.
*/
// Get query string
org.restlet.data.Reference ref = getRequest().getResourceRef();
String query = ref.getQuery(false);
if (query != null) {
// Encode + symbols
org.restlet.data.Form form = new org.restlet.data.Form(query.replace("+", "%2B"));
Map<String, String> params = form.getValuesMap();
// Decode + symbols again
for (String param : params.keySet()) {
params.put(param, params.get(param).replace("%2B", "+"));
}
return params;
} else {
return new HashMap<String, String>();
}
}
protected List<String> getAcceptedMediaTypes() {
List<String> acceptedMediaTypes = new ArrayList<String>();
for (Preference<MediaType> p : getRequest().getClientInfo().getAcceptedMediaTypes()) {
acceptedMediaTypes.add(p.getMetadata().toString());
}
return acceptedMediaTypes;
}
public GenericResource getResource() {
return resource;
}
public Request getRequest() {
return resource.getRequest();
}
public Response getResponse() {
return resource.getResponse();
}
public Set<String> getAttributeNames() {
return resource.getAttributeNames();
}
public void setAttributeNames(Set<String> attributeNames) {
resource.setAttributeNames(attributeNames);
}
public AMEESpringServer getActiveServer() {
return (AMEESpringServer) getRequest().getAttributes().get("activeServer");
}
protected Representation getJsonRepresentation(JSONObject result) {
Representation representation = null;
try {
if (result != null) {
// Add version.
result.put("version", getResource().getSupportedVersion().toString());
// Handle validationResult.
if (result.has("validationResult")) {
getResource().addValidationResult(new ValidationResult(result.getJSONObject("validationResult")));
}
// Handle status.
if (result.has("status")) {
if (isOk(result)) {
representation = new JsonRepresentation(result);
} else if (isInvalid(result)) {
getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
representation = new JsonRepresentation(result);
} else if (isNotFound(result)) {
getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND);
} else if (isNotAuthenticated(result)) {
getResponse().setStatus(Status.CLIENT_ERROR_UNAUTHORIZED);
} else if (isNotAuthorized(result)) {
getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN);
} else if (isTimedOut(result)) {
getResponse().setStatus(Status.SERVER_ERROR_SERVICE_UNAVAILABLE);
} else if (isMediaTypeNotSupported(result)) {
getResponse().setStatus(Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE);
} else if (isInternalError(result)) {
getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
} else {
log.warn("getJsonRepresentation() Status code not handled: " + result.getString("status"));
}
}
}
} catch (JSONException e) {
throw new RuntimeException("Caught JSONException: " + e.getMessage(), e);
}
return representation;
}
protected Representation getDomRepresentation(Document document) {
Representation representation = null;
if (document != null) {
Element result = document.getRootElement();
if ((result != null) && result.getName().equals("Representation")) {
// Add version.
result.addContent(new Element("Version").setText(getResource().getSupportedVersion().toString()));
// Handle ValidationResult.
if (result.getChild("ValidationResult") != null) {
getResource().addValidationResult(new ValidationResult(result.getChild("ValidationResult")));
}
// Handle status.
if (result.getChild("Status") != null) {
String status = result.getChild("Status").getValue();
try {
if (status.equals("OK")) {
representation = new DomRepresentation(MediaType.APPLICATION_XML, ResourceBuildManager.DOM_OUTPUTTER.output(document));
} else if (status.equals("INVALID")) {
getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
representation = new DomRepresentation(MediaType.APPLICATION_XML, ResourceBuildManager.DOM_OUTPUTTER.output(document));
} else if (status.equals("NOT_FOUND")) {
getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND);
} else if (status.equals("NOT_AUTHENTICATED")) {
getResponse().setStatus(Status.CLIENT_ERROR_UNAUTHORIZED);
} else if (status.equals("NOT_AUTHORIZED")) {
getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN);
} else if (status.equals("TIMED_OUT")) {
getResponse().setStatus(Status.SERVER_ERROR_SERVICE_UNAVAILABLE);
} else if (status.equals("MEDIA_TYPE_NOT_SUPPORTED")) {
getResponse().setStatus(Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE);
} else if (status.equals("INTERNAL_ERROR")) {
getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
} else {
log.warn("getDomRepresentation() Status code not handled: " + status);
}
} catch (JDOMException e) {
throw new RuntimeException("Caught JDOMException: " + e.getMessage(), e);
}
}
} else if ((result != null) && result.getName().equals("ecoSpold")) {
try {
representation = new DomRepresentation(MediaType.valueOf("application/x.ecospold+xml"), ResourceBuildManager.DOM_OUTPUTTER.output(document));
} catch (JDOMException e) {
throw new RuntimeException("Caught JDOMException: " + e.getMessage(), e);
}
}
}
return representation;
}
} |
package com.codeborne.selenide;
import com.codeborne.selenide.ex.ElementNotFound;
import com.codeborne.selenide.ex.UIAssertionError;
import com.codeborne.selenide.impl.BySelectorCollection;
import com.codeborne.selenide.impl.Cleanup;
import com.codeborne.selenide.impl.CollectionElement;
import com.codeborne.selenide.impl.CollectionElementByCondition;
import com.codeborne.selenide.impl.Describe;
import com.codeborne.selenide.impl.FilteringCollection;
import com.codeborne.selenide.impl.HeadOfCollection;
import com.codeborne.selenide.impl.LastCollectionElement;
import com.codeborne.selenide.impl.SelenideElementIterator;
import com.codeborne.selenide.impl.SelenideElementListIterator;
import com.codeborne.selenide.impl.TailOfCollection;
import com.codeborne.selenide.impl.WebElementsCollection;
import com.codeborne.selenide.impl.WebElementsCollectionWrapper;
import com.codeborne.selenide.logevents.SelenideLog;
import com.codeborne.selenide.logevents.SelenideLogger;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptException;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
import java.util.AbstractList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import static com.codeborne.selenide.Condition.exist;
import static com.codeborne.selenide.Condition.not;
import static com.codeborne.selenide.logevents.ErrorsCollector.validateAssertionMode;
import static com.codeborne.selenide.logevents.LogEvent.EventStatus.PASS;
import static java.lang.System.lineSeparator;
import static java.util.stream.Collectors.toList;
@ParametersAreNonnullByDefault
public class ElementsCollection extends AbstractList<SelenideElement> {
private final WebElementsCollection collection;
public ElementsCollection(WebElementsCollection collection) {
this.collection = collection;
}
public ElementsCollection(Driver driver, Collection<? extends WebElement> elements) {
this(new WebElementsCollectionWrapper(driver, elements));
}
public ElementsCollection(Driver driver, String cssSelector) {
this(driver, By.cssSelector(cssSelector));
}
public ElementsCollection(Driver driver, By seleniumSelector) {
this(new BySelectorCollection(driver, seleniumSelector));
}
public ElementsCollection(Driver driver, WebElement parent, String cssSelector) {
this(driver, parent, By.cssSelector(cssSelector));
}
public ElementsCollection(Driver driver, WebElement parent, By seleniumSelector) {
this(new BySelectorCollection(driver, parent, seleniumSelector));
}
/**
* Deprecated. Use {@code $$.shouldHave(size(expectedSize))} instead.
*/
@Nonnull
public ElementsCollection shouldHaveSize(int expectedSize) {
return shouldHave(CollectionCondition.size(expectedSize));
}
/**
* For example: {@code $$(".error").shouldBe(empty)}
*/
@Nonnull
public ElementsCollection shouldBe(CollectionCondition... conditions) {
return should("be", driver().config().timeout(), conditions);
}
@Nonnull
public ElementsCollection shouldBe(CollectionCondition condition, long timeoutMs) {
return should("be", timeoutMs, toArray(condition));
}
/**
* For example:
* {@code $$(".error").shouldHave(size(3))}
* {@code $$(".error").shouldHave(texts("Error1", "Error2"))}
*/
@Nonnull
public ElementsCollection shouldHave(CollectionCondition... conditions) {
return should("have", driver().config().timeout(), conditions);
}
/**
* Check if a collection matches given condition within given period
*
* @param timeoutMs maximum waiting time in milliseconds
*/
@Nonnull
public ElementsCollection shouldHave(CollectionCondition condition, long timeoutMs) {
return should("have", timeoutMs, toArray(condition));
}
private CollectionCondition[] toArray(CollectionCondition condition) {
return new CollectionCondition[]{condition};
}
protected ElementsCollection should(String prefix, long timeoutMs, CollectionCondition... conditions) {
validateAssertionMode(driver().config());
SelenideLog log = SelenideLogger.beginStep(collection.description(), "should " + prefix, (Object[]) conditions);
try {
for (CollectionCondition condition : conditions) {
waitUntil(condition, timeoutMs);
}
SelenideLogger.commitStep(log, PASS);
return this;
}
catch (Error error) {
Error wrappedError = UIAssertionError.wrap(driver(), error, timeoutMs);
SelenideLogger.commitStep(log, wrappedError);
switch (driver().config().assertionMode()) {
case SOFT:
return this;
default:
throw wrappedError;
}
}
catch (RuntimeException e) {
SelenideLogger.commitStep(log, e);
throw e;
}
}
protected void waitUntil(CollectionCondition condition, long timeoutMs) {
Exception lastError = null;
List<WebElement> actualElements = null;
Stopwatch stopwatch = new Stopwatch(timeoutMs);
do {
try {
actualElements = collection.getElements();
if (condition.test(actualElements)) {
return;
}
}
catch (JavascriptException e) {
throw e;
}
catch (WebDriverException elementNotFound) {
lastError = elementNotFound;
if (Cleanup.of.isInvalidSelectorError(elementNotFound)) {
throw Cleanup.of.wrap(elementNotFound);
}
}
catch (IndexOutOfBoundsException outOfCollection) {
if (condition.applyNull()) {
return;
}
throw new ElementNotFound(collection.driver(), collection.description(), exist, outOfCollection);
}
sleep(driver().config().pollingInterval());
}
while (!stopwatch.isTimeoutReached());
condition.fail(collection, actualElements, lastError, timeoutMs);
}
void sleep(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}
/**
* Filters collection elements based on the given condition (lazy evaluation)
* ATTENTION! Doesn't start any search yet. Search will be started when action or assert is applied
* @param condition condition
* @return ElementsCollection
*/
@Nonnull
public ElementsCollection filter(Condition condition) {
return new ElementsCollection(new FilteringCollection(collection, condition));
}
/**
* Filters collection elements based on the given condition (lazy evaluation)
* ATTENTION! Doesn't start any search yet. Search will be started when action or assert is applied
* @see #filter(Condition)
* @param condition condition
* @return ElementsCollection
*/
@Nonnull
public ElementsCollection filterBy(Condition condition) {
return filter(condition);
}
/**
* Filters elements excluding those which met the given condition (lazy evaluation)
* ATTENTION! Doesn't start any search yet. Search will be started when action or assert is applied
* @param condition condition
* @return ElementsCollection
*/
@Nonnull
public ElementsCollection exclude(Condition condition) {
return new ElementsCollection(new FilteringCollection(collection, not(condition)));
}
/**
* Filters elements excluding those which met the given condition (lazy evaluation)
* ATTENTION! Doesn't start any search yet. Search will be started when action or assert is applied
* @see #exclude(Condition)
* @param condition condition
* @return ElementsCollection
*/
@Nonnull
public ElementsCollection excludeWith(Condition condition) {
return exclude(condition);
}
/**
* Find the first element which met the given condition (lazy evaluation)
* ATTENTION! Doesn't start any search yet. Search will be started when action or assert is applied
* @param condition condition
* @return SelenideElement
*/
@Nonnull
public SelenideElement find(Condition condition) {
return CollectionElementByCondition.wrap(collection, condition);
}
/**
* Find the first element which met the given condition (lazy evaluation)
* ATTENTION! Doesn't start any search yet. Search will be started when action or assert is applied
* @see #find(Condition)
* @param condition condition
* @return SelenideElement
*/
@Nonnull
public SelenideElement findBy(Condition condition) {
return find(condition);
}
private List<WebElement> getElements() {
return collection.getElements();
}
/**
* Gets all the texts in elements collection
* @return array of texts
*/
@Nonnull
public List<String> texts() {
return texts(getElements());
}
/**
* Fail-safe method for retrieving texts of given elements.
* @param elements Any collection of WebElements
* @return Array of texts (or exceptions in case of any WebDriverExceptions)
*/
@Nonnull
public static List<String> texts(Collection<WebElement> elements) {
return elements.stream().map(ElementsCollection::getText).collect(toList());
}
private static String getText(WebElement element) {
try {
return element.getText();
} catch (WebDriverException elementDisappeared) {
return elementDisappeared.toString();
}
}
/**
* Outputs string presentation of the element's collection
* @param elements elements of string
* @return String
*/
@Nonnull
public static String elementsToString(Driver driver, @Nullable Collection<WebElement> elements) {
if (elements == null) {
return "[not loaded yet...]";
}
if (elements.isEmpty()) {
return "[]";
}
StringBuilder sb = new StringBuilder(256);
sb.append("[").append(lineSeparator()).append("\t");
for (WebElement element : elements) {
if (sb.length() > 4) {
sb.append(",").append(lineSeparator()).append("\t");
}
sb.append(Describe.describe(driver, element));
}
sb.append(lineSeparator()).append("]");
return sb.toString();
}
/**
* Gets the n-th element of collection (lazy evaluation)
* ATTENTION! Doesn't start any search yet. Search will be started when action or assert is applied (.click(), should..() etc.)
*
* @param index 0..N
* @return the n-th element of collection
*/
@Override
public SelenideElement get(int index) {
return CollectionElement.wrap(collection, index);
}
/**
* returns the first element of the collection
* ATTENTION! Doesn't start any search yet. Search will be started when action or assert is applied (.click(), should..() etc.)
* NOTICE: $(css) is faster and returns the same result as $$(css).first()
* @return the first element of the collection
*/
@Nonnull
public SelenideElement first() {
return get(0);
}
/**
* returns the last element of the collection (lazy evaluation)
* ATTENTION! Doesn't start any search yet. Search will be started when action or assert is applied (.click(), should..() etc.)
* @return the last element of the collection
*/
@Nonnull
public SelenideElement last() {
return LastCollectionElement.wrap(collection);
}
/**
* returns the first n elements of the collection (lazy evaluation)
* ATTENTION! Doesn't start any search yet. Search will be started when action or assert is applied (.click(), should..() etc.)
* @param elements number of elements 1..N
*/
@Nonnull
public ElementsCollection first(int elements) {
return new ElementsCollection(new HeadOfCollection(collection, elements));
}
/**
* returns the last n elements of the collection (lazy evaluation)
* ATTENTION! Doesn't start any search yet. Search will be started when action or assert is applied (.click(), should..() etc.)
* @param elements number of elements 1..N
*/
@Nonnull
public ElementsCollection last(int elements) {
return new ElementsCollection(new TailOfCollection(collection, elements));
}
/**
* return actual size of the collection, doesn't wait on collection to be loaded.
* ATTENTION not recommended for use in tests. Use collection.shouldHave(size(n)); for assertions instead.
* @return actual size of the collection
*/
@Override
public int size() {
try {
return getElements().size();
} catch (IndexOutOfBoundsException outOfCollection) {
return 0;
}
}
@Override
@Nonnull
public Iterator<SelenideElement> iterator() {
return new SelenideElementIterator(fetch());
}
@Override
@Nonnull
public ListIterator<SelenideElement> listIterator(int index) {
return new SelenideElementListIterator(fetch(), index);
}
private WebElementsCollectionWrapper fetch() {
List<WebElement> fetchedElements = collection.getElements();
return new WebElementsCollectionWrapper(driver(), fetchedElements);
}
@Override
@Nonnull
public Object[] toArray() {
List<WebElement> fetchedElements = collection.getElements();
Object[] result = new Object[fetchedElements.size()];
for (int i = 0; i < result.length; i++) {
result[i] = CollectionElement.wrap(collection, i);
}
return result;
}
/**
* Takes the snapshot of current state of this collection.
* Succeeding calls to this object WILL NOT RELOAD collection element from browser.
*
* Use it to speed up your tests - but only if you know that collection will not be changed during the test.
*
* @return current state of this collection
*/
@Nonnull
public ElementsCollection snapshot() {
return new ElementsCollection(fetch());
}
@Override
public String toString() {
try {
return elementsToString(driver(), getElements());
} catch (RuntimeException e) {
return String.format("[%s]", Cleanup.of.webdriverExceptionMessage(e));
}
}
private Driver driver() {
return collection.driver();
}
} |
package com.conveyal.taui.models;
import com.conveyal.r5.analyst.scenario.StopSpec;
import com.conveyal.r5.util.ExceptionUtils;
import com.conveyal.taui.AnalysisServerException;
import com.vividsolutions.jts.geom.Coordinate;
import org.geotools.geometry.jts.JTS;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.TransformException;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import java.util.stream.Collectors;
/**
* An intermediate step between the front-end representation of new or extended trips and the form that R5 expects.
* Ideally we'd just convert directly to those R5 StopSpecs, but we need to use this intermediate type to track
* distanceFromStart for generating hop times from speeds.
* See conveyal/analysis-backend#175 for a potential cleaner solution.
*/
class ModificationStop {
// General Constants
private static double MIN_SPACING_PERCENTAGE = 0.25;
private static int DEFAULT_SEGMENT_SPEED_KPH = 15;
// Conversion Factors
public static int SECONDS_PER_HOUR = 60 * 60;
public static int METERS_PER_KM = 1000;
/** The WGS84 latitude and longitude of the stop. */
private final Coordinate coordinate;
/** The GTFS stop_id of a stop if it's being reused, or null if it was newly created in the editor. */
private final String id;
/**
* The distance of a stop from the beginning of the trip in meters, used for generating travel times from speeds.
* See conveyal/analysis-backend#175 for a way to elimiate this (persist the times instead of the speeds.)
*/
private final double distanceFromStart;
/** True if the stop was one of the ones generated automatically at regular intervals along the new route. */
private final boolean autoGenerated;
/**
* Constructor for ModificationStops. It creates an immutable object with all fields final.
*/
private ModificationStop (Coordinate c, String id, double distanceFromStart, boolean autoGenerated) {
this.coordinate = c;
this.id = id;
this.distanceFromStart = distanceFromStart;
this.autoGenerated = autoGenerated;
}
/**
* Convert a list of ModificationStops (which are internal to the backend conversion process) to a list of the
* StopSpec type required by r5.
*/
static List<StopSpec> toStopSpecs (List<ModificationStop> stops) {
return stops.stream()
.map(s -> {
if (s.id == null || s.autoGenerated){
return new StopSpec(s.coordinate.x, s.coordinate.y);
} else {
// Stop references an existing GTFS stop ID, send that instead of its coordinates.
return new StopSpec(s.id);
}
})
.collect(Collectors.toList());
}
/**
* Convert a list of Segments from a modification (the front-end representation) to this internal
* backend representation.
*/
static List<ModificationStop> getStopsFromSegments (List<Segment> segments) {
// Keep a stack of Stops because as part of auto-generating stops we sometimes need to back one out.
Stack<ModificationStop> stops = new Stack<>();
CoordinateReferenceSystem crs = DefaultGeographicCRS.WGS84;
if (segments == null || segments.size() == 0) {
return new ArrayList<>();
}
Segment firstSegment = segments.get(0);
if (firstSegment.stopAtStart) {
stops.add(new ModificationStop(firstSegment.geometry.getCoordinates()[0],
firstSegment.fromStopId, 0, false));
}
double distanceToLastStop = 0; // distance to previously created stop, from start of pattern
double distanceToLineSegmentStart = 0; // from start of pattern
for (Segment segment : segments) {
// TODO sanity check that each segment's final point matches the first point of the next segment
Coordinate[] coords = segment.geometry.getCoordinates();
int spacing = segment.spacing;
boolean autoCreateStops = spacing > 0;
for (int i = 1; i < coords.length; i++) {
Coordinate c0 = coords[i - 1];
Coordinate c1 = coords[i];
double distanceThisLineSegmentMeters;
try {
// JTS orthodromic distance returns meters, considering the input coordinate system.
distanceThisLineSegmentMeters = JTS.orthodromicDistance(c0, c1, crs);
} catch (TransformException e) {
throw AnalysisServerException.unknown(ExceptionUtils.asString(e));
}
if (autoCreateStops) {
// Auto-create stops while this segment includes at least one point that is more than 'spacing'
// meters farther along the pattern than the previously created stop
while (distanceToLastStop + spacing < distanceToLineSegmentStart + distanceThisLineSegmentMeters) {
double frac = (distanceToLastStop + spacing - distanceToLineSegmentStart) / distanceThisLineSegmentMeters;
if (frac < 0) frac = 0;
Coordinate c = new Coordinate(c0.x + (c1.x - c0.x) * frac, c0.y + (c1.y - c0.y) * frac);
// We can't just add segment.spacing because of converting negative fractions to zero above.
// This can happen when the last segment did not have automatic stop creation, or had a larger
// spacing. TODO in the latter case, we probably want to continue to apply the spacing from the
// last line segment until we create a new stop?
distanceToLastStop = distanceToLineSegmentStart + frac * distanceThisLineSegmentMeters;
stops.add(new ModificationStop(c, null, distanceToLastStop, true));
}
}
distanceToLineSegmentStart += distanceThisLineSegmentMeters;
}
if (segment.stopAtEnd) {
// If the last auto-generated stop was too close to a manually created stop (other than the first stop),
// remove it.
if (autoCreateStops && stops.size() > 1) {
ModificationStop lastStop = stops.peek();
if (lastStop.autoGenerated
&& (distanceToLineSegmentStart - distanceToLastStop) / spacing < MIN_SPACING_PERCENTAGE) {
stops.pop();
}
}
Coordinate endCoord = coords[coords.length - 1];
stops.add(new ModificationStop(endCoord, segment.toStopId, distanceToLineSegmentStart, false));
// restart the auto-generated stop spacing
// distanceToLineSegmentStart was already set to the next line segment
distanceToLastStop = distanceToLineSegmentStart;
}
}
return new ArrayList<>(stops);
}
static int[] getDwellTimes (List<ModificationStop> stops, Integer[] dwellTimes, int defaultDwellTime) {
if (stops == null || stops.size() == 0) {
return new int[0];
}
int[] stopDwellTimes = new int[stops.size()];
// This "real" stop index is the index into the originally supplied stops, ignoring the auto-generated ones.
int realStopIndex = 0;
for (int i = 0; i < stops.size(); i++) {
if (stops.get(i).autoGenerated || dwellTimes == null || dwellTimes.length <= realStopIndex) {
stopDwellTimes[i] = defaultDwellTime;
} else {
Integer specificDwellTime = dwellTimes[realStopIndex];
stopDwellTimes[i] = specificDwellTime != null ? specificDwellTime : defaultDwellTime;
realStopIndex++;
}
}
return stopDwellTimes;
}
static int[] getHopTimes (List<ModificationStop> stops, int[] segmentSpeedsKph) {
if (stops == null || stops.size() < 2) {
return new int[0];
}
int[] hopTimesSeconds = new int[stops.size() - 1];
ModificationStop lastStop = stops.get(0);
// This "real" stop index is the index into the originally supplied stops, ignoring the auto-generated ones.
int realStopIndex = 0;
for (int i = 0; i < hopTimesSeconds.length; i++) {
ModificationStop stop = stops.get(i + 1);
double hopDistance = stop.distanceFromStart - lastStop.distanceFromStart;
int segmentSpeedKph = segmentSpeedsKph.length > realStopIndex ? segmentSpeedsKph[realStopIndex] :
DEFAULT_SEGMENT_SPEED_KPH;
hopTimesSeconds[i] = (int) (hopDistance / (segmentSpeedKph * METERS_PER_KM) * SECONDS_PER_HOUR);
if (stop.autoGenerated) {
realStopIndex++;
}
lastStop = stop;
}
return hopTimesSeconds;
}
} |
package com.dianping.cat.report.chart.impl;
import java.io.File;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.unidal.helper.Files;
import org.unidal.lookup.annotation.Inject;
import com.dianping.cat.Cat;
import com.dianping.cat.consumer.metric.model.entity.MetricReport;
import com.dianping.cat.consumer.metric.model.transform.DefaultSaxParser;
import com.dianping.cat.helper.TimeUtil;
import com.dianping.cat.report.chart.CachedMetricReportService;
import com.dianping.cat.report.page.model.spi.ModelService;
import com.dianping.cat.report.page.userMonitor.UserMonitorConvert;
import com.dianping.cat.report.service.ReportService;
import com.dianping.cat.service.ModelPeriod;
import com.dianping.cat.service.ModelRequest;
import com.dianping.cat.service.ModelResponse;
public class CachedMetricReportServiceImpl implements CachedMetricReportService {
@Inject
private ReportService m_reportService;
@Inject
private ModelService<MetricReport> m_service;
private final Map<String, MetricReport> m_metricReports = new LinkedHashMap<String, MetricReport>() {
private static final long serialVersionUID = 1L;
@Override
protected boolean removeEldestEntry(Entry<String, MetricReport> eldest) {
return size() > 500;
}
};
private MetricReport getReportFromCache(String product, long date) {
String key = product + date;
MetricReport result = m_metricReports.get(key);
if (result == null) {
Date start = new Date(date);
Date end = new Date(date + TimeUtil.ONE_HOUR);
try {
result = m_reportService.queryMetricReport(product, start, end);
m_metricReports.put(key, result);
} catch (Exception e) {
Cat.logError(e);
}
}
return result;
}
@Override
public MetricReport queryMetricReport(String product, Date start) {
long time = start.getTime();
ModelPeriod period = ModelPeriod.getByTime(time);
if (period == ModelPeriod.CURRENT || period == ModelPeriod.LAST) {
ModelRequest request = new ModelRequest(product, time);
if (m_service.isEligable(request)) {
ModelResponse<MetricReport> response = m_service.invoke(request);
MetricReport report = response.getModel();
return report;
} else {
throw new RuntimeException("Internal error: no eligable metric service registered for " + request + "!");
}
} else {
return getReportFromCache(product, time);
}
}
private MetricReport hackForTest(String product, Map<String, String> properties) {
MetricReport report = null;
try {
String content = Files.forIO().readFrom(new File("/tmp/data.txt"), "utf-8");
report = DefaultSaxParser.parse(content);
report.setProduct(product);
} catch (Exception e) {
e.printStackTrace();
}
String city = properties.get("city");
String channel = properties.get("channel");
String type = properties.get("type");
UserMonitorConvert convert = new UserMonitorConvert(type, city, channel);
convert.visitMetricReport(report);
return convert.getReport();
}
@Override
public MetricReport queryUserMonitorReport(String product, Map<String, String> properties, Date start) {
long time = start.getTime();
ModelPeriod period = ModelPeriod.getByTime(time);
if (period == ModelPeriod.CURRENT || period == ModelPeriod.LAST) {
ModelRequest request = new ModelRequest(product, time);
request.getProperties().putAll(properties);
if (m_service.isEligable(request)) {
ModelResponse<MetricReport> response = m_service.invoke(request);
MetricReport report = response.getModel();
return hackForTest(product, properties);
// return report;
} else {
throw new RuntimeException("Internal error: no eligable metric service registered for " + request + "!");
}
} else {
MetricReport report = getReportFromCache(product, time);
// return report;
return hackForTest(product, properties);
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.